udp_echo: fix cut-through server 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_ATTACHED,
54   STATE_BOUND,
55   STATE_READY,
56   STATE_FAILED,
57   STATE_DISCONNECTING,
58   STATE_DETACHED
59 } connection_state_t;
60
61 typedef struct
62 {
63   /* vpe input queue */
64   svm_queue_t *vl_input_queue;
65
66   /* API client handle */
67   u32 my_client_index;
68
69   /* The URI we're playing with */
70   u8 *listen_uri;
71
72   /* URI for connect */
73   u8 *connect_uri;
74
75   /* Session pool */
76   app_session_t *sessions;
77
78   /* Hash table for disconnect processing */
79   uword *session_index_by_vpp_handles;
80
81   /* fifo segment */
82   svm_fifo_segment_private_t *seg;
83
84   /* intermediate rx buffer */
85   u8 *rx_buf;
86
87   u32 fifo_size;
88   int i_am_server;
89   u8 is_connected;
90
91   /* Our event queue */
92   svm_msg_q_t *our_event_queue;
93   svm_msg_q_t *ct_event_queue;
94
95   /* $$$ single thread only for the moment */
96   svm_msg_q_t *vpp_event_queue;
97
98   /* $$$$ hack: cut-through session index */
99   volatile u32 cut_through_session_index;
100   volatile u32 connected_session;
101
102   /* unique segment name counter */
103   u32 unique_segment_index;
104
105   pid_t my_pid;
106
107   /* pthread handle */
108   pthread_t cut_through_thread_handle;
109
110   /* For deadman timers */
111   clib_time_t clib_time;
112
113   /* State of the connection, shared between msg RX thread and main thread */
114   volatile connection_state_t state;
115
116   volatile int time_to_stop;
117   volatile int time_to_print_stats;
118
119   u32 configured_segment_size;
120
121   /* VNET_API_ERROR_FOO -> "Foo" hash table */
122   uword *error_string_by_error_number;
123
124   /* convenience */
125   svm_fifo_segment_main_t *segment_main;
126
127   u8 *connect_test_data;
128
129   uword *segments_table;
130   u8 do_echo;
131   u8 have_return;
132   u64 total_to_send;
133   u64 bytes_to_send;
134   u64 bytes_sent;
135 } udp_echo_main_t;
136
137 udp_echo_main_t udp_echo_main;
138
139 static void
140 stop_signal (int signum)
141 {
142   udp_echo_main_t *um = &udp_echo_main;
143
144   um->time_to_stop = 1;
145 }
146
147 static void
148 stats_signal (int signum)
149 {
150   udp_echo_main_t *um = &udp_echo_main;
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 static 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_FLAGS] |= APP_OPTIONS_FLAGS_USE_MQ_FOR_CTRL_MSGS;
314   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 2;
315   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = utm->fifo_size;
316   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = utm->fifo_size;
317   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
318   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
319   bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 16768;
320   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
321 }
322
323 void
324 application_detach (udp_echo_main_t * utm)
325 {
326   vl_api_application_detach_t *bmp;
327   bmp = vl_msg_api_alloc (sizeof (*bmp));
328   memset (bmp, 0, sizeof (*bmp));
329
330   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
331   bmp->client_index = utm->my_client_index;
332   bmp->context = ntohl (0xfeedface);
333   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
334 }
335
336 static void
337 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
338                                            mp)
339 {
340   udp_echo_main_t *utm = &udp_echo_main;
341   svm_fifo_segment_create_args_t _a = { 0 }, *a = &_a;
342   int rv;
343
344   if (mp->retval)
345     {
346       clib_warning ("attach failed: %d", mp->retval);
347       utm->state = STATE_FAILED;
348       return;
349     }
350
351   if (mp->segment_name_length == 0)
352     {
353       clib_warning ("segment_name_length zero");
354       return;
355     }
356
357   a->segment_name = (char *) mp->segment_name;
358   a->segment_size = mp->segment_size;
359
360   ASSERT (mp->app_event_queue_address);
361
362   /* Attach to the segment vpp created */
363   rv = svm_fifo_segment_attach (a);
364   if (rv)
365     {
366       clib_warning ("svm_fifo_segment_attach ('%s') failed",
367                     mp->segment_name);
368       return;
369     }
370
371   utm->our_event_queue = uword_to_pointer (mp->app_event_queue_address,
372                                            svm_msg_q_t *);
373   utm->state = STATE_ATTACHED;
374 }
375
376 static void
377 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
378                                            mp)
379 {
380   if (mp->retval)
381     clib_warning ("detach returned with err: %d", mp->retval);
382   udp_echo_main.state = STATE_DETACHED;
383 }
384
385 u8 *
386 format_api_error (u8 * s, va_list * args)
387 {
388   udp_echo_main_t *utm = va_arg (*args, udp_echo_main_t *);
389   i32 error = va_arg (*args, u32);
390   uword *p;
391
392   p = hash_get (utm->error_string_by_error_number, -error);
393
394   if (p)
395     s = format (s, "%s", p[0]);
396   else
397     s = format (s, "%d", error);
398   return s;
399 }
400
401 int
402 wait_for_state_change (udp_echo_main_t * utm, connection_state_t state)
403 {
404 #if CLIB_DEBUG > 0
405 #define TIMEOUT 600.0
406 #else
407 #define TIMEOUT 600.0
408 #endif
409
410   f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
411
412   while (clib_time_now (&utm->clib_time) < timeout)
413     {
414       if (utm->state == state)
415         return 0;
416       if (utm->state == STATE_FAILED)
417         return -1;
418     }
419   return -1;
420 }
421
422 u64 server_bytes_received, server_bytes_sent;
423
424 static void *
425 cut_through_thread_fn (void *arg)
426 {
427   app_session_t *s;
428   svm_fifo_t *rx_fifo;
429   svm_fifo_t *tx_fifo;
430   u8 *my_copy_buffer = 0;
431   udp_echo_main_t *utm = &udp_echo_main;
432   i32 actual_transfer;
433   int rv, do_dequeue = 0;
434   u32 buffer_offset;
435
436   while (utm->cut_through_session_index == ~0)
437     ;
438
439   s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index);
440
441   rx_fifo = s->rx_fifo;
442   tx_fifo = s->tx_fifo;
443
444   vec_validate (my_copy_buffer, 64 * 1024 - 1);
445
446   while (1)
447     {
448       do
449         {
450           /* We read from the tx fifo and write to the rx fifo */
451           if (utm->have_return || do_dequeue)
452             actual_transfer = svm_fifo_dequeue_nowait (rx_fifo,
453                                                        vec_len
454                                                        (my_copy_buffer),
455                                                        my_copy_buffer);
456           else
457             {
458               /* We don't do anything with the data, drop it */
459               actual_transfer = svm_fifo_max_dequeue (rx_fifo);
460               svm_fifo_dequeue_drop (rx_fifo, actual_transfer);
461             }
462         }
463       while (actual_transfer <= 0);
464
465       server_bytes_received += actual_transfer;
466
467       if (utm->have_return)
468         {
469           buffer_offset = 0;
470           while (actual_transfer > 0)
471             {
472               rv = svm_fifo_enqueue_nowait (tx_fifo, actual_transfer,
473                                             my_copy_buffer + buffer_offset);
474               if (rv > 0)
475                 {
476                   actual_transfer -= rv;
477                   buffer_offset += rv;
478                   server_bytes_sent += rv;
479                 }
480
481             }
482         }
483       if (PREDICT_FALSE (utm->time_to_stop))
484         break;
485     }
486
487   pthread_exit (0);
488 }
489
490 static void
491 session_accepted_handler (session_accepted_msg_t * mp)
492 {
493   app_session_evt_t _app_evt, *app_evt = &_app_evt;
494   udp_echo_main_t *utm = &udp_echo_main;
495   session_accepted_reply_msg_t *rmp;
496   svm_fifo_t *rx_fifo, *tx_fifo;
497   app_session_t *session;
498   static f64 start_time;
499   u32 session_index;
500   int rv = 0;
501
502   if (start_time == 0.0)
503     start_time = clib_time_now (&utm->clib_time);
504
505   utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
506                                            svm_msg_q_t *);
507   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
508   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
509
510   pool_get (utm->sessions, session);
511   memset (session, 0, sizeof (*session));
512   session_index = session - utm->sessions;
513   session->session_index = session_index;
514
515   /* Cut-through case */
516   if (mp->server_event_queue_address)
517     {
518       clib_warning ("cut-through session");
519       session->vpp_evt_q = uword_to_pointer (mp->client_event_queue_address,
520                                              svm_msg_q_t *);
521       sleep (1);
522       rx_fifo->master_session_index = session_index;
523       tx_fifo->master_session_index = session_index;
524       utm->cut_through_session_index = session_index;
525       session->rx_fifo = rx_fifo;
526       session->tx_fifo = tx_fifo;
527       session->is_dgram = 0;
528
529       rv = pthread_create (&utm->cut_through_thread_handle,
530                            NULL /*attr */ , cut_through_thread_fn, 0);
531       if (rv)
532         {
533           clib_warning ("pthread_create returned %d", rv);
534           rv = VNET_API_ERROR_SYSCALL_ERROR_1;
535         }
536     }
537   else
538     {
539       rx_fifo->client_session_index = session_index;
540       tx_fifo->client_session_index = session_index;
541       session->rx_fifo = rx_fifo;
542       session->tx_fifo = tx_fifo;
543       clib_memcpy (&session->transport.rmt_ip, mp->ip,
544                    sizeof (ip46_address_t));
545       session->transport.is_ip4 = mp->is_ip4;
546       session->transport.rmt_port = mp->port;
547     }
548
549   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
550   if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
551     {
552       f64 now = clib_time_now (&utm->clib_time);
553       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
554                pool_elts (utm->sessions), now - start_time,
555                (f64) pool_elts (utm->sessions) / (now - start_time));
556     }
557
558   app_alloc_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt,
559                              SESSION_CTRL_EVT_ACCEPTED_REPLY);
560   rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
561   rmp->handle = mp->handle;
562   rmp->context = mp->context;
563   rmp->retval = rv;
564   app_send_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt);
565
566   CLIB_MEMORY_BARRIER ();
567   utm->state = STATE_READY;
568 }
569
570 static void
571 session_disconnected_handler (session_disconnected_msg_t * mp)
572 {
573   app_session_evt_t _app_evt, *app_evt = &_app_evt;
574   udp_echo_main_t *utm = &udp_echo_main;
575   session_disconnected_reply_msg_t *rmp;
576   app_session_t *session;
577   uword *p;
578   int rv = 0;
579
580   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
581
582   if (p)
583     {
584       session = pool_elt_at_index (utm->sessions, p[0]);
585       hash_unset (utm->session_index_by_vpp_handles, mp->handle);
586       clib_warning ("disconnecting %u", session->session_index);
587       pool_put (utm->sessions, session);
588     }
589   else
590     {
591       clib_warning ("couldn't find session key %llx", mp->handle);
592       return;
593     }
594
595   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
596                              SESSION_CTRL_EVT_DISCONNECTED_REPLY);
597   rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
598   rmp->retval = rv;
599   rmp->handle = mp->handle;
600   rmp->context = mp->context;
601   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
602 }
603
604 static void
605 session_connected_handler (session_connected_msg_t * mp)
606 {
607   udp_echo_main_t *utm = &udp_echo_main;
608   unformat_input_t _input, *input = &_input;
609   session_endpoint_extended_t _sep, *sep = &_sep;
610   app_session_t *session;
611
612   ASSERT (utm->i_am_server == 0);
613
614   if (mp->retval)
615     {
616       clib_warning ("failed connect");
617       return;
618     }
619
620   ASSERT (mp->server_rx_fifo && mp->server_tx_fifo);
621
622   pool_get (utm->sessions, session);
623   session->session_index = session - utm->sessions;
624   session->rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
625   session->tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
626
627   /* Cut-through case */
628   if (mp->client_event_queue_address)
629     {
630       clib_warning ("cut-through session");
631       session->vpp_evt_q = uword_to_pointer (mp->server_event_queue_address,
632                                              svm_msg_q_t *);
633       utm->ct_event_queue = uword_to_pointer (mp->client_event_queue_address,
634                                               svm_msg_q_t *);
635       utm->cut_through_session_index = session->session_index;
636       session->is_dgram = 0;
637       sleep (1);
638       session->rx_fifo->client_session_index = session->session_index;
639       session->tx_fifo->client_session_index = session->session_index;
640     }
641   else
642     {
643       utm->connected_session = session->session_index;
644       utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
645                                                svm_msg_q_t *);
646
647       session->rx_fifo->client_session_index = session->session_index;
648       session->tx_fifo->client_session_index = session->session_index;
649       clib_memcpy (&session->transport.lcl_ip, mp->lcl_ip,
650                    sizeof (ip46_address_t));
651       session->transport.is_ip4 = mp->is_ip4;
652       session->transport.lcl_port = mp->lcl_port;
653
654       unformat_init_vector (input, utm->connect_uri);
655       if (!unformat (input, "%U", unformat_uri, sep))
656         {
657           clib_warning ("can't figure out remote ip and port");
658           utm->state = STATE_FAILED;
659           unformat_free (input);
660           return;
661         }
662       unformat_free (input);
663       clib_memcpy (&session->transport.rmt_ip, &sep->ip,
664                    sizeof (ip46_address_t));
665       session->transport.rmt_port = sep->port;
666       session->is_dgram = !utm->is_connected;
667     }
668   utm->state = STATE_READY;
669 }
670
671 static void
672 session_bound_handler (session_bound_msg_t * mp)
673 {
674   udp_echo_main_t *utm = &udp_echo_main;
675   svm_fifo_t *rx_fifo, *tx_fifo;
676   app_session_t *session;
677   u32 session_index;
678
679   if (mp->retval)
680     {
681       clib_warning ("bind failed: %d", mp->retval);
682       utm->state = STATE_FAILED;
683       return;
684     }
685
686   rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *);
687   tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *);
688
689   pool_get (utm->sessions, session);
690   memset (session, 0, sizeof (*session));
691   session_index = session - utm->sessions;
692
693   rx_fifo->client_session_index = session_index;
694   tx_fifo->client_session_index = session_index;
695   session->rx_fifo = rx_fifo;
696   session->tx_fifo = tx_fifo;
697   clib_memcpy (&session->transport.lcl_ip, mp->lcl_ip,
698                sizeof (ip46_address_t));
699   session->transport.is_ip4 = mp->lcl_is_ip4;
700   session->transport.lcl_port = mp->lcl_port;
701   session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *);
702
703   utm->state = utm->is_connected ? STATE_BOUND : STATE_READY;
704 }
705
706 static void
707 handle_mq_event (session_event_t * e)
708 {
709   switch (e->event_type)
710     {
711     case SESSION_CTRL_EVT_BOUND:
712       session_bound_handler ((session_bound_msg_t *) e->data);
713       break;
714     case SESSION_CTRL_EVT_ACCEPTED:
715       session_accepted_handler ((session_accepted_msg_t *) e->data);
716       break;
717     case SESSION_CTRL_EVT_CONNECTED:
718       session_connected_handler ((session_connected_msg_t *) e->data);
719       break;
720     case SESSION_CTRL_EVT_DISCONNECTED:
721       session_disconnected_handler ((session_disconnected_msg_t *) e->data);
722       break;
723     default:
724       clib_warning ("unhandled %u", e->event_type);
725     }
726 }
727
728 static void
729 udp_client_send_connect (udp_echo_main_t * utm)
730 {
731   vl_api_connect_uri_t *cmp;
732   cmp = vl_msg_api_alloc (sizeof (*cmp));
733   memset (cmp, 0, sizeof (*cmp));
734
735   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
736   cmp->client_index = utm->my_client_index;
737   cmp->context = ntohl (0xfeedface);
738   memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
739   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
740 }
741
742 static void
743 send_test_chunk (udp_echo_main_t * utm, app_session_t * s, u32 bytes)
744 {
745   u64 test_buf_len, bytes_this_chunk, test_buf_offset;
746
747   u8 *test_data = utm->connect_test_data;
748   u32 bytes_to_snd, enq_space, min_chunk;
749   session_evt_type_t et = FIFO_EVENT_APP_TX;
750   int written;
751
752   test_buf_len = vec_len (test_data);
753   test_buf_offset = utm->bytes_sent % test_buf_len;
754   bytes_this_chunk = clib_min (test_buf_len - test_buf_offset,
755                                utm->bytes_to_send);
756   enq_space = svm_fifo_max_enqueue (s->tx_fifo);
757   bytes_this_chunk = clib_min (bytes_this_chunk, enq_space);
758   et += (s->session_index == utm->cut_through_session_index);
759
760   if (s->is_dgram)
761     written = app_send_dgram_raw (s->tx_fifo, &s->transport, s->vpp_evt_q,
762                                   test_data + test_buf_offset,
763                                   bytes_this_chunk, et, SVM_Q_WAIT);
764   else
765     written = app_send_stream_raw (s->tx_fifo, s->vpp_evt_q,
766                                    test_data + test_buf_offset,
767                                    bytes_this_chunk, et, SVM_Q_WAIT);
768
769   if (written > 0)
770     {
771       utm->bytes_to_send -= written;
772       utm->bytes_sent += written;
773     }
774 }
775
776 static void
777 recv_test_chunk (udp_echo_main_t * utm, app_session_t * s)
778 {
779   app_recv (s, utm->rx_buf, vec_len (utm->rx_buf));
780 }
781
782 void
783 client_send_data (udp_echo_main_t * utm, u32 session_index)
784 {
785   f64 start_time, end_time, delta;
786   app_session_t *session;
787   char *transfer_type;
788   u8 *test_data;
789   int i;
790
791   vec_validate_aligned (utm->connect_test_data, 1024 * 1024 - 1,
792                         CLIB_CACHE_LINE_BYTES);
793   for (i = 0; i < vec_len (utm->connect_test_data); i++)
794     utm->connect_test_data[i] = i & 0xff;
795
796   test_data = utm->connect_test_data;
797   session = pool_elt_at_index (utm->sessions, session_index);
798   ASSERT (vec_len (test_data) > 0);
799
800   utm->total_to_send = utm->bytes_to_send;
801   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
802   start_time = clib_time_now (&utm->clib_time);
803   while (!utm->time_to_stop && utm->bytes_to_send)
804     {
805       send_test_chunk (utm, session, 0);
806       if (utm->have_return)
807         recv_test_chunk (utm, session);
808       if (utm->time_to_stop)
809         break;
810     }
811
812   if (utm->have_return)
813     {
814       f64 timeout = clib_time_now (&utm->clib_time) + 5;
815       while (clib_time_now (&utm->clib_time) < timeout)
816         recv_test_chunk (utm, session);
817     }
818
819   end_time = clib_time_now (&utm->clib_time);
820   delta = end_time - start_time;
821   transfer_type = utm->have_return ? "full-duplex" : "half-duplex";
822   clib_warning ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds",
823                 utm->total_to_send, utm->total_to_send / (1ULL << 20),
824                 utm->total_to_send / (1ULL << 30), delta);
825   clib_warning ("%.2f bytes/second %s", ((f64) utm->total_to_send) / (delta),
826                 transfer_type);
827   clib_warning ("%.4f gbit/second %s",
828                 (((f64) utm->total_to_send * 8.0) / delta / 1e9),
829                 transfer_type);
830 }
831
832 static int
833 application_attach (udp_echo_main_t * utm)
834 {
835   application_send_attach (utm);
836   if (wait_for_state_change (utm, STATE_ATTACHED))
837     {
838       clib_warning ("timeout waiting for STATE_ATTACHED");
839       return -1;
840     }
841   return 0;
842 }
843
844 static void
845 client_test (udp_echo_main_t * utm)
846 {
847   f64 start_time, timeout = 100.0;
848   app_session_t *session;
849   svm_msg_q_msg_t msg;
850   session_event_t *e;
851
852   if (application_attach (utm))
853     return;
854
855   udp_client_send_connect (utm);
856
857   start_time = clib_time_now (&utm->clib_time);
858   while (pool_elts (utm->sessions) != 1 && utm->state != STATE_FAILED)
859     {
860       svm_msg_q_sub (utm->our_event_queue, &msg, SVM_Q_WAIT, 0);
861       e = svm_msg_q_msg_data (utm->our_event_queue, &msg);
862       handle_mq_event (e);
863       svm_msg_q_free_msg (utm->our_event_queue, &msg);
864
865       if (clib_time_now (&utm->clib_time) - start_time >= timeout)
866         break;
867     }
868
869   if (utm->cut_through_session_index != ~0)
870     client_send_data (utm, utm->cut_through_session_index);
871   else
872     client_send_data (utm, utm->connected_session);
873
874   application_detach (utm);
875   wait_for_state_change (utm, STATE_DETACHED);
876 }
877
878 static void
879 vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
880 {
881   udp_echo_main_t *utm = &udp_echo_main;
882   svm_fifo_t *rx_fifo, *tx_fifo;
883   app_session_t *session;
884   u32 session_index;
885
886   if (mp->retval)
887     {
888       clib_warning ("bind failed: %d", mp->retval);
889       utm->state = STATE_FAILED;
890       return;
891     }
892
893   rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *);
894   tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *);
895
896   pool_get (utm->sessions, session);
897   memset (session, 0, sizeof (*session));
898   session_index = session - utm->sessions;
899
900   rx_fifo->client_session_index = session_index;
901   tx_fifo->client_session_index = session_index;
902   session->rx_fifo = rx_fifo;
903   session->tx_fifo = tx_fifo;
904   clib_memcpy (&session->transport.lcl_ip, mp->lcl_ip,
905                sizeof (ip46_address_t));
906   session->transport.is_ip4 = mp->lcl_is_ip4;
907   session->transport.lcl_port = mp->lcl_port;
908   session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *);
909
910   utm->state = utm->is_connected ? STATE_BOUND : STATE_READY;
911 }
912
913 static void
914 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
915 {
916   udp_echo_main_t *utm = &udp_echo_main;
917   svm_fifo_segment_create_args_t _a, *a = &_a;
918   svm_fifo_segment_private_t *seg;
919   u8 *seg_name;
920   int rv;
921
922   memset (a, 0, sizeof (*a));
923   a->segment_name = (char *) mp->segment_name;
924   a->segment_size = mp->segment_size;
925   /* Attach to the segment vpp created */
926   rv = svm_fifo_segment_attach (a);
927   if (rv)
928     {
929       clib_warning ("svm_fifo_segment_attach ('%s') failed",
930                     mp->segment_name);
931       return;
932     }
933   seg = svm_fifo_segment_get_segment (a->new_segment_indices[0]);
934   clib_warning ("Mapped new segment '%s' size %d", seg->ssvm.name,
935                 seg->ssvm.ssvm_size);
936   seg_name = format (0, "%s", (char *) mp->segment_name);
937   hash_set_mem (utm->segments_table, seg_name, a->new_segment_indices[0]);
938   vec_free (seg_name);
939 }
940
941 static void
942 vl_api_unmap_segment_t_handler (vl_api_unmap_segment_t * mp)
943 {
944   udp_echo_main_t *utm = &udp_echo_main;
945   svm_fifo_segment_private_t *seg;
946   u64 *seg_indexp;
947   u8 *seg_name;
948
949
950   seg_name = format (0, "%s", mp->segment_name);
951   seg_indexp = hash_get_mem (utm->segments_table, seg_name);
952   if (!seg_indexp)
953     {
954       clib_warning ("segment not mapped: %s", seg_name);
955       return;
956     }
957   hash_unset_mem (utm->segments_table, seg_name);
958   seg = svm_fifo_segment_get_segment ((u32) seg_indexp[0]);
959   svm_fifo_segment_delete (seg);
960   clib_warning ("Unmapped segment '%s'", seg_name);
961   vec_free (seg_name);
962 }
963
964 static void
965 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
966 {
967   udp_echo_main_t *utm = &udp_echo_main;
968
969   if (mp->retval != 0)
970     clib_warning ("returned %d", ntohl (mp->retval));
971
972   utm->state = STATE_START;
973 }
974
975 static void
976   vl_api_app_cut_through_registration_add_t_handler
977   (vl_api_app_cut_through_registration_add_t * mp)
978 {
979
980 }
981
982 #define foreach_tcp_echo_msg                                            \
983 _(BIND_URI_REPLY, bind_uri_reply)                                       \
984 _(UNBIND_URI_REPLY, unbind_uri_reply)                                   \
985 _(MAP_ANOTHER_SEGMENT, map_another_segment)                             \
986 _(UNMAP_SEGMENT, unmap_segment)                                         \
987 _(APPLICATION_ATTACH_REPLY, application_attach_reply)                   \
988 _(APPLICATION_DETACH_REPLY, application_detach_reply)                   \
989 _(APP_CUT_THROUGH_REGISTRATION_ADD, app_cut_through_registration_add)   \
990
991 void
992 tcp_echo_api_hookup (udp_echo_main_t * utm)
993 {
994 #define _(N,n)                                                  \
995     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
996                            vl_api_##n##_t_handler,              \
997                            vl_noop_handler,                     \
998                            vl_api_##n##_t_endian,               \
999                            vl_api_##n##_t_print,                \
1000                            sizeof(vl_api_##n##_t), 1);
1001   foreach_tcp_echo_msg;
1002 #undef _
1003
1004 }
1005
1006 int
1007 connect_to_vpp (char *name)
1008 {
1009   udp_echo_main_t *utm = &udp_echo_main;
1010   api_main_t *am = &api_main;
1011
1012   if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
1013     return -1;
1014
1015   utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
1016   utm->my_client_index = am->my_client_index;
1017
1018   return 0;
1019 }
1020
1021 void
1022 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
1023 {
1024   clib_warning ("BUG");
1025 }
1026
1027 static void
1028 init_error_string_table (udp_echo_main_t * utm)
1029 {
1030   utm->error_string_by_error_number = hash_create (0, sizeof (uword));
1031
1032 #define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
1033   foreach_vnet_api_error;
1034 #undef _
1035
1036   hash_set (utm->error_string_by_error_number, 99, "Misc");
1037 }
1038
1039 void
1040 server_handle_fifo_event_rx (udp_echo_main_t * utm, u32 session_index)
1041 {
1042   svm_fifo_t *rx_fifo, *tx_fifo;
1043   int n_read;
1044   app_session_t *session;
1045   int rv;
1046   u32 max_dequeue, offset, max_transfer, rx_buf_len;
1047   session_evt_type_t et = FIFO_EVENT_APP_TX;
1048
1049   session = pool_elt_at_index (utm->sessions, session_index);
1050   rx_buf_len = vec_len (utm->rx_buf);
1051   rx_fifo = session->rx_fifo;
1052   tx_fifo = session->tx_fifo;
1053
1054   et += (session->session_index == utm->cut_through_session_index);
1055
1056   max_dequeue = svm_fifo_max_dequeue (rx_fifo);
1057   /* Allow enqueuing of a new event */
1058   svm_fifo_unset_event (rx_fifo);
1059
1060   if (PREDICT_FALSE (!max_dequeue))
1061     return;
1062
1063   /* Read the max_dequeue */
1064   do
1065     {
1066       max_transfer = clib_min (rx_buf_len, max_dequeue);
1067       if (session->is_dgram)
1068         n_read = app_recv_dgram_raw (rx_fifo, utm->rx_buf, max_transfer,
1069                                      &session->transport, 0, 0);
1070       else
1071         n_read = app_recv_stream_raw (rx_fifo, utm->rx_buf, max_transfer, 0,
1072                                       0);
1073
1074       if (n_read > 0)
1075         max_dequeue -= n_read;
1076
1077       /* Reflect if a non-drop session */
1078       if (utm->have_return && n_read > 0)
1079         {
1080           offset = 0;
1081           do
1082             {
1083               if (session->is_dgram)
1084                 rv = app_send_dgram_raw (tx_fifo, &session->transport,
1085                                          session->vpp_evt_q,
1086                                          &utm->rx_buf[offset], n_read, et,
1087                                          SVM_Q_WAIT);
1088               else
1089                 rv = app_send_stream_raw (tx_fifo, session->vpp_evt_q,
1090                                           &utm->rx_buf[offset], n_read, et,
1091                                           SVM_Q_WAIT);
1092               if (rv > 0)
1093                 {
1094                   n_read -= rv;
1095                   offset += rv;
1096                 }
1097             }
1098           while ((rv <= 0 || n_read > 0) && !utm->time_to_stop);
1099
1100           /* If event wasn't set, add one */
1101           if (svm_fifo_set_event (tx_fifo))
1102             app_send_io_evt_to_vpp (session->vpp_evt_q, tx_fifo,
1103                                     et, SVM_Q_WAIT);
1104         }
1105     }
1106   while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop);
1107 }
1108
1109 static void
1110 server_handle_event_queue (udp_echo_main_t * utm)
1111 {
1112   session_event_t *e;
1113   svm_msg_q_msg_t msg;
1114   svm_msg_q_t *mq = utm->our_event_queue;
1115   int i;
1116
1117   while (utm->state != STATE_READY)
1118     sleep (5);
1119
1120   while (1)
1121     {
1122       if (svm_msg_q_sub (mq, &msg, SVM_Q_WAIT, 0))
1123         {
1124           clib_warning ("svm msg q returned");
1125           continue;
1126         }
1127       e = svm_msg_q_msg_data (mq, &msg);
1128       switch (e->event_type)
1129         {
1130         case FIFO_EVENT_APP_RX:
1131           server_handle_fifo_event_rx (utm, e->fifo->client_session_index);
1132           break;
1133         case SESSION_IO_EVT_CT_TX:
1134           break;
1135
1136         default:
1137           handle_mq_event (e);
1138           break;
1139         }
1140       svm_msg_q_free_msg (mq, &msg);
1141       if (PREDICT_FALSE (utm->time_to_stop == 1))
1142         return;
1143       if (PREDICT_FALSE (utm->time_to_print_stats == 1))
1144         {
1145           utm->time_to_print_stats = 0;
1146           fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
1147         }
1148     }
1149 }
1150
1151 static void
1152 server_unbind (udp_echo_main_t * utm)
1153 {
1154   vl_api_unbind_uri_t *ump;
1155
1156   ump = vl_msg_api_alloc (sizeof (*ump));
1157   memset (ump, 0, sizeof (*ump));
1158
1159   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1160   ump->client_index = utm->my_client_index;
1161   memcpy (ump->uri, utm->listen_uri, vec_len (utm->listen_uri));
1162   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
1163 }
1164
1165 static void
1166 server_bind (udp_echo_main_t * utm)
1167 {
1168   vl_api_bind_uri_t *bmp;
1169
1170   bmp = vl_msg_api_alloc (sizeof (*bmp));
1171   memset (bmp, 0, sizeof (*bmp));
1172
1173   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1174   bmp->client_index = utm->my_client_index;
1175   bmp->context = ntohl (0xfeedface);
1176   memcpy (bmp->uri, utm->listen_uri, vec_len (utm->listen_uri));
1177   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
1178 }
1179
1180 void
1181 udp_server_test (udp_echo_main_t * utm)
1182 {
1183   u8 wait_for_state = utm->is_connected ? STATE_BOUND : STATE_READY;
1184   application_send_attach (utm);
1185
1186   /* Bind to uri */
1187   server_bind (utm);
1188
1189   if (wait_for_state_change (utm, wait_for_state))
1190     {
1191       clib_warning ("timeout waiting for state change");
1192       return;
1193     }
1194
1195   server_handle_event_queue (utm);
1196
1197   /* Cleanup */
1198   server_unbind (utm);
1199
1200   if (wait_for_state_change (utm, STATE_START))
1201     {
1202       clib_warning ("timeout waiting for STATE_START");
1203       return;
1204     }
1205
1206   application_detach (utm);
1207
1208   fformat (stdout, "Test complete...\n");
1209 }
1210
1211 int
1212 main (int argc, char **argv)
1213 {
1214   udp_echo_main_t *utm = &udp_echo_main;
1215   u8 *uri = (u8 *) "udp://6.0.1.1/1234";
1216   unformat_input_t _argv, *a = &_argv;
1217   int i_am_server = 1;
1218   app_session_t *session;
1219   u8 *chroot_prefix;
1220   char *app_name;
1221   u32 tmp;
1222   int i;
1223
1224   clib_mem_init_thread_safe (0, 256 << 20);
1225
1226   svm_fifo_segment_main_init (0x200000000ULL, 20);
1227
1228   vec_validate (utm->rx_buf, 128 << 10);
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   utm->have_return = 1;
1234   utm->bytes_to_send = 1024;
1235   utm->fifo_size = 128 << 10;
1236   utm->segment_main = &svm_fifo_segment_main;
1237   utm->cut_through_session_index = ~0;
1238   clib_time_init (&utm->clib_time);
1239
1240   init_error_string_table (utm);
1241   unformat_init_command_line (a, argv);
1242
1243   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1244     {
1245       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1246         {
1247           vl_set_memory_root_path ((char *) chroot_prefix);
1248         }
1249       else if (unformat (a, "uri %s", &uri))
1250         ;
1251       else if (unformat (a, "segment-size %dM", &tmp))
1252         utm->configured_segment_size = tmp << 20;
1253       else if (unformat (a, "segment-size %dG", &tmp))
1254         utm->configured_segment_size = tmp << 30;
1255       else if (unformat (a, "server"))
1256         i_am_server = 1;
1257       else if (unformat (a, "client"))
1258         i_am_server = 0;
1259       else if (unformat (a, "no-return"))
1260         utm->have_return = 0;
1261       else if (unformat (a, "mbytes %d", &tmp))
1262         utm->bytes_to_send = (u64) tmp << 20;
1263       else if (unformat (a, "fifo-size %d", &tmp))
1264         utm->fifo_size = tmp << 10;
1265       else
1266         {
1267           fformat (stderr, "%s: usage [server|client]\n");
1268           exit (1);
1269         }
1270     }
1271
1272   utm->i_am_server = i_am_server;
1273
1274   setup_signal_handlers ();
1275   tcp_echo_api_hookup (utm);
1276
1277   if (i_am_server)
1278     {
1279       utm->listen_uri = format (0, "%s%c", uri, 0);
1280       utm->is_connected = (utm->listen_uri[4] == 'c');
1281       app_name = "udp_echo_server";
1282     }
1283   else
1284     {
1285       app_name = "udp_echo_client";
1286       utm->connect_uri = format (0, "%s%c", uri, 0);
1287       utm->is_connected = (utm->connect_uri[4] == 'c');
1288     }
1289   if (connect_to_vpp (app_name) < 0)
1290     {
1291       svm_region_exit ();
1292       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1293       exit (1);
1294     }
1295
1296   if (i_am_server == 0)
1297     {
1298       client_test (utm);
1299       goto done;
1300     }
1301
1302   /* $$$$ hack preallocation */
1303   for (i = 0; i < 200000; i++)
1304     {
1305       pool_get (utm->sessions, session);
1306       memset (session, 0, sizeof (*session));
1307     }
1308   for (i = 0; i < 200000; i++)
1309     pool_put_index (utm->sessions, i);
1310
1311   udp_server_test (utm);
1312
1313 done:
1314   vl_client_disconnect_from_vlib ();
1315   exit (0);
1316 }
1317
1318 #undef vl_api_version
1319 #define vl_api_version(n,v) static u32 vpe_api_version = v;
1320 #include <vpp/api/vpe.api.h>
1321 #undef vl_api_version
1322
1323 void
1324 vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
1325 {
1326   /*
1327    * Send the main API signature in slot 0. This bit of code must
1328    * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
1329    */
1330   mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
1331 }
1332
1333 u32
1334 vl (void *p)
1335 {
1336   return vec_len (p);
1337 }
1338
1339 /*
1340  * fd.io coding-style-patch-verification: ON
1341  *
1342  * Local Variables:
1343  * eval: (c-set-style "gnu")
1344  * End:
1345  */