hsa: echo clients connect improvements
[vpp.git] / src / plugins / hs_apps / echo_client.c
1 /*
2  * echo_client.c - vpp built-in echo client code
3  *
4  * Copyright (c) 2017-2019 by Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/vnet.h>
19 #include <vlibapi/api.h>
20 #include <vlibmemory/api.h>
21 #include <hs_apps/echo_client.h>
22
23 echo_client_main_t echo_client_main;
24
25 #define ECHO_CLIENT_DBG (0)
26 #define DBG(_fmt, _args...)                     \
27     if (ECHO_CLIENT_DBG)                                \
28       clib_warning (_fmt, ##_args)
29
30 static void
31 signal_evt_to_cli_i (int *code)
32 {
33   echo_client_main_t *ecm = &echo_client_main;
34   ASSERT (vlib_get_thread_index () == 0);
35   vlib_process_signal_event (ecm->vlib_main, ecm->cli_node_index, *code, 0);
36 }
37
38 static void
39 signal_evt_to_cli (int code)
40 {
41   if (vlib_get_thread_index () != 0)
42     vl_api_rpc_call_main_thread (signal_evt_to_cli_i, (u8 *) & code,
43                                  sizeof (code));
44   else
45     signal_evt_to_cli_i (&code);
46 }
47
48 static void
49 send_data_chunk (echo_client_main_t * ecm, eclient_session_t * s)
50 {
51   u8 *test_data = ecm->connect_test_data;
52   int test_buf_len, test_buf_offset, rv;
53   u32 bytes_this_chunk;
54
55   test_buf_len = vec_len (test_data);
56   ASSERT (test_buf_len > 0);
57   test_buf_offset = s->bytes_sent % test_buf_len;
58   bytes_this_chunk = clib_min (test_buf_len - test_buf_offset,
59                                s->bytes_to_send);
60
61   if (!ecm->is_dgram)
62     {
63       if (ecm->no_copy)
64         {
65           svm_fifo_t *f = s->data.tx_fifo;
66           rv = clib_min (svm_fifo_max_enqueue_prod (f), bytes_this_chunk);
67           svm_fifo_enqueue_nocopy (f, rv);
68           session_send_io_evt_to_thread_custom (
69             &f->shr->master_session_index, s->thread_index, SESSION_IO_EVT_TX);
70         }
71       else
72         rv = app_send_stream (&s->data, test_data + test_buf_offset,
73                               bytes_this_chunk, 0);
74     }
75   else
76     {
77       svm_fifo_t *f = s->data.tx_fifo;
78       u32 max_enqueue = svm_fifo_max_enqueue_prod (f);
79
80       if (max_enqueue < sizeof (session_dgram_hdr_t))
81         return;
82
83       max_enqueue -= sizeof (session_dgram_hdr_t);
84
85       if (ecm->no_copy)
86         {
87           session_dgram_hdr_t hdr;
88           app_session_transport_t *at = &s->data.transport;
89
90           rv = clib_min (max_enqueue, bytes_this_chunk);
91
92           hdr.data_length = rv;
93           hdr.data_offset = 0;
94           clib_memcpy_fast (&hdr.rmt_ip, &at->rmt_ip,
95                             sizeof (ip46_address_t));
96           hdr.is_ip4 = at->is_ip4;
97           hdr.rmt_port = at->rmt_port;
98           clib_memcpy_fast (&hdr.lcl_ip, &at->lcl_ip,
99                             sizeof (ip46_address_t));
100           hdr.lcl_port = at->lcl_port;
101           svm_fifo_enqueue (f, sizeof (hdr), (u8 *) & hdr);
102           svm_fifo_enqueue_nocopy (f, rv);
103           session_send_io_evt_to_thread_custom (
104             &f->shr->master_session_index, s->thread_index, SESSION_IO_EVT_TX);
105         }
106       else
107         {
108           bytes_this_chunk = clib_min (bytes_this_chunk, max_enqueue);
109           rv = app_send_dgram (&s->data, test_data + test_buf_offset,
110                                bytes_this_chunk, 0);
111         }
112     }
113
114   /* If we managed to enqueue data... */
115   if (rv > 0)
116     {
117       /* Account for it... */
118       s->bytes_to_send -= rv;
119       s->bytes_sent += rv;
120
121       if (ECHO_CLIENT_DBG)
122         {
123           /* *INDENT-OFF* */
124           ELOG_TYPE_DECLARE (e) =
125             {
126               .format = "tx-enq: xfer %d bytes, sent %u remain %u",
127               .format_args = "i4i4i4",
128             };
129           /* *INDENT-ON* */
130           struct
131           {
132             u32 data[3];
133           } *ed;
134           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
135           ed->data[0] = rv;
136           ed->data[1] = s->bytes_sent;
137           ed->data[2] = s->bytes_to_send;
138         }
139     }
140 }
141
142 static void
143 receive_data_chunk (echo_client_main_t * ecm, eclient_session_t * s)
144 {
145   svm_fifo_t *rx_fifo = s->data.rx_fifo;
146   u32 thread_index = vlib_get_thread_index ();
147   int n_read, i;
148
149   if (ecm->test_bytes)
150     {
151       if (!ecm->is_dgram)
152         n_read = app_recv_stream (&s->data, ecm->rx_buf[thread_index],
153                                   vec_len (ecm->rx_buf[thread_index]));
154       else
155         n_read = app_recv_dgram (&s->data, ecm->rx_buf[thread_index],
156                                  vec_len (ecm->rx_buf[thread_index]));
157     }
158   else
159     {
160       n_read = svm_fifo_max_dequeue_cons (rx_fifo);
161       svm_fifo_dequeue_drop (rx_fifo, n_read);
162     }
163
164   if (n_read > 0)
165     {
166       if (ECHO_CLIENT_DBG)
167         {
168           /* *INDENT-OFF* */
169           ELOG_TYPE_DECLARE (e) =
170             {
171               .format = "rx-deq: %d bytes",
172               .format_args = "i4",
173             };
174           /* *INDENT-ON* */
175           struct
176           {
177             u32 data[1];
178           } *ed;
179           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
180           ed->data[0] = n_read;
181         }
182
183       if (ecm->test_bytes)
184         {
185           for (i = 0; i < n_read; i++)
186             {
187               if (ecm->rx_buf[thread_index][i]
188                   != ((s->bytes_received + i) & 0xff))
189                 {
190                   clib_warning ("read %d error at byte %lld, 0x%x not 0x%x",
191                                 n_read, s->bytes_received + i,
192                                 ecm->rx_buf[thread_index][i],
193                                 ((s->bytes_received + i) & 0xff));
194                   ecm->test_failed = 1;
195                 }
196             }
197         }
198       ASSERT (n_read <= s->bytes_to_receive);
199       s->bytes_to_receive -= n_read;
200       s->bytes_received += n_read;
201     }
202 }
203
204 static uword
205 echo_client_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
206                      vlib_frame_t * frame)
207 {
208   echo_client_main_t *ecm = &echo_client_main;
209   int my_thread_index = vlib_get_thread_index ();
210   eclient_session_t *sp;
211   int i;
212   int delete_session;
213   u32 *connection_indices;
214   u32 *connections_this_batch;
215   u32 nconnections_this_batch;
216
217   connection_indices = ecm->connection_index_by_thread[my_thread_index];
218   connections_this_batch =
219     ecm->connections_this_batch_by_thread[my_thread_index];
220
221   if ((ecm->run_test != ECHO_CLIENTS_RUNNING) ||
222       ((vec_len (connection_indices) == 0)
223        && vec_len (connections_this_batch) == 0))
224     return 0;
225
226   /* Grab another pile of connections */
227   if (PREDICT_FALSE (vec_len (connections_this_batch) == 0))
228     {
229       nconnections_this_batch =
230         clib_min (ecm->connections_per_batch, vec_len (connection_indices));
231
232       ASSERT (nconnections_this_batch > 0);
233       vec_validate (connections_this_batch, nconnections_this_batch - 1);
234       clib_memcpy_fast (connections_this_batch,
235                         connection_indices + vec_len (connection_indices)
236                         - nconnections_this_batch,
237                         nconnections_this_batch * sizeof (u32));
238       _vec_len (connection_indices) -= nconnections_this_batch;
239     }
240
241   if (PREDICT_FALSE (ecm->prev_conns != ecm->connections_per_batch
242                      && ecm->prev_conns == vec_len (connections_this_batch)))
243     {
244       ecm->repeats++;
245       ecm->prev_conns = vec_len (connections_this_batch);
246       if (ecm->repeats == 500000)
247         {
248           clib_warning ("stuck clients");
249         }
250     }
251   else
252     {
253       ecm->prev_conns = vec_len (connections_this_batch);
254       ecm->repeats = 0;
255     }
256
257   for (i = 0; i < vec_len (connections_this_batch); i++)
258     {
259       delete_session = 1;
260
261       sp = pool_elt_at_index (ecm->sessions, connections_this_batch[i]);
262
263       if (sp->bytes_to_send > 0)
264         {
265           send_data_chunk (ecm, sp);
266           delete_session = 0;
267         }
268       if (sp->bytes_to_receive > 0)
269         {
270           delete_session = 0;
271         }
272       if (PREDICT_FALSE (delete_session == 1))
273         {
274           session_t *s;
275
276           clib_atomic_fetch_add (&ecm->tx_total, sp->bytes_sent);
277           clib_atomic_fetch_add (&ecm->rx_total, sp->bytes_received);
278           s = session_get_from_handle_if_valid (sp->vpp_session_handle);
279
280           if (s)
281             {
282               vnet_disconnect_args_t _a, *a = &_a;
283               a->handle = session_handle (s);
284               a->app_index = ecm->app_index;
285               vnet_disconnect_session (a);
286
287               vec_delete (connections_this_batch, 1, i);
288               i--;
289               clib_atomic_fetch_add (&ecm->ready_connections, -1);
290             }
291           else
292             {
293               clib_warning ("session AWOL?");
294               vec_delete (connections_this_batch, 1, i);
295             }
296
297           /* Kick the debug CLI process */
298           if (ecm->ready_connections == 0)
299             {
300               signal_evt_to_cli (2);
301             }
302         }
303     }
304
305   ecm->connection_index_by_thread[my_thread_index] = connection_indices;
306   ecm->connections_this_batch_by_thread[my_thread_index] =
307     connections_this_batch;
308   return 0;
309 }
310
311 VLIB_REGISTER_NODE (echo_clients_node) =
312 {
313   .function = echo_client_node_fn,
314   .name = "echo-clients",
315   .type = VLIB_NODE_TYPE_INPUT,
316   .state = VLIB_NODE_STATE_DISABLED,
317 };
318
319 static void
320 ec_reset_runtime_config (echo_client_main_t *ecm)
321 {
322   ecm->n_clients = 1;
323   ecm->quic_streams = 1;
324   ecm->bytes_to_send = 8192;
325   ecm->no_return = 0;
326   ecm->fifo_size = 64 << 10;
327   ecm->connections_per_batch = 1000;
328   ecm->private_segment_count = 0;
329   ecm->private_segment_size = 256 << 20;
330   ecm->no_output = 0;
331   ecm->test_bytes = 0;
332   ecm->test_failed = 0;
333   ecm->tls_engine = CRYPTO_ENGINE_OPENSSL;
334   ecm->no_copy = 0;
335   ecm->run_test = ECHO_CLIENTS_STARTING;
336   ecm->ready_connections = 0;
337   ecm->rx_total = 0;
338   ecm->tx_total = 0;
339   ecm->barrier_acq_needed = 0;
340   ecm->prealloc_sessions = 0;
341   ecm->prealloc_fifos = 0;
342   ecm->appns_id = 0;
343   ecm->appns_secret = 0;
344   ecm->attach_flags = 0;
345   ecm->syn_timeout = 20.0;
346   ecm->test_timeout = 20.0;
347   vec_free (ecm->connect_uri);
348 }
349
350 static int
351 echo_clients_init (vlib_main_t * vm)
352 {
353   echo_client_main_t *ecm = &echo_client_main;
354   vlib_thread_main_t *vtm = vlib_get_thread_main ();
355   u32 num_threads;
356   int i;
357
358   ec_reset_runtime_config (ecm);
359
360   /* Store cli process node index for signaling */
361   ecm->cli_node_index = vlib_get_current_process (vm)->node_runtime.node_index;
362   ecm->vlib_main = vm;
363
364   if (vlib_num_workers ())
365     {
366       /* The request came over the binary api and the inband cli handler
367        * is not mp_safe. Drop the barrier to make sure the workers are not
368        * blocked.
369        */
370       if (vlib_thread_is_main_w_barrier ())
371         {
372           ecm->barrier_acq_needed = 1;
373           vlib_worker_thread_barrier_release (vm);
374         }
375       /*
376        * There's a good chance that both the client and the server echo
377        * apps will be enabled so make sure the session queue node polls on
378        * the main thread as connections will probably be established on it.
379        */
380       vlib_node_set_state (vm, session_queue_node.index,
381                            VLIB_NODE_STATE_POLLING);
382
383       clib_spinlock_init (&ecm->sessions_lock);
384     }
385
386   /* App init done only once */
387   if (ecm->app_is_init)
388     return 0;
389
390   num_threads = 1 /* main thread */  + vtm->n_threads;
391
392   /* Init test data. Big buffer */
393   vec_validate (ecm->connect_test_data, 4 * 1024 * 1024 - 1);
394   for (i = 0; i < vec_len (ecm->connect_test_data); i++)
395     ecm->connect_test_data[i] = i & 0xff;
396
397   vec_validate (ecm->rx_buf, num_threads - 1);
398   for (i = 0; i < num_threads; i++)
399     vec_validate (ecm->rx_buf[i], vec_len (ecm->connect_test_data) - 1);
400
401   ecm->app_is_init = 1;
402
403   vec_validate (ecm->connection_index_by_thread, vtm->n_vlib_mains);
404   vec_validate (ecm->connections_this_batch_by_thread, vtm->n_vlib_mains);
405   vec_validate (ecm->quic_session_index_by_thread, vtm->n_vlib_mains);
406   vec_validate (ecm->vpp_event_queue, vtm->n_vlib_mains);
407
408   vlib_worker_thread_barrier_sync (vm);
409   vnet_session_enable_disable (vm, 1 /* turn on session and transports */);
410   vlib_worker_thread_barrier_release (vm);
411
412   /* Turn on the builtin client input nodes */
413   for (i = 0; i < vtm->n_vlib_mains; i++)
414     vlib_node_set_state (vlib_get_main_by_index (i), echo_clients_node.index,
415                          VLIB_NODE_STATE_POLLING);
416
417   return 0;
418 }
419
420 static void
421 echo_clients_cleanup (echo_client_main_t *ecm)
422 {
423   int i;
424
425   for (i = 0; i < vec_len (ecm->connection_index_by_thread); i++)
426     {
427       vec_reset_length (ecm->connection_index_by_thread[i]);
428       vec_reset_length (ecm->connections_this_batch_by_thread[i]);
429       vec_reset_length (ecm->quic_session_index_by_thread[i]);
430     }
431
432   pool_free (ecm->sessions);
433   vec_free (ecm->connect_uri);
434   vec_free (ecm->appns_id);
435   clib_spinlock_free (&ecm->sessions_lock);
436
437   if (ecm->barrier_acq_needed)
438     vlib_worker_thread_barrier_sync (ecm->vlib_main);
439 }
440
441 static int
442 quic_echo_clients_qsession_connected_callback (u32 app_index, u32 api_context,
443                                                session_t * s,
444                                                session_error_t err)
445 {
446   echo_client_main_t *ecm = &echo_client_main;
447   vnet_connect_args_t *a = 0;
448   int rv;
449   u8 thread_index = vlib_get_thread_index ();
450   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
451   u32 stream_n;
452   session_handle_t handle;
453
454   DBG ("QUIC Connection handle %d", session_handle (s));
455
456   vec_validate (a, 1);
457   a->uri = (char *) ecm->connect_uri;
458   if (parse_uri (a->uri, &sep))
459     return -1;
460   sep.parent_handle = handle = session_handle (s);
461
462   for (stream_n = 0; stream_n < ecm->quic_streams; stream_n++)
463     {
464       clib_memset (a, 0, sizeof (*a));
465       a->app_index = ecm->app_index;
466       a->api_context = -1 - api_context;
467       clib_memcpy (&a->sep_ext, &sep, sizeof (sep));
468
469       DBG ("QUIC opening stream %d", stream_n);
470       if ((rv = vnet_connect (a)))
471         {
472           clib_error ("Stream session %d opening failed: %d", stream_n, rv);
473           return -1;
474         }
475       DBG ("QUIC stream %d connected", stream_n);
476     }
477   /*
478    * 's' is no longer valid, its underlying pool could have been moved in
479    * vnet_connect()
480    */
481   vec_add1 (ecm->quic_session_index_by_thread[thread_index], handle);
482   vec_free (a);
483   return 0;
484 }
485
486 static int
487 quic_echo_clients_session_connected_callback (u32 app_index, u32 api_context,
488                                               session_t * s,
489                                               session_error_t err)
490 {
491   echo_client_main_t *ecm = &echo_client_main;
492   eclient_session_t *session;
493   u32 session_index;
494   u8 thread_index;
495
496   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
497     return -1;
498
499   if (err)
500     {
501       clib_warning ("connection %d failed!", api_context);
502       ecm->run_test = ECHO_CLIENTS_EXITING;
503       signal_evt_to_cli (-1);
504       return 0;
505     }
506
507   if (s->listener_handle == SESSION_INVALID_HANDLE)
508     return quic_echo_clients_qsession_connected_callback (app_index,
509                                                           api_context, s,
510                                                           err);
511   DBG ("STREAM Connection callback %d", api_context);
512
513   thread_index = s->thread_index;
514   ASSERT (thread_index == vlib_get_thread_index ()
515           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
516
517   if (!ecm->vpp_event_queue[thread_index])
518     ecm->vpp_event_queue[thread_index] =
519       session_main_get_vpp_event_queue (thread_index);
520
521   /*
522    * Setup session
523    */
524   clib_spinlock_lock_if_init (&ecm->sessions_lock);
525   pool_get (ecm->sessions, session);
526   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
527
528   clib_memset (session, 0, sizeof (*session));
529   session_index = session - ecm->sessions;
530   session->bytes_to_send = ecm->bytes_to_send;
531   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
532   session->data.rx_fifo = s->rx_fifo;
533   session->data.rx_fifo->shr->client_session_index = session_index;
534   session->data.tx_fifo = s->tx_fifo;
535   session->data.tx_fifo->shr->client_session_index = session_index;
536   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
537   session->vpp_session_handle = session_handle (s);
538
539   if (ecm->is_dgram)
540     {
541       transport_connection_t *tc;
542       tc = session_get_transport (s);
543       clib_memcpy_fast (&session->data.transport, tc,
544                         sizeof (session->data.transport));
545       session->data.is_dgram = 1;
546     }
547
548   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
549   clib_atomic_fetch_add (&ecm->ready_connections, 1);
550   if (ecm->ready_connections == ecm->expected_connections)
551     {
552       ecm->run_test = ECHO_CLIENTS_RUNNING;
553       /* Signal the CLI process that the action is starting... */
554       signal_evt_to_cli (1);
555     }
556
557   return 0;
558 }
559
560 static int
561 echo_clients_session_connected_callback (u32 app_index, u32 api_context,
562                                          session_t * s, session_error_t err)
563 {
564   echo_client_main_t *ecm = &echo_client_main;
565   eclient_session_t *session;
566   u32 session_index;
567   u8 thread_index;
568
569   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
570     return -1;
571
572   if (err)
573     {
574       clib_warning ("connection %d failed!", api_context);
575       ecm->run_test = ECHO_CLIENTS_EXITING;
576       signal_evt_to_cli (-1);
577       return 0;
578     }
579
580   thread_index = s->thread_index;
581   ASSERT (thread_index == vlib_get_thread_index ()
582           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
583
584   if (!ecm->vpp_event_queue[thread_index])
585     ecm->vpp_event_queue[thread_index] =
586       session_main_get_vpp_event_queue (thread_index);
587
588   /*
589    * Setup session
590    */
591   clib_spinlock_lock_if_init (&ecm->sessions_lock);
592   pool_get (ecm->sessions, session);
593   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
594
595   clib_memset (session, 0, sizeof (*session));
596   session_index = session - ecm->sessions;
597   session->bytes_to_send = ecm->bytes_to_send;
598   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
599   session->data.rx_fifo = s->rx_fifo;
600   session->data.rx_fifo->shr->client_session_index = session_index;
601   session->data.tx_fifo = s->tx_fifo;
602   session->data.tx_fifo->shr->client_session_index = session_index;
603   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
604   session->vpp_session_handle = session_handle (s);
605
606   if (ecm->is_dgram)
607     {
608       transport_connection_t *tc;
609       tc = session_get_transport (s);
610       clib_memcpy_fast (&session->data.transport, tc,
611                         sizeof (session->data.transport));
612       session->data.is_dgram = 1;
613     }
614
615   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
616   clib_atomic_fetch_add (&ecm->ready_connections, 1);
617   if (ecm->ready_connections == ecm->expected_connections)
618     {
619       ecm->run_test = ECHO_CLIENTS_RUNNING;
620       /* Signal the CLI process that the action is starting... */
621       signal_evt_to_cli (1);
622     }
623
624   return 0;
625 }
626
627 static void
628 echo_clients_session_reset_callback (session_t * s)
629 {
630   echo_client_main_t *ecm = &echo_client_main;
631   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
632
633   if (s->session_state == SESSION_STATE_READY)
634     clib_warning ("Reset active connection %U", format_session, s, 2);
635
636   a->handle = session_handle (s);
637   a->app_index = ecm->app_index;
638   vnet_disconnect_session (a);
639   return;
640 }
641
642 static int
643 echo_clients_session_create_callback (session_t * s)
644 {
645   return 0;
646 }
647
648 static void
649 echo_clients_session_disconnect_callback (session_t * s)
650 {
651   echo_client_main_t *ecm = &echo_client_main;
652   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
653   a->handle = session_handle (s);
654   a->app_index = ecm->app_index;
655   vnet_disconnect_session (a);
656   return;
657 }
658
659 void
660 echo_clients_session_disconnect (session_t * s)
661 {
662   echo_client_main_t *ecm = &echo_client_main;
663   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
664   a->handle = session_handle (s);
665   a->app_index = ecm->app_index;
666   vnet_disconnect_session (a);
667 }
668
669 static int
670 echo_clients_rx_callback (session_t * s)
671 {
672   echo_client_main_t *ecm = &echo_client_main;
673   eclient_session_t *sp;
674
675   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_RUNNING))
676     {
677       echo_clients_session_disconnect (s);
678       return -1;
679     }
680
681   sp =
682     pool_elt_at_index (ecm->sessions, s->rx_fifo->shr->client_session_index);
683   receive_data_chunk (ecm, sp);
684
685   if (svm_fifo_max_dequeue_cons (s->rx_fifo))
686     {
687       if (svm_fifo_set_event (s->rx_fifo))
688         session_send_io_evt_to_thread (s->rx_fifo, SESSION_IO_EVT_BUILTIN_RX);
689     }
690   return 0;
691 }
692
693 int
694 echo_client_add_segment_callback (u32 client_index, u64 segment_handle)
695 {
696   /* New heaps may be added */
697   return 0;
698 }
699
700 static session_cb_vft_t echo_clients = {
701   .session_reset_callback = echo_clients_session_reset_callback,
702   .session_connected_callback = echo_clients_session_connected_callback,
703   .session_accept_callback = echo_clients_session_create_callback,
704   .session_disconnect_callback = echo_clients_session_disconnect_callback,
705   .builtin_app_rx_callback = echo_clients_rx_callback,
706   .add_segment_callback = echo_client_add_segment_callback
707 };
708
709 static clib_error_t *
710 echo_clients_attach ()
711 {
712   vnet_app_add_cert_key_pair_args_t _ck_pair, *ck_pair = &_ck_pair;
713   echo_client_main_t *ecm = &echo_client_main;
714   vnet_app_attach_args_t _a, *a = &_a;
715   u32 prealloc_fifos;
716   u64 options[18];
717   int rv;
718
719   clib_memset (a, 0, sizeof (*a));
720   clib_memset (options, 0, sizeof (options));
721
722   a->api_client_index = ~0;
723   a->name = format (0, "echo_client");
724   if (ecm->transport_proto == TRANSPORT_PROTO_QUIC)
725     echo_clients.session_connected_callback =
726       quic_echo_clients_session_connected_callback;
727   a->session_cb_vft = &echo_clients;
728
729   prealloc_fifos = ecm->prealloc_fifos ? ecm->expected_connections : 1;
730
731   options[APP_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
732   options[APP_OPTIONS_SEGMENT_SIZE] = ecm->private_segment_size;
733   options[APP_OPTIONS_ADD_SEGMENT_SIZE] = ecm->private_segment_size;
734   options[APP_OPTIONS_RX_FIFO_SIZE] = ecm->fifo_size;
735   options[APP_OPTIONS_TX_FIFO_SIZE] = ecm->fifo_size;
736   options[APP_OPTIONS_PRIVATE_SEGMENT_COUNT] = ecm->private_segment_count;
737   options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = prealloc_fifos;
738   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
739   options[APP_OPTIONS_TLS_ENGINE] = ecm->tls_engine;
740   options[APP_OPTIONS_PCT_FIRST_ALLOC] = 100;
741   options[APP_OPTIONS_FLAGS] |= ecm->attach_flags;
742   if (ecm->appns_id)
743     {
744       options[APP_OPTIONS_NAMESPACE_SECRET] = ecm->appns_secret;
745       a->namespace_id = ecm->appns_id;
746     }
747   a->options = options;
748
749   if ((rv = vnet_application_attach (a)))
750     return clib_error_return (0, "attach returned %d", rv);
751
752   ecm->app_index = a->app_index;
753   vec_free (a->name);
754
755   clib_memset (ck_pair, 0, sizeof (*ck_pair));
756   ck_pair->cert = (u8 *) test_srv_crt_rsa;
757   ck_pair->key = (u8 *) test_srv_key_rsa;
758   ck_pair->cert_len = test_srv_crt_rsa_len;
759   ck_pair->key_len = test_srv_key_rsa_len;
760   vnet_app_add_cert_key_pair (ck_pair);
761   ecm->ckpair_index = ck_pair->index;
762
763   ecm->test_client_attached = 1;
764
765   return 0;
766 }
767
768 static int
769 echo_clients_detach ()
770 {
771   echo_client_main_t *ecm = &echo_client_main;
772   vnet_app_detach_args_t _da, *da = &_da;
773   int rv;
774
775   if (!ecm->test_client_attached)
776     return 0;
777
778   da->app_index = ecm->app_index;
779   da->api_client_index = ~0;
780   rv = vnet_application_detach (da);
781   ecm->test_client_attached = 0;
782   ecm->app_index = ~0;
783   vnet_app_del_cert_key_pair (ecm->ckpair_index);
784
785   return rv;
786 }
787
788 static void *
789 echo_client_thread_fn (void *arg)
790 {
791   return 0;
792 }
793
794 /** Start a transmit thread */
795 int
796 echo_clients_start_tx_pthread (echo_client_main_t * ecm)
797 {
798   if (ecm->client_thread_handle == 0)
799     {
800       int rv = pthread_create (&ecm->client_thread_handle,
801                                NULL /*attr */ ,
802                                echo_client_thread_fn, 0);
803       if (rv)
804         {
805           ecm->client_thread_handle = 0;
806           return -1;
807         }
808     }
809   return 0;
810 }
811
812 static int
813 ec_transport_needs_crypto (transport_proto_t proto)
814 {
815   return proto == TRANSPORT_PROTO_TLS || proto == TRANSPORT_PROTO_DTLS ||
816          proto == TRANSPORT_PROTO_QUIC;
817 }
818
819 clib_error_t *
820 echo_clients_connect (vlib_main_t *vm)
821 {
822   echo_client_main_t *ecm = &echo_client_main;
823   vnet_connect_args_t _a = {}, *a = &_a;
824   int ci = 0, rv, needs_crypto;
825   clib_error_t *error = 0;
826   u32 n_clients;
827
828   n_clients = ecm->n_clients;
829   needs_crypto = ec_transport_needs_crypto (ecm->transport_proto);
830   clib_memcpy (&a->sep_ext, &ecm->connect_sep, sizeof (ecm->connect_sep));
831   a->app_index = ecm->app_index;
832
833   vlib_worker_thread_barrier_sync (vm);
834
835   while (ci < n_clients)
836     {
837       a->api_context = ci;
838       if (needs_crypto)
839         {
840           session_endpoint_alloc_ext_cfg (&a->sep_ext,
841                                           TRANSPORT_ENDPT_EXT_CFG_CRYPTO);
842           a->sep_ext.ext_cfg->crypto.ckpair_index = ecm->ckpair_index;
843         }
844
845       rv = vnet_connect (a);
846
847       if (needs_crypto)
848         clib_mem_free (a->sep_ext.ext_cfg);
849
850       if (rv)
851         {
852           error = clib_error_return (0, "connect returned: %d", rv);
853           break;
854         }
855
856       ci += 1;
857
858       /* Crude pacing for call setups  */
859       if ((ci % 16) == 0)
860         {
861           vlib_worker_thread_barrier_release (vm);
862
863           ASSERT (ci >= ecm->ready_connections);
864           if (ci - ecm->ready_connections > 128)
865             {
866               while (ci - ecm->ready_connections > 128)
867                 vlib_process_suspend (vm, 100e-6);
868             }
869           else
870             {
871               vlib_process_suspend (vm, 50e-6);
872             }
873
874           vlib_worker_thread_barrier_sync (vm);
875         }
876     }
877
878   vlib_worker_thread_barrier_release (vm);
879
880   return error;
881 }
882
883 #define ec_cli(_fmt, _args...)                                                \
884   if (!ecm->no_output)                                                        \
885   vlib_cli_output (vm, _fmt, ##_args)
886
887 static clib_error_t *
888 echo_clients_command_fn (vlib_main_t *vm, unformat_input_t *input,
889                          vlib_cli_command_t *cmd)
890 {
891   unformat_input_t _line_input, *line_input = &_line_input;
892   char *default_uri = "tcp://6.0.1.1/1234", *transfer_type;
893   echo_client_main_t *ecm = &echo_client_main;
894   uword *event_data = 0, event_type;
895   clib_error_t *error = 0;
896   int rv, had_config = 1;
897   u64 tmp, total_bytes;
898   f64 delta;
899
900   if (ecm->test_client_attached)
901     return clib_error_return (0, "failed: already running!");
902
903   if (echo_clients_init (vm))
904     {
905       error = clib_error_return (0, "failed init");
906       goto cleanup;
907     }
908
909   if (!unformat_user (input, unformat_line_input, line_input))
910     {
911       had_config = 0;
912       goto parse_config;
913     }
914
915   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
916     {
917       if (unformat (line_input, "uri %s", &ecm->connect_uri))
918         ;
919       else if (unformat (line_input, "nclients %d", &ecm->n_clients))
920         ;
921       else if (unformat (line_input, "quic-streams %d", &ecm->quic_streams))
922         ;
923       else if (unformat (line_input, "mbytes %lld", &tmp))
924         ecm->bytes_to_send = tmp << 20;
925       else if (unformat (line_input, "gbytes %lld", &tmp))
926         ecm->bytes_to_send = tmp << 30;
927       else if (unformat (line_input, "bytes %U", unformat_memory_size,
928                          &ecm->bytes_to_send))
929         ;
930       else if (unformat (line_input, "test-timeout %f", &ecm->test_timeout))
931         ;
932       else if (unformat (line_input, "syn-timeout %f", &ecm->syn_timeout))
933         ;
934       else if (unformat (line_input, "no-return"))
935         ecm->no_return = 1;
936       else if (unformat (line_input, "fifo-size %d", &ecm->fifo_size))
937         ecm->fifo_size <<= 10;
938       else if (unformat (line_input, "private-segment-count %d",
939                          &ecm->private_segment_count))
940         ;
941       else if (unformat (line_input, "private-segment-size %U",
942                          unformat_memory_size, &ecm->private_segment_size))
943         ;
944       else if (unformat (line_input, "preallocate-fifos"))
945         ecm->prealloc_fifos = 1;
946       else if (unformat (line_input, "preallocate-sessions"))
947         ecm->prealloc_sessions = 1;
948       else if (unformat (line_input, "client-batch %d",
949                          &ecm->connections_per_batch))
950         ;
951       else if (unformat (line_input, "appns %_%v%_", &ecm->appns_id))
952         ;
953       else if (unformat (line_input, "all-scope"))
954         ecm->attach_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE |
955                               APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
956       else if (unformat (line_input, "local-scope"))
957         ecm->attach_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
958       else if (unformat (line_input, "global-scope"))
959         ecm->attach_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
960       else if (unformat (line_input, "secret %lu", &ecm->appns_secret))
961         ;
962       else if (unformat (line_input, "no-output"))
963         ecm->no_output = 1;
964       else if (unformat (line_input, "test-bytes"))
965         ecm->test_bytes = 1;
966       else if (unformat (line_input, "tls-engine %d", &ecm->tls_engine))
967         ;
968       else
969         {
970           error = clib_error_return (0, "failed: unknown input `%U'",
971                                      format_unformat_error, line_input);
972           goto cleanup;
973         }
974     }
975
976 parse_config:
977
978   ecm->expected_connections = ecm->n_clients * ecm->quic_streams;
979
980   if (!ecm->connect_uri)
981     {
982       clib_warning ("No uri provided. Using default: %s", default_uri);
983       ecm->connect_uri = format (0, "%s%c", default_uri, 0);
984     }
985
986   if ((rv = parse_uri ((char *) ecm->connect_uri, &ecm->connect_sep)))
987     {
988       error = clib_error_return (0, "Uri parse error: %d", rv);
989       goto cleanup;
990     }
991   ecm->transport_proto = ecm->connect_sep.transport_proto;
992   ecm->is_dgram = (ecm->transport_proto == TRANSPORT_PROTO_UDP);
993
994   if (ecm->prealloc_sessions)
995     pool_init_fixed (ecm->sessions, 1.1 * ecm->n_clients);
996
997   if ((error = echo_clients_attach ()))
998     {
999       clib_error_report (error);
1000       goto cleanup;
1001     }
1002
1003   /*
1004    * Start. Fire off connect requests
1005    */
1006
1007   ecm->syn_start_time = vlib_time_now (vm);
1008   if ((error = echo_clients_connect (vm)))
1009     {
1010       goto cleanup;
1011     }
1012
1013   /*
1014    * Park until the sessions come up, or syn_timeout seconds pass
1015    */
1016
1017   vlib_process_wait_for_event_or_clock (vm, ecm->syn_timeout);
1018   event_type = vlib_process_get_events (vm, &event_data);
1019   switch (event_type)
1020     {
1021     case ~0:
1022       ec_cli ("Timeout with only %d sessions active...",
1023               ecm->ready_connections);
1024       error = clib_error_return (0, "failed: syn timeout with %d sessions",
1025                                  ecm->ready_connections);
1026       goto cleanup;
1027
1028     case 1:
1029       delta = vlib_time_now (vm) - ecm->syn_start_time;
1030       if (delta != 0.0)
1031         ec_cli ("%d three-way handshakes in %.2f seconds %.2f/s",
1032                 ecm->n_clients, delta, ((f64) ecm->n_clients) / delta);
1033       break;
1034
1035     default:
1036       ec_cli ("unexpected event(1): %d", event_type);
1037       error = clib_error_return (0, "failed: unexpected event(1): %d",
1038                                  event_type);
1039       goto cleanup;
1040     }
1041
1042   /*
1043    * Wait for the sessions to finish or test_timeout seconds pass
1044    */
1045   ecm->test_start_time = vlib_time_now (ecm->vlib_main);
1046   ec_cli ("Test started at %.6f", ecm->test_start_time);
1047   vlib_process_wait_for_event_or_clock (vm, ecm->test_timeout);
1048   event_type = vlib_process_get_events (vm, &event_data);
1049   switch (event_type)
1050     {
1051     case ~0:
1052       ec_cli ("Timeout with %d sessions still active...",
1053               ecm->ready_connections);
1054       error = clib_error_return (0, "failed: timeout with %d sessions",
1055                                  ecm->ready_connections);
1056       goto cleanup;
1057
1058     case 2:
1059       ecm->test_end_time = vlib_time_now (vm);
1060       ec_cli ("Test finished at %.6f", ecm->test_end_time);
1061       break;
1062
1063     default:
1064       ec_cli ("unexpected event(2): %d", event_type);
1065       error = clib_error_return (0, "failed: unexpected event(2): %d",
1066                                  event_type);
1067       goto cleanup;
1068     }
1069
1070   /*
1071    * Done. Compute stats
1072    */
1073   delta = ecm->test_end_time - ecm->test_start_time;
1074   if (delta == 0.0)
1075     {
1076       ec_cli ("zero delta-t?");
1077       error = clib_error_return (0, "failed: zero delta-t");
1078       goto cleanup;
1079     }
1080
1081   total_bytes = (ecm->no_return ? ecm->tx_total : ecm->rx_total);
1082   transfer_type = ecm->no_return ? "half-duplex" : "full-duplex";
1083   ec_cli ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds", total_bytes,
1084           total_bytes / (1ULL << 20), total_bytes / (1ULL << 30), delta);
1085   ec_cli ("%.2f bytes/second %s", ((f64) total_bytes) / (delta),
1086           transfer_type);
1087   ec_cli ("%.4f gbit/second %s", (((f64) total_bytes * 8.0) / delta / 1e9),
1088           transfer_type);
1089
1090   if (ecm->test_bytes && ecm->test_failed)
1091     error = clib_error_return (0, "failed: test bytes");
1092
1093 cleanup:
1094
1095   /*
1096    * Cleanup
1097    */
1098   ecm->run_test = ECHO_CLIENTS_EXITING;
1099   vlib_process_wait_for_event_or_clock (vm, 10e-3);
1100
1101   /* Detach the application, so we can use different fifo sizes next time */
1102   if (echo_clients_detach ())
1103     {
1104       error = clib_error_return (0, "failed: app detach");
1105       ec_cli ("WARNING: app detach failed...");
1106     }
1107
1108   echo_clients_cleanup (ecm);
1109   if (had_config)
1110     unformat_free (line_input);
1111
1112   if (error)
1113     ec_cli ("test failed");
1114
1115   return error;
1116 }
1117
1118 VLIB_CLI_COMMAND (echo_clients_command, static) =
1119 {
1120   .path = "test echo clients",
1121   .short_help = "test echo clients [nclients %d][[m|g]bytes <bytes>]"
1122       "[test-timeout <time>][syn-timeout <time>][no-return][fifo-size <size>]"
1123       "[private-segment-count <count>][private-segment-size <bytes>[m|g]]"
1124       "[preallocate-fifos][preallocate-sessions][client-batch <batch-size>]"
1125       "[uri <tcp://ip/port>][test-bytes][no-output]",
1126   .function = echo_clients_command_fn,
1127   .is_mp_safe = 1,
1128 };
1129
1130 clib_error_t *
1131 echo_clients_main_init (vlib_main_t * vm)
1132 {
1133   echo_client_main_t *ecm = &echo_client_main;
1134   ecm->app_is_init = 0;
1135   return 0;
1136 }
1137
1138 VLIB_INIT_FUNCTION (echo_clients_main_init);
1139
1140 /*
1141  * fd.io coding-style-patch-verification: ON
1142  *
1143  * Local Variables:
1144  * eval: (c-set-style "gnu")
1145  * End:
1146  */