Improve fifo allocator performance
[vpp.git] / src / vnet / tcp / builtin_client.c
1 /*
2  * builtin_client.c - vpp built-in tcp client/connect code
3  *
4  * Copyright (c) 2017 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 <vnet/plugin/plugin.h>
20 #include <vnet/tcp/builtin_client.h>
21
22 #include <vlibapi/api.h>
23 #include <vlibmemory/api.h>
24 #include <vlibsocket/api.h>
25 #include <vpp/app/version.h>
26
27 /* define message IDs */
28 #include <vpp/api/vpe_msg_enum.h>
29
30 /* define message structures */
31 #define vl_typedefs
32 #include <vpp/api/vpe_all_api_h.h>
33 #undef vl_typedefs
34
35 /* define generated endian-swappers */
36 #define vl_endianfun
37 #include <vpp/api/vpe_all_api_h.h>
38 #undef vl_endianfun
39
40 /* instantiate all the print functions we know about */
41 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
42 #define vl_printfun
43 #include <vpp/api/vpe_all_api_h.h>
44 #undef vl_printfun
45
46 #define TCP_BUILTIN_CLIENT_DBG (1)
47
48 static void
49 send_test_chunk (tclient_main_t * tm, session_t * s)
50 {
51   u8 *test_data = tm->connect_test_data;
52   int test_buf_offset;
53   u32 bytes_this_chunk;
54   session_fifo_event_t evt;
55   static int serial_number = 0;
56   int rv;
57
58   ASSERT (vec_len (test_data) > 0);
59
60   test_buf_offset = s->bytes_sent % vec_len (test_data);
61   bytes_this_chunk = vec_len (test_data) - test_buf_offset;
62
63   bytes_this_chunk = bytes_this_chunk < s->bytes_to_send
64     ? bytes_this_chunk : s->bytes_to_send;
65
66   rv = svm_fifo_enqueue_nowait (s->server_tx_fifo, bytes_this_chunk,
67                                 test_data + test_buf_offset);
68
69   /* If we managed to enqueue data... */
70   if (rv > 0)
71     {
72       /* Account for it... */
73       s->bytes_to_send -= rv;
74       s->bytes_sent += rv;
75
76       if (TCP_BUILTIN_CLIENT_DBG)
77         {
78           /* *INDENT-OFF* */
79           ELOG_TYPE_DECLARE (e) =
80             {
81               .format = "tx-enq: xfer %d bytes, sent %u remain %u",
82               .format_args = "i4i4i4",
83             };
84           /* *INDENT-ON* */
85           struct
86           {
87             u32 data[3];
88           } *ed;
89           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
90           ed->data[0] = rv;
91           ed->data[1] = s->bytes_sent;
92           ed->data[2] = s->bytes_to_send;
93         }
94
95       /* Poke the TCP state machine */
96       if (svm_fifo_set_event (s->server_tx_fifo))
97         {
98           /* Fabricate TX event, send to vpp */
99           evt.fifo = s->server_tx_fifo;
100           evt.event_type = FIFO_EVENT_APP_TX;
101           evt.event_id = serial_number++;
102
103           unix_shared_memory_queue_add (tm->vpp_event_queue, (u8 *) & evt,
104                                         0 /* do wait for mutex */ );
105         }
106     }
107 }
108
109 static void
110 receive_test_chunk (tclient_main_t * tm, session_t * s)
111 {
112   svm_fifo_t *rx_fifo = s->server_rx_fifo;
113   int n_read, test_bytes = 0;
114
115   /* Allow enqueuing of new event */
116   // svm_fifo_unset_event (rx_fifo);
117
118   n_read = svm_fifo_dequeue_nowait (rx_fifo, vec_len (tm->rx_buf),
119                                     tm->rx_buf);
120   if (n_read > 0)
121     {
122       if (TCP_BUILTIN_CLIENT_DBG)
123         {
124           /* *INDENT-OFF* */
125           ELOG_TYPE_DECLARE (e) =
126             {
127               .format = "rx-deq: %d bytes",
128               .format_args = "i4",
129             };
130           /* *INDENT-ON* */
131           struct
132           {
133             u32 data[1];
134           } *ed;
135           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
136           ed->data[0] = n_read;
137         }
138
139       if (test_bytes)
140         {
141           int i;
142           for (i = 0; i < n_read; i++)
143             {
144               if (tm->rx_buf[i] != ((s->bytes_received + i) & 0xff))
145                 {
146                   clib_warning ("read %d error at byte %lld, 0x%x not 0x%x",
147                                 n_read, s->bytes_received + i, tm->rx_buf[i],
148                                 ((s->bytes_received + i) & 0xff));
149                 }
150             }
151         }
152       s->bytes_to_receive -= n_read;
153       s->bytes_received += n_read;
154     }
155 }
156
157 static uword
158 builtin_client_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
159                         vlib_frame_t * frame)
160 {
161   tclient_main_t *tm = &tclient_main;
162   int my_thread_index = vlib_get_thread_index ();
163   vl_api_disconnect_session_t *dmp;
164   session_t *sp;
165   int i;
166   int delete_session;
167   u32 *connection_indices;
168
169   connection_indices = tm->connection_index_by_thread[my_thread_index];
170
171   if (tm->run_test == 0 || vec_len (connection_indices) == 0)
172     return 0;
173
174   for (i = 0; i < vec_len (connection_indices); i++)
175     {
176       delete_session = 1;
177
178       sp = pool_elt_at_index (tm->sessions, connection_indices[i]);
179
180       if (sp->bytes_to_send > 0)
181         {
182           send_test_chunk (tm, sp);
183           delete_session = 0;
184         }
185       if (sp->bytes_to_receive > 0)
186         {
187           receive_test_chunk (tm, sp);
188           delete_session = 0;
189         }
190       if (PREDICT_FALSE (delete_session == 1))
191         {
192           __sync_fetch_and_add (&tm->rx_total, sp->bytes_received);
193           dmp = vl_msg_api_alloc_as_if_client (sizeof (*dmp));
194           memset (dmp, 0, sizeof (*dmp));
195           dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
196           dmp->client_index = tm->my_client_index;
197           dmp->handle = sp->vpp_session_handle;
198           vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & dmp);
199           vec_delete (connection_indices, 1, i);
200           tm->connection_index_by_thread[my_thread_index] =
201             connection_indices;
202           __sync_fetch_and_add (&tm->ready_connections, -1);
203
204           /* Kick the debug CLI process */
205           if (tm->ready_connections == 0)
206             {
207               tm->test_end_time = vlib_time_now (vm);
208               vlib_process_signal_event (vm, tm->cli_node_index,
209                                          2, 0 /* data */ );
210             }
211         }
212     }
213   return 0;
214 }
215
216 /* *INDENT-OFF* */
217 VLIB_REGISTER_NODE (builtin_client_node) =
218 {
219   .function = builtin_client_node_fn,
220   .name = "builtin-tcp-client",
221   .type = VLIB_NODE_TYPE_INPUT,
222   .state = VLIB_NODE_STATE_DISABLED,
223 };
224 /* *INDENT-ON* */
225
226
227 /* So we don't get "no handler for... " msgs */
228 static void
229 vl_api_memclnt_create_reply_t_handler (vl_api_memclnt_create_reply_t * mp)
230 {
231   vlib_main_t *vm = vlib_get_main ();
232   tclient_main_t *tm = &tclient_main;
233   tm->my_client_index = mp->index;
234   vlib_process_signal_event (vm, tm->node_index, 1 /* evt */ ,
235                              0 /* data */ );
236 }
237
238 static void
239 vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
240 {
241   tclient_main_t *tm = &tclient_main;
242   session_t *session;
243   u32 session_index;
244   i32 retval = /* clib_net_to_host_u32 ( */ mp->retval /*) */ ;
245   int i;
246
247   if (retval < 0)
248     {
249       clib_warning ("connection failed: retval %d", retval);
250       return;
251     }
252
253   tm->our_event_queue =
254     uword_to_pointer (mp->vpp_event_queue_address,
255                       unix_shared_memory_queue_t *);
256   tm->vpp_event_queue =
257     uword_to_pointer (mp->vpp_event_queue_address,
258                       unix_shared_memory_queue_t *);
259
260   /*
261    * Setup session
262    */
263   pool_get (tm->sessions, session);
264   memset (session, 0, sizeof (*session));
265   session_index = session - tm->sessions;
266   session->bytes_to_receive = session->bytes_to_send = tm->bytes_to_send;
267
268   session->server_rx_fifo =
269     uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
270   session->server_rx_fifo->client_session_index = session_index;
271   session->server_tx_fifo =
272     uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
273   session->server_tx_fifo->client_session_index = session_index;
274   session->vpp_session_handle = mp->handle;
275
276   /* Add it to the session lookup table */
277   hash_set (tm->session_index_by_vpp_handles, mp->handle, session_index);
278
279   if (tm->ready_connections == tm->expected_connections - 1)
280     {
281       vlib_thread_main_t *thread_main = vlib_get_thread_main ();
282       int thread_index;
283
284       thread_index = 0;
285       for (i = 0; i < pool_elts (tm->sessions); i++)
286         {
287           vec_add1 (tm->connection_index_by_thread[thread_index], i);
288           thread_index++;
289           if (thread_index == thread_main->n_vlib_mains)
290             thread_index = 0;
291         }
292     }
293   __sync_fetch_and_add (&tm->ready_connections, 1);
294   if (tm->ready_connections == tm->expected_connections)
295     {
296       tm->run_test = 1;
297       tm->test_start_time = vlib_time_now (tm->vlib_main);
298       /* Signal the CLI process that the action is starting... */
299       vlib_process_signal_event (tm->vlib_main, tm->cli_node_index,
300                                  1, 0 /* data */ );
301     }
302 }
303
304 static int
305 create_api_loopback (tclient_main_t * tm)
306 {
307   vlib_main_t *vm = vlib_get_main ();
308   vl_api_memclnt_create_t _m, *mp = &_m;
309   extern void vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t *);
310   api_main_t *am = &api_main;
311   vl_shmem_hdr_t *shmem_hdr;
312   uword *event_data = 0, event_type;
313   int resolved = 0;
314
315   /*
316    * Create a "loopback" API client connection
317    * Don't do things like this unless you know what you're doing...
318    */
319
320   shmem_hdr = am->shmem_hdr;
321   tm->vl_input_queue = shmem_hdr->vl_input_queue;
322   memset (mp, 0, sizeof (*mp));
323   mp->_vl_msg_id = VL_API_MEMCLNT_CREATE;
324   mp->context = 0xFEEDFACE;
325   mp->input_queue = pointer_to_uword (tm->vl_input_queue);
326   strncpy ((char *) mp->name, "tcp_tester", sizeof (mp->name) - 1);
327
328   vl_api_memclnt_create_t_handler (mp);
329
330   /* Wait for reply */
331   tm->node_index = vlib_get_current_process (vm)->node_runtime.node_index;
332   vlib_process_wait_for_event_or_clock (vm, 1.0);
333   event_type = vlib_process_get_events (vm, &event_data);
334   switch (event_type)
335     {
336     case 1:
337       resolved = 1;
338       break;
339     case ~0:
340       /* timed out */
341       break;
342     default:
343       clib_warning ("unknown event_type %d", event_type);
344     }
345   if (!resolved)
346     return -1;
347   return 0;
348 }
349
350 #define foreach_tclient_static_api_msg          \
351 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
352 _(CONNECT_URI_REPLY, connect_uri_reply)
353
354 static clib_error_t *
355 tclient_api_hookup (vlib_main_t * vm)
356 {
357   vl_msg_api_msg_config_t _c, *c = &_c;
358
359   /* Hook up client-side static APIs to our handlers */
360 #define _(N,n) do {                                             \
361     c->id = VL_API_##N;                                         \
362     c->name = #n;                                               \
363     c->handler = vl_api_##n##_t_handler;                        \
364     c->cleanup = vl_noop_handler;                               \
365     c->endian = vl_api_##n##_t_endian;                          \
366     c->print = vl_api_##n##_t_print;                            \
367     c->size = sizeof(vl_api_##n##_t);                           \
368     c->traced = 1; /* trace, so these msgs print */             \
369     c->replay = 0; /* don't replay client create/delete msgs */ \
370     c->message_bounce = 0; /* don't bounce this message */      \
371     vl_msg_api_config(c);} while (0);
372
373   foreach_tclient_static_api_msg;
374 #undef _
375
376   return 0;
377 }
378
379 static int
380 tcp_test_clients_init (vlib_main_t * vm)
381 {
382   tclient_main_t *tm = &tclient_main;
383   vlib_thread_main_t *thread_main = vlib_get_thread_main ();
384   int i;
385
386   tclient_api_hookup (vm);
387   if (create_api_loopback (tm))
388     return -1;
389
390   /* Init test data */
391   vec_validate (tm->connect_test_data, 64 * 1024 - 1);
392   for (i = 0; i < vec_len (tm->connect_test_data); i++)
393     tm->connect_test_data[i] = i & 0xff;
394
395   tm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
396   vec_validate (tm->rx_buf, vec_len (tm->connect_test_data) - 1);
397
398   tm->is_init = 1;
399   tm->vlib_main = vm;
400
401   vec_validate (tm->connection_index_by_thread, thread_main->n_vlib_mains);
402   return 0;
403 }
404
405 static int
406 builtin_session_connected_callback (u32 app_index, u32 api_context,
407                                     stream_session_t * s, u8 is_fail)
408 {
409   vl_api_connect_uri_reply_t _m, *mp = &_m;
410   unix_shared_memory_queue_t *q;
411   application_t *app;
412   unix_shared_memory_queue_t *vpp_queue;
413
414   app = application_get (app_index);
415   q = vl_api_client_index_to_input_queue (app->api_client_index);
416
417   if (!q)
418     return -1;
419
420   memset (mp, 0, sizeof (*mp));
421   mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_CONNECT_URI_REPLY);
422   mp->context = api_context;
423   if (!is_fail)
424     {
425       vpp_queue = session_manager_get_vpp_event_queue (s->thread_index);
426       mp->server_rx_fifo = pointer_to_uword (s->server_rx_fifo);
427       mp->server_tx_fifo = pointer_to_uword (s->server_tx_fifo);
428       mp->handle = stream_session_handle (s);
429       mp->vpp_event_queue_address = pointer_to_uword (vpp_queue);
430       mp->retval = 0;
431       s->session_state = SESSION_STATE_READY;
432     }
433   else
434     {
435       mp->retval = clib_host_to_net_u32 (VNET_API_ERROR_SESSION_CONNECT_FAIL);
436     }
437
438   vl_api_connect_uri_reply_t_handler (mp);
439
440   return 0;
441 }
442
443 static void
444 builtin_session_reset_callback (stream_session_t * s)
445 {
446   return;
447 }
448
449 static int
450 builtin_session_create_callback (stream_session_t * s)
451 {
452   return 0;
453 }
454
455 static void
456 builtin_session_disconnect_callback (stream_session_t * s)
457 {
458   return;
459 }
460
461 static int
462 builtin_server_rx_callback (stream_session_t * s)
463 {
464   return 0;
465 }
466
467 /* *INDENT-OFF* */
468 static session_cb_vft_t builtin_clients =
469   {
470     .session_reset_callback = builtin_session_reset_callback,
471     .session_connected_callback = builtin_session_connected_callback,
472     .session_accept_callback = builtin_session_create_callback,
473     .session_disconnect_callback = builtin_session_disconnect_callback,
474     .builtin_server_rx_callback = builtin_server_rx_callback
475   };
476 /* *INDENT-ON* */
477
478 static int
479 attach_builtin_test_clients ()
480 {
481   tclient_main_t *tm = &tclient_main;
482   vnet_app_attach_args_t _a, *a = &_a;
483   u8 segment_name[128];
484   u32 segment_name_length;
485   u64 options[16];
486
487   segment_name_length = ARRAY_LEN (segment_name);
488
489   memset (a, 0, sizeof (*a));
490   memset (options, 0, sizeof (options));
491
492   a->api_client_index = tm->my_client_index;
493   a->segment_name = segment_name;
494   a->segment_name_length = segment_name_length;
495   a->session_cb_vft = &builtin_clients;
496
497   options[SESSION_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
498   options[SESSION_OPTIONS_SEGMENT_SIZE] = (2 << 30);    /*$$$$ config / arg */
499   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_BUILTIN_APP;
500
501   a->options = options;
502
503   return vnet_application_attach (a);
504 }
505
506 static clib_error_t *
507 test_tcp_clients_command_fn (vlib_main_t * vm,
508                              unformat_input_t * input,
509                              vlib_cli_command_t * cmd)
510 {
511   tclient_main_t *tm = &tclient_main;
512   vlib_thread_main_t *thread_main = vlib_get_thread_main ();
513   uword *event_data = 0;
514   uword event_type;
515   u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234";
516   u8 *uri;
517   u32 n_clients = 1;
518   int i;
519   u64 tmp;
520   f64 cli_timeout = 20.0;
521   f64 delta;
522
523   tm->bytes_to_send = 8192;
524   vec_free (tm->connect_uri);
525
526   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
527     {
528       if (unformat (input, "nclients %d", &n_clients))
529         ;
530       else if (unformat (input, "mbytes %lld", &tmp))
531         tm->bytes_to_send = tmp << 20;
532       else if (unformat (input, "gbytes %lld", &tmp))
533         tm->bytes_to_send = tmp << 30;
534       else if (unformat (input, "bytes %lld", &tm->bytes_to_send))
535         ;
536       else if (unformat (input, "uri %s", &tm->connect_uri))
537         ;
538       else if (unformat (input, "cli-timeout %f", &cli_timeout))
539         ;
540       else
541         return clib_error_return (0, "unknown input `%U'",
542                                   format_unformat_error, input);
543     }
544
545   if (tm->is_init == 0)
546     {
547       if (tcp_test_clients_init (vm))
548         return clib_error_return (0, "failed init");
549     }
550
551   tm->ready_connections = 0;
552   tm->expected_connections = n_clients;
553   tm->rx_total = 0;
554
555   uri = connect_uri;
556   if (tm->connect_uri)
557     uri = tm->connect_uri;
558
559 #if TCP_BUILTIN_CLIENT_PTHREAD
560   /* Start a transmit thread */
561   if (tm->client_thread_handle == 0)
562     {
563       int rv = pthread_create (&tm->client_thread_handle,
564                                NULL /*attr */ ,
565                                tclient_thread_fn, 0);
566       if (rv)
567         {
568           tm->client_thread_handle = 0;
569           return clib_error_return (0, "pthread_create returned %d", rv);
570         }
571     }
572 #endif
573   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
574   if (tm->test_client_attached == 0)
575     attach_builtin_test_clients ();
576   tm->test_client_attached = 1;
577
578   /* Turn on the builtin client input nodes */
579   for (i = 0; i < thread_main->n_vlib_mains; i++)
580     vlib_node_set_state (vlib_mains[i], builtin_client_node.index,
581                          VLIB_NODE_STATE_POLLING);
582
583   tm->cli_node_index = vlib_get_current_process (vm)->node_runtime.node_index;
584
585   /* Fire off connect requests */
586   for (i = 0; i < n_clients; i++)
587     {
588       vl_api_connect_uri_t _cmp, *cmp = &_cmp;
589       void vl_api_connect_uri_t_handler (vl_api_connect_uri_t * cmp);
590
591       memset (cmp, 0, sizeof (*cmp));
592
593       cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
594       cmp->client_index = tm->my_client_index;
595       cmp->context = ntohl (0xfeedface);
596       memcpy (cmp->uri, uri, strlen ((char *) uri) + 1);
597
598       vl_api_connect_uri_t_handler (cmp);
599       /* Crude pacing for call setups, 100k/sec  */
600       vlib_process_suspend (vm, 10e-6);
601     }
602
603   /* Park until the sessions come up, or ten seconds elapse... */
604   vlib_process_wait_for_event_or_clock (vm, 10.0 /* timeout, seconds */ );
605   event_type = vlib_process_get_events (vm, &event_data);
606
607   switch (event_type)
608     {
609     case ~0:
610       vlib_cli_output (vm, "Timeout with only %d sessions active...",
611                        tm->ready_connections);
612       goto cleanup;
613
614     case 1:
615       vlib_cli_output (vm, "Test started at %.6f", tm->test_start_time);
616       break;
617
618     default:
619       vlib_cli_output (vm, "unexpected event(1): %d", event_type);
620       goto cleanup;
621     }
622
623   /* Now wait for the sessions to finish... */
624   vlib_process_wait_for_event_or_clock (vm, cli_timeout);
625   event_type = vlib_process_get_events (vm, &event_data);
626
627   switch (event_type)
628     {
629     case ~0:
630       vlib_cli_output (vm, "Timeout with %d sessions still active...",
631                        tm->ready_connections);
632       goto cleanup;
633
634     case 2:
635       vlib_cli_output (vm, "Test finished at %.6f", tm->test_end_time);
636       break;
637
638     default:
639       vlib_cli_output (vm, "unexpected event(2): %d", event_type);
640       goto cleanup;
641     }
642
643   delta = tm->test_end_time - tm->test_start_time;
644
645   if (delta != 0.0)
646     {
647       vlib_cli_output (vm,
648                        "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds",
649                        tm->rx_total, tm->rx_total / (1ULL << 20),
650                        tm->rx_total / (1ULL << 30), delta);
651       vlib_cli_output (vm, "%.2f bytes/second full-duplex",
652                        ((f64) tm->rx_total) / (delta));
653       vlib_cli_output (vm, "%.4f gbit/second full-duplex",
654                        (((f64) tm->rx_total * 8.0) / delta / 1e9));
655     }
656   else
657     vlib_cli_output (vm, "zero delta-t?");
658
659 cleanup:
660   pool_free (tm->sessions);
661   for (i = 0; i < vec_len (tm->connection_index_by_thread); i++)
662     vec_reset_length (tm->connection_index_by_thread[i]);
663
664   return 0;
665 }
666
667 /* *INDENT-OFF* */
668 VLIB_CLI_COMMAND (test_clients_command, static) =
669 {
670   .path = "test tcp clients",
671   .short_help = "test tcp clients [nclients %d]"
672   "[iterations %d] [bytes %d] [uri tcp://6.0.1.1/1234]",
673   .function = test_tcp_clients_command_fn,
674 };
675 /* *INDENT-ON* */
676
677 clib_error_t *
678 tcp_test_clients_main_init (vlib_main_t * vm)
679 {
680   tclient_main_t *tm = &tclient_main;
681   tm->is_init = 0;
682   return 0;
683 }
684
685 VLIB_INIT_FUNCTION (tcp_test_clients_main_init);
686
687 /*
688  * fd.io coding-style-patch-verification: ON
689  *
690  * Local Variables:
691  * eval: (c-set-style "gnu")
692  * End:
693  */