hsa: allow large segments for echo apps
[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 /* *INDENT-OFF* */
312 VLIB_REGISTER_NODE (echo_clients_node) =
313 {
314   .function = echo_client_node_fn,
315   .name = "echo-clients",
316   .type = VLIB_NODE_TYPE_INPUT,
317   .state = VLIB_NODE_STATE_DISABLED,
318 };
319 /* *INDENT-ON* */
320
321 static int
322 echo_clients_init (vlib_main_t * vm)
323 {
324   echo_client_main_t *ecm = &echo_client_main;
325   vlib_thread_main_t *vtm = vlib_get_thread_main ();
326   u32 num_threads;
327   int i;
328
329   num_threads = 1 /* main thread */  + vtm->n_threads;
330
331   /* Init test data. Big buffer */
332   vec_validate (ecm->connect_test_data, 4 * 1024 * 1024 - 1);
333   for (i = 0; i < vec_len (ecm->connect_test_data); i++)
334     ecm->connect_test_data[i] = i & 0xff;
335
336   vec_validate (ecm->rx_buf, num_threads - 1);
337   for (i = 0; i < num_threads; i++)
338     vec_validate (ecm->rx_buf[i], vec_len (ecm->connect_test_data) - 1);
339
340   ecm->is_init = 1;
341
342   vec_validate (ecm->connection_index_by_thread, vtm->n_vlib_mains);
343   vec_validate (ecm->connections_this_batch_by_thread, vtm->n_vlib_mains);
344   vec_validate (ecm->quic_session_index_by_thread, vtm->n_vlib_mains);
345   vec_validate (ecm->vpp_event_queue, vtm->n_vlib_mains);
346
347   return 0;
348 }
349
350 static int
351 quic_echo_clients_qsession_connected_callback (u32 app_index, u32 api_context,
352                                                session_t * s,
353                                                session_error_t err)
354 {
355   echo_client_main_t *ecm = &echo_client_main;
356   vnet_connect_args_t *a = 0;
357   int rv;
358   u8 thread_index = vlib_get_thread_index ();
359   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
360   u32 stream_n;
361   session_handle_t handle;
362
363   DBG ("QUIC Connection handle %d", session_handle (s));
364
365   vec_validate (a, 1);
366   a->uri = (char *) ecm->connect_uri;
367   if (parse_uri (a->uri, &sep))
368     return -1;
369   sep.parent_handle = handle = session_handle (s);
370
371   for (stream_n = 0; stream_n < ecm->quic_streams; stream_n++)
372     {
373       clib_memset (a, 0, sizeof (*a));
374       a->app_index = ecm->app_index;
375       a->api_context = -1 - api_context;
376       clib_memcpy (&a->sep_ext, &sep, sizeof (sep));
377
378       DBG ("QUIC opening stream %d", stream_n);
379       if ((rv = vnet_connect (a)))
380         {
381           clib_error ("Stream session %d opening failed: %d", stream_n, rv);
382           return -1;
383         }
384       DBG ("QUIC stream %d connected", stream_n);
385     }
386   /*
387    * 's' is no longer valid, its underlying pool could have been moved in
388    * vnet_connect()
389    */
390   vec_add1 (ecm->quic_session_index_by_thread[thread_index], handle);
391   vec_free (a);
392   return 0;
393 }
394
395 static int
396 quic_echo_clients_session_connected_callback (u32 app_index, u32 api_context,
397                                               session_t * s,
398                                               session_error_t err)
399 {
400   echo_client_main_t *ecm = &echo_client_main;
401   eclient_session_t *session;
402   u32 session_index;
403   u8 thread_index;
404
405   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
406     return -1;
407
408   if (err)
409     {
410       clib_warning ("connection %d failed!", api_context);
411       ecm->run_test = ECHO_CLIENTS_EXITING;
412       signal_evt_to_cli (-1);
413       return 0;
414     }
415
416   if (s->listener_handle == SESSION_INVALID_HANDLE)
417     return quic_echo_clients_qsession_connected_callback (app_index,
418                                                           api_context, s,
419                                                           err);
420   DBG ("STREAM Connection callback %d", api_context);
421
422   thread_index = s->thread_index;
423   ASSERT (thread_index == vlib_get_thread_index ()
424           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
425
426   if (!ecm->vpp_event_queue[thread_index])
427     ecm->vpp_event_queue[thread_index] =
428       session_main_get_vpp_event_queue (thread_index);
429
430   /*
431    * Setup session
432    */
433   clib_spinlock_lock_if_init (&ecm->sessions_lock);
434   pool_get (ecm->sessions, session);
435   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
436
437   clib_memset (session, 0, sizeof (*session));
438   session_index = session - ecm->sessions;
439   session->bytes_to_send = ecm->bytes_to_send;
440   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
441   session->data.rx_fifo = s->rx_fifo;
442   session->data.rx_fifo->shr->client_session_index = session_index;
443   session->data.tx_fifo = s->tx_fifo;
444   session->data.tx_fifo->shr->client_session_index = session_index;
445   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
446   session->vpp_session_handle = session_handle (s);
447
448   if (ecm->is_dgram)
449     {
450       transport_connection_t *tc;
451       tc = session_get_transport (s);
452       clib_memcpy_fast (&session->data.transport, tc,
453                         sizeof (session->data.transport));
454       session->data.is_dgram = 1;
455     }
456
457   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
458   clib_atomic_fetch_add (&ecm->ready_connections, 1);
459   if (ecm->ready_connections == ecm->expected_connections)
460     {
461       ecm->run_test = ECHO_CLIENTS_RUNNING;
462       /* Signal the CLI process that the action is starting... */
463       signal_evt_to_cli (1);
464     }
465
466   return 0;
467 }
468
469 static int
470 echo_clients_session_connected_callback (u32 app_index, u32 api_context,
471                                          session_t * s, session_error_t err)
472 {
473   echo_client_main_t *ecm = &echo_client_main;
474   eclient_session_t *session;
475   u32 session_index;
476   u8 thread_index;
477
478   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
479     return -1;
480
481   if (err)
482     {
483       clib_warning ("connection %d failed!", api_context);
484       ecm->run_test = ECHO_CLIENTS_EXITING;
485       signal_evt_to_cli (-1);
486       return 0;
487     }
488
489   thread_index = s->thread_index;
490   ASSERT (thread_index == vlib_get_thread_index ()
491           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
492
493   if (!ecm->vpp_event_queue[thread_index])
494     ecm->vpp_event_queue[thread_index] =
495       session_main_get_vpp_event_queue (thread_index);
496
497   /*
498    * Setup session
499    */
500   clib_spinlock_lock_if_init (&ecm->sessions_lock);
501   pool_get (ecm->sessions, session);
502   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
503
504   clib_memset (session, 0, sizeof (*session));
505   session_index = session - ecm->sessions;
506   session->bytes_to_send = ecm->bytes_to_send;
507   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
508   session->data.rx_fifo = s->rx_fifo;
509   session->data.rx_fifo->shr->client_session_index = session_index;
510   session->data.tx_fifo = s->tx_fifo;
511   session->data.tx_fifo->shr->client_session_index = session_index;
512   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
513   session->vpp_session_handle = session_handle (s);
514
515   if (ecm->is_dgram)
516     {
517       transport_connection_t *tc;
518       tc = session_get_transport (s);
519       clib_memcpy_fast (&session->data.transport, tc,
520                         sizeof (session->data.transport));
521       session->data.is_dgram = 1;
522     }
523
524   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
525   clib_atomic_fetch_add (&ecm->ready_connections, 1);
526   if (ecm->ready_connections == ecm->expected_connections)
527     {
528       ecm->run_test = ECHO_CLIENTS_RUNNING;
529       /* Signal the CLI process that the action is starting... */
530       signal_evt_to_cli (1);
531     }
532
533   return 0;
534 }
535
536 static void
537 echo_clients_session_reset_callback (session_t * s)
538 {
539   echo_client_main_t *ecm = &echo_client_main;
540   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
541
542   if (s->session_state == SESSION_STATE_READY)
543     clib_warning ("Reset active connection %U", format_session, s, 2);
544
545   a->handle = session_handle (s);
546   a->app_index = ecm->app_index;
547   vnet_disconnect_session (a);
548   return;
549 }
550
551 static int
552 echo_clients_session_create_callback (session_t * s)
553 {
554   return 0;
555 }
556
557 static void
558 echo_clients_session_disconnect_callback (session_t * s)
559 {
560   echo_client_main_t *ecm = &echo_client_main;
561   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
562   a->handle = session_handle (s);
563   a->app_index = ecm->app_index;
564   vnet_disconnect_session (a);
565   return;
566 }
567
568 void
569 echo_clients_session_disconnect (session_t * s)
570 {
571   echo_client_main_t *ecm = &echo_client_main;
572   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
573   a->handle = session_handle (s);
574   a->app_index = ecm->app_index;
575   vnet_disconnect_session (a);
576 }
577
578 static int
579 echo_clients_rx_callback (session_t * s)
580 {
581   echo_client_main_t *ecm = &echo_client_main;
582   eclient_session_t *sp;
583
584   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_RUNNING))
585     {
586       echo_clients_session_disconnect (s);
587       return -1;
588     }
589
590   sp =
591     pool_elt_at_index (ecm->sessions, s->rx_fifo->shr->client_session_index);
592   receive_data_chunk (ecm, sp);
593
594   if (svm_fifo_max_dequeue_cons (s->rx_fifo))
595     {
596       if (svm_fifo_set_event (s->rx_fifo))
597         session_send_io_evt_to_thread (s->rx_fifo, SESSION_IO_EVT_BUILTIN_RX);
598     }
599   return 0;
600 }
601
602 int
603 echo_client_add_segment_callback (u32 client_index, u64 segment_handle)
604 {
605   /* New heaps may be added */
606   return 0;
607 }
608
609 /* *INDENT-OFF* */
610 static session_cb_vft_t echo_clients = {
611   .session_reset_callback = echo_clients_session_reset_callback,
612   .session_connected_callback = echo_clients_session_connected_callback,
613   .session_accept_callback = echo_clients_session_create_callback,
614   .session_disconnect_callback = echo_clients_session_disconnect_callback,
615   .builtin_app_rx_callback = echo_clients_rx_callback,
616   .add_segment_callback = echo_client_add_segment_callback
617 };
618 /* *INDENT-ON* */
619
620 static clib_error_t *
621 echo_clients_attach (u8 * appns_id, u64 appns_flags, u64 appns_secret)
622 {
623   vnet_app_add_cert_key_pair_args_t _ck_pair, *ck_pair = &_ck_pair;
624   echo_client_main_t *ecm = &echo_client_main;
625   vnet_app_attach_args_t _a, *a = &_a;
626   u32 prealloc_fifos;
627   u64 options[18];
628   int rv;
629
630   clib_memset (a, 0, sizeof (*a));
631   clib_memset (options, 0, sizeof (options));
632
633   a->api_client_index = ~0;
634   a->name = format (0, "echo_client");
635   if (ecm->transport_proto == TRANSPORT_PROTO_QUIC)
636     echo_clients.session_connected_callback =
637       quic_echo_clients_session_connected_callback;
638   a->session_cb_vft = &echo_clients;
639
640   prealloc_fifos = ecm->prealloc_fifos ? ecm->expected_connections : 1;
641
642   options[APP_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
643   options[APP_OPTIONS_SEGMENT_SIZE] = ecm->private_segment_size;
644   options[APP_OPTIONS_ADD_SEGMENT_SIZE] = ecm->private_segment_size;
645   options[APP_OPTIONS_RX_FIFO_SIZE] = ecm->fifo_size;
646   options[APP_OPTIONS_TX_FIFO_SIZE] = ecm->fifo_size;
647   options[APP_OPTIONS_PRIVATE_SEGMENT_COUNT] = ecm->private_segment_count;
648   options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = prealloc_fifos;
649   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
650   options[APP_OPTIONS_TLS_ENGINE] = ecm->tls_engine;
651   options[APP_OPTIONS_PCT_FIRST_ALLOC] = 100;
652   if (appns_id)
653     {
654       options[APP_OPTIONS_FLAGS] |= appns_flags;
655       options[APP_OPTIONS_NAMESPACE_SECRET] = appns_secret;
656     }
657   a->options = options;
658   a->namespace_id = appns_id;
659
660   if ((rv = vnet_application_attach (a)))
661     return clib_error_return (0, "attach returned %d", rv);
662
663   ecm->app_index = a->app_index;
664   vec_free (a->name);
665
666   clib_memset (ck_pair, 0, sizeof (*ck_pair));
667   ck_pair->cert = (u8 *) test_srv_crt_rsa;
668   ck_pair->key = (u8 *) test_srv_key_rsa;
669   ck_pair->cert_len = test_srv_crt_rsa_len;
670   ck_pair->key_len = test_srv_key_rsa_len;
671   vnet_app_add_cert_key_pair (ck_pair);
672   ecm->ckpair_index = ck_pair->index;
673
674   return 0;
675 }
676
677 static int
678 echo_clients_detach ()
679 {
680   echo_client_main_t *ecm = &echo_client_main;
681   vnet_app_detach_args_t _da, *da = &_da;
682   int rv;
683
684   da->app_index = ecm->app_index;
685   da->api_client_index = ~0;
686   rv = vnet_application_detach (da);
687   ecm->test_client_attached = 0;
688   ecm->app_index = ~0;
689   vnet_app_del_cert_key_pair (ecm->ckpair_index);
690
691   return rv;
692 }
693
694 static void *
695 echo_client_thread_fn (void *arg)
696 {
697   return 0;
698 }
699
700 /** Start a transmit thread */
701 int
702 echo_clients_start_tx_pthread (echo_client_main_t * ecm)
703 {
704   if (ecm->client_thread_handle == 0)
705     {
706       int rv = pthread_create (&ecm->client_thread_handle,
707                                NULL /*attr */ ,
708                                echo_client_thread_fn, 0);
709       if (rv)
710         {
711           ecm->client_thread_handle = 0;
712           return -1;
713         }
714     }
715   return 0;
716 }
717
718 static int
719 echo_client_transport_needs_crypto (transport_proto_t proto)
720 {
721   return proto == TRANSPORT_PROTO_TLS || proto == TRANSPORT_PROTO_DTLS ||
722          proto == TRANSPORT_PROTO_QUIC;
723 }
724
725 clib_error_t *
726 echo_clients_connect (vlib_main_t * vm, u32 n_clients)
727 {
728   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
729   echo_client_main_t *ecm = &echo_client_main;
730   vnet_connect_args_t _a, *a = &_a;
731   int i, rv;
732
733   clib_memset (a, 0, sizeof (*a));
734
735   if (parse_uri ((char *) ecm->connect_uri, &sep))
736     return clib_error_return (0, "invalid uri");
737
738   for (i = 0; i < n_clients; i++)
739     {
740       clib_memcpy (&a->sep_ext, &sep, sizeof (sep));
741       a->api_context = i;
742       a->app_index = ecm->app_index;
743       if (echo_client_transport_needs_crypto (a->sep_ext.transport_proto))
744         {
745           session_endpoint_alloc_ext_cfg (&a->sep_ext,
746                                           TRANSPORT_ENDPT_EXT_CFG_CRYPTO);
747           a->sep_ext.ext_cfg->crypto.ckpair_index = ecm->ckpair_index;
748         }
749
750       vlib_worker_thread_barrier_sync (vm);
751       rv = vnet_connect (a);
752       if (a->sep_ext.ext_cfg)
753         clib_mem_free (a->sep_ext.ext_cfg);
754       if (rv)
755         {
756           vlib_worker_thread_barrier_release (vm);
757           return clib_error_return (0, "connect returned: %d", rv);
758         }
759       vlib_worker_thread_barrier_release (vm);
760
761       /* Crude pacing for call setups  */
762       if ((i % 16) == 0)
763         vlib_process_suspend (vm, 100e-6);
764       ASSERT (i + 1 >= ecm->ready_connections);
765       while (i + 1 - ecm->ready_connections > 128)
766         vlib_process_suspend (vm, 1e-3);
767     }
768   return 0;
769 }
770
771 #define ec_cli_output(_fmt, _args...)                   \
772   if (!ecm->no_output)                                  \
773     vlib_cli_output(vm, _fmt, ##_args)
774
775 static clib_error_t *
776 echo_clients_command_fn (vlib_main_t * vm,
777                          unformat_input_t * input, vlib_cli_command_t * cmd)
778 {
779   echo_client_main_t *ecm = &echo_client_main;
780   vlib_thread_main_t *thread_main = vlib_get_thread_main ();
781   u64 tmp, total_bytes, appns_flags = 0, appns_secret = 0;
782   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
783   f64 test_timeout = 20.0, syn_timeout = 20.0, delta;
784   char *default_uri = "tcp://6.0.1.1/1234";
785   u8 *appns_id = 0, barrier_acq_needed = 0;
786   int preallocate_sessions = 0, i, rv;
787   uword *event_data = 0, event_type;
788   f64 time_before_connects;
789   u32 n_clients = 1;
790   char *transfer_type;
791   clib_error_t *error = 0;
792
793   ecm->quic_streams = 1;
794   ecm->bytes_to_send = 8192;
795   ecm->no_return = 0;
796   ecm->fifo_size = 64 << 10;
797   ecm->connections_per_batch = 1000;
798   ecm->private_segment_count = 0;
799   ecm->private_segment_size = 256 << 20;
800   ecm->no_output = 0;
801   ecm->test_bytes = 0;
802   ecm->test_failed = 0;
803   ecm->vlib_main = vm;
804   ecm->tls_engine = CRYPTO_ENGINE_OPENSSL;
805   ecm->no_copy = 0;
806   ecm->run_test = ECHO_CLIENTS_STARTING;
807
808   if (vlib_num_workers ())
809     {
810       /* The request came over the binary api and the inband cli handler
811        * is not mp_safe. Drop the barrier to make sure the workers are not
812        * blocked.
813        */
814       if (vlib_thread_is_main_w_barrier ())
815         {
816           barrier_acq_needed = 1;
817           vlib_worker_thread_barrier_release (vm);
818         }
819       /*
820        * There's a good chance that both the client and the server echo
821        * apps will be enabled so make sure the session queue node polls on
822        * the main thread as connections will probably be established on it.
823        */
824       vlib_node_set_state (vm, session_queue_node.index,
825                            VLIB_NODE_STATE_POLLING);
826     }
827
828   if (thread_main->n_vlib_mains > 1)
829     clib_spinlock_init (&ecm->sessions_lock);
830   vec_free (ecm->connect_uri);
831
832   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
833     {
834       if (unformat (input, "uri %s", &ecm->connect_uri))
835         ;
836       else if (unformat (input, "nclients %d", &n_clients))
837         ;
838       else if (unformat (input, "quic-streams %d", &ecm->quic_streams))
839         ;
840       else if (unformat (input, "mbytes %lld", &tmp))
841         ecm->bytes_to_send = tmp << 20;
842       else if (unformat (input, "gbytes %lld", &tmp))
843         ecm->bytes_to_send = tmp << 30;
844       else if (unformat (input, "bytes %lld", &ecm->bytes_to_send))
845         ;
846       else if (unformat (input, "test-timeout %f", &test_timeout))
847         ;
848       else if (unformat (input, "syn-timeout %f", &syn_timeout))
849         ;
850       else if (unformat (input, "no-return"))
851         ecm->no_return = 1;
852       else if (unformat (input, "fifo-size %d", &ecm->fifo_size))
853         ecm->fifo_size <<= 10;
854       else if (unformat (input, "private-segment-count %d",
855                          &ecm->private_segment_count))
856         ;
857       else if (unformat (input, "private-segment-size %U",
858                          unformat_memory_size, &ecm->private_segment_size))
859         ;
860       else if (unformat (input, "preallocate-fifos"))
861         ecm->prealloc_fifos = 1;
862       else if (unformat (input, "preallocate-sessions"))
863         preallocate_sessions = 1;
864       else
865         if (unformat (input, "client-batch %d", &ecm->connections_per_batch))
866         ;
867       else if (unformat (input, "appns %_%v%_", &appns_id))
868         ;
869       else if (unformat (input, "all-scope"))
870         appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
871                         | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
872       else if (unformat (input, "local-scope"))
873         appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
874       else if (unformat (input, "global-scope"))
875         appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
876       else if (unformat (input, "secret %lu", &appns_secret))
877         ;
878       else if (unformat (input, "no-output"))
879         ecm->no_output = 1;
880       else if (unformat (input, "test-bytes"))
881         ecm->test_bytes = 1;
882       else if (unformat (input, "tls-engine %d", &ecm->tls_engine))
883         ;
884       else
885         {
886           error = clib_error_return (0, "failed: unknown input `%U'",
887                                      format_unformat_error, input);
888           goto cleanup;
889         }
890     }
891
892   /* Store cli process node index for signalling */
893   ecm->cli_node_index =
894     vlib_get_current_process (vm)->node_runtime.node_index;
895
896   if (ecm->is_init == 0)
897     {
898       if (echo_clients_init (vm))
899         {
900           error = clib_error_return (0, "failed init");
901           goto cleanup;
902         }
903     }
904
905
906   ecm->ready_connections = 0;
907   ecm->expected_connections = n_clients * ecm->quic_streams;
908   ecm->rx_total = 0;
909   ecm->tx_total = 0;
910
911   if (!ecm->connect_uri)
912     {
913       clib_warning ("No uri provided. Using default: %s", default_uri);
914       ecm->connect_uri = format (0, "%s%c", default_uri, 0);
915     }
916
917   if ((rv = parse_uri ((char *) ecm->connect_uri, &sep)))
918     {
919       error = clib_error_return (0, "Uri parse error: %d", rv);
920       goto cleanup;
921     }
922   ecm->transport_proto = sep.transport_proto;
923   ecm->is_dgram = (sep.transport_proto == TRANSPORT_PROTO_UDP);
924
925 #if ECHO_CLIENT_PTHREAD
926   echo_clients_start_tx_pthread ();
927 #endif
928
929   vlib_worker_thread_barrier_sync (vm);
930   vnet_session_enable_disable (vm, 1 /* turn on session and transports */ );
931   vlib_worker_thread_barrier_release (vm);
932
933   if (ecm->test_client_attached == 0)
934     {
935       if ((error = echo_clients_attach (appns_id, appns_flags, appns_secret)))
936         {
937           vec_free (appns_id);
938           clib_error_report (error);
939           goto cleanup;
940         }
941       vec_free (appns_id);
942     }
943   ecm->test_client_attached = 1;
944
945   /* Turn on the builtin client input nodes */
946   for (i = 0; i < thread_main->n_vlib_mains; i++)
947     vlib_node_set_state (vlib_get_main_by_index (i), echo_clients_node.index,
948                          VLIB_NODE_STATE_POLLING);
949
950   if (preallocate_sessions)
951     pool_init_fixed (ecm->sessions, 1.1 * n_clients);
952
953   /* Fire off connect requests */
954   time_before_connects = vlib_time_now (vm);
955   if ((error = echo_clients_connect (vm, n_clients)))
956     {
957       goto cleanup;
958     }
959
960   /* Park until the sessions come up, or ten seconds elapse... */
961   vlib_process_wait_for_event_or_clock (vm, syn_timeout);
962   event_type = vlib_process_get_events (vm, &event_data);
963   switch (event_type)
964     {
965     case ~0:
966       ec_cli_output ("Timeout with only %d sessions active...",
967                      ecm->ready_connections);
968       error = clib_error_return (0, "failed: syn timeout with %d sessions",
969                                  ecm->ready_connections);
970       goto cleanup;
971
972     case 1:
973       delta = vlib_time_now (vm) - time_before_connects;
974       if (delta != 0.0)
975         ec_cli_output ("%d three-way handshakes in %.2f seconds %.2f/s",
976                        n_clients, delta, ((f64) n_clients) / delta);
977
978       ecm->test_start_time = vlib_time_now (ecm->vlib_main);
979       ec_cli_output ("Test started at %.6f", ecm->test_start_time);
980       break;
981
982     default:
983       ec_cli_output ("unexpected event(1): %d", event_type);
984       error = clib_error_return (0, "failed: unexpected event(1): %d",
985                                  event_type);
986       goto cleanup;
987     }
988
989   /* Now wait for the sessions to finish... */
990   vlib_process_wait_for_event_or_clock (vm, test_timeout);
991   event_type = vlib_process_get_events (vm, &event_data);
992   switch (event_type)
993     {
994     case ~0:
995       ec_cli_output ("Timeout with %d sessions still active...",
996                      ecm->ready_connections);
997       error = clib_error_return (0, "failed: timeout with %d sessions",
998                                  ecm->ready_connections);
999       goto cleanup;
1000
1001     case 2:
1002       ecm->test_end_time = vlib_time_now (vm);
1003       ec_cli_output ("Test finished at %.6f", ecm->test_end_time);
1004       break;
1005
1006     default:
1007       ec_cli_output ("unexpected event(2): %d", event_type);
1008       error = clib_error_return (0, "failed: unexpected event(2): %d",
1009                                  event_type);
1010       goto cleanup;
1011     }
1012
1013   delta = ecm->test_end_time - ecm->test_start_time;
1014   if (delta != 0.0)
1015     {
1016       total_bytes = (ecm->no_return ? ecm->tx_total : ecm->rx_total);
1017       transfer_type = ecm->no_return ? "half-duplex" : "full-duplex";
1018       ec_cli_output ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds",
1019                      total_bytes, total_bytes / (1ULL << 20),
1020                      total_bytes / (1ULL << 30), delta);
1021       ec_cli_output ("%.2f bytes/second %s", ((f64) total_bytes) / (delta),
1022                      transfer_type);
1023       ec_cli_output ("%.4f gbit/second %s",
1024                      (((f64) total_bytes * 8.0) / delta / 1e9),
1025                      transfer_type);
1026     }
1027   else
1028     {
1029       ec_cli_output ("zero delta-t?");
1030       error = clib_error_return (0, "failed: zero delta-t");
1031       goto cleanup;
1032     }
1033
1034   if (ecm->test_bytes && ecm->test_failed)
1035     error = clib_error_return (0, "failed: test bytes");
1036
1037 cleanup:
1038   ecm->run_test = ECHO_CLIENTS_EXITING;
1039   vlib_process_wait_for_event_or_clock (vm, 10e-3);
1040   for (i = 0; i < vec_len (ecm->connection_index_by_thread); i++)
1041     {
1042       vec_reset_length (ecm->connection_index_by_thread[i]);
1043       vec_reset_length (ecm->connections_this_batch_by_thread[i]);
1044       vec_reset_length (ecm->quic_session_index_by_thread[i]);
1045     }
1046
1047   pool_free (ecm->sessions);
1048
1049   /* Detach the application, so we can use different fifo sizes next time */
1050   if (ecm->test_client_attached)
1051     {
1052       if (echo_clients_detach ())
1053         {
1054           error = clib_error_return (0, "failed: app detach");
1055           ec_cli_output ("WARNING: app detach failed...");
1056         }
1057     }
1058   if (error)
1059     ec_cli_output ("test failed");
1060   vec_free (ecm->connect_uri);
1061   clib_spinlock_free (&ecm->sessions_lock);
1062
1063   if (barrier_acq_needed)
1064     vlib_worker_thread_barrier_sync (vm);
1065
1066   return error;
1067 }
1068
1069 /* *INDENT-OFF* */
1070 VLIB_CLI_COMMAND (echo_clients_command, static) =
1071 {
1072   .path = "test echo clients",
1073   .short_help = "test echo clients [nclients %d][[m|g]bytes <bytes>]"
1074       "[test-timeout <time>][syn-timeout <time>][no-return][fifo-size <size>]"
1075       "[private-segment-count <count>][private-segment-size <bytes>[m|g]]"
1076       "[preallocate-fifos][preallocate-sessions][client-batch <batch-size>]"
1077       "[uri <tcp://ip/port>][test-bytes][no-output]",
1078   .function = echo_clients_command_fn,
1079   .is_mp_safe = 1,
1080 };
1081 /* *INDENT-ON* */
1082
1083 clib_error_t *
1084 echo_clients_main_init (vlib_main_t * vm)
1085 {
1086   echo_client_main_t *ecm = &echo_client_main;
1087   ecm->is_init = 0;
1088   return 0;
1089 }
1090
1091 VLIB_INIT_FUNCTION (echo_clients_main_init);
1092
1093 /*
1094  * fd.io coding-style-patch-verification: ON
1095  *
1096  * Local Variables:
1097  * eval: (c-set-style "gnu")
1098  * End:
1099  */