summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorFlorin Coras <fcoras@cisco.com>2021-11-30 20:21:57 -0800
committerDamjan Marion <dmarion@me.com>2021-12-22 20:53:32 +0000
commitc824977ed38738985864c4524510f37a41453f7d (patch)
treee3ffc4e6bd0c3fccc1e3c1106a8ee1b9127bd511 /src
parentd51250f5e2bc99784399b196733e813fef000d71 (diff)
session: fix segment alloc/free worker race
Avoid scenarios where a worker allocates a segment but while it drops the segment manager writer lock and acquires the reader lock another worker uses the segment and frees it. Type: fix Thanks to wanghanlin@corp.netease.com for the report. Signed-off-by: Florin Coras <fcoras@cisco.com> Change-Id: I0a88d738c51b33fd07c34916f125c98806861a06
Diffstat (limited to 'src')
-rw-r--r--src/vnet/session/segment_manager.c173
-rw-r--r--src/vnet/session/segment_manager.h16
2 files changed, 119 insertions, 70 deletions
diff --git a/src/vnet/session/segment_manager.c b/src/vnet/session/segment_manager.c
index 184d3fd597d..cbf6207060c 100644
--- a/src/vnet/session/segment_manager.c
+++ b/src/vnet/session/segment_manager.c
@@ -89,7 +89,7 @@ segment_manager_segment_index (segment_manager_t * sm, fifo_segment_t * seg)
*/
static inline int
segment_manager_add_segment_inline (segment_manager_t *sm, uword segment_size,
- u8 notify_app, u8 flags)
+ u8 notify_app, u8 flags, u8 need_lock)
{
segment_manager_main_t *smm = &sm_main;
segment_manager_props_t *props;
@@ -112,7 +112,7 @@ segment_manager_add_segment_inline (segment_manager_t *sm, uword segment_size,
/*
* Allocate fifo segment and grab lock if needed
*/
- if (vlib_num_workers ())
+ if (need_lock)
clib_rwlock_writer_lock (&sm->segments_rwlock);
pool_get_zero (sm->segments, fs);
@@ -179,7 +179,7 @@ segment_manager_add_segment_inline (segment_manager_t *sm, uword segment_size,
}
done:
- if (vlib_num_workers ())
+ if (need_lock)
clib_rwlock_writer_unlock (&sm->segments_rwlock);
return fs_index;
@@ -189,14 +189,16 @@ int
segment_manager_add_segment (segment_manager_t *sm, uword segment_size,
u8 notify_app)
{
- return segment_manager_add_segment_inline (sm, segment_size, notify_app, 0);
+ return segment_manager_add_segment_inline (sm, segment_size, notify_app,
+ 0 /* flags */, 0 /* need_lock */);
}
int
segment_manager_add_segment2 (segment_manager_t *sm, uword segment_size,
u8 flags)
{
- return segment_manager_add_segment_inline (sm, segment_size, 0, flags);
+ return segment_manager_add_segment_inline (sm, segment_size, 0, flags,
+ vlib_num_workers ());
}
/**
@@ -333,12 +335,6 @@ segment_manager_segment_reader_unlock (segment_manager_t * sm)
clib_rwlock_reader_unlock (&sm->segments_rwlock);
}
-void
-segment_manager_segment_writer_unlock (segment_manager_t * sm)
-{
- clib_rwlock_writer_unlock (&sm->segments_rwlock);
-}
-
segment_manager_t *
segment_manager_alloc (void)
{
@@ -740,92 +736,131 @@ segment_manager_try_alloc_fifos (fifo_segment_t * fifo_segment,
return 0;
}
+static inline int
+sm_lookup_segment_and_alloc_fifos (segment_manager_t *sm,
+ segment_manager_props_t *props,
+ u32 thread_index, svm_fifo_t **rx_fifo,
+ svm_fifo_t **tx_fifo)
+{
+ uword free_bytes, max_free_bytes;
+ fifo_segment_t *cur, *fs = 0;
+ u32 fs_index;
+ int rv;
+
+ max_free_bytes = props->rx_fifo_size + props->tx_fifo_size - 1;
+
+ pool_foreach (cur, sm->segments)
+ {
+ if (fifo_segment_flags (cur) & FIFO_SEGMENT_F_CUSTOM_USE)
+ continue;
+ free_bytes = fifo_segment_available_bytes (cur);
+ if (free_bytes > max_free_bytes)
+ {
+ max_free_bytes = free_bytes;
+ fs = cur;
+ }
+ }
+
+ if (PREDICT_FALSE (!fs))
+ return SESSION_E_SEG_NO_SPACE;
+
+ fs_index = segment_manager_segment_index (sm, fs);
+ rv = segment_manager_try_alloc_fifos (fs, thread_index, props->rx_fifo_size,
+ props->tx_fifo_size, rx_fifo, tx_fifo);
+
+ return rv ? SESSION_E_SEG_NO_SPACE : fs_index;
+}
+
+static int
+sm_lock_and_alloc_segment_and_fifos (segment_manager_t *sm,
+ segment_manager_props_t *props,
+ u32 thread_index, svm_fifo_t **rx_fifo,
+ svm_fifo_t **tx_fifo)
+{
+ int new_fs_index, rv;
+ fifo_segment_t *fs;
+
+ if (!props->add_segment)
+ return SESSION_E_SEG_NO_SPACE;
+
+ clib_rwlock_writer_lock (&sm->segments_rwlock);
+
+ /* Make sure there really is no free space. Another worker might've freed
+ * some fifos or allocated a segment */
+ rv = sm_lookup_segment_and_alloc_fifos (sm, props, thread_index, rx_fifo,
+ tx_fifo);
+ if (rv > 0)
+ goto done;
+
+ new_fs_index =
+ segment_manager_add_segment (sm, 0 /* segment_size*/, 1 /* notify_app */);
+ if (new_fs_index < 0)
+ {
+ rv = SESSION_E_SEG_CREATE;
+ goto done;
+ }
+ fs = segment_manager_get_segment (sm, new_fs_index);
+ rv = segment_manager_try_alloc_fifos (fs, thread_index, props->rx_fifo_size,
+ props->tx_fifo_size, rx_fifo, tx_fifo);
+ if (rv)
+ {
+ clib_warning ("Added a segment, still can't allocate a fifo");
+ rv = SESSION_E_SEG_NO_SPACE2;
+ goto done;
+ }
+
+ rv = new_fs_index;
+
+done:
+
+ clib_rwlock_writer_unlock (&sm->segments_rwlock);
+
+ return rv;
+}
+
int
segment_manager_alloc_session_fifos (segment_manager_t * sm,
u32 thread_index,
svm_fifo_t ** rx_fifo,
svm_fifo_t ** tx_fifo)
{
- int alloc_fail = 1, rv = 0, new_fs_index;
- uword free_bytes, max_free_bytes = 0;
segment_manager_props_t *props;
- fifo_segment_t *fs = 0, *cur;
- u32 sm_index, fs_index;
+ u32 sm_index;
+ int fs_index;
props = segment_manager_properties_get (sm);
+ sm_index = segment_manager_index (sm);
/*
- * Find the first free segment to allocate the fifos in
+ * Fast path: find the first segment with enough free space and
+ * try to allocate the fifos. Done with reader lock
*/
segment_manager_segment_reader_lock (sm);
- pool_foreach (cur, sm->segments) {
- if (fifo_segment_flags (cur) & FIFO_SEGMENT_F_CUSTOM_USE)
- continue;
- free_bytes = fifo_segment_available_bytes (cur);
- if (free_bytes > max_free_bytes)
- {
- max_free_bytes = free_bytes;
- fs = cur;
- }
- }
-
- if (fs)
- {
- alloc_fail = segment_manager_try_alloc_fifos (fs, thread_index,
- props->rx_fifo_size,
- props->tx_fifo_size,
- rx_fifo, tx_fifo);
- /* On success, keep lock until fifos are initialized */
- if (!alloc_fail)
- goto alloc_success;
- }
+ fs_index = sm_lookup_segment_and_alloc_fifos (sm, props, thread_index,
+ rx_fifo, tx_fifo);
segment_manager_segment_reader_unlock (sm);
/*
- * Allocation failed, see if we can add a new segment
+ * Slow path: if no fifo segment or alloc fail grab writer lock and try
+ * to allocate new segment
*/
- if (props->add_segment)
+ if (PREDICT_FALSE (fs_index < 0))
{
- if ((new_fs_index = segment_manager_add_segment (sm, 0, 1)) < 0)
- {
- clib_warning ("Failed to add new segment");
- return SESSION_E_SEG_CREATE;
- }
- fs = segment_manager_get_segment_w_lock (sm, new_fs_index);
- alloc_fail = segment_manager_try_alloc_fifos (fs, thread_index,
- props->rx_fifo_size,
- props->tx_fifo_size,
- rx_fifo, tx_fifo);
- if (alloc_fail)
- {
- clib_warning ("Added a segment, still can't allocate a fifo");
- segment_manager_segment_reader_unlock (sm);
- return SESSION_E_SEG_NO_SPACE2;
- }
+ fs_index = sm_lock_and_alloc_segment_and_fifos (sm, props, thread_index,
+ rx_fifo, tx_fifo);
+ if (fs_index < 0)
+ return fs_index;
}
- else
- {
- SESSION_DBG ("Can't add new seg and no space to allocate fifos!");
- return SESSION_E_SEG_NO_SPACE;
- }
-
-alloc_success:
- ASSERT (rx_fifo && tx_fifo);
- sm_index = segment_manager_index (sm);
- fs_index = segment_manager_segment_index (sm, fs);
(*tx_fifo)->segment_manager = sm_index;
(*rx_fifo)->segment_manager = sm_index;
(*tx_fifo)->segment_index = fs_index;
(*rx_fifo)->segment_index = fs_index;
- /* Drop the lock after app is notified */
- segment_manager_segment_reader_unlock (sm);
-
- return rv;
+ return 0;
}
void
diff --git a/src/vnet/session/segment_manager.h b/src/vnet/session/segment_manager.h
index 5a3d772ff02..8b722a02324 100644
--- a/src/vnet/session/segment_manager.h
+++ b/src/vnet/session/segment_manager.h
@@ -102,8 +102,23 @@ segment_manager_t *segment_manager_get (u32 index);
segment_manager_t *segment_manager_get_if_valid (u32 index);
u32 segment_manager_index (segment_manager_t * sm);
+/**
+ * Add segment without lock
+ *
+ * @param sm Segment manager
+ * @param segment_size Size of segment to be added
+ * @param notify_app Flag set if app notification requested
+ */
int segment_manager_add_segment (segment_manager_t *sm, uword segment_size,
u8 notify_app);
+
+/**
+ * Add segment with lock
+ *
+ * @param sm Segment manager
+ * @param segment_size Size of segment to be added
+ * @param flags Flags to be set on segment
+ */
int segment_manager_add_segment2 (segment_manager_t *sm, uword segment_size,
u8 flags);
void segment_manager_del_segment (segment_manager_t * sm,
@@ -122,7 +137,6 @@ u64 segment_manager_make_segment_handle (u32 segment_manager_index,
u64 segment_manager_segment_handle (segment_manager_t * sm,
fifo_segment_t * segment);
void segment_manager_segment_reader_unlock (segment_manager_t * sm);
-void segment_manager_segment_writer_unlock (segment_manager_t * sm);
int segment_manager_alloc_session_fifos (segment_manager_t * sm,
u32 thread_index,
7' href='#n617'>617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
/*
 * Copyright (c) 2011-2016 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @file
 * @brief BFD CLI implementation
 */

#include <vlib/vlib.h>
#include <vlib/cli.h>
#include <vppinfra/format.h>
#include <vppinfra/warnings.h>
#include <vnet/api_errno.h>
#include <vnet/ip/format.h>
#include <vnet/bfd/bfd_api.h>
#include <vnet/bfd/bfd_main.h>

static u8 *
format_bfd_session_cli (u8 * s, va_list * args)
{
  vlib_main_t *vm = va_arg (*args, vlib_main_t *);
  bfd_main_t *bm = va_arg (*args, bfd_main_t *);
  bfd_session_t *bs = va_arg (*args, bfd_session_t *);
  switch (bs->transport)
    {
    case BFD_TRANSPORT_UDP4:
      s = format (s, "%=10u %-32s %20U %20U\n", bs->bs_idx, "IPv4 address",
		  format_ip4_address, bs->udp.key.local_addr.ip4.as_u8,
		  format_ip4_address, bs->udp.key.peer_addr.ip4.as_u8);
      break;
    case BFD_TRANSPORT_UDP6:
      s = format (s, "%=10u %-32s %20U %20U\n", bs->bs_idx, "IPv6 address",
		  format_ip6_address, &bs->udp.key.local_addr.ip6,
		  format_ip6_address, &bs->udp.key.peer_addr.ip6);
      break;
    }
  s = format (s, "%10s %-32s %20s %20s\n", "", "Session state",
	      bfd_state_string (bs->local_state),
	      bfd_state_string (bs->remote_state));
  s = format (s, "%10s %-32s %20s %20s\n", "", "Diagnostic code",
	      bfd_diag_code_string (bs->local_diag),
	      bfd_diag_code_string (bs->remote_diag));
  s = format (s, "%10s %-32s %20u %20u\n", "", "Detect multiplier",
	      bs->local_detect_mult, bs->remote_detect_mult);
  s = format (s, "%10s %-32s %20u %20llu\n", "",
	      "Required Min Rx Interval (usec)",
	      bs->config_required_min_rx_usec, bs->remote_min_rx_usec);
  s = format (s, "%10s %-32s %20u %20u\n", "",
	      "Desired Min Tx Interval (usec)",
	      bs->config_desired_min_tx_usec, bfd_clocks_to_usec (bm,
								  bs->remote_desired_min_tx_clocks));
  s =
    format (s, "%10s %-32s %20u\n", "", "Transmit interval",
	    bfd_clocks_to_usec (bm, bs->transmit_interval_clocks));
  u64 now = clib_cpu_time_now ();
  u8 *tmp = NULL;
  if (bs->last_tx_clocks > 0)
    {
      tmp = format (tmp, "%.2fs ago", (now - bs->last_tx_clocks) *
		    vm->clib_time.seconds_per_clock);
      s = format (s, "%10s %-32s %20v\n", "", "Last control frame tx", tmp);
      vec_reset_length (tmp);
    }
  if (bs->last_rx_clocks)
    {
      tmp = format (tmp, "%.2fs ago", (now - bs->last_rx_clocks) *
		    vm->clib_time.seconds_per_clock);
      s = format (s, "%10s %-32s %20v\n", "", "Last control frame rx", tmp);
      vec_reset_length (tmp);
    }
  s =
    format (s, "%10s %-32s %20u %20llu\n", "", "Min Echo Rx Interval (usec)",
	    1, bs->remote_min_echo_rx_usec);
  if (bs->echo)
    {
      s = format (s, "%10s %-32s %20u\n", "", "Echo transmit interval",
		  bfd_clocks_to_usec (bm, bs->echo_transmit_interval_clocks));
      tmp = format (tmp, "%.2fs ago", (now - bs->echo_last_tx_clocks) *
		    vm->clib_time.seconds_per_clock);
      s = format (s, "%10s %-32s %20v\n", "", "Last echo frame tx", tmp);
      vec_reset_length (tmp);
      tmp = format (tmp, "%.6fs",
		    (bs->echo_last_rx_clocks - bs->echo_last_tx_clocks) *
		    vm->clib_time.seconds_per_clock);
      s =
	format (s, "%10s %-32s %20v\n", "", "Last echo frame roundtrip time",
		tmp);
    }
  vec_free (tmp);
  tmp = NULL;
  s = format (s, "%10s %-32s %20s %20s\n", "", "Demand mode", "no",
	      bs->remote_demand ? "yes" : "no");
  s = format (s, "%10s %-32s %20s\n", "", "Poll state",
	      bfd_poll_state_string (bs->poll_state));
  if (bs->auth.curr_key)
    {
      s = format (s, "%10s %-32s %20u\n", "", "Authentication config key ID",
		  bs->auth.curr_key->conf_key_id);
      s = format (s, "%10s %-32s %20u\n", "", "Authentication BFD key ID",
		  bs->auth.curr_bfd_key_id);
      s = format (s, "%10s %-32s %20u %20u\n", "", "Sequence number",
		  bs->auth.local_seq_number, bs->auth.remote_seq_number);
    }
  return s;
}

static clib_error_t *
show_bfd (vlib_main_t * vm, unformat_input_t * input,
	  CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  bfd_main_t *bm = &bfd_main;
  bfd_session_t *bs = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  if (unformat (line_input, "keys"))
    {
      bfd_auth_key_t *key = NULL;
      u8 *s = format (NULL, "%=10s %=25s %=10s\n", "Configuration Key ID",
		      "Type", "Use Count");
      /* *INDENT-OFF* */
      pool_foreach (key, bm->auth_keys, {
        s = format (s, "%10u %-25s %10u\n", key->conf_key_id,
                    bfd_auth_type_str (key->auth_type), key->use_count);
      });
      /* *INDENT-ON* */
      vlib_cli_output (vm, "%v\n", s);
      vec_free (s);
      vlib_cli_output (vm, "Number of configured BFD keys: %lu\n",
		       (u64) pool_elts (bm->auth_keys));
    }
  else if (unformat (line_input, "sessions"))
    {
      u8 *s = format (NULL, "%=10s %=32s %=20s %=20s\n", "Index", "Property",
		      "Local value", "Remote value");
      /* *INDENT-OFF* */
      pool_foreach (bs, bm->sessions, {
        s = format (s, "%U", format_bfd_session_cli, vm, bm, bs);
      });
      /* *INDENT-ON* */
      vlib_cli_output (vm, "%v", s);
      vec_free (s);
      vlib_cli_output (vm, "Number of configured BFD sessions: %lu\n",
		       (u64) pool_elts (bm->sessions));
    }
  else if (unformat (line_input, "echo-source"))
    {
      int is_set;
      u32 sw_if_index;
      int have_usable_ip4;
      ip4_address_t ip4;
      int have_usable_ip6;
      ip6_address_t ip6;
      bfd_udp_get_echo_source (&is_set, &sw_if_index, &have_usable_ip4, &ip4,
			       &have_usable_ip6, &ip6);
      if (is_set)
	{
	  vnet_sw_interface_t *sw_if =
	    vnet_get_sw_interface_or_null (&vnet_main, sw_if_index);
	  vnet_hw_interface_t *hw_if =
	    vnet_get_hw_interface (&vnet_main, sw_if->hw_if_index);
	  u8 *s = format (NULL, "UDP echo source is: %v\n", hw_if->name);
	  s = format (s, "IPv4 address usable as echo source: ");
	  if (have_usable_ip4)
	    {
	      s = format (s, "%U\n", format_ip4_address, &ip4);
	    }
	  else
	    {
	      s = format (s, "none\n");
	    }
	  s = format (s, "IPv6 address usable as echo source: ");
	  if (have_usable_ip6)
	    {
	      s = format (s, "%U\n", format_ip6_address, &ip6);
	    }
	  else
	    {
	      s = format (s, "none\n");
	    }
	  vlib_cli_output (vm, "%v", s);
	  vec_free (s);
	}
      else
	{
	  vlib_cli_output (vm, "UDP echo source is not set.\n");
	}
    }
  else
    {
      vlib_cli_output (vm, "Number of configured BFD sessions: %lu\n",
		       (u64) pool_elts (bm->sessions));
      vlib_cli_output (vm, "Number of configured BFD keys: %lu\n",
		       (u64) pool_elts (bm->auth_keys));
    }
  return 0;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (show_bfd_command, static) = {
  .path = "show bfd",
  .short_help = "show bfd [keys|sessions|echo-source]",
  .function = show_bfd,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_key_add (vlib_main_t * vm, unformat_input_t * input,
		 CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  int have_key_id = 0;
  u32 key_id = 0;
  u8 *vec_auth_type = NULL;
  bfd_auth_type_e auth_type = BFD_AUTH_TYPE_reserved;
  u8 *secret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
  static const u8 keyed_sha1[] = "keyed-sha1";
  static const u8 meticulous_keyed_sha1[] = "meticulous-keyed-sha1";

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      if (unformat (line_input, "conf-key-id %u", &key_id))
	{
	  have_key_id = 1;
	}
      else if (unformat (line_input, "type %U", unformat_token, "a-zA-Z0-9-",
			 &vec_auth_type))
	{
	  if (vec_len (vec_auth_type) == sizeof (keyed_sha1) - 1 &&
	      0 == memcmp (vec_auth_type, keyed_sha1,
			   sizeof (keyed_sha1) - 1))
	    {
	      auth_type = BFD_AUTH_TYPE_keyed_sha1;
	    }
	  else if (vec_len (vec_auth_type) ==
		   sizeof (meticulous_keyed_sha1) - 1 &&
		   0 == memcmp (vec_auth_type, meticulous_keyed_sha1,
				sizeof (meticulous_keyed_sha1) - 1))
	    {
	      auth_type = BFD_AUTH_TYPE_meticulous_keyed_sha1;
	    }
	  else
	    {
	      ret = clib_error_return (0, "invalid type `%v'", vec_auth_type);
	      goto out;
	    }
	}
      else
	if (unformat (line_input, "secret %U", unformat_hex_string, &secret))
	{
	  /* nothing to do here */
	}
      else
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  if (!have_key_id)
    {
      ret =
	clib_error_return (0, "required parameter missing: `conf-key-id'");
      goto out;
    }
  if (!vec_auth_type)
    {
      ret = clib_error_return (0, "required parameter missing: `type'");
      goto out;
    }
  if (!secret)
    {
      ret = clib_error_return (0, "required parameter missing: `secret'");
      goto out;
    }

  vnet_api_error_t rv =
    bfd_auth_set_key (key_id, auth_type, vec_len (secret), secret);
  if (rv)
    {
      ret =
	clib_error_return (0, "`bfd_auth_set_key' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
    }

out:
  vec_free (vec_auth_type);
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_key_add_command, static) = {
  .path = "bfd key set",
  .short_help = "bfd key set"
                " conf-key-id <id>"
                " type <keyed-sha1|meticulous-keyed-sha1> "
                " secret <secret>",
  .function = bfd_cli_key_add,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_key_del (vlib_main_t * vm, unformat_input_t * input,
		 CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  u32 key_id = 0;
  unformat_input_t _line_input, *line_input = &_line_input;

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      if (!unformat (line_input, "conf-key-id %u", &key_id))
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  vnet_api_error_t rv = bfd_auth_del_key (key_id);
  if (rv)
    {
      ret =
	clib_error_return (0, "`bfd_auth_del_key' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_key_del_command, static) = {
  .path = "bfd key del",
  .short_help = "bfd key del conf-key-id <id>",
  .function = bfd_cli_key_del,
};
/* *INDENT-ON* */

#define INTERFACE_STR "interface"
#define LOCAL_ADDR_STR "local-addr"
#define PEER_ADDR_STR "peer-addr"
#define CONF_KEY_ID_STR "conf-key-id"
#define BFD_KEY_ID_STR "bfd-key-id"
#define DESIRED_MIN_TX_STR "desired-min-tx"
#define REQUIRED_MIN_RX_STR "required-min-rx"
#define DETECT_MULT_STR "detect-mult"
#define ADMIN_STR "admin"
#define DELAYED_STR "delayed"

static const unsigned mandatory = 1;
static const unsigned optional = 0;

#define DECLARE(t, n, s, r, ...) \
  int have_##n = 0;              \
  t n;

#define UNFORMAT(t, n, s, r, ...)              \
  if (unformat (line_input, s " " __VA_ARGS__, &n)) \
    {                                          \
      something_parsed = 1;                    \
      have_##n = 1;                            \
    }

#define CHECK_MANDATORY(t, n, s, r, ...)                                  \
WARN_OFF(tautological-compare)                                            \
  if (mandatory == r && !have_##n)                                        \
    {                                                                     \
      WARN_ON(tautological-compare)                                       \
      ret = clib_error_return (0, "Required parameter `%s' missing.", s); \
      goto out;                                                           \
    }

static clib_error_t *
bfd_cli_udp_session_add (vlib_main_t * vm, unformat_input_t * input,
			 CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_add_cli_param(F)              \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)                                       \
  F (u32, desired_min_tx, DESIRED_MIN_TX_STR, mandatory, "%u")    \
  F (u32, required_min_rx, REQUIRED_MIN_RX_STR, mandatory, "%u")  \
  F (u32, detect_mult, DETECT_MULT_STR, mandatory, "%u")          \
  F (u32, conf_key_id, CONF_KEY_ID_STR, optional, "%u")           \
  F (u32, bfd_key_id, BFD_KEY_ID_STR, optional, "%u")

  foreach_bfd_cli_udp_session_add_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_add_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_session_add_cli_param (CHECK_MANDATORY);

  if (1 == have_conf_key_id + have_bfd_key_id)
    {
      ret = clib_error_return (0, "Incompatible parameter combination, `%s' "
			       "and `%s' must be either both specified or none",
			       CONF_KEY_ID_STR, BFD_KEY_ID_STR);
      goto out;
    }

  if (detect_mult > 255)
    {
      ret = clib_error_return (0, "%s value `%u' out of range <1,255>",
			       DETECT_MULT_STR, detect_mult);
      goto out;
    }

  if (have_bfd_key_id && bfd_key_id > 255)
    {
      ret = clib_error_return (0, "%s value `%u' out of range <1,255>",
			       BFD_KEY_ID_STR, bfd_key_id);
      goto out;
    }

  vnet_api_error_t rv =
    bfd_udp_add_session (sw_if_index, &local_addr, &peer_addr, desired_min_tx,
			 required_min_rx,
			 detect_mult, have_conf_key_id, conf_key_id,
			 bfd_key_id);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_add_add_session' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_add_command, static) = {
  .path = "bfd udp session add",
  .short_help = "bfd udp session add"
                " interface <interface>"
                " local-addr <local-address>"
                " peer-addr <peer-address>"
                " desired-min-tx <desired min tx interval>"
                " required-min-rx <required min rx interval>"
                " detect-mult <detect multiplier> "
                "["
                " conf-key-id <config key ID>"
                " bfd-key-id <BFD key ID>"
                "]",
  .function = bfd_cli_udp_session_add,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_session_mod (vlib_main_t * vm, unformat_input_t * input,
			 CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_mod_cli_param(F)              \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)                                       \
  F (u32, desired_min_tx, DESIRED_MIN_TX_STR, mandatory, "%u")    \
  F (u32, required_min_rx, REQUIRED_MIN_RX_STR, mandatory, "%u")  \
  F (u32, detect_mult, DETECT_MULT_STR, mandatory, "%u")

  foreach_bfd_cli_udp_session_mod_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_mod_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_session_mod_cli_param (CHECK_MANDATORY);

  if (detect_mult > 255)
    {
      ret = clib_error_return (0, "%s value `%u' out of range <1,255>",
			       DETECT_MULT_STR, detect_mult);
      goto out;
    }

  vnet_api_error_t rv =
    bfd_udp_mod_session (sw_if_index, &local_addr, &peer_addr,
			 desired_min_tx, required_min_rx, detect_mult);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_udp_mod_session' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_mod_command, static) = {
  .path = "bfd udp session mod",
  .short_help = "bfd udp session mod interface"
                " <interface> local-addr"
                " <local-address> peer-addr"
                " <peer-address> desired-min-tx"
                " <desired min tx interval> required-min-rx"
                " <required min rx interval> detect-mult"
                " <detect multiplier> ",
  .function = bfd_cli_udp_session_mod,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_session_del (vlib_main_t * vm, unformat_input_t * input,
			 CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_del_cli_param(F)              \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)

  foreach_bfd_cli_udp_session_del_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_del_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_session_del_cli_param (CHECK_MANDATORY);

  vnet_api_error_t rv =
    bfd_udp_del_session (sw_if_index, &local_addr, &peer_addr);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_udp_del_session' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_del_command, static) = {
  .path = "bfd udp session del",
  .short_help = "bfd udp session del interface"
                " <interface> local-addr"
                " <local-address> peer-addr"
                "<peer-address> ",
  .function = bfd_cli_udp_session_del,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_session_set_flags (vlib_main_t * vm, unformat_input_t * input,
			       CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_set_flags_cli_param(F)        \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)                                       \
  F (u8 *, admin_up_down_token, ADMIN_STR, mandatory, "%v",       \
     &admin_up_down_token)

  foreach_bfd_cli_udp_session_set_flags_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_set_flags_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_session_set_flags_cli_param (CHECK_MANDATORY);

  u8 admin_up_down;
  static const char up[] = "up";
  static const char down[] = "down";
  if (!memcmp (admin_up_down_token, up, sizeof (up) - 1))
    {
      admin_up_down = 1;
    }
  else if (!memcmp (admin_up_down_token, down, sizeof (down) - 1))
    {
      admin_up_down = 0;
    }
  else
    {
      ret =
	clib_error_return (0, "Unrecognized value for `%s' parameter: `%v'",
			   ADMIN_STR, admin_up_down_token);
      goto out;
    }
  vnet_api_error_t rv = bfd_udp_session_set_flags (sw_if_index, &local_addr,
						   &peer_addr, admin_up_down);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_udp_session_set_flags' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_set_flags_command, static) = {
  .path = "bfd udp session set-flags",
  .short_help = "bfd udp session set-flags"
                " interface <interface>"
                " local-addr <local-address>"
                " peer-addr <peer-address>"
                " admin <up|down>",
  .function = bfd_cli_udp_session_set_flags,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_session_auth_activate (vlib_main_t * vm,
				   unformat_input_t * input,
				   CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_auth_activate_cli_param(F)    \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)                                       \
  F (u8 *, delayed_token, DELAYED_STR, optional, "%v")            \
  F (u32, conf_key_id, CONF_KEY_ID_STR, mandatory, "%u")          \
  F (u32, bfd_key_id, BFD_KEY_ID_STR, mandatory, "%u")

  foreach_bfd_cli_udp_session_auth_activate_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_auth_activate_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_session_auth_activate_cli_param (CHECK_MANDATORY);

  u8 is_delayed = 0;
  if (have_delayed_token)
    {
      static const char yes[] = "yes";
      static const char no[] = "no";
      if (!memcmp (delayed_token, yes, sizeof (yes) - 1))
	{
	  is_delayed = 1;
	}
      else if (!memcmp (delayed_token, no, sizeof (no) - 1))
	{
	  is_delayed = 0;
	}
      else
	{
	  ret =
	    clib_error_return (0,
			       "Unrecognized value for `%s' parameter: `%v'",
			       DELAYED_STR, delayed_token);
	  goto out;
	}
    }

  if (have_bfd_key_id && bfd_key_id > 255)
    {
      ret = clib_error_return (0, "%s value `%u' out of range <1,255>",
			       BFD_KEY_ID_STR, bfd_key_id);
      goto out;
    }

  vnet_api_error_t rv =
    bfd_udp_auth_activate (sw_if_index, &local_addr, &peer_addr, conf_key_id,
			   bfd_key_id, is_delayed);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_udp_auth_activate' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_auth_activate_command, static) = {
  .path = "bfd udp session auth activate",
  .short_help = "bfd udp session auth activate"
                " interface <interface>"
                " local-addr <local-address>"
                " peer-addr <peer-address>"
                " conf-key-id <config key ID>"
                " bfd-key-id <BFD key ID>"
                " [ delayed <yes|no> ]",
  .function = bfd_cli_udp_session_auth_activate,
};

static clib_error_t *
bfd_cli_udp_session_auth_deactivate (vlib_main_t *vm, unformat_input_t *input,
                                     CLIB_UNUSED (vlib_cli_command_t *lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_session_auth_deactivate_cli_param(F)  \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",            \
     unformat_vnet_sw_interface, &vnet_main)                      \
  F (ip46_address_t, local_addr, LOCAL_ADDR_STR, mandatory, "%U", \
     unformat_ip46_address)                                       \
  F (ip46_address_t, peer_addr, PEER_ADDR_STR, mandatory, "%U",   \
     unformat_ip46_address)                                       \
  F (u8 *, delayed_token, DELAYED_STR, optional, "%v")

  foreach_bfd_cli_udp_session_auth_deactivate_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_session_auth_deactivate_cli_param (UNFORMAT);

      if (!something_parsed)
        {
          ret = clib_error_return (0, "Unknown input `%U'",
                                   format_unformat_error, input);
          goto out;
        }
    }

  foreach_bfd_cli_udp_session_auth_deactivate_cli_param (CHECK_MANDATORY);

  u8 is_delayed = 0;
  if (have_delayed_token)
    {
      static const char yes[] = "yes";
      static const char no[] = "no";
      if (!memcmp (delayed_token, yes, sizeof (yes) - 1))
        {
          is_delayed = 1;
        }
      else if (!memcmp (delayed_token, no, sizeof (no) - 1))
        {
          is_delayed = 0;
        }
      else
        {
          ret = clib_error_return (
              0, "Unrecognized value for `%s' parameter: `%v'", DELAYED_STR,
              delayed_token);
          goto out;
        }
    }

  vnet_api_error_t rv = bfd_udp_auth_deactivate (sw_if_index, &local_addr,
                                                 &peer_addr, is_delayed);
  if (rv)
    {
      ret = clib_error_return (
          0, "`bfd_udp_auth_deactivate' API call failed, rv=%d:%U", (int)rv,
          format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_session_auth_deactivate_command, static) = {
  .path = "bfd udp session auth deactivate",
  .short_help = "bfd udp session auth deactivate"
                " interface <interface>"
                " local-addr <local-address>"
                " peer-addr <peer-address>"
                "[ delayed <yes|no> ]",
  .function = bfd_cli_udp_session_auth_deactivate,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_set_echo_source (vlib_main_t * vm, unformat_input_t * input,
			     CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  clib_error_t *ret = NULL;
  unformat_input_t _line_input, *line_input = &_line_input;
#define foreach_bfd_cli_udp_set_echo_source_cli_param(F) \
  F (u32, sw_if_index, INTERFACE_STR, mandatory, "%U",   \
     unformat_vnet_sw_interface, &vnet_main)

  foreach_bfd_cli_udp_set_echo_source_cli_param (DECLARE);

  /* Get a line of input. */
  if (!unformat_user (input, unformat_line_input, line_input))
    return 0;

  while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
    {
      int something_parsed = 0;
      foreach_bfd_cli_udp_set_echo_source_cli_param (UNFORMAT);

      if (!something_parsed)
	{
	  ret = clib_error_return (0, "Unknown input `%U'",
				   format_unformat_error, line_input);
	  goto out;
	}
    }

  foreach_bfd_cli_udp_set_echo_source_cli_param (CHECK_MANDATORY);

  vnet_api_error_t rv = bfd_udp_set_echo_source (sw_if_index);
  if (rv)
    {
      ret =
	clib_error_return (0,
			   "`bfd_udp_set_echo_source' API call failed, rv=%d:%U",
			   (int) rv, format_vnet_api_errno, rv);
      goto out;
    }

out:
  return ret;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_set_echo_source_cmd, static) = {
  .path = "bfd udp echo-source set",
  .short_help = "bfd udp echo-source set interface <interface>",
  .function = bfd_cli_udp_set_echo_source,
};
/* *INDENT-ON* */

static clib_error_t *
bfd_cli_udp_del_echo_source (vlib_main_t * vm, unformat_input_t * input,
			     CLIB_UNUSED (vlib_cli_command_t * lmd))
{
  vnet_api_error_t rv = bfd_udp_del_echo_source ();
  if (rv)
    {
      return clib_error_return (0,
				"`bfd_udp_del_echo_source' API call failed, rv=%d:%U",
				(int) rv, format_vnet_api_errno, rv);
    }

  return 0;
}

/* *INDENT-OFF* */
VLIB_CLI_COMMAND (bfd_cli_udp_del_echo_source_cmd, static) = {
  .path = "bfd udp echo-source del",
  .short_help = "bfd udp echo-source del",
  .function = bfd_cli_udp_del_echo_source,
};
/* *INDENT-ON* */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */