udp/session: refactor to support dgram mode
[vpp.git] / src / tests / vnet / session / udp_echo.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <stdio.h>
17 #include <setjmp.h>
18 #include <signal.h>
19 #include <vppinfra/clib.h>
20 #include <vppinfra/format.h>
21 #include <vppinfra/error.h>
22 #include <vppinfra/time.h>
23 #include <vppinfra/macros.h>
24 #include <vnet/vnet.h>
25 #include <vlib/vlib.h>
26 #include <vlib/unix/unix.h>
27 #include <vlibapi/api.h>
28 #include <vlibmemory/api.h>
29 #include <vpp/api/vpe_msg_enum.h>
30 #include <svm/svm_fifo_segment.h>
31 #include <pthread.h>
32 #include <vnet/session/application_interface.h>
33
34 #define vl_typedefs             /* define message structures */
35 #include <vpp/api/vpe_all_api_h.h>
36 #undef vl_typedefs
37
38 /* declare message handlers for each api */
39
40 #define vl_endianfun            /* define message structures */
41 #include <vpp/api/vpe_all_api_h.h>
42 #undef vl_endianfun
43
44 /* instantiate all the print functions we know about */
45 #define vl_print(handle, ...)
46 #define vl_printfun
47 #include <vpp/api/vpe_all_api_h.h>
48 #undef vl_printfun
49
50 typedef enum
51 {
52   STATE_START,
53   STATE_BOUND,
54   STATE_READY,
55   STATE_FAILED,
56   STATE_DISCONNECTING,
57 } connection_state_t;
58
59 typedef struct
60 {
61   /* vpe input queue */
62   svm_queue_t *vl_input_queue;
63
64   /* API client handle */
65   u32 my_client_index;
66
67   /* The URI we're playing with */
68   u8 *listen_uri;
69
70   /* URI for connect */
71   u8 *connect_uri;
72
73   /* Session pool */
74   app_session_t *sessions;
75
76   /* Hash table for disconnect processing */
77   uword *session_index_by_vpp_handles;
78
79   /* fifo segment */
80   svm_fifo_segment_private_t *seg;
81
82   /* intermediate rx buffer */
83   u8 *rx_buf;
84
85   u32 fifo_size;
86   int i_am_server;
87   u8 is_connected;
88
89   /* Our event queue */
90   svm_queue_t *our_event_queue;
91
92   /* $$$ single thread only for the moment */
93   svm_queue_t *vpp_event_queue;
94
95   /* $$$$ hack: cut-through session index */
96   volatile u32 cut_through_session_index;
97   volatile u32 connected_session;
98
99   /* unique segment name counter */
100   u32 unique_segment_index;
101
102   pid_t my_pid;
103
104   /* pthread handle */
105   pthread_t cut_through_thread_handle;
106
107   /* For deadman timers */
108   clib_time_t clib_time;
109
110   /* State of the connection, shared between msg RX thread and main thread */
111   volatile connection_state_t state;
112
113   volatile int time_to_stop;
114   volatile int time_to_print_stats;
115
116   u32 configured_segment_size;
117
118   /* VNET_API_ERROR_FOO -> "Foo" hash table */
119   uword *error_string_by_error_number;
120
121   /* convenience */
122   svm_fifo_segment_main_t *segment_main;
123
124   u8 *connect_test_data;
125
126   uword *segments_table;
127   u8 do_echo;
128 } udp_echo_main_t;
129
130 #if CLIB_DEBUG > 0
131 #define NITER 10000
132 #else
133 #define NITER 4000000
134 #endif
135
136 udp_echo_main_t udp_echo_main;
137
138 static void
139 stop_signal (int signum)
140 {
141   udp_echo_main_t *um = &udp_echo_main;
142
143   um->time_to_stop = 1;
144 }
145
146 static void
147 stats_signal (int signum)
148 {
149   udp_echo_main_t *um = &udp_echo_main;
150
151   um->time_to_print_stats = 1;
152 }
153
154 static clib_error_t *
155 setup_signal_handlers (void)
156 {
157   signal (SIGINT, stats_signal);
158   signal (SIGQUIT, stop_signal);
159   signal (SIGTERM, stop_signal);
160
161   return 0;
162 }
163
164 uword
165 unformat_ip4_address (unformat_input_t * input, va_list * args)
166 {
167   u8 *result = va_arg (*args, u8 *);
168   unsigned a[4];
169
170   if (!unformat (input, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]))
171     return 0;
172
173   if (a[0] >= 256 || a[1] >= 256 || a[2] >= 256 || a[3] >= 256)
174     return 0;
175
176   result[0] = a[0];
177   result[1] = a[1];
178   result[2] = a[2];
179   result[3] = a[3];
180
181   return 1;
182 }
183
184 uword
185 unformat_ip6_address (unformat_input_t * input, va_list * args)
186 {
187   ip6_address_t *result = va_arg (*args, ip6_address_t *);
188   u16 hex_quads[8];
189   uword hex_quad, n_hex_quads, hex_digit, n_hex_digits;
190   uword c, n_colon, double_colon_index;
191
192   n_hex_quads = hex_quad = n_hex_digits = n_colon = 0;
193   double_colon_index = ARRAY_LEN (hex_quads);
194   while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT)
195     {
196       hex_digit = 16;
197       if (c >= '0' && c <= '9')
198         hex_digit = c - '0';
199       else if (c >= 'a' && c <= 'f')
200         hex_digit = c + 10 - 'a';
201       else if (c >= 'A' && c <= 'F')
202         hex_digit = c + 10 - 'A';
203       else if (c == ':' && n_colon < 2)
204         n_colon++;
205       else
206         {
207           unformat_put_input (input);
208           break;
209         }
210
211       /* Too many hex quads. */
212       if (n_hex_quads >= ARRAY_LEN (hex_quads))
213         return 0;
214
215       if (hex_digit < 16)
216         {
217           hex_quad = (hex_quad << 4) | hex_digit;
218
219           /* Hex quad must fit in 16 bits. */
220           if (n_hex_digits >= 4)
221             return 0;
222
223           n_colon = 0;
224           n_hex_digits++;
225         }
226
227       /* Save position of :: */
228       if (n_colon == 2)
229         {
230           /* More than one :: ? */
231           if (double_colon_index < ARRAY_LEN (hex_quads))
232             return 0;
233           double_colon_index = n_hex_quads;
234         }
235
236       if (n_colon > 0 && n_hex_digits > 0)
237         {
238           hex_quads[n_hex_quads++] = hex_quad;
239           hex_quad = 0;
240           n_hex_digits = 0;
241         }
242     }
243
244   if (n_hex_digits > 0)
245     hex_quads[n_hex_quads++] = hex_quad;
246
247   {
248     word i;
249
250     /* Expand :: to appropriate number of zero hex quads. */
251     if (double_colon_index < ARRAY_LEN (hex_quads))
252       {
253         word n_zero = ARRAY_LEN (hex_quads) - n_hex_quads;
254
255         for (i = n_hex_quads - 1; i >= (signed) double_colon_index; i--)
256           hex_quads[n_zero + i] = hex_quads[i];
257
258         for (i = 0; i < n_zero; i++)
259           hex_quads[double_colon_index + i] = 0;
260
261         n_hex_quads = ARRAY_LEN (hex_quads);
262       }
263
264     /* Too few hex quads given. */
265     if (n_hex_quads < ARRAY_LEN (hex_quads))
266       return 0;
267
268     for (i = 0; i < ARRAY_LEN (hex_quads); i++)
269       result->as_u16[i] = clib_host_to_net_u16 (hex_quads[i]);
270
271     return 1;
272   }
273 }
274
275 uword
276 unformat_uri (unformat_input_t * input, va_list * args)
277 {
278   session_endpoint_extended_t *sep = va_arg (*args,
279                                              session_endpoint_extended_t *);
280   u32 port;
281   char *tmp;
282
283   if (unformat (input, "%s://%U/%d", &tmp, unformat_ip4_address, &sep->ip.ip4,
284                 &port))
285     {
286       sep->port = clib_host_to_net_u16 (port);
287       sep->is_ip4 = 1;
288       return 1;
289     }
290   else if (unformat (input, "%s://%U/%d", &tmp, unformat_ip6_address,
291                      &sep->ip.ip6, &port))
292     {
293       sep->port = clib_host_to_net_u16 (port);
294       sep->is_ip4 = 0;
295       return 1;
296     }
297   return 0;
298 }
299
300 void
301 application_send_attach (udp_echo_main_t * utm)
302 {
303   vl_api_application_attach_t *bmp;
304   bmp = vl_msg_api_alloc (sizeof (*bmp));
305   memset (bmp, 0, sizeof (*bmp));
306
307   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
308   bmp->client_index = utm->my_client_index;
309   bmp->context = ntohl (0xfeedface);
310   bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ADD_SEGMENT;
311   bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
312   bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
313   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 2;
314   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = utm->fifo_size;
315   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = utm->fifo_size;
316   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
317   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
318   bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 16768;
319   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
320 }
321
322 void
323 application_detach (udp_echo_main_t * utm)
324 {
325   vl_api_application_detach_t *bmp;
326   bmp = vl_msg_api_alloc (sizeof (*bmp));
327   memset (bmp, 0, sizeof (*bmp));
328
329   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
330   bmp->client_index = utm->my_client_index;
331   bmp->context = ntohl (0xfeedface);
332   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
333 }
334
335 static void
336 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
337                                            mp)
338 {
339   udp_echo_main_t *utm = &udp_echo_main;
340   svm_fifo_segment_create_args_t _a = { 0 }, *a = &_a;
341   int rv;
342
343   if (mp->retval)
344     {
345       clib_warning ("attach failed: %d", mp->retval);
346       utm->state = STATE_FAILED;
347       return;
348     }
349
350   if (mp->segment_name_length == 0)
351     {
352       clib_warning ("segment_name_length zero");
353       return;
354     }
355
356   a->segment_name = (char *) mp->segment_name;
357   a->segment_size = mp->segment_size;
358
359   ASSERT (mp->app_event_queue_address);
360
361   /* Attach to the segment vpp created */
362   rv = svm_fifo_segment_attach (a);
363   if (rv)
364     {
365       clib_warning ("svm_fifo_segment_attach ('%s') failed",
366                     mp->segment_name);
367       return;
368     }
369
370   utm->our_event_queue =
371     uword_to_pointer (mp->app_event_queue_address, svm_queue_t *);
372 }
373
374 static void
375 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
376                                            mp)
377 {
378   if (mp->retval)
379     clib_warning ("detach returned with err: %d", mp->retval);
380 }
381
382 u8 *
383 format_api_error (u8 * s, va_list * args)
384 {
385   udp_echo_main_t *utm = va_arg (*args, udp_echo_main_t *);
386   i32 error = va_arg (*args, u32);
387   uword *p;
388
389   p = hash_get (utm->error_string_by_error_number, -error);
390
391   if (p)
392     s = format (s, "%s", p[0]);
393   else
394     s = format (s, "%d", error);
395   return s;
396 }
397
398 int
399 wait_for_state_change (udp_echo_main_t * utm, connection_state_t state)
400 {
401 #if CLIB_DEBUG > 0
402 #define TIMEOUT 600.0
403 #else
404 #define TIMEOUT 600.0
405 #endif
406
407   f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
408
409   while (clib_time_now (&utm->clib_time) < timeout)
410     {
411       if (utm->state == state)
412         return 0;
413     }
414   return -1;
415 }
416
417 u64 server_bytes_received, server_bytes_sent;
418
419 static void *
420 cut_through_thread_fn (void *arg)
421 {
422   app_session_t *s;
423   svm_fifo_t *rx_fifo;
424   svm_fifo_t *tx_fifo;
425   u8 *my_copy_buffer = 0;
426   udp_echo_main_t *utm = &udp_echo_main;
427   i32 actual_transfer;
428   int rv;
429   u32 buffer_offset;
430
431   while (utm->cut_through_session_index == ~0)
432     ;
433
434   s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index);
435
436   rx_fifo = s->rx_fifo;
437   tx_fifo = s->tx_fifo;
438
439   vec_validate (my_copy_buffer, 64 * 1024 - 1);
440
441   while (true)
442     {
443       /* We read from the tx fifo and write to the rx fifo */
444       do
445         {
446           actual_transfer = svm_fifo_dequeue_nowait (rx_fifo,
447                                                      vec_len (my_copy_buffer),
448                                                      my_copy_buffer);
449         }
450       while (actual_transfer <= 0);
451
452       server_bytes_received += actual_transfer;
453
454       buffer_offset = 0;
455       while (actual_transfer > 0)
456         {
457           rv = svm_fifo_enqueue_nowait (tx_fifo, actual_transfer,
458                                         my_copy_buffer + buffer_offset);
459           if (rv > 0)
460             {
461               actual_transfer -= rv;
462               buffer_offset += rv;
463               server_bytes_sent += rv;
464             }
465
466         }
467       if (PREDICT_FALSE (utm->time_to_stop))
468         break;
469     }
470
471   pthread_exit (0);
472 }
473
474 static void
475 udp_client_connect (udp_echo_main_t * utm)
476 {
477   vl_api_connect_uri_t *cmp;
478   cmp = vl_msg_api_alloc (sizeof (*cmp));
479   memset (cmp, 0, sizeof (*cmp));
480
481   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
482   cmp->client_index = utm->my_client_index;
483   cmp->context = ntohl (0xfeedface);
484   memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
485   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
486 }
487
488 static void
489 client_send_cut_through (udp_echo_main_t * utm, app_session_t * session)
490 {
491   int i;
492   u8 *test_data = 0;
493   u64 bytes_received = 0, bytes_sent = 0;
494   i32 bytes_to_read;
495   int rv;
496   f64 before, after, delta, bytes_per_second;
497   svm_fifo_t *rx_fifo, *tx_fifo;
498   int buffer_offset, bytes_to_send = 0;
499
500   /*
501    * Prepare test data
502    */
503   vec_validate (test_data, 64 * 1024 - 1);
504   for (i = 0; i < vec_len (test_data); i++)
505     test_data[i] = i & 0xff;
506
507   rx_fifo = session->rx_fifo;
508   tx_fifo = session->tx_fifo;
509
510   before = clib_time_now (&utm->clib_time);
511
512   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
513
514   for (i = 0; i < NITER; i++)
515     {
516       bytes_to_send = vec_len (test_data);
517       buffer_offset = 0;
518       while (bytes_to_send > 0)
519         {
520           rv = svm_fifo_enqueue_nowait (tx_fifo, bytes_to_send,
521                                         test_data + buffer_offset);
522
523           if (rv > 0)
524             {
525               bytes_to_send -= rv;
526               buffer_offset += rv;
527               bytes_sent += rv;
528             }
529         }
530
531       bytes_to_read = svm_fifo_max_dequeue (rx_fifo);
532       bytes_to_read = vec_len (utm->rx_buf) > bytes_to_read ?
533         bytes_to_read : vec_len (utm->rx_buf);
534
535       buffer_offset = 0;
536       while (bytes_to_read > 0)
537         {
538           rv = svm_fifo_dequeue_nowait (rx_fifo,
539                                         bytes_to_read,
540                                         utm->rx_buf + buffer_offset);
541           if (rv > 0)
542             {
543               bytes_to_read -= rv;
544               buffer_offset += rv;
545               bytes_received += rv;
546             }
547         }
548     }
549   while (bytes_received < bytes_sent)
550     {
551       rv =
552         svm_fifo_dequeue_nowait (rx_fifo, vec_len (utm->rx_buf), utm->rx_buf);
553       if (rv > 0)
554         {
555 #if CLIB_DEBUG > 0
556           int j;
557           for (j = 0; j < rv; j++)
558             {
559               if (utm->rx_buf[j] != ((bytes_received + j) & 0xff))
560                 {
561                   clib_warning ("error at byte %lld, 0x%x not 0x%x",
562                                 bytes_received + j,
563                                 utm->rx_buf[j],
564                                 ((bytes_received + j) & 0xff));
565                 }
566             }
567 #endif
568           bytes_received += (u64) rv;
569         }
570     }
571
572   after = clib_time_now (&utm->clib_time);
573   delta = after - before;
574   bytes_per_second = 0.0;
575
576   if (delta > 0.0)
577     bytes_per_second = (f64) bytes_received / delta;
578
579   fformat (stdout,
580            "Done: %lld recv bytes in %.2f seconds, %.2f bytes/sec...\n\n",
581            bytes_received, delta, bytes_per_second);
582   fformat (stdout,
583            "Done: %lld sent bytes in %.2f seconds, %.2f bytes/sec...\n\n",
584            bytes_sent, delta, bytes_per_second);
585   fformat (stdout,
586            "client -> server -> client round trip: %.2f Gbit/sec \n\n",
587            (bytes_per_second * 8.0) / 1e9);
588 }
589
590 static void
591 send_test_chunk (udp_echo_main_t * utm, app_session_t * s, u32 bytes)
592 {
593   u8 *test_data = utm->connect_test_data;
594   int test_buf_offset = 0;
595   u64 bytes_sent = 0;
596   u32 bytes_to_snd;
597   int rv;
598
599   bytes_to_snd = (bytes == 0) ? vec_len (test_data) : bytes;
600   if (bytes_to_snd > vec_len (test_data))
601     bytes_to_snd = vec_len (test_data);
602
603   while (bytes_to_snd > 0 && !utm->time_to_stop)
604     {
605       rv = app_send (s, test_data + test_buf_offset, bytes_to_snd, 0);
606       if (rv > 0)
607         {
608           bytes_to_snd -= rv;
609           test_buf_offset += rv;
610           bytes_sent += rv;
611         }
612     }
613 }
614
615 static void
616 recv_test_chunk (udp_echo_main_t * utm, app_session_t * s)
617 {
618   app_recv (s, utm->rx_buf, vec_len (utm->rx_buf));
619 }
620
621 void
622 client_send_data (udp_echo_main_t * utm)
623 {
624   u8 *test_data;
625   app_session_t *session;
626   u32 n_iterations;
627   int i;
628
629   vec_validate (utm->connect_test_data, 64 * 1024 - 1);
630   for (i = 0; i < vec_len (utm->connect_test_data); i++)
631     utm->connect_test_data[i] = i & 0xff;
632
633   test_data = utm->connect_test_data;
634   session = pool_elt_at_index (utm->sessions, utm->connected_session);
635   ASSERT (vec_len (test_data) > 0);
636
637   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
638   n_iterations = NITER;
639
640   for (i = 0; i < n_iterations; i++)
641     {
642       send_test_chunk (utm, session, 0);
643       recv_test_chunk (utm, session);
644       if (utm->time_to_stop)
645         break;
646     }
647
648   f64 timeout = clib_time_now (&utm->clib_time) + 5;
649   while (clib_time_now (&utm->clib_time) < timeout)
650     {
651       recv_test_chunk (utm, session);
652     }
653
654 }
655
656 static void
657 client_test (udp_echo_main_t * utm)
658 {
659   app_session_t *session;
660
661   application_send_attach (utm);
662   udp_client_connect (utm);
663
664   if (wait_for_state_change (utm, STATE_READY))
665     {
666       clib_warning ("timeout waiting for STATE_READY");
667       return;
668     }
669
670   if (utm->cut_through_session_index != ~0)
671     {
672       session = pool_elt_at_index (utm->sessions,
673                                    utm->cut_through_session_index);
674       client_send_cut_through (utm, session);
675     }
676   else
677     {
678       session = pool_elt_at_index (utm->sessions, utm->connected_session);
679       client_send_data (utm);
680     }
681
682   application_detach (utm);
683 }
684
685 static void
686 vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
687 {
688   udp_echo_main_t *utm = &udp_echo_main;
689   svm_fifo_t *rx_fifo, *tx_fifo;
690   app_session_t *session;
691   u32 session_index;
692
693   if (mp->retval)
694     {
695       clib_warning ("bind failed: %d", mp->retval);
696       utm->state = STATE_FAILED;
697       return;
698     }
699
700   rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *);
701   tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *);
702
703   pool_get (utm->sessions, session);
704   memset (session, 0, sizeof (*session));
705   session_index = session - utm->sessions;
706
707   rx_fifo->client_session_index = session_index;
708   tx_fifo->client_session_index = session_index;
709   session->rx_fifo = rx_fifo;
710   session->tx_fifo = tx_fifo;
711   clib_memcpy (&session->transport.lcl_ip, mp->lcl_ip,
712                sizeof (ip46_address_t));
713   session->transport.is_ip4 = mp->lcl_is_ip4;
714   session->transport.lcl_port = mp->lcl_port;
715   session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_queue_t *);
716
717   utm->state = utm->is_connected ? STATE_BOUND : STATE_READY;
718 }
719
720 static void
721 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
722 {
723   udp_echo_main_t *utm = &udp_echo_main;
724   svm_fifo_segment_create_args_t _a, *a = &_a;
725   svm_fifo_segment_private_t *seg;
726   u8 *seg_name;
727   int rv;
728
729   memset (a, 0, sizeof (*a));
730   a->segment_name = (char *) mp->segment_name;
731   a->segment_size = mp->segment_size;
732   /* Attach to the segment vpp created */
733   rv = svm_fifo_segment_attach (a);
734   if (rv)
735     {
736       clib_warning ("svm_fifo_segment_attach ('%s') failed",
737                     mp->segment_name);
738       return;
739     }
740   seg = svm_fifo_segment_get_segment (a->new_segment_indices[0]);
741   clib_warning ("Mapped new segment '%s' size %d", seg->ssvm.name,
742                 seg->ssvm.ssvm_size);
743   seg_name = format (0, "%s", (char *) mp->segment_name);
744   hash_set_mem (utm->segments_table, seg_name, a->new_segment_indices[0]);
745   vec_free (seg_name);
746 }
747
748 static void
749 vl_api_unmap_segment_t_handler (vl_api_unmap_segment_t * mp)
750 {
751   udp_echo_main_t *utm = &udp_echo_main;
752   svm_fifo_segment_private_t *seg;
753   u64 *seg_indexp;
754   u8 *seg_name;
755
756
757   seg_name = format (0, "%s", mp->segment_name);
758   seg_indexp = hash_get_mem (utm->segments_table, seg_name);
759   if (!seg_indexp)
760     {
761       clib_warning ("segment not mapped: %s", seg_name);
762       return;
763     }
764   hash_unset_mem (utm->segments_table, seg_name);
765   seg = svm_fifo_segment_get_segment ((u32) seg_indexp[0]);
766   svm_fifo_segment_delete (seg);
767   clib_warning ("Unmapped segment '%s'", seg_name);
768   vec_free (seg_name);
769 }
770
771 /**
772  * Acting as server for redirected connect requests
773  */
774 static void
775 vl_api_connect_uri_t_handler (vl_api_connect_uri_t * mp)
776 {
777   u32 segment_index;
778   udp_echo_main_t *utm = &udp_echo_main;
779   svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
780   svm_fifo_segment_create_args_t _a, *a = &_a;
781   svm_fifo_segment_private_t *seg;
782   svm_queue_t *client_q;
783   vl_api_connect_session_reply_t *rmp;
784   app_session_t *session = 0;
785   int rv = 0;
786
787   /* Create the segment */
788   a->segment_name = (char *) format (0, "%d:segment%d%c", utm->my_pid,
789                                      utm->unique_segment_index++, 0);
790   a->segment_size = utm->configured_segment_size;
791
792   rv = svm_fifo_segment_create (a);
793   if (rv)
794     {
795       clib_warning ("sm_fifo_segment_create ('%s') failed", a->segment_name);
796       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
797       goto send_reply;
798     }
799
800   vec_add2 (utm->seg, seg, 1);
801
802   segment_index = vec_len (sm->segments) - 1;
803   memcpy (seg, sm->segments + segment_index, sizeof (utm->seg[0]));
804
805   pool_get (utm->sessions, session);
806
807   session->rx_fifo = svm_fifo_segment_alloc_fifo
808     (utm->seg, 128 * 1024, FIFO_SEGMENT_RX_FREELIST);
809   ASSERT (session->rx_fifo);
810
811   session->tx_fifo = svm_fifo_segment_alloc_fifo
812     (utm->seg, 128 * 1024, FIFO_SEGMENT_TX_FREELIST);
813   ASSERT (session->tx_fifo);
814
815   session->rx_fifo->master_session_index = session - utm->sessions;
816   session->tx_fifo->master_session_index = session - utm->sessions;
817   utm->cut_through_session_index = session - utm->sessions;
818
819   rv = pthread_create (&utm->cut_through_thread_handle,
820                        NULL /*attr */ , cut_through_thread_fn, 0);
821   if (rv)
822     {
823       clib_warning ("pthread_create returned %d", rv);
824       rv = VNET_API_ERROR_SYSCALL_ERROR_1;
825     }
826
827 send_reply:
828   rmp = vl_msg_api_alloc (sizeof (*rmp));
829   memset (rmp, 0, sizeof (*rmp));
830
831   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SESSION_REPLY);
832   rmp->context = mp->context;
833   rmp->retval = ntohl (rv);
834   rmp->segment_name_length = vec_len (a->segment_name);
835   if (session)
836     {
837       rmp->server_rx_fifo = pointer_to_uword (session->rx_fifo);
838       rmp->server_tx_fifo = pointer_to_uword (session->tx_fifo);
839     }
840
841   memcpy (rmp->segment_name, a->segment_name, vec_len (a->segment_name));
842
843   vec_free (a->segment_name);
844
845   client_q = uword_to_pointer (mp->client_queue_address, svm_queue_t *);
846   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
847 }
848
849 static void
850 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
851 {
852   udp_echo_main_t *utm = &udp_echo_main;
853
854   if (mp->retval != 0)
855     clib_warning ("returned %d", ntohl (mp->retval));
856
857   utm->state = STATE_START;
858 }
859
860 static void
861 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
862 {
863   udp_echo_main_t *utm = &udp_echo_main;
864   vl_api_accept_session_reply_t *rmp;
865   svm_fifo_t *rx_fifo, *tx_fifo;
866   app_session_t *session;
867   static f64 start_time;
868   u32 session_index;
869   int rv = 0;
870
871   if (start_time == 0.0)
872     start_time = clib_time_now (&utm->clib_time);
873
874   utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
875                                            svm_queue_t *);
876   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
877   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
878
879   pool_get (utm->sessions, session);
880   memset (session, 0, sizeof (*session));
881   session_index = session - utm->sessions;
882
883   /* Cut-through case */
884   if (mp->server_event_queue_address)
885     {
886       clib_warning ("cut-through session");
887       utm->our_event_queue = uword_to_pointer (mp->server_event_queue_address,
888                                                svm_queue_t *);
889       rx_fifo->master_session_index = session_index;
890       tx_fifo->master_session_index = session_index;
891       utm->cut_through_session_index = session_index;
892       session->rx_fifo = rx_fifo;
893       session->tx_fifo = tx_fifo;
894
895       rv = pthread_create (&utm->cut_through_thread_handle,
896                            NULL /*attr */ , cut_through_thread_fn, 0);
897       if (rv)
898         {
899           clib_warning ("pthread_create returned %d", rv);
900           rv = VNET_API_ERROR_SYSCALL_ERROR_1;
901         }
902       utm->do_echo = 1;
903     }
904   else
905     {
906       rx_fifo->client_session_index = session_index;
907       tx_fifo->client_session_index = session_index;
908       session->rx_fifo = rx_fifo;
909       session->tx_fifo = tx_fifo;
910       clib_memcpy (&session->transport.rmt_ip, mp->ip,
911                    sizeof (ip46_address_t));
912       session->transport.is_ip4 = mp->is_ip4;
913       session->transport.rmt_port = mp->port;
914     }
915
916   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
917   if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
918     {
919       f64 now = clib_time_now (&utm->clib_time);
920       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
921                pool_elts (utm->sessions), now - start_time,
922                (f64) pool_elts (utm->sessions) / (now - start_time));
923     }
924
925   rmp = vl_msg_api_alloc (sizeof (*rmp));
926   memset (rmp, 0, sizeof (*rmp));
927   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
928   rmp->handle = mp->handle;
929   rmp->context = mp->context;
930   rmp->retval = rv;
931   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
932
933   CLIB_MEMORY_BARRIER ();
934   utm->state = STATE_READY;
935 }
936
937 static void
938 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
939 {
940   udp_echo_main_t *utm = &udp_echo_main;
941   app_session_t *session;
942   vl_api_disconnect_session_reply_t *rmp;
943   uword *p;
944   int rv = 0;
945
946   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
947
948   if (p)
949     {
950       session = pool_elt_at_index (utm->sessions, p[0]);
951       hash_unset (utm->session_index_by_vpp_handles, mp->handle);
952       pool_put (utm->sessions, session);
953     }
954   else
955     {
956       clib_warning ("couldn't find session key %llx", mp->handle);
957       rv = -11;
958     }
959
960   rmp = vl_msg_api_alloc (sizeof (*rmp));
961   memset (rmp, 0, sizeof (*rmp));
962   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
963   rmp->retval = rv;
964   rmp->handle = mp->handle;
965   rmp->context = mp->context;
966   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
967 }
968
969 static void
970 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
971 {
972   udp_echo_main_t *utm = &udp_echo_main;
973   unformat_input_t _input, *input = &_input;
974   session_endpoint_extended_t _sep, *sep = &_sep;
975   app_session_t *session;
976
977   ASSERT (utm->i_am_server == 0);
978
979   if (mp->retval)
980     {
981       clib_warning ("failed connect");
982       return;
983     }
984
985   ASSERT (mp->server_rx_fifo && mp->server_tx_fifo);
986
987   pool_get (utm->sessions, session);
988   session->rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
989   session->tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
990   session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
991                                          svm_queue_t *);
992   /* Cut-through case */
993   if (mp->client_event_queue_address)
994     {
995       clib_warning ("cut-through session");
996       utm->cut_through_session_index = session - utm->sessions;
997       utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
998                                                svm_queue_t *);
999       utm->our_event_queue = uword_to_pointer (mp->client_event_queue_address,
1000                                                svm_queue_t *);
1001       utm->do_echo = 1;
1002     }
1003   else
1004     {
1005       utm->connected_session = session - utm->sessions;
1006       utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
1007                                                svm_queue_t *);
1008
1009       clib_memcpy (&session->transport.lcl_ip, mp->lcl_ip,
1010                    sizeof (ip46_address_t));
1011       session->transport.is_ip4 = mp->is_ip4;
1012       session->transport.lcl_port = mp->lcl_port;
1013
1014       unformat_init_vector (input, utm->connect_uri);
1015       if (!unformat (input, "%U", unformat_uri, sep))
1016         {
1017           clib_warning ("can't figure out remote ip and port");
1018           utm->state = STATE_FAILED;
1019           unformat_free (input);
1020           return;
1021         }
1022       unformat_free (input);
1023       clib_memcpy (&session->transport.rmt_ip, &sep->ip,
1024                    sizeof (ip46_address_t));
1025       session->transport.rmt_port = sep->port;
1026       session->is_dgram = !utm->is_connected;
1027     }
1028   utm->state = STATE_READY;
1029 }
1030
1031 #define foreach_tcp_echo_msg                            \
1032 _(BIND_URI_REPLY, bind_uri_reply)                       \
1033 _(CONNECT_URI, connect_uri)                             \
1034 _(CONNECT_SESSION_REPLY, connect_session_reply)         \
1035 _(UNBIND_URI_REPLY, unbind_uri_reply)                   \
1036 _(ACCEPT_SESSION, accept_session)                       \
1037 _(DISCONNECT_SESSION, disconnect_session)               \
1038 _(MAP_ANOTHER_SEGMENT, map_another_segment)             \
1039 _(UNMAP_SEGMENT, unmap_segment)                         \
1040 _(APPLICATION_ATTACH_REPLY, application_attach_reply)   \
1041 _(APPLICATION_DETACH_REPLY, application_detach_reply)   \
1042
1043 void
1044 tcp_echo_api_hookup (udp_echo_main_t * utm)
1045 {
1046 #define _(N,n)                                                  \
1047     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1048                            vl_api_##n##_t_handler,              \
1049                            vl_noop_handler,                     \
1050                            vl_api_##n##_t_endian,               \
1051                            vl_api_##n##_t_print,                \
1052                            sizeof(vl_api_##n##_t), 1);
1053   foreach_tcp_echo_msg;
1054 #undef _
1055
1056 }
1057
1058 int
1059 connect_to_vpp (char *name)
1060 {
1061   udp_echo_main_t *utm = &udp_echo_main;
1062   api_main_t *am = &api_main;
1063
1064   if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
1065     return -1;
1066
1067   utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
1068   utm->my_client_index = am->my_client_index;
1069
1070   return 0;
1071 }
1072
1073 void
1074 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
1075 {
1076   clib_warning ("BUG");
1077 }
1078
1079 static void
1080 init_error_string_table (udp_echo_main_t * utm)
1081 {
1082   utm->error_string_by_error_number = hash_create (0, sizeof (uword));
1083
1084 #define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
1085   foreach_vnet_api_error;
1086 #undef _
1087
1088   hash_set (utm->error_string_by_error_number, 99, "Misc");
1089 }
1090
1091 void
1092 server_handle_fifo_event_rx (udp_echo_main_t * utm, session_fifo_event_t * e)
1093 {
1094   app_session_t *s;
1095   int rv;
1096
1097   s = pool_elt_at_index (utm->sessions, e->fifo->client_session_index);
1098   app_recv (s, utm->rx_buf, vec_len (utm->rx_buf));
1099
1100   if (utm->do_echo)
1101     {
1102       do
1103         {
1104           rv = app_send_stream (s, utm->rx_buf, vec_len (utm->rx_buf), 0);
1105         }
1106       while (rv == SVM_FIFO_FULL);
1107     }
1108 }
1109
1110 void
1111 server_handle_event_queue (udp_echo_main_t * utm)
1112 {
1113   session_fifo_event_t _e, *e = &_e;
1114
1115   while (utm->state != STATE_READY)
1116     sleep (5);
1117
1118   while (1)
1119     {
1120       svm_queue_sub (utm->our_event_queue, (u8 *) e, SVM_Q_WAIT, 0);
1121       switch (e->event_type)
1122         {
1123         case FIFO_EVENT_APP_RX:
1124           server_handle_fifo_event_rx (utm, e);
1125           break;
1126
1127         case FIFO_EVENT_DISCONNECT:
1128           return;
1129
1130         default:
1131           clib_warning ("unknown event type %d", e->event_type);
1132           break;
1133         }
1134       if (PREDICT_FALSE (utm->time_to_stop == 1))
1135         return;
1136       if (PREDICT_FALSE (utm->time_to_print_stats == 1))
1137         {
1138           utm->time_to_print_stats = 0;
1139           fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
1140         }
1141     }
1142 }
1143
1144 static void
1145 server_unbind (udp_echo_main_t * utm)
1146 {
1147   vl_api_unbind_uri_t *ump;
1148
1149   ump = vl_msg_api_alloc (sizeof (*ump));
1150   memset (ump, 0, sizeof (*ump));
1151
1152   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1153   ump->client_index = utm->my_client_index;
1154   memcpy (ump->uri, utm->listen_uri, vec_len (utm->listen_uri));
1155   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
1156 }
1157
1158 static void
1159 server_bind (udp_echo_main_t * utm)
1160 {
1161   vl_api_bind_uri_t *bmp;
1162
1163   bmp = vl_msg_api_alloc (sizeof (*bmp));
1164   memset (bmp, 0, sizeof (*bmp));
1165
1166   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1167   bmp->client_index = utm->my_client_index;
1168   bmp->context = ntohl (0xfeedface);
1169   memcpy (bmp->uri, utm->listen_uri, vec_len (utm->listen_uri));
1170   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
1171 }
1172
1173 void
1174 udp_server_test (udp_echo_main_t * utm)
1175 {
1176   u8 wait_for_state = utm->is_connected ? STATE_BOUND : STATE_READY;
1177   application_send_attach (utm);
1178
1179   /* Bind to uri */
1180   server_bind (utm);
1181
1182   if (wait_for_state_change (utm, wait_for_state))
1183     {
1184       clib_warning ("timeout waiting for state change");
1185       return;
1186     }
1187
1188   server_handle_event_queue (utm);
1189
1190   /* Cleanup */
1191   server_unbind (utm);
1192
1193   if (wait_for_state_change (utm, STATE_START))
1194     {
1195       clib_warning ("timeout waiting for STATE_START");
1196       return;
1197     }
1198
1199   application_detach (utm);
1200
1201   fformat (stdout, "Test complete...\n");
1202 }
1203
1204 int
1205 main (int argc, char **argv)
1206 {
1207   udp_echo_main_t *utm = &udp_echo_main;
1208   u8 *uri = (u8 *) "udp://0.0.0.0/1234";
1209   unformat_input_t _argv, *a = &_argv;
1210   int i_am_server = 1;
1211   app_session_t *session;
1212   u8 *chroot_prefix;
1213   char *app_name;
1214   mheap_t *h;
1215   u8 *heap;
1216   u32 tmp;
1217   int i;
1218
1219   clib_mem_init (0, 256 << 20);
1220
1221   heap = clib_mem_get_per_cpu_heap ();
1222   h = mheap_header (heap);
1223
1224   /* make the main heap thread-safe */
1225   h->flags |= MHEAP_FLAG_THREAD_SAFE;
1226
1227   vec_validate (utm->rx_buf, 8192);
1228
1229   utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1230   utm->my_pid = getpid ();
1231   utm->configured_segment_size = 1 << 20;
1232   utm->segments_table = hash_create_vec (0, sizeof (u8), sizeof (u64));
1233
1234   clib_time_init (&utm->clib_time);
1235   init_error_string_table (utm);
1236   svm_fifo_segment_main_init (0x200000000ULL, 20);
1237   unformat_init_command_line (a, argv);
1238
1239   utm->fifo_size = 128 << 10;
1240
1241   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1242     {
1243       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1244         {
1245           vl_set_memory_root_path ((char *) chroot_prefix);
1246         }
1247       else if (unformat (a, "uri %s", &uri))
1248         ;
1249       else if (unformat (a, "segment-size %dM", &tmp))
1250         utm->configured_segment_size = tmp << 20;
1251       else if (unformat (a, "segment-size %dG", &tmp))
1252         utm->configured_segment_size = tmp << 30;
1253       else if (unformat (a, "server"))
1254         i_am_server = 1;
1255       else if (unformat (a, "client"))
1256         i_am_server = 0;
1257       else
1258         {
1259           fformat (stderr, "%s: usage [server|client]\n");
1260           exit (1);
1261         }
1262     }
1263
1264   utm->cut_through_session_index = ~0;
1265   utm->i_am_server = i_am_server;
1266   utm->segment_main = &svm_fifo_segment_main;
1267
1268   setup_signal_handlers ();
1269   tcp_echo_api_hookup (utm);
1270
1271   if (i_am_server)
1272     {
1273       utm->listen_uri = format (0, "%s%c", uri, 0);
1274       utm->is_connected = (utm->listen_uri[4] == 'c');
1275       app_name = "udp_echo_server";
1276     }
1277   else
1278     {
1279       app_name = "udp_echo_client";
1280       utm->connect_uri = format (0, "%s%c", uri, 0);
1281       utm->is_connected = (utm->connect_uri[4] == 'c');
1282     }
1283   if (connect_to_vpp (app_name) < 0)
1284     {
1285       svm_region_exit ();
1286       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1287       exit (1);
1288     }
1289
1290   if (i_am_server == 0)
1291     {
1292       client_test (utm);
1293       exit (0);
1294     }
1295
1296   /* $$$$ hack preallocation */
1297   for (i = 0; i < 200000; i++)
1298     {
1299       pool_get (utm->sessions, session);
1300       memset (session, 0, sizeof (*session));
1301     }
1302   for (i = 0; i < 200000; i++)
1303     pool_put_index (utm->sessions, i);
1304
1305   udp_server_test (utm);
1306
1307   vl_client_disconnect_from_vlib ();
1308   exit (0);
1309 }
1310
1311 #undef vl_api_version
1312 #define vl_api_version(n,v) static u32 vpe_api_version = v;
1313 #include <vpp/api/vpe.api.h>
1314 #undef vl_api_version
1315
1316 void
1317 vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
1318 {
1319   /*
1320    * Send the main API signature in slot 0. This bit of code must
1321    * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
1322    */
1323   mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
1324 }
1325
1326 u32
1327 vl (void *p)
1328 {
1329   return vec_len (p);
1330 }
1331
1332 /*
1333  * fd.io coding-style-patch-verification: ON
1334  *
1335  * Local Variables:
1336  * eval: (c-set-style "gnu")
1337  * End:
1338  */