vpp_echo.c revision c4c4cf50
1/*
2 * Copyright (c) 2019 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <stdio.h>
17#include <signal.h>
18
19#include <vlibmemory/api.h>
20#include <svm/fifo_segment.h>
21
22#include <hs_apps/sapi/vpp_echo_common.h>
23
24echo_main_t echo_main;
25
26static void
27echo_session_prealloc (echo_main_t * em)
28{
29  /* We need to prealloc to avoid vec resize in threads */
30  echo_session_t *session;
31  int i;
32  for (i = 0; i < em->n_sessions; i++)
33    {
34      pool_get (em->sessions, session);
35      clib_memset (session, 0, sizeof (*session));
36      session->session_index = session - em->sessions;
37      session->listener_index = SESSION_INVALID_INDEX;
38      session->session_state = ECHO_SESSION_STATE_INITIAL;
39    }
40}
41
42static void
43echo_assert_test_suceeded (echo_main_t * em)
44{
45  if (em->rx_results_diff)
46    CHECK_DIFF (ECHO_FAIL_TEST_ASSERT_RX_TOTAL, em->stats.rx_expected,
47		em->stats.rx_total, "Invalid amount of data received");
48  else
49    CHECK_SAME (ECHO_FAIL_TEST_ASSERT_RX_TOTAL, em->stats.rx_expected,
50		em->stats.rx_total, "Invalid amount of data received");
51
52  if (em->tx_results_diff)
53    CHECK_DIFF (ECHO_FAIL_TEST_ASSERT_TX_TOTAL, em->stats.tx_expected,
54		em->stats.tx_total, "Invalid amount of data sent");
55  else
56    CHECK_SAME (ECHO_FAIL_TEST_ASSERT_TX_TOTAL, em->stats.tx_expected,
57		em->stats.tx_total, "Invalid amount of data sent");
58
59  clib_spinlock_lock (&em->sid_vpp_handles_lock);
60  CHECK_SAME (ECHO_FAIL_TEST_ASSERT_ALL_SESSIONS_CLOSED,
61	      0, hash_elts (em->session_index_by_vpp_handles),
62	      "Some sessions are still open");
63  clib_spinlock_unlock (&em->sid_vpp_handles_lock);
64}
65
66always_inline void
67echo_session_dequeue_notify (echo_session_t * s)
68{
69  int rv;
70  if (!svm_fifo_set_event (s->rx_fifo))
71    return;
72  if ((rv =
73       app_send_io_evt_to_vpp (s->vpp_evt_q, s->rx_fifo->master_session_index,
74			       SESSION_IO_EVT_RX, SVM_Q_WAIT)))
75    ECHO_FAIL (ECHO_FAIL_SEND_IO_EVT, "app_send_io_evt_to_vpp errored %d",
76	       rv);
77  svm_fifo_clear_deq_ntf (s->rx_fifo);
78}
79
80static void
81stop_signal (int signum)
82{
83  echo_main_t *em = &echo_main;
84  em->time_to_stop = 1;
85}
86
87int
88connect_to_vpp (char *name)
89{
90  echo_main_t *em = &echo_main;
91  api_main_t *am = vlibapi_get_main ();
92
93  if (em->use_sock_api)
94    {
95      if (vl_socket_client_connect ((char *) em->socket_name, name,
96				    0 /* default rx, tx buffer */ ))
97	{
98	  ECHO_FAIL (ECHO_FAIL_SOCKET_CONNECT, "socket connect failed");
99	  return -1;
100	}
101
102      if (vl_socket_client_init_shm (0, 1 /* want_pthread */ ))
103	{
104	  ECHO_FAIL (ECHO_FAIL_INIT_SHM_API, "init shm api failed");
105	  return -1;
106	}
107    }
108  else
109    {
110      if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
111	{
112	  ECHO_FAIL (ECHO_FAIL_SHMEM_CONNECT, "shmem connect failed");
113	  return -1;
114	}
115    }
116  em->vl_input_queue = am->shmem_hdr->vl_input_queue;
117  em->my_client_index = am->my_client_index;
118  return 0;
119}
120
121static void
122print_global_json_stats (echo_main_t * em)
123{
124  u8 *start_evt =
125    format (0, "%U", echo_format_timing_event, em->timing.start_event);
126  u8 *end_evt =
127    format (0, "%U", echo_format_timing_event, em->timing.end_event);
128  u8 start_evt_missing = !(em->timing.events_sent & em->timing.start_event);
129  u8 end_evt_missing = (em->rx_results_diff || em->tx_results_diff) ? 0 :
130    !(em->timing.events_sent & em->timing.end_event);
131  f64 deltat = start_evt_missing || end_evt_missing ? 0 :
132    em->timing.end_time - em->timing.start_time;
133
134  if (start_evt_missing)
135    ECHO_FAIL (ECHO_FAIL_MISSING_START_EVENT,
136	       "Expected event %v to happen, but it did not!", start_evt);
137
138  if (end_evt_missing)
139    ECHO_FAIL (ECHO_FAIL_MISSING_END_EVENT,
140	       "Expected event %v to happen, but it did not!", end_evt);
141
142  fformat (stdout, "vpp_echo JSON stats:\n{\n");
143  fformat (stdout, "  \"role\": \"%s\",\n",
144	   em->i_am_master ? "server" : "client");
145  fformat (stdout, "  \"time\": \"%.9f\",\n", deltat);
146  fformat (stdout, "  \"start_evt\": \"%v\",\n", start_evt);
147  fformat (stdout, "  \"start_evt_missing\": \"%s\",\n",
148	   start_evt_missing ? "True" : "False");
149  fformat (stdout, "  \"end_evt\": \"%v\",\n", end_evt);
150  fformat (stdout, "  \"end_evt_missing\": \"%s\",\n",
151	   end_evt_missing ? "True" : "False");
152  fformat (stdout, "  \"rx_data\": %lld,\n", em->stats.rx_total);
153  fformat (stdout, "  \"tx_data\": %lld,\n", em->stats.tx_total);
154  fformat (stdout, "  \"closing\": {\n");
155  fformat (stdout, "    \"reset\": { \"q\": %d, \"s\": %d },\n",
156	   em->stats.reset_count.q, em->stats.reset_count.s);
157  fformat (stdout, "    \"recv evt\": { \"q\": %d, \"s\": %d },\n",
158	   em->stats.close_count.q, em->stats.close_count.s);
159  fformat (stdout, "    \"send evt\": { \"q\": %d, \"s\": %d },\n",
160	   em->stats.active_count.q, em->stats.active_count.s);
161  fformat (stdout, "    \"clean\": { \"q\": %d, \"s\": %d }\n",
162	   em->stats.clean_count.q, em->stats.clean_count.s);
163  fformat (stdout, "    \"accepted\": { \"q\": %d, \"s\": %d }\n",
164	   em->stats.accepted_count.q, em->stats.accepted_count.s);
165  fformat (stdout, "    \"connected\": { \"q\": %d, \"s\": %d }\n",
166	   em->stats.connected_count.q, em->stats.connected_count.s);
167  fformat (stdout, "  }\n");
168  fformat (stdout, "  \"results\": {\n");
169  fformat (stdout, "    \"has_failed\": \"%d\"\n", em->has_failed);
170  fformat (stdout, "    \"fail_descr\": \"%v\"\n", em->fail_descr);
171  fformat (stdout, "  }\n");
172  fformat (stdout, "}\n");
173  fflush (stdout);
174  vec_free (start_evt);
175  vec_free (end_evt);
176}
177
178static void
179print_global_stats (echo_main_t * em)
180{
181  u8 *start_evt =
182    format (0, "%U", echo_format_timing_event, em->timing.start_event);
183  u8 *end_evt =
184    format (0, "%U", echo_format_timing_event, em->timing.end_event);
185  u8 start_evt_missing = !(em->timing.events_sent & em->timing.start_event);
186  u8 end_evt_missing = (em->rx_results_diff || em->tx_results_diff) ? 0 :
187    !(em->timing.events_sent & em->timing.end_event);
188  f64 deltat = start_evt_missing || end_evt_missing ? 0 :
189    em->timing.end_time - em->timing.start_time;
190
191  if (start_evt_missing)
192    ECHO_FAIL (ECHO_FAIL_MISSING_START_EVENT,
193	       "Expected event %v to happen, but it did not!", start_evt);
194
195  if (end_evt_missing)
196    ECHO_FAIL (ECHO_FAIL_MISSING_END_EVENT,
197	       "Expected event %v to happen, but it did not!", end_evt);
198
199  fformat (stdout, "Timing %v:%v\n", start_evt, end_evt);
200  if (start_evt_missing)
201    fformat (stdout, "Missing Start Timing Event (%v)!\n", start_evt);
202  if (end_evt_missing)
203    fformat (stdout, "Missing End Timing Event (%v)!\n", end_evt);
204  fformat (stdout, "-------- TX --------\n");
205  fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.6f seconds\n",
206	   em->stats.tx_total, em->stats.tx_total / (1ULL << 20),
207	   em->stats.tx_total / (1ULL << 30), deltat);
208  if (deltat)
209    fformat (stdout, "%.4f Gbit/second\n",
210	     (em->stats.tx_total * 8.0) / deltat / 1e9);
211  fformat (stdout, "-------- RX --------\n");
212  fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.6f seconds\n",
213	   em->stats.rx_total, em->stats.rx_total / (1ULL << 20),
214	   em->stats.rx_total / (1ULL << 30), deltat);
215  if (deltat)
216    fformat (stdout, "%.4f Gbit/second\n",
217	     (em->stats.rx_total * 8.0) / deltat / 1e9);
218  fformat (stdout, "--------------------\n");
219  fformat (stdout, "Received close on %d streams (and %d Quic conn)\n",
220	   em->stats.close_count.s, em->stats.close_count.q);
221  fformat (stdout, "Received reset on %d streams (and %d Quic conn)\n",
222	   em->stats.reset_count.s, em->stats.reset_count.q);
223  fformat (stdout, "Sent close on     %d streams (and %d Quic conn)\n",
224	   em->stats.active_count.s, em->stats.active_count.q);
225  fformat (stdout, "Discarded         %d streams (and %d Quic conn)\n",
226	   em->stats.clean_count.s, em->stats.clean_count.q);
227  fformat (stdout, "--------------------\n");
228  fformat (stdout, "Got accept on     %d streams (and %d Quic conn)\n",
229	   em->stats.accepted_count.s, em->stats.accepted_count.q);
230  fformat (stdout, "Got connected on  %d streams (and %d Quic conn)\n",
231	   em->stats.connected_count.s, em->stats.connected_count.q);
232  if (em->has_failed)
233    fformat (stdout, "\nFailure Return Status: %d\n%v", em->has_failed,
234	     em->fail_descr);
235  vec_free (start_evt);
236  vec_free (end_evt);
237}
238
239void
240echo_update_count_on_session_close (echo_main_t * em, echo_session_t * s)
241{
242
243  ECHO_LOG (2, "[%lu/%lu] -> %U -> [%lu/%lu]",
244	    s->bytes_received, s->bytes_received + s->bytes_to_receive,
245	    echo_format_session, s, s->bytes_sent,
246	    s->bytes_sent + s->bytes_to_send);
247
248  if (PREDICT_FALSE
249      ((em->stats.rx_total == em->stats.rx_expected)
250       && (em->stats.tx_total == em->stats.tx_expected)))
251    echo_notify_event (em, ECHO_EVT_LAST_BYTE);
252}
253
254static void
255echo_free_sessions (echo_main_t * em)
256{
257  /* Free marked sessions */
258  echo_session_t *s;
259  u32 *session_indexes = 0, *session_index;
260
261  /* *INDENT-OFF* */
262  pool_foreach (s, em->sessions,
263  ({
264    if (s->session_state == ECHO_SESSION_STATE_CLOSED)
265      vec_add1 (session_indexes, s->session_index);}
266  ));
267  /* *INDENT-ON* */
268  vec_foreach (session_index, session_indexes)
269  {
270    /* Free session */
271    s = pool_elt_at_index (em->sessions, *session_index);
272    echo_session_handle_add_del (em, s->vpp_session_handle,
273				 SESSION_INVALID_INDEX);
274    clib_memset (s, 0xfe, sizeof (*s));
275    pool_put (em->sessions, s);
276  }
277}
278
279static void
280test_recv_bytes (echo_main_t * em, echo_session_t * s, u8 * rx_buf,
281		 u32 n_read)
282{
283  u32 i;
284  u8 expected;
285  for (i = 0; i < n_read; i++)
286    {
287      expected = (s->bytes_received + i) & 0xff;
288      if (rx_buf[i] == expected || em->max_test_msg > 0)
289	continue;
290      ECHO_LOG (1, "Session 0x%lx byte %lld was 0x%x expected 0x%x",
291		s->vpp_session_handle, s->bytes_received + i, rx_buf[i],
292		expected);
293      em->max_test_msg--;
294      if (em->max_test_msg == 0)
295	ECHO_LOG (1, "Too many errors, hiding next ones");
296      if (em->test_return_packets == RETURN_PACKETS_ASSERT)
297	ECHO_FAIL (ECHO_FAIL_TEST_BYTES_ERR, "test-bytes errored");
298    }
299}
300
301static int
302recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf)
303{
304  int n_read;
305  n_read = app_recv ((app_session_t *) s, rx_buf, vec_len (rx_buf));
306  if (n_read <= 0)
307    return 0;
308  if (svm_fifo_needs_deq_ntf (s->rx_fifo, n_read))
309    echo_session_dequeue_notify (s);
310
311  if (em->test_return_packets)
312    test_recv_bytes (em, s, rx_buf, n_read);
313
314  s->bytes_received += n_read;
315  s->bytes_to_receive -= n_read;
316  clib_atomic_fetch_add (&em->stats.rx_total, n_read);
317  return n_read;
318}
319
320static int
321send_data_chunk (echo_session_t * s, u8 * tx_buf, int offset, int len)
322{
323  int n_sent;
324  int bytes_this_chunk = clib_min (s->bytes_to_send, len - offset);
325  echo_main_t *em = &echo_main;
326
327  if (!bytes_this_chunk)
328    return 0;
329  n_sent = app_send ((app_session_t *) s, tx_buf + offset,
330		     bytes_this_chunk, SVM_Q_WAIT);
331  if (n_sent < 0)
332    return 0;
333  s->bytes_to_send -= n_sent;
334  s->bytes_sent += n_sent;
335  clib_atomic_fetch_add (&em->stats.tx_total, n_sent);
336  return n_sent;
337}
338
339static int
340mirror_data_chunk (echo_main_t * em, echo_session_t * s, u8 * tx_buf, u64 len)
341{
342  u64 n_sent = 0;
343  while (n_sent < len && !em->time_to_stop)
344    n_sent += send_data_chunk (s, tx_buf, n_sent, len);
345  return n_sent;
346}
347
348static inline void
349echo_check_closed_listener (echo_main_t * em, echo_session_t * s)
350{
351  echo_session_t *ls;
352  /* if parent has died, terminate gracefully */
353  if (s->listener_index == SESSION_INVALID_INDEX)
354    {
355      ECHO_LOG (3, "%U: listener_index == SESSION_INVALID_INDEX",
356		echo_format_session, s);
357      return;
358    }
359  ls = pool_elt_at_index (em->sessions, s->listener_index);
360  if (ls->session_state < ECHO_SESSION_STATE_CLOSING)
361    {
362      ECHO_LOG (3, "%U: ls->session_state (%d) < "
363		"ECHO_SESSION_STATE_CLOSING (%d)",
364		echo_format_session, ls, ls->session_state,
365		ECHO_SESSION_STATE_CLOSING);
366      return;
367    }
368
369  ECHO_LOG (3, "%U died, close child %U", echo_format_session, ls,
370	    echo_format_session, s);
371  echo_update_count_on_session_close (em, s);
372  em->proto_cb_vft->cleanup_cb (s, 1 /* parent_died */ );
373}
374
375/*
376 * Rx/Tx polling thread per connection
377 */
378static void
379echo_handle_data (echo_main_t * em, echo_session_t * s, u8 * rx_buf)
380{
381  int n_read, n_sent = 0;
382
383  n_read = recv_data_chunk (em, s, rx_buf);
384  if ((em->data_source == ECHO_TEST_DATA_SOURCE) && s->bytes_to_send)
385    n_sent = send_data_chunk (s, em->connect_test_data,
386			      s->bytes_sent % em->tx_buf_size,
387			      em->tx_buf_size);
388  else if (em->data_source == ECHO_RX_DATA_SOURCE)
389    n_sent = mirror_data_chunk (em, s, rx_buf, n_read);
390  if (!s->bytes_to_send && !s->bytes_to_receive)
391    {
392      /* Session is done, need to close */
393      if (s->session_state == ECHO_SESSION_STATE_AWAIT_DATA)
394	s->session_state = ECHO_SESSION_STATE_CLOSING;
395      else
396	{
397	  s->session_state = ECHO_SESSION_STATE_AWAIT_CLOSING;
398	  if (em->send_stream_disconnects == ECHO_CLOSE_F_ACTIVE)
399	    {
400	      echo_send_rpc (em, echo_send_disconnect_session,
401			     (echo_rpc_args_t *) & s->vpp_session_handle);
402	      clib_atomic_fetch_add (&em->stats.active_count.s, 1);
403	    }
404	  else if (em->send_stream_disconnects == ECHO_CLOSE_F_NONE)
405	    {
406	      s->session_state = ECHO_SESSION_STATE_CLOSING;
407	      clib_atomic_fetch_add (&em->stats.clean_count.s, 1);
408	    }
409	}
410      ECHO_LOG (3, "%U: %U", echo_format_session, s,
411		echo_format_session_state, s->session_state);
412      return;
413    }
414
415  /* Check for idle clients */
416  if (em->log_lvl > 1)
417    {
418      if (n_sent || n_read)
419	s->idle_cycles = 0;
420      else if (s->idle_cycles++ == LOG_EVERY_N_IDLE_CYCLES)
421	{
422	  s->idle_cycles = 0;
423	  ECHO_LOG (2, "Idle client TX:%dB RX:%dB", s->bytes_to_send,
424		    s->bytes_to_receive);
425	  ECHO_LOG (2, "Idle FIFOs TX:%dB RX:%dB",
426		    svm_fifo_max_dequeue (s->tx_fifo),
427		    svm_fifo_max_dequeue (s->rx_fifo));
428	  ECHO_LOG (2, "Session 0x%lx state %U", s->vpp_session_handle,
429		    echo_format_session_state, s->session_state);
430	}
431    }
432}
433
434static void *
435echo_data_thread_fn (void *arg)
436{
437  clib_mem_set_thread_index ();	/* First thing to do in client thread */
438  echo_main_t *em = &echo_main;
439  u32 N = em->n_clients;
440  u32 n = (N + em->n_rx_threads - 1) / em->n_rx_threads;
441  u32 idx = (u64) arg;
442  if (n * idx >= N)
443    {
444      ECHO_LOG (2, "Thread %u exiting, no sessions to care for", idx);
445      pthread_exit (0);
446    }
447  u32 thread_n_sessions = clib_min (n, N - n * idx);
448
449  u32 i = 0;
450  u32 n_closed_sessions = 0;
451  u32 session_index;
452  u8 *rx_buf = 0;
453  echo_session_t *s;
454  vec_validate (rx_buf, em->rx_buf_size);
455
456  for (i = 0; !em->time_to_stop; i = (i + 1) % thread_n_sessions)
457    {
458      n_closed_sessions = i == 0 ? 0 : n_closed_sessions;
459      session_index = em->data_thread_args[n * idx + i];
460      if (session_index == SESSION_INVALID_INDEX)
461	continue;
462      s = pool_elt_at_index (em->sessions, session_index);
463      switch (s->session_state)
464	{
465	case ECHO_SESSION_STATE_READY:
466	case ECHO_SESSION_STATE_AWAIT_DATA:
467	  echo_handle_data (em, s, rx_buf);
468	  echo_check_closed_listener (em, s);
469	  break;
470	case ECHO_SESSION_STATE_AWAIT_CLOSING:
471	  ECHO_LOG (3, "%U: %U", echo_format_session, s,
472		    echo_format_session_state, s->session_state);
473	  echo_check_closed_listener (em, s);
474	  break;
475	case ECHO_SESSION_STATE_CLOSING:
476	  ECHO_LOG (3, "%U: %U", echo_format_session, s,
477		    echo_format_session_state, s->session_state);
478	  echo_update_count_on_session_close (em, s);
479	  em->proto_cb_vft->cleanup_cb (s, 0 /* parent_died */ );
480	  break;
481	case ECHO_SESSION_STATE_CLOSED:
482	  ECHO_LOG (3, "%U: %U", echo_format_session, s,
483		    echo_format_session_state, s->session_state);
484	  n_closed_sessions++;
485	  break;
486	}
487      if (n_closed_sessions == thread_n_sessions)
488	break;
489    }
490  ECHO_LOG (2, "Mission accomplished!");
491  pthread_exit (0);
492}
493
494static void
495session_unlisten_handler (session_unlisten_reply_msg_t * mp)
496{
497  echo_session_t *ls;
498  echo_main_t *em = &echo_main;
499
500  ls = echo_get_session_from_handle (em, mp->handle);
501  em->proto_cb_vft->cleanup_cb (ls, 0 /* parent_died */ );
502  ls->session_state = ECHO_SESSION_STATE_CLOSED;
503  if (--em->listen_session_cnt == 0)
504    em->state = STATE_DISCONNECTED;
505}
506
507static void
508session_bound_handler (session_bound_msg_t * mp)
509{
510  echo_main_t *em = &echo_main;
511  echo_session_t *listen_session;
512  if (mp->retval)
513    {
514      ECHO_FAIL (ECHO_FAIL_BIND, "bind failed: %U", format_api_error,
515		 clib_net_to_host_u32 (mp->retval));
516      return;
517    }
518  ECHO_LOG (1, "listening on %U:%u", format_ip46_address, mp->lcl_ip,
519	    mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
520	    clib_net_to_host_u16 (mp->lcl_port));
521
522  /* Allocate local session and set it up */
523  listen_session = echo_session_new (em);
524  listen_session->session_type = ECHO_SESSION_TYPE_LISTEN;
525  listen_session->vpp_session_handle = mp->handle;
526  echo_session_handle_add_del (em, mp->handle, listen_session->session_index);
527  vec_add1 (em->listen_session_indexes, listen_session->session_index);
528  if (++em->listen_session_cnt == em->n_uris)
529    em->state = STATE_LISTEN;
530  if (em->proto_cb_vft->bound_uri_cb)
531    em->proto_cb_vft->bound_uri_cb (mp, listen_session);
532}
533
534static int
535echo_segment_is_not_mapped (u64 segment_handle)
536{
537  echo_main_t *em = &echo_main;
538  uword *segment_present;
539  ECHO_LOG (3, "Check if segment mapped 0x%lx...", segment_handle);
540  clib_spinlock_lock (&em->segment_handles_lock);
541  segment_present = hash_get (em->shared_segment_handles, segment_handle);
542  clib_spinlock_unlock (&em->segment_handles_lock);
543  if (segment_present != 0)
544    return 0;
545  ECHO_LOG (2, "Segment not mapped (0x%lx)", segment_handle);
546  return -1;
547}
548
549static void
550session_accepted_handler (session_accepted_msg_t * mp)
551{
552  app_session_evt_t _app_evt, *app_evt = &_app_evt;
553  session_accepted_reply_msg_t *rmp;
554  svm_fifo_t *rx_fifo, *tx_fifo;
555  echo_main_t *em = &echo_main;
556  echo_session_t *session, *ls;
557
558  if (!(ls = echo_get_session_from_handle (em, mp->listener_handle)))
559    {
560      ECHO_FAIL (ECHO_FAIL_SESSION_ACCEPTED_BAD_LISTENER,
561		 "Unknown listener handle 0x%lx", mp->listener_handle);
562      return;
563    }
564  if (echo_segment_is_not_mapped (mp->segment_handle))
565    {
566      ECHO_FAIL (ECHO_FAIL_ACCEPTED_WAIT_FOR_SEG_ALLOC,
567		 "accepted wait_for_segment_allocation errored");
568      return;
569    }
570
571  /* Allocate local session and set it up */
572  session = echo_session_new (em);
573  session->vpp_session_handle = mp->handle;
574
575  rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
576  rx_fifo->client_session_index = session->session_index;
577  tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
578  tx_fifo->client_session_index = session->session_index;
579
580  session->rx_fifo = rx_fifo;
581  session->tx_fifo = tx_fifo;
582
583  /* session->transport needed by app_send_dgram */
584  clib_memcpy_fast (&session->transport.rmt_ip, &mp->rmt.ip,
585		    sizeof (ip46_address_t));
586  session->transport.is_ip4 = mp->rmt.is_ip4;
587  session->transport.rmt_port = mp->rmt.port;
588  clib_memcpy_fast (&session->transport.lcl_ip, &em->uri_elts.ip,
589		    sizeof (ip46_address_t));
590  session->transport.lcl_port = em->uri_elts.port;
591
592  session->vpp_session_handle = mp->handle;
593  session->start = clib_time_now (&em->clib_time);
594  session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
595					 svm_msg_q_t *);
596  session->listener_index = ls->session_index;
597
598  /* Add it to lookup table */
599  ECHO_LOG (2, "Accepted session 0x%lx S[%u] -> 0x%lx S[%u]",
600	    mp->handle, session->session_index,
601	    mp->listener_handle, session->listener_index);
602  echo_session_handle_add_del (em, mp->handle, session->session_index);
603
604  app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
605			     SESSION_CTRL_EVT_ACCEPTED_REPLY);
606  rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
607  rmp->handle = mp->handle;
608  rmp->context = mp->context;
609  app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
610  em->proto_cb_vft->accepted_cb (mp, session);
611}
612
613static void
614session_connected_handler (session_connected_msg_t * mp)
615{
616  echo_main_t *em = &echo_main;
617  echo_session_t *session;
618  u32 listener_index = htonl (mp->context);
619  svm_fifo_t *rx_fifo, *tx_fifo;
620
621  clib_atomic_add_fetch (&em->max_sim_connects, 1);
622
623  if (mp->retval)
624    {
625      if (em->proto_cb_vft->connected_cb)
626	em->
627	  proto_cb_vft->connected_cb ((session_connected_bundled_msg_t *) mp,
628				      listener_index, 1 /* is_failed */ );
629      return;
630    }
631
632  session = echo_session_new (em);
633  if (echo_segment_is_not_mapped (mp->segment_handle))
634    {
635      ECHO_FAIL (ECHO_FAIL_CONNECTED_WAIT_FOR_SEG_ALLOC,
636		 "connected wait_for_segment_allocation errored");
637      return;
638    }
639
640  rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
641  rx_fifo->client_session_index = session->session_index;
642  tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
643  tx_fifo->client_session_index = session->session_index;
644
645  session->rx_fifo = rx_fifo;
646  session->tx_fifo = tx_fifo;
647  session->vpp_session_handle = mp->handle;
648  session->start = clib_time_now (&em->clib_time);
649  session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
650					 svm_msg_q_t *);
651  session->listener_index = listener_index;
652  /* session->transport needed by app_send_dgram */
653  clib_memcpy_fast (&session->transport.lcl_ip, &mp->lcl.ip,
654		    sizeof (ip46_address_t));
655  session->transport.is_ip4 = mp->lcl.is_ip4;
656  session->transport.lcl_port = mp->lcl.port;
657  clib_memcpy_fast (&session->transport.rmt_ip, &em->uri_elts.ip,
658		    sizeof (ip46_address_t));
659  session->transport.rmt_port = em->uri_elts.port;
660
661  echo_session_handle_add_del (em, mp->handle, session->session_index);
662  em->proto_cb_vft->connected_cb ((session_connected_bundled_msg_t *) mp,
663				  session->session_index, 0 /* is_failed */ );
664}
665
666/*
667 *
668 *  End of ECHO callback definitions
669 *
670 */
671
672static void
673session_disconnected_handler (session_disconnected_msg_t * mp)
674{
675  app_session_evt_t _app_evt, *app_evt = &_app_evt;
676  session_disconnected_reply_msg_t *rmp;
677  echo_main_t *em = &echo_main;
678  echo_session_t *s;
679  if (!(s = echo_get_session_from_handle (em, mp->handle)))
680    {
681      ECHO_LOG (1, "Invalid vpp_session_handle: 0x%lx", mp->handle);
682      return;
683    }
684  if (s->session_state == ECHO_SESSION_STATE_CLOSED)
685    {
686      ECHO_LOG (2, "%U: already in ECHO_SESSION_STATE_CLOSED",
687		echo_format_session, s);
688    }
689  else
690    {
691      ECHO_LOG (2, "%U: passive close", echo_format_session, s);
692      em->proto_cb_vft->disconnected_cb (mp, s);
693    }
694  app_alloc_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt,
695			     SESSION_CTRL_EVT_DISCONNECTED_REPLY);
696  rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
697  rmp->retval = 0;
698  rmp->handle = mp->handle;
699  rmp->context = mp->context;
700  app_send_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt);
701}
702
703static void
704session_reset_handler (session_reset_msg_t * mp)
705{
706  app_session_evt_t _app_evt, *app_evt = &_app_evt;
707  echo_main_t *em = &echo_main;
708  session_reset_reply_msg_t *rmp;
709  echo_session_t *s = 0;
710  if (!(s = echo_get_session_from_handle (em, mp->handle)))
711    {
712      ECHO_LOG (1, "Invalid vpp_session_handle: 0x%lx", mp->handle);
713      return;
714    }
715  ECHO_LOG (2, "%U: session reset", echo_format_session, s);
716  em->proto_cb_vft->reset_cb (mp, s);
717
718  app_alloc_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt,
719			     SESSION_CTRL_EVT_RESET_REPLY);
720  rmp = (session_reset_reply_msg_t *) app_evt->evt->data;
721  rmp->retval = 0;
722  rmp->handle = mp->handle;
723  app_send_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt);
724}
725
726static void
727add_segment_handler (session_app_add_segment_msg_t * mp)
728{
729  fifo_segment_main_t *sm = &echo_main.segment_main;
730  fifo_segment_create_args_t _a, *a = &_a;
731  echo_main_t *em = &echo_main;
732  int *fds = 0, i;
733  char *seg_name = (char *) mp->segment_name;
734  u64 segment_handle = mp->segment_handle;
735
736  if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT)
737    {
738      vec_validate (fds, 1);
739      if (vl_socket_client_recv_fd_msg (fds, 1, 5))
740	{
741	  ECHO_FAIL (ECHO_FAIL_VL_API_RECV_FD_MSG,
742		     "vl_socket_client_recv_fd_msg failed");
743	  goto failed;
744	}
745
746      if (echo_ssvm_segment_attach (seg_name, SSVM_SEGMENT_MEMFD, fds[0]))
747	{
748	  ECHO_FAIL (ECHO_FAIL_VL_API_SVM_FIFO_SEG_ATTACH,
749		     "svm_fifo_segment_attach ('%s') "
750		     "failed on SSVM_SEGMENT_MEMFD", seg_name);
751	  goto failed;
752	}
753      vec_free (fds);
754    }
755  else
756    {
757      clib_memset (a, 0, sizeof (*a));
758      a->segment_name = seg_name;
759      a->segment_size = mp->segment_size;
760      /* Attach to the segment vpp created */
761      if (fifo_segment_attach (sm, a))
762	{
763	  ECHO_FAIL (ECHO_FAIL_VL_API_FIFO_SEG_ATTACH,
764		     "fifo_segment_attach ('%s') failed", seg_name);
765	  goto failed;
766	}
767    }
768  echo_segment_handle_add_del (em, segment_handle, 1 /* add */ );
769  ECHO_LOG (2, "Mapped segment 0x%lx", segment_handle);
770  return;
771
772failed:
773  for (i = 0; i < vec_len (fds); i++)
774    close (fds[i]);
775  vec_free (fds);
776}
777
778static void
779del_segment_handler (session_app_del_segment_msg_t * mp)
780{
781  echo_main_t *em = &echo_main;
782  echo_segment_handle_add_del (em, mp->segment_handle, 0 /* add */ );
783  ECHO_LOG (2, "Unmaped segment 0x%lx", mp->segment_handle);
784}
785
786static void
787handle_mq_event (session_event_t * e)
788{
789  switch (e->event_type)
790    {
791    case SESSION_CTRL_EVT_BOUND:
792      return session_bound_handler ((session_bound_msg_t *) e->data);
793    case SESSION_CTRL_EVT_ACCEPTED:
794      return session_accepted_handler ((session_accepted_msg_t *) e->data);
795    case SESSION_CTRL_EVT_CONNECTED:
796      return session_connected_handler ((session_connected_msg_t *) e->data);
797    case SESSION_CTRL_EVT_DISCONNECTED:
798      return session_disconnected_handler ((session_disconnected_msg_t *)
799					   e->data);
800    case SESSION_CTRL_EVT_RESET:
801      return session_reset_handler ((session_reset_msg_t *) e->data);
802    case SESSION_CTRL_EVT_UNLISTEN_REPLY:
803      return session_unlisten_handler ((session_unlisten_reply_msg_t *)
804				       e->data);
805    case SESSION_CTRL_EVT_APP_ADD_SEGMENT:
806      add_segment_handler ((session_app_add_segment_msg_t *) e->data);
807      break;
808    case SESSION_CTRL_EVT_APP_DEL_SEGMENT:
809      del_segment_handler ((session_app_del_segment_msg_t *) e->data);
810      break;
811    case SESSION_IO_EVT_RX:
812      break;
813    default:
814      ECHO_LOG (1, "unhandled event %u", e->event_type);
815    }
816}
817
818static void
819echo_process_rpcs (echo_main_t * em)
820{
821  echo_rpc_msg_t *rpc;
822  svm_msg_q_msg_t msg;
823  svm_msg_q_t *mq = em->rpc_msq_queue;
824
825  while (em->state < STATE_DATA_DONE && !em->time_to_stop)
826    {
827      svm_msg_q_lock (mq);
828      if (svm_msg_q_is_empty (mq) && svm_msg_q_timedwait (mq, 1))
829	{
830	  svm_msg_q_unlock (mq);
831	  continue;
832	}
833      svm_msg_q_sub_w_lock (mq, &msg);
834      rpc = svm_msg_q_msg_data (mq, &msg);
835      svm_msg_q_unlock (mq);
836      ((echo_rpc_t) rpc->fp) (em, &rpc->args);
837      svm_msg_q_free_msg (mq, &msg);
838    }
839}
840
841static inline void
842echo_print_periodic_stats (echo_main_t * em)
843{
844  f64 delta, now = clib_time_now (&em->clib_time);
845  echo_stats_t _st, *st = &_st;
846  echo_stats_t *lst = &em->last_stat_sampling;
847  delta = now - em->last_stat_sampling_ts;
848  if (delta < em->periodic_stats_delta)
849    return;
850
851  clib_memcpy_fast (st, &em->stats, sizeof (*st));
852  if (st->rx_total - lst->rx_total)
853    clib_warning ("RX: %U", echo_format_bytes_per_sec,
854		  (st->rx_total - lst->rx_total) / delta);
855  if (st->tx_total - lst->tx_total)
856    clib_warning ("TX: %U", echo_format_bytes_per_sec,
857		  (st->tx_total - lst->tx_total) / delta);
858  if (st->connected_count.q - lst->connected_count.q)
859    clib_warning ("conn: %d/s",
860		  st->connected_count.q - lst->connected_count.q);
861  if (st->accepted_count.q - lst->accepted_count.q)
862    clib_warning ("accept: %d/s",
863		  st->accepted_count.q - lst->accepted_count.q);
864
865  clib_memcpy_fast (lst, st, sizeof (*st));
866  em->last_stat_sampling_ts = now;
867}
868
869static void *
870echo_mq_thread_fn (void *arg)
871{
872  clib_mem_set_thread_index ();	/* First thing to do in client thread */
873  svm_msg_q_msg_t *msg_vec = 0;
874  echo_main_t *em = &echo_main;
875  session_event_t *e;
876  svm_msg_q_msg_t *msg;
877  svm_msg_q_t *mq;
878  int i;
879
880  vec_validate (msg_vec, em->evt_q_size);
881  vec_reset_length (msg_vec);
882  wait_for_state_change (em, STATE_ATTACHED, 0);
883  mq = em->app_mq;
884  if (em->state < STATE_ATTACHED || !mq)
885    {
886      ECHO_FAIL (ECHO_FAIL_APP_ATTACH, "Application failed to attach");
887      pthread_exit (0);
888    }
889
890  while (em->state < STATE_DETACHED && !em->time_to_stop)
891    {
892      if (em->periodic_stats_delta)
893	echo_print_periodic_stats (em);
894
895      svm_msg_q_lock (mq);
896      if (svm_msg_q_is_empty (mq) && svm_msg_q_timedwait (mq, 1))
897	{
898	  svm_msg_q_unlock (mq);
899	  continue;
900	}
901      for (i = 0; i < svm_msg_q_size (mq); i++)
902	{
903	  vec_add2 (msg_vec, msg, 1);
904	  svm_msg_q_sub_w_lock (mq, msg);
905	}
906      svm_msg_q_unlock (mq);
907
908      for (i = 0; i < vec_len (msg_vec); i++)
909	{
910	  msg = vec_elt_at_index (msg_vec, i);
911	  e = svm_msg_q_msg_data (mq, msg);
912	  handle_mq_event (e);
913	  svm_msg_q_free_msg (mq, msg);	/* No lock, single thread dequeuing */
914	}
915      vec_reset_length (msg_vec);
916    }
917  vec_free (msg_vec);
918  pthread_exit (0);
919}
920
921static inline void
922echo_cycle_ip (echo_main_t * em, ip46_address_t * ip, ip46_address_t * src_ip,
923	       u32 i)
924{
925  u8 *ipu8;
926  u8 l;
927  if (i % em->n_uris == 0)
928    {
929      clib_memcpy_fast (ip, src_ip, sizeof (*ip));
930      return;
931    }
932  l = em->uri_elts.is_ip4 ? 3 : 15;
933  ipu8 = em->uri_elts.is_ip4 ? ip->ip4.as_u8 : ip->ip6.as_u8;
934  while (ipu8[l] == 0xf)
935    ipu8[l--] = 0;
936  if (l)
937    ipu8[l]++;
938}
939
940static void
941clients_run (echo_main_t * em)
942{
943  echo_connect_args_t _a, *a = &_a;
944  u64 i;
945
946  a->context = SESSION_INVALID_INDEX;
947  a->parent_session_handle = SESSION_INVALID_HANDLE;
948  clib_memset (&a->lcl_ip, 0, sizeof (a->lcl_ip));
949
950  echo_notify_event (em, ECHO_EVT_FIRST_QCONNECT);
951  for (i = 0; i < em->n_connects; i++)
952    {
953      echo_cycle_ip (em, &a->ip, &em->uri_elts.ip, i);
954      if (em->lcl_ip_set)
955	echo_cycle_ip (em, &a->lcl_ip, &em->lcl_ip, i);
956      echo_send_connect (em, a);
957    }
958  wait_for_state_change (em, STATE_READY, 0);
959  ECHO_LOG (2, "App is ready");
960  echo_process_rpcs (em);
961}
962
963static void
964server_run (echo_main_t * em)
965{
966  echo_session_t *ls;
967  ip46_address_t _ip, *ip = &_ip;
968  u32 *listen_session_index;
969  u32 i;
970
971  for (i = 0; i < em->n_uris; i++)
972    {
973      echo_cycle_ip (em, ip, &em->uri_elts.ip, i);
974      echo_send_listen (em, ip);
975    }
976  wait_for_state_change (em, STATE_READY, 0);
977  ECHO_LOG (2, "App is ready");
978  echo_process_rpcs (em);
979  /* Cleanup */
980  vec_foreach (listen_session_index, em->listen_session_indexes)
981  {
982    ECHO_LOG (2, "Unbind listen port %d", em->listen_session_cnt);
983    ls = pool_elt_at_index (em->sessions, *listen_session_index);
984    echo_send_unbind (em, ls);
985  }
986  if (wait_for_state_change (em, STATE_DISCONNECTED, TIMEOUT))
987    {
988      ECHO_FAIL (ECHO_FAIL_SERVER_DISCONNECT_TIMEOUT,
989		 "Timeout waiting for state disconnected");
990      return;
991    }
992}
993
994static void
995print_usage_and_exit (void)
996{
997  echo_main_t *em = &echo_main;
998  int i;
999  fprintf (stderr,
1000	   "Usage: vpp_echo [socket-name SOCKET] [client|server] [uri URI] [OPTIONS]\n"
1001	   "Generates traffic and assert correct teardown of the hoststack\n"
1002	   "\n"
1003	   "  socket-name PATH    Specify the binary socket path to connect to VPP\n"
1004	   "  use-svm-api         Use SVM API to connect to VPP\n"
1005	   "  test-bytes[:assert] Check data correctness when receiving (assert fails on first error)\n"
1006	   "  fifo-size N[K|M|G]  Use N[K|M|G] fifos\n"
1007	   "  mq-size N           Use mq with N slots for [vpp_echo->vpp] communication\n"
1008	   "  max-sim-connects N  Do not allow more than N mq events inflight\n"
1009	   "  rx-buf N[K|M|G]     Use N[Kb|Mb|GB] RX buffer\n"
1010	   "  tx-buf N[K|M|G]     Use N[Kb|Mb|GB] TX test buffer\n"
1011	   "  appns NAMESPACE     Use the namespace NAMESPACE\n"
1012	   "  all-scope           all-scope option\n"
1013	   "  local-scope         local-scope option\n"
1014	   "  global-scope        global-scope option\n"
1015	   "  secret SECRET       set namespace secret\n"
1016	   "  chroot prefix PATH  Use PATH as memory root path\n"
1017	   "  sclose=[Y|N|W]      When stream is done, send[Y]|nop[N]|wait[W] for close\n"
1018	   "  nuris N             Cycle through N consecutive (src&dst) ips when creating connections\n"
1019	   "  lcl IP              Set the local ip to use as a client (use with nuris to set first src ip)\n"
1020	   "\n"
1021	   "  time START:END      Time between evts START & END, events being :\n"
1022	   "                       start - Start of the app\n"
1023	   "                       qconnect    - first Connection connect sent\n"
1024	   "                       qconnected  - last Connection connected\n"
1025	   "                       sconnect    - first Stream connect sent\n"
1026	   "                       sconnected  - last Stream got connected\n"
1027	   "                       lastbyte    - Last expected byte received\n"
1028	   "                       exit        - Exiting of the app\n"
1029	   "  rx-results-diff     Rx results different to pass test\n"
1030	   "  tx-results-diff     Tx results different to pass test\n"
1031	   "  json                Output global stats in json\n"
1032	   "  stats N             Output stats evry N secs\n"
1033	   "  log=N               Set the log level to [0: no output, 1:errors, 2:log]\n"
1034	   "  crypto [engine]     Set the crypto engine [openssl, vpp, picotls, mbedtls]\n"
1035	   "\n"
1036	   "  nclients N          Open N clients sending data\n"
1037	   "  nthreads N          Use N busy loop threads for data [in addition to main & msg queue]\n"
1038	   "  TX=1337[K|M|G]|RX   Send 1337 [K|M|G]bytes, use TX=RX to reflect the data\n"
1039	   "  RX=1337[K|M|G]      Expect 1337 [K|M|G]bytes\n" "\n");
1040  for (i = 0; i < TRANSPORT_N_PROTO; i++)
1041    {
1042      echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
1043      if (vft && vft->print_usage_cb)
1044	vft->print_usage_cb ();
1045    }
1046  fprintf (stderr, "\nDefault configuration is :\n"
1047	   " server nclients 1 [quic-streams 1] RX=64Kb TX=RX\n"
1048	   " client nclients 1 [quic-streams 1] RX=64Kb TX=64Kb\n");
1049  exit (ECHO_FAIL_USAGE);
1050}
1051
1052static int
1053echo_process_each_proto_opts (unformat_input_t * a)
1054{
1055  echo_main_t *em = &echo_main;
1056  int i, rv;
1057  for (i = 0; i < TRANSPORT_N_PROTO; i++)
1058    {
1059      echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
1060      if (vft && vft->process_opts_cb)
1061	if ((rv = vft->process_opts_cb (a)))
1062	  return rv;
1063    }
1064  return 0;
1065}
1066
1067static void
1068echo_set_each_proto_defaults_before_opts (echo_main_t * em)
1069{
1070  int i;
1071  for (i = 0; i < TRANSPORT_N_PROTO; i++)
1072    {
1073      echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
1074      if (vft && vft->set_defaults_before_opts_cb)
1075	vft->set_defaults_before_opts_cb ();
1076    }
1077}
1078
1079void
1080echo_process_opts (int argc, char **argv)
1081{
1082  echo_main_t *em = &echo_main;
1083  unformat_input_t _argv, *a = &_argv;
1084  u8 *chroot_prefix;
1085  u8 *uri = 0;
1086  u8 default_f_active;
1087  uword tmp;
1088
1089  unformat_init_command_line (a, argv);
1090  while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1091    {
1092      if (echo_process_each_proto_opts (a))
1093	;
1094      else if (unformat (a, "chroot prefix %s", &chroot_prefix))
1095	vl_set_memory_root_path ((char *) chroot_prefix);
1096      else if (unformat (a, "uri %s", &uri))
1097	em->uri = format (0, "%s%c", uri, 0);
1098      else if (unformat (a, "lcl %U", unformat_ip46_address, &em->lcl_ip))
1099	em->lcl_ip_set = 1;
1100      else if (unformat (a, "nuris %u", &em->n_uris))
1101	em->n_sessions = em->n_clients + em->n_uris;
1102      else if (unformat (a, "server"))
1103	em->i_am_master = 1;
1104      else if (unformat (a, "client"))
1105	em->i_am_master = 0;
1106      else if (unformat (a, "test-bytes:assert"))
1107	em->test_return_packets = RETURN_PACKETS_ASSERT;
1108      else if (unformat (a, "test-bytes"))
1109	em->test_return_packets = RETURN_PACKETS_LOG_WRONG;
1110      else if (unformat (a, "socket-name %s", &em->socket_name))
1111	;
1112      else if (unformat (a, "use-svm-api"))
1113	em->use_sock_api = 0;
1114      else if (unformat (a, "fifo-size %U", unformat_memory_size, &tmp))
1115	{
1116	  if (tmp >= 0x100000000ULL)
1117	    {
1118	      fprintf (stderr,
1119		       "ERROR: fifo-size %ld (0x%lx) too large\n", tmp, tmp);
1120	      print_usage_and_exit ();
1121	    }
1122	  em->fifo_size = tmp;
1123	}
1124      else if (unformat (a, "prealloc-fifos %u", &em->prealloc_fifo_pairs))
1125	;
1126      else
1127	if (unformat (a, "rx-buf %U", unformat_data_size, &em->rx_buf_size))
1128	;
1129      else
1130	if (unformat (a, "tx-buf %U", unformat_data_size, &em->tx_buf_size))
1131	;
1132      else if (unformat (a, "mq-size %d", &em->evt_q_size))
1133	;
1134      else if (unformat (a, "nclients %d", &em->n_clients))
1135	{
1136	  em->n_sessions = em->n_clients + em->n_uris;
1137	  em->n_connects = em->n_clients;
1138	}
1139      else if (unformat (a, "nthreads %d", &em->n_rx_threads))
1140	;
1141      else if (unformat (a, "crypto %U", echo_unformat_crypto_engine, &tmp))
1142	em->crypto_engine = tmp;
1143      else if (unformat (a, "appns %_%v%_", &em->appns_id))
1144	;
1145      else if (unformat (a, "all-scope"))
1146	em->appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
1147			    | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
1148      else if (unformat (a, "local-scope"))
1149	em->appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
1150      else if (unformat (a, "global-scope"))
1151	em->appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1152      else if (unformat (a, "secret %lu", &em->appns_secret))
1153	;
1154      else if (unformat (a, "TX=RX"))
1155	em->data_source = ECHO_RX_DATA_SOURCE;
1156      else if (unformat (a, "TX=%U", unformat_data_size, &em->bytes_to_send))
1157	;
1158      else if (unformat (a, "RX=%U", unformat_data_size,
1159			 &em->bytes_to_receive))
1160	;
1161      else if (unformat (a, "rx-results-diff"))
1162	em->rx_results_diff = 1;
1163      else if (unformat (a, "tx-results-diff"))
1164	em->tx_results_diff = 1;
1165      else if (unformat (a, "json"))
1166	em->output_json = 1;
1167      else if (unformat (a, "stats %d", &em->periodic_stats_delta))
1168	;
1169      else if (unformat (a, "wait-for-gdb"))
1170	em->wait_for_gdb = 1;
1171      else if (unformat (a, "log=%d", &em->log_lvl))
1172	;
1173      else if (unformat (a, "sclose=%U",
1174			 echo_unformat_close, &em->send_stream_disconnects))
1175	;
1176      else if (unformat (a, "time %U:%U",
1177			 echo_unformat_timing_event, &em->timing.start_event,
1178			 echo_unformat_timing_event, &em->timing.end_event))
1179	;
1180      else if (unformat (a, "max-sim-connects %d", &em->max_sim_connects))
1181	;
1182      else
1183	print_usage_and_exit ();
1184    }
1185
1186  /* setting default for unset values
1187   *
1188   * bytes_to_send / bytes_to_receive & data_source  */
1189  if (em->bytes_to_receive == (u64) ~ 0)
1190    em->bytes_to_receive = 64 << 10;	/* default */
1191  if (em->bytes_to_send == (u64) ~ 0)
1192    em->bytes_to_send = 64 << 10;	/* default */
1193  else if (em->bytes_to_send == 0)
1194    em->data_source = ECHO_NO_DATA_SOURCE;
1195  else
1196    em->data_source = ECHO_TEST_DATA_SOURCE;
1197
1198  if (em->data_source == ECHO_INVALID_DATA_SOURCE)
1199    em->data_source =
1200      em->i_am_master ? ECHO_RX_DATA_SOURCE : ECHO_TEST_DATA_SOURCE;
1201  if (em->data_source == ECHO_RX_DATA_SOURCE)
1202    em->bytes_to_send = em->bytes_to_receive;
1203
1204  /* disconnect flags  */
1205  if (em->i_am_master)
1206    default_f_active =
1207      em->bytes_to_send == 0 ? ECHO_CLOSE_F_ACTIVE : ECHO_CLOSE_F_PASSIVE;
1208  else
1209    default_f_active =
1210      em->bytes_to_receive == 0 ? ECHO_CLOSE_F_PASSIVE : ECHO_CLOSE_F_ACTIVE;
1211  if (em->send_stream_disconnects == ECHO_CLOSE_F_INVALID)
1212    em->send_stream_disconnects = default_f_active;
1213
1214  if (em->max_sim_connects == 0)
1215    em->max_sim_connects = em->evt_q_size >> 1;
1216
1217  if (em->wait_for_gdb)
1218    {
1219      volatile u64 nop = 0;
1220
1221      clib_warning ("Waiting for gdb...");
1222      while (em->wait_for_gdb)
1223	nop++;
1224      clib_warning ("Resuming execution (%llu)!", nop);
1225    }
1226}
1227
1228void
1229echo_process_uri (echo_main_t * em)
1230{
1231  unformat_input_t _input, *input = &_input;
1232  u32 port;
1233  unformat_init_string (input, (char *) em->uri, strlen ((char *) em->uri));
1234  if (unformat
1235      (input, "%U://%U/%d", unformat_transport_proto,
1236       &em->uri_elts.transport_proto, unformat_ip4_address,
1237       &em->uri_elts.ip.ip4, &port))
1238    em->uri_elts.is_ip4 = 1;
1239  else
1240    if (unformat
1241	(input, "%U://%U/%d", unformat_transport_proto,
1242	 &em->uri_elts.transport_proto, unformat_ip6_address,
1243	 &em->uri_elts.ip.ip6, &port))
1244    em->uri_elts.is_ip4 = 0;
1245  else
1246    ECHO_FAIL (ECHO_FAIL_INVALID_URI, "Unable to process uri");
1247  em->uri_elts.port = clib_host_to_net_u16 (port);
1248  unformat_free (input);
1249}
1250
1251static void __clib_constructor
1252vpp_echo_init ()
1253{
1254  /* init memory before proto register themselves */
1255  echo_main_t *em = &echo_main;
1256  clib_mem_init_thread_safe (0, 256 << 20);
1257  clib_memset (em, 0, sizeof (*em));
1258}
1259
1260int
1261main (int argc, char **argv)
1262{
1263  echo_main_t *em = &echo_main;
1264  fifo_segment_main_t *sm = &em->segment_main;
1265  char *app_name;
1266  u64 i;
1267  svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1268  u32 rpc_queue_size = 256 << 10;
1269
1270  em->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1271  clib_spinlock_init (&em->sid_vpp_handles_lock);
1272  em->shared_segment_handles = hash_create (0, sizeof (uword));
1273  clib_spinlock_init (&em->segment_handles_lock);
1274  em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0);
1275  em->use_sock_api = 1;
1276  em->fifo_size = 64 << 10;
1277  em->prealloc_fifo_pairs = 16;
1278  em->n_clients = 1;
1279  em->n_connects = 1;
1280  em->n_sessions = 2;
1281  em->max_test_msg = 50;
1282  em->time_to_stop = 0;
1283  em->i_am_master = 1;
1284  em->n_rx_threads = 4;
1285  em->evt_q_size = 256;
1286  em->lcl_ip_set = 0;
1287  clib_memset (&em->lcl_ip, 0, sizeof (em->lcl_ip));
1288  em->test_return_packets = RETURN_PACKETS_NOTEST;
1289  em->timing.start_event = ECHO_EVT_FIRST_QCONNECT;
1290  em->timing.end_event = ECHO_EVT_LAST_BYTE;
1291  em->bytes_to_receive = ~0;	/* defaulted when we know if server/client */
1292  em->bytes_to_send = ~0;	/* defaulted when we know if server/client */
1293  em->rx_buf_size = 1 << 20;
1294  em->tx_buf_size = 1 << 20;
1295  em->data_source = ECHO_INVALID_DATA_SOURCE;
1296  em->uri = format (0, "%s%c", "tcp://0.0.0.0/1234", 0);
1297  em->n_uris = 1;
1298  em->max_sim_connects = 0;
1299  em->listen_session_cnt = 0;
1300  em->crypto_engine = CRYPTO_ENGINE_NONE;
1301  echo_set_each_proto_defaults_before_opts (em);
1302  echo_process_opts (argc, argv);
1303  echo_process_uri (em);
1304  em->proto_cb_vft = em->available_proto_cb_vft[em->uri_elts.transport_proto];
1305  if (!em->proto_cb_vft)
1306    {
1307      ECHO_FAIL (ECHO_FAIL_PROTOCOL_NOT_SUPPORTED,
1308		 "Protocol %U is not supported",
1309		 format_transport_proto, em->uri_elts.transport_proto);
1310      goto exit_on_error;
1311    }
1312  if (em->proto_cb_vft->set_defaults_after_opts_cb)
1313    em->proto_cb_vft->set_defaults_after_opts_cb ();
1314
1315  em->stats.rx_expected = em->bytes_to_receive * em->n_clients;
1316  em->stats.tx_expected = em->bytes_to_send * em->n_clients;
1317
1318  vec_validate (em->data_thread_handles, em->n_rx_threads);
1319  vec_validate (em->data_thread_args, em->n_clients);
1320  for (i = 0; i < em->n_clients; i++)
1321    em->data_thread_args[i] = SESSION_INVALID_INDEX;
1322  clib_time_init (&em->clib_time);
1323  init_error_string_table ();
1324  fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20);
1325  vec_validate (em->connect_test_data, em->tx_buf_size);
1326  for (i = 0; i < em->tx_buf_size; i++)
1327    em->connect_test_data[i] = i & 0xff;
1328
1329  /* *INDENT-OFF* */
1330  svm_msg_q_ring_cfg_t rc[1] = {
1331    {rpc_queue_size, sizeof (echo_rpc_msg_t), 0},
1332  };
1333  /* *INDENT-ON* */
1334  cfg->consumer_pid = getpid ();
1335  cfg->n_rings = 1;
1336  cfg->q_nitems = rpc_queue_size;
1337  cfg->ring_cfgs = rc;
1338  em->rpc_msq_queue = svm_msg_q_alloc (cfg);
1339
1340  signal (SIGINT, stop_signal);
1341  signal (SIGQUIT, stop_signal);
1342  signal (SIGTERM, stop_signal);
1343  echo_api_hookup (em);
1344
1345  app_name = em->i_am_master ? "echo_server" : "echo_client";
1346  if (connect_to_vpp (app_name))
1347    {
1348      svm_region_exit ();
1349      ECHO_FAIL (ECHO_FAIL_CONNECT_TO_VPP, "Couldn't connect to vpp");
1350      goto exit_on_error;
1351    }
1352
1353  echo_session_prealloc (em);
1354  echo_notify_event (em, ECHO_EVT_START);
1355
1356  echo_send_attach (em);
1357  if (wait_for_state_change (em, STATE_ATTACHED_NO_CERT, TIMEOUT))
1358    {
1359      ECHO_FAIL (ECHO_FAIL_ATTACH_TO_VPP,
1360		 "Couldn't attach to vpp, did you run <session enable> ?");
1361      goto exit_on_error;
1362    }
1363
1364  if (em->uri_elts.transport_proto != TRANSPORT_PROTO_QUIC
1365      && em->uri_elts.transport_proto != TRANSPORT_PROTO_TLS)
1366    em->state = STATE_ATTACHED;
1367  else
1368    {
1369      ECHO_LOG (2, "Adding crypto context %U", echo_format_crypto_engine,
1370		em->crypto_engine);
1371      echo_send_add_cert_key (em);
1372      if (wait_for_state_change (em, STATE_ATTACHED, TIMEOUT))
1373	{
1374	  ECHO_FAIL (ECHO_FAIL_APP_ATTACH,
1375		     "Couldn't add crypto context to vpp\n");
1376	  exit (1);
1377	}
1378    }
1379
1380  if (pthread_create (&em->mq_thread_handle,
1381		      NULL /*attr */ , echo_mq_thread_fn, 0))
1382    {
1383      ECHO_FAIL (ECHO_FAIL_PTHREAD_CREATE, "pthread create errored");
1384      goto exit_on_error;
1385    }
1386
1387  for (i = 0; i < em->n_rx_threads; i++)
1388    if (pthread_create (&em->data_thread_handles[i],
1389			NULL /*attr */ , echo_data_thread_fn, (void *) i))
1390      {
1391	ECHO_FAIL (ECHO_FAIL_PTHREAD_CREATE,
1392		   "pthread create errored (index %d)", i);
1393	goto exit_on_error;
1394      }
1395  if (em->i_am_master)
1396    server_run (em);
1397  else
1398    clients_run (em);
1399  echo_notify_event (em, ECHO_EVT_EXIT);
1400  echo_free_sessions (em);
1401  echo_send_del_cert_key (em);
1402  if (wait_for_state_change (em, STATE_CLEANED_CERT_KEY, TIMEOUT))
1403    {
1404      ECHO_FAIL (ECHO_FAIL_DEL_CERT_KEY, "Couldn't cleanup cert and key");
1405      goto exit_on_error;
1406    }
1407
1408  echo_send_detach (em);
1409  if (wait_for_state_change (em, STATE_DETACHED, TIMEOUT))
1410    {
1411      ECHO_FAIL (ECHO_FAIL_DETACH, "Couldn't detach from vpp");
1412      goto exit_on_error;
1413    }
1414  int *rv;
1415  pthread_join (em->mq_thread_handle, (void **) &rv);
1416  if (rv)
1417    {
1418      ECHO_FAIL (ECHO_FAIL_MQ_PTHREAD, "mq pthread errored %d", rv);
1419      goto exit_on_error;
1420    }
1421  if (em->use_sock_api)
1422    vl_socket_client_disconnect ();
1423  else
1424    vl_client_disconnect_from_vlib ();
1425  echo_assert_test_suceeded (em);
1426exit_on_error:
1427  ECHO_LOG (1, "Test complete !\n");
1428  if (em->output_json)
1429    print_global_json_stats (em);
1430  else
1431    print_global_stats (em);
1432  vec_free (em->fail_descr);
1433  exit (em->has_failed);
1434}
1435
1436/*
1437 * fd.io coding-style-patch-verification: ON
1438 *
1439 * Local Variables:
1440 * eval: (c-set-style "gnu")
1441 * End:
1442 */
1443