session: remove deprecated binary apis
[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   svm_fifo_segment_main_t segment_main;
125
126   u8 *connect_test_data;
127
128   uword *segments_table;
129   u8 do_echo;
130   u8 have_return;
131   u64 total_to_send;
132   u64 bytes_to_send;
133   u64 bytes_sent;
134 } udp_echo_main_t;
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   um->time_to_print_stats = 1;
151 }
152
153 static clib_error_t *
154 setup_signal_handlers (void)
155 {
156   signal (SIGINT, stats_signal);
157   signal (SIGQUIT, stop_signal);
158   signal (SIGTERM, stop_signal);
159
160   return 0;
161 }
162
163 uword
164 unformat_ip4_address (unformat_input_t * input, va_list * args)
165 {
166   u8 *result = va_arg (*args, u8 *);
167   unsigned a[4];
168
169   if (!unformat (input, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]))
170     return 0;
171
172   if (a[0] >= 256 || a[1] >= 256 || a[2] >= 256 || a[3] >= 256)
173     return 0;
174
175   result[0] = a[0];
176   result[1] = a[1];
177   result[2] = a[2];
178   result[3] = a[3];
179
180   return 1;
181 }
182
183 uword
184 unformat_ip6_address (unformat_input_t * input, va_list * args)
185 {
186   ip6_address_t *result = va_arg (*args, ip6_address_t *);
187   u16 hex_quads[8];
188   uword hex_quad, n_hex_quads, hex_digit, n_hex_digits;
189   uword c, n_colon, double_colon_index;
190
191   n_hex_quads = hex_quad = n_hex_digits = n_colon = 0;
192   double_colon_index = ARRAY_LEN (hex_quads);
193   while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT)
194     {
195       hex_digit = 16;
196       if (c >= '0' && c <= '9')
197         hex_digit = c - '0';
198       else if (c >= 'a' && c <= 'f')
199         hex_digit = c + 10 - 'a';
200       else if (c >= 'A' && c <= 'F')
201         hex_digit = c + 10 - 'A';
202       else if (c == ':' && n_colon < 2)
203         n_colon++;
204       else
205         {
206           unformat_put_input (input);
207           break;
208         }
209
210       /* Too many hex quads. */
211       if (n_hex_quads >= ARRAY_LEN (hex_quads))
212         return 0;
213
214       if (hex_digit < 16)
215         {
216           hex_quad = (hex_quad << 4) | hex_digit;
217
218           /* Hex quad must fit in 16 bits. */
219           if (n_hex_digits >= 4)
220             return 0;
221
222           n_colon = 0;
223           n_hex_digits++;
224         }
225
226       /* Save position of :: */
227       if (n_colon == 2)
228         {
229           /* More than one :: ? */
230           if (double_colon_index < ARRAY_LEN (hex_quads))
231             return 0;
232           double_colon_index = n_hex_quads;
233         }
234
235       if (n_colon > 0 && n_hex_digits > 0)
236         {
237           hex_quads[n_hex_quads++] = hex_quad;
238           hex_quad = 0;
239           n_hex_digits = 0;
240         }
241     }
242
243   if (n_hex_digits > 0)
244     hex_quads[n_hex_quads++] = hex_quad;
245
246   {
247     word i;
248
249     /* Expand :: to appropriate number of zero hex quads. */
250     if (double_colon_index < ARRAY_LEN (hex_quads))
251       {
252         word n_zero = ARRAY_LEN (hex_quads) - n_hex_quads;
253
254         for (i = n_hex_quads - 1; i >= (signed) double_colon_index; i--)
255           hex_quads[n_zero + i] = hex_quads[i];
256
257         for (i = 0; i < n_zero; i++)
258           hex_quads[double_colon_index + i] = 0;
259
260         n_hex_quads = ARRAY_LEN (hex_quads);
261       }
262
263     /* Too few hex quads given. */
264     if (n_hex_quads < ARRAY_LEN (hex_quads))
265       return 0;
266
267     for (i = 0; i < ARRAY_LEN (hex_quads); i++)
268       result->as_u16[i] = clib_host_to_net_u16 (hex_quads[i]);
269
270     return 1;
271   }
272 }
273
274 uword
275 unformat_uri (unformat_input_t * input, va_list * args)
276 {
277   session_endpoint_cfg_t *sep = va_arg (*args, session_endpoint_cfg_t *);
278   u32 port;
279   char *tmp;
280
281   if (unformat (input, "%s://%U/%d", &tmp, unformat_ip4_address, &sep->ip.ip4,
282                 &port))
283     {
284       sep->port = clib_host_to_net_u16 (port);
285       sep->is_ip4 = 1;
286       return 1;
287     }
288   else if (unformat (input, "%s://%U/%d", &tmp, unformat_ip6_address,
289                      &sep->ip.ip6, &port))
290     {
291       sep->port = clib_host_to_net_u16 (port);
292       sep->is_ip4 = 0;
293       return 1;
294     }
295   return 0;
296 }
297
298 static void
299 application_send_attach (udp_echo_main_t * utm)
300 {
301   vl_api_application_attach_t *bmp;
302   bmp = vl_msg_api_alloc (sizeof (*bmp));
303   clib_memset (bmp, 0, sizeof (*bmp));
304
305   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
306   bmp->client_index = utm->my_client_index;
307   bmp->context = ntohl (0xfeedface);
308   bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ADD_SEGMENT;
309   bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
310   bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
311   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 2;
312   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = utm->fifo_size;
313   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = utm->fifo_size;
314   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
315   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
316   bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 16768;
317   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
318 }
319
320 void
321 application_detach (udp_echo_main_t * utm)
322 {
323   vl_api_application_detach_t *bmp;
324   bmp = vl_msg_api_alloc (sizeof (*bmp));
325   clib_memset (bmp, 0, sizeof (*bmp));
326
327   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
328   bmp->client_index = utm->my_client_index;
329   bmp->context = ntohl (0xfeedface);
330   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
331 }
332
333 static void
334 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
335                                            mp)
336 {
337   svm_fifo_segment_create_args_t _a = { 0 }, *a = &_a;
338   udp_echo_main_t *utm = &udp_echo_main;
339   svm_fifo_segment_main_t *sm = &utm->segment_main;
340   int rv;
341
342   if (mp->retval)
343     {
344       clib_warning ("attach failed: %d", mp->retval);
345       utm->state = STATE_FAILED;
346       return;
347     }
348
349   if (mp->segment_name_length == 0)
350     {
351       clib_warning ("segment_name_length zero");
352       return;
353     }
354
355   a->segment_name = (char *) mp->segment_name;
356   a->segment_size = mp->segment_size;
357
358   ASSERT (mp->app_event_queue_address);
359
360   /* Attach to the segment vpp created */
361   rv = svm_fifo_segment_attach (sm, a);
362   if (rv)
363     {
364       clib_warning ("svm_fifo_segment_attach ('%s') failed",
365                     mp->segment_name);
366       return;
367     }
368
369   utm->our_event_queue = uword_to_pointer (mp->app_event_queue_address,
370                                            svm_msg_q_t *);
371   utm->state = STATE_ATTACHED;
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   udp_echo_main.state = STATE_DETACHED;
381 }
382
383 u8 *
384 format_api_error (u8 * s, va_list * args)
385 {
386   udp_echo_main_t *utm = va_arg (*args, udp_echo_main_t *);
387   i32 error = va_arg (*args, u32);
388   uword *p;
389
390   p = hash_get (utm->error_string_by_error_number, -error);
391
392   if (p)
393     s = format (s, "%s", p[0]);
394   else
395     s = format (s, "%d", error);
396   return s;
397 }
398
399 int
400 wait_for_state_change (udp_echo_main_t * utm, connection_state_t state)
401 {
402 #if CLIB_DEBUG > 0
403 #define TIMEOUT 600.0
404 #else
405 #define TIMEOUT 600.0
406 #endif
407
408   f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
409
410   while (clib_time_now (&utm->clib_time) < timeout)
411     {
412       if (utm->state == state)
413         return 0;
414       if (utm->state == STATE_FAILED)
415         return -1;
416     }
417   return -1;
418 }
419
420 u64 server_bytes_received, server_bytes_sent;
421
422 static void *
423 cut_through_thread_fn (void *arg)
424 {
425   app_session_t *s;
426   svm_fifo_t *rx_fifo;
427   svm_fifo_t *tx_fifo;
428   u8 *my_copy_buffer = 0;
429   udp_echo_main_t *utm = &udp_echo_main;
430   i32 actual_transfer;
431   int rv, do_dequeue = 0;
432   u32 buffer_offset;
433
434   while (utm->cut_through_session_index == ~0)
435     ;
436
437   s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index);
438
439   rx_fifo = s->rx_fifo;
440   tx_fifo = s->tx_fifo;
441
442   vec_validate (my_copy_buffer, 64 * 1024 - 1);
443
444   while (1)
445     {
446       do
447         {
448           /* We read from the tx fifo and write to the rx fifo */
449           if (utm->have_return || do_dequeue)
450             actual_transfer = svm_fifo_dequeue_nowait (rx_fifo,
451                                                        vec_len
452                                                        (my_copy_buffer),
453                                                        my_copy_buffer);
454           else
455             {
456               /* We don't do anything with the data, drop it */
457               actual_transfer = svm_fifo_max_dequeue (rx_fifo);
458               svm_fifo_dequeue_drop (rx_fifo, actual_transfer);
459             }
460         }
461       while (actual_transfer <= 0);
462
463       server_bytes_received += actual_transfer;
464
465       if (utm->have_return)
466         {
467           buffer_offset = 0;
468           while (actual_transfer > 0)
469             {
470               rv = svm_fifo_enqueue_nowait (tx_fifo, actual_transfer,
471                                             my_copy_buffer + buffer_offset);
472               if (rv > 0)
473                 {
474                   actual_transfer -= rv;
475                   buffer_offset += rv;
476                   server_bytes_sent += rv;
477                 }
478
479             }
480         }
481       if (PREDICT_FALSE (utm->time_to_stop))
482         break;
483     }
484
485   pthread_exit (0);
486 }
487
488 static void
489 session_accepted_handler (session_accepted_msg_t * mp)
490 {
491   app_session_evt_t _app_evt, *app_evt = &_app_evt;
492   udp_echo_main_t *utm = &udp_echo_main;
493   session_accepted_reply_msg_t *rmp;
494   svm_fifo_t *rx_fifo, *tx_fifo;
495   app_session_t *session;
496   static f64 start_time;
497   u32 session_index;
498   int rv = 0;
499
500   if (start_time == 0.0)
501     start_time = clib_time_now (&utm->clib_time);
502
503   utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
504                                            svm_msg_q_t *);
505   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
506   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
507
508   pool_get (utm->sessions, session);
509   clib_memset (session, 0, sizeof (*session));
510   session_index = session - utm->sessions;
511   session->session_index = session_index;
512
513   /* Cut-through case */
514   if (mp->server_event_queue_address)
515     {
516       clib_warning ("cut-through session");
517       session->vpp_evt_q = uword_to_pointer (mp->client_event_queue_address,
518                                              svm_msg_q_t *);
519       sleep (1);
520       rx_fifo->master_session_index = session_index;
521       tx_fifo->master_session_index = session_index;
522       utm->cut_through_session_index = session_index;
523       session->rx_fifo = rx_fifo;
524       session->tx_fifo = tx_fifo;
525       session->is_dgram = 0;
526
527       rv = pthread_create (&utm->cut_through_thread_handle,
528                            NULL /*attr */ , cut_through_thread_fn, 0);
529       if (rv)
530         {
531           clib_warning ("pthread_create returned %d", rv);
532           rv = VNET_API_ERROR_SYSCALL_ERROR_1;
533         }
534     }
535   else
536     {
537       rx_fifo->client_session_index = session_index;
538       tx_fifo->client_session_index = session_index;
539       session->rx_fifo = rx_fifo;
540       session->tx_fifo = tx_fifo;
541       clib_memcpy_fast (&session->transport.rmt_ip, mp->ip,
542                         sizeof (ip46_address_t));
543       session->transport.is_ip4 = mp->is_ip4;
544       session->transport.rmt_port = mp->port;
545     }
546
547   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
548   if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
549     {
550       f64 now = clib_time_now (&utm->clib_time);
551       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
552                pool_elts (utm->sessions), now - start_time,
553                (f64) pool_elts (utm->sessions) / (now - start_time));
554     }
555
556   app_alloc_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt,
557                              SESSION_CTRL_EVT_ACCEPTED_REPLY);
558   rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
559   rmp->handle = mp->handle;
560   rmp->context = mp->context;
561   rmp->retval = rv;
562   app_send_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt);
563
564   CLIB_MEMORY_BARRIER ();
565   utm->state = STATE_READY;
566 }
567
568 static void
569 session_disconnected_handler (session_disconnected_msg_t * mp)
570 {
571   app_session_evt_t _app_evt, *app_evt = &_app_evt;
572   udp_echo_main_t *utm = &udp_echo_main;
573   session_disconnected_reply_msg_t *rmp;
574   app_session_t *session;
575   uword *p;
576   int rv = 0;
577
578   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
579
580   if (p)
581     {
582       session = pool_elt_at_index (utm->sessions, p[0]);
583       hash_unset (utm->session_index_by_vpp_handles, mp->handle);
584       clib_warning ("disconnecting %u", session->session_index);
585       pool_put (utm->sessions, session);
586     }
587   else
588     {
589       clib_warning ("couldn't find session key %llx", mp->handle);
590       return;
591     }
592
593   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
594                              SESSION_CTRL_EVT_DISCONNECTED_REPLY);
595   rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
596   rmp->retval = rv;
597   rmp->handle = mp->handle;
598   rmp->context = mp->context;
599   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
600 }
601
602 static void
603 session_connected_handler (session_connected_msg_t * mp)
604 {
605   udp_echo_main_t *utm = &udp_echo_main;
606   unformat_input_t _input, *input = &_input;
607   session_endpoint_cfg_t _sep, *sep = &_sep;
608   app_session_t *session;
609
610   ASSERT (utm->i_am_server == 0);
611
612   if (mp->retval)
613     {
614       clib_warning ("failed connect");
615       return;
616     }
617
618   ASSERT (mp->server_rx_fifo && mp->server_tx_fifo);
619
620   pool_get (utm->sessions, session);
621   session->session_index = session - utm->sessions;
622   session->rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
623   session->tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
624
625   /* Cut-through case */
626   if (mp->client_event_queue_address)
627     {
628       clib_warning ("cut-through session");
629       session->vpp_evt_q = uword_to_pointer (mp->server_event_queue_address,
630                                              svm_msg_q_t *);
631       utm->ct_event_queue = uword_to_pointer (mp->client_event_queue_address,
632                                               svm_msg_q_t *);
633       utm->cut_through_session_index = session->session_index;
634       session->is_dgram = 0;
635       sleep (1);
636       session->rx_fifo->client_session_index = session->session_index;
637       session->tx_fifo->client_session_index = session->session_index;
638     }
639   else
640     {
641       utm->connected_session = session->session_index;
642       utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
643                                                svm_msg_q_t *);
644
645       session->rx_fifo->client_session_index = session->session_index;
646       session->tx_fifo->client_session_index = session->session_index;
647       clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip,
648                         sizeof (ip46_address_t));
649       session->transport.is_ip4 = mp->is_ip4;
650       session->transport.lcl_port = mp->lcl_port;
651
652       unformat_init_vector (input, utm->connect_uri);
653       if (!unformat (input, "%U", unformat_uri, sep))
654         {
655           clib_warning ("can't figure out remote ip and port");
656           utm->state = STATE_FAILED;
657           unformat_free (input);
658           return;
659         }
660       unformat_free (input);
661       clib_memcpy_fast (&session->transport.rmt_ip, &sep->ip,
662                         sizeof (ip46_address_t));
663       session->transport.rmt_port = sep->port;
664       session->is_dgram = !utm->is_connected;
665     }
666   utm->state = STATE_READY;
667 }
668
669 static void
670 session_bound_handler (session_bound_msg_t * mp)
671 {
672   udp_echo_main_t *utm = &udp_echo_main;
673   svm_fifo_t *rx_fifo, *tx_fifo;
674   app_session_t *session;
675   u32 session_index;
676
677   if (mp->retval)
678     {
679       clib_warning ("bind failed: %d", mp->retval);
680       utm->state = STATE_FAILED;
681       return;
682     }
683
684   rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *);
685   tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *);
686
687   pool_get (utm->sessions, session);
688   clib_memset (session, 0, sizeof (*session));
689   session_index = session - utm->sessions;
690
691   rx_fifo->client_session_index = session_index;
692   tx_fifo->client_session_index = session_index;
693   session->rx_fifo = rx_fifo;
694   session->tx_fifo = tx_fifo;
695   clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip,
696                     sizeof (ip46_address_t));
697   session->transport.is_ip4 = mp->lcl_is_ip4;
698   session->transport.lcl_port = mp->lcl_port;
699   session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *);
700
701   utm->state = utm->is_connected ? STATE_BOUND : STATE_READY;
702 }
703
704 static void
705 handle_mq_event (session_event_t * e)
706 {
707   switch (e->event_type)
708     {
709     case SESSION_CTRL_EVT_BOUND:
710       session_bound_handler ((session_bound_msg_t *) e->data);
711       break;
712     case SESSION_CTRL_EVT_ACCEPTED:
713       session_accepted_handler ((session_accepted_msg_t *) e->data);
714       break;
715     case SESSION_CTRL_EVT_CONNECTED:
716       session_connected_handler ((session_connected_msg_t *) e->data);
717       break;
718     case SESSION_CTRL_EVT_DISCONNECTED:
719       session_disconnected_handler ((session_disconnected_msg_t *) e->data);
720       break;
721     default:
722       clib_warning ("unhandled %u", e->event_type);
723     }
724 }
725
726 static void
727 udp_client_send_connect (udp_echo_main_t * utm)
728 {
729   vl_api_connect_uri_t *cmp;
730   cmp = vl_msg_api_alloc (sizeof (*cmp));
731   clib_memset (cmp, 0, sizeof (*cmp));
732
733   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
734   cmp->client_index = utm->my_client_index;
735   cmp->context = ntohl (0xfeedface);
736   memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
737   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
738 }
739
740 static void
741 send_test_chunk (udp_echo_main_t * utm, app_session_t * s, u32 bytes)
742 {
743   u64 test_buf_len, bytes_this_chunk, test_buf_offset;
744
745   u8 *test_data = utm->connect_test_data;
746   u32 bytes_to_snd, enq_space, min_chunk;
747   session_evt_type_t et = FIFO_EVENT_APP_TX;
748   int written;
749
750   test_buf_len = vec_len (test_data);
751   test_buf_offset = utm->bytes_sent % test_buf_len;
752   bytes_this_chunk = clib_min (test_buf_len - test_buf_offset,
753                                utm->bytes_to_send);
754   enq_space = svm_fifo_max_enqueue (s->tx_fifo);
755   bytes_this_chunk = clib_min (bytes_this_chunk, enq_space);
756   et += (s->session_index == utm->cut_through_session_index);
757
758   if (s->is_dgram)
759     written = app_send_dgram_raw (s->tx_fifo, &s->transport, s->vpp_evt_q,
760                                   test_data + test_buf_offset,
761                                   bytes_this_chunk, et, SVM_Q_WAIT);
762   else
763     written = app_send_stream_raw (s->tx_fifo, s->vpp_evt_q,
764                                    test_data + test_buf_offset,
765                                    bytes_this_chunk, et, SVM_Q_WAIT);
766
767   if (written > 0)
768     {
769       utm->bytes_to_send -= written;
770       utm->bytes_sent += written;
771     }
772 }
773
774 static void
775 recv_test_chunk (udp_echo_main_t * utm, app_session_t * s)
776 {
777   app_recv (s, utm->rx_buf, vec_len (utm->rx_buf));
778 }
779
780 void
781 client_send_data (udp_echo_main_t * utm, u32 session_index)
782 {
783   f64 start_time, end_time, delta;
784   app_session_t *session;
785   char *transfer_type;
786   u8 *test_data;
787   int i;
788
789   vec_validate_aligned (utm->connect_test_data, 1024 * 1024 - 1,
790                         CLIB_CACHE_LINE_BYTES);
791   for (i = 0; i < vec_len (utm->connect_test_data); i++)
792     utm->connect_test_data[i] = i & 0xff;
793
794   test_data = utm->connect_test_data;
795   session = pool_elt_at_index (utm->sessions, session_index);
796   ASSERT (vec_len (test_data) > 0);
797
798   utm->total_to_send = utm->bytes_to_send;
799   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
800   start_time = clib_time_now (&utm->clib_time);
801   while (!utm->time_to_stop && utm->bytes_to_send)
802     {
803       send_test_chunk (utm, session, 0);
804       if (utm->have_return)
805         recv_test_chunk (utm, session);
806       if (utm->time_to_stop)
807         break;
808     }
809
810   if (utm->have_return)
811     {
812       f64 timeout = clib_time_now (&utm->clib_time) + 5;
813       while (clib_time_now (&utm->clib_time) < timeout)
814         recv_test_chunk (utm, session);
815     }
816
817   end_time = clib_time_now (&utm->clib_time);
818   delta = end_time - start_time;
819   transfer_type = utm->have_return ? "full-duplex" : "half-duplex";
820   clib_warning ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds",
821                 utm->total_to_send, utm->total_to_send / (1ULL << 20),
822                 utm->total_to_send / (1ULL << 30), delta);
823   clib_warning ("%.2f bytes/second %s", ((f64) utm->total_to_send) / (delta),
824                 transfer_type);
825   clib_warning ("%.4f gbit/second %s",
826                 (((f64) utm->total_to_send * 8.0) / delta / 1e9),
827                 transfer_type);
828 }
829
830 static int
831 application_attach (udp_echo_main_t * utm)
832 {
833   application_send_attach (utm);
834   if (wait_for_state_change (utm, STATE_ATTACHED))
835     {
836       clib_warning ("timeout waiting for STATE_ATTACHED");
837       return -1;
838     }
839   return 0;
840 }
841
842 static void
843 client_test (udp_echo_main_t * utm)
844 {
845   f64 start_time, timeout = 100.0;
846   app_session_t *session;
847   svm_msg_q_msg_t msg;
848   session_event_t *e;
849
850   if (application_attach (utm))
851     return;
852
853   udp_client_send_connect (utm);
854
855   start_time = clib_time_now (&utm->clib_time);
856   while (pool_elts (utm->sessions) != 1 && utm->state != STATE_FAILED)
857     {
858       svm_msg_q_sub (utm->our_event_queue, &msg, SVM_Q_WAIT, 0);
859       e = svm_msg_q_msg_data (utm->our_event_queue, &msg);
860       handle_mq_event (e);
861       svm_msg_q_free_msg (utm->our_event_queue, &msg);
862
863       if (clib_time_now (&utm->clib_time) - start_time >= timeout)
864         break;
865     }
866
867   if (utm->cut_through_session_index != ~0)
868     client_send_data (utm, utm->cut_through_session_index);
869   else
870     client_send_data (utm, utm->connected_session);
871
872   application_detach (utm);
873   wait_for_state_change (utm, STATE_DETACHED);
874 }
875
876 static void
877 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
878 {
879   svm_fifo_segment_create_args_t _a, *a = &_a;
880   udp_echo_main_t *utm = &udp_echo_main;
881   svm_fifo_segment_main_t *sm = &utm->segment_main;
882   svm_fifo_segment_private_t *seg;
883   int rv;
884
885   clib_memset (a, 0, sizeof (*a));
886   a->segment_name = (char *) mp->segment_name;
887   a->segment_size = mp->segment_size;
888   /* Attach to the segment vpp created */
889   rv = svm_fifo_segment_attach (sm, a);
890   if (rv)
891     {
892       clib_warning ("svm_fifo_segment_attach ('%s') failed",
893                     mp->segment_name);
894       return;
895     }
896   seg = svm_fifo_segment_get_segment (sm, a->new_segment_indices[0]);
897   clib_warning ("Mapped new segment '%s' size %d", seg->ssvm.name,
898                 seg->ssvm.ssvm_size);
899   hash_set (utm->segments_table, clib_net_to_host_u64 (mp->segment_handle),
900             a->new_segment_indices[0]);
901 }
902
903 static void
904 vl_api_unmap_segment_t_handler (vl_api_unmap_segment_t * mp)
905 {
906   udp_echo_main_t *utm = &udp_echo_main;
907   svm_fifo_segment_main_t *sm = &utm->segment_main;
908   svm_fifo_segment_private_t *seg;
909   uword *seg_indexp;
910   u64 segment_handle;
911
912   segment_handle = clib_net_to_host_u64 (mp->segment_handle);
913   seg_indexp = hash_get (utm->segments_table, segment_handle);
914   if (!seg_indexp)
915     {
916       clib_warning ("segment not mapped: %s", segment_handle);
917       return;
918     }
919   hash_unset (utm->segments_table, segment_handle);
920   seg = svm_fifo_segment_get_segment (sm, (u32) seg_indexp[0]);
921   svm_fifo_segment_delete (sm, seg);
922   clib_warning ("Unmapped segment '%s'", segment_handle);
923 }
924
925 static void
926 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
927 {
928   udp_echo_main_t *utm = &udp_echo_main;
929
930   if (mp->retval != 0)
931     clib_warning ("returned %d", ntohl (mp->retval));
932
933   utm->state = STATE_START;
934 }
935
936 static void
937   vl_api_app_cut_through_registration_add_t_handler
938   (vl_api_app_cut_through_registration_add_t * mp)
939 {
940
941 }
942
943 #define foreach_tcp_echo_msg                                            \
944 _(UNBIND_URI_REPLY, unbind_uri_reply)                                   \
945 _(MAP_ANOTHER_SEGMENT, map_another_segment)                             \
946 _(UNMAP_SEGMENT, unmap_segment)                                         \
947 _(APPLICATION_ATTACH_REPLY, application_attach_reply)                   \
948 _(APPLICATION_DETACH_REPLY, application_detach_reply)                   \
949 _(APP_CUT_THROUGH_REGISTRATION_ADD, app_cut_through_registration_add)   \
950
951 void
952 tcp_echo_api_hookup (udp_echo_main_t * utm)
953 {
954 #define _(N,n)                                                  \
955     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
956                            vl_api_##n##_t_handler,              \
957                            vl_noop_handler,                     \
958                            vl_api_##n##_t_endian,               \
959                            vl_api_##n##_t_print,                \
960                            sizeof(vl_api_##n##_t), 1);
961   foreach_tcp_echo_msg;
962 #undef _
963
964 }
965
966 int
967 connect_to_vpp (char *name)
968 {
969   udp_echo_main_t *utm = &udp_echo_main;
970   api_main_t *am = &api_main;
971
972   if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
973     return -1;
974
975   utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
976   utm->my_client_index = am->my_client_index;
977
978   return 0;
979 }
980
981 void
982 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
983 {
984   clib_warning ("BUG");
985 }
986
987 static void
988 init_error_string_table (udp_echo_main_t * utm)
989 {
990   utm->error_string_by_error_number = hash_create (0, sizeof (uword));
991
992 #define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
993   foreach_vnet_api_error;
994 #undef _
995
996   hash_set (utm->error_string_by_error_number, 99, "Misc");
997 }
998
999 void
1000 server_handle_fifo_event_rx (udp_echo_main_t * utm, u32 session_index)
1001 {
1002   svm_fifo_t *rx_fifo, *tx_fifo;
1003   int n_read;
1004   app_session_t *session;
1005   int rv;
1006   u32 max_dequeue, offset, max_transfer, rx_buf_len;
1007   session_evt_type_t et = FIFO_EVENT_APP_TX;
1008
1009   session = pool_elt_at_index (utm->sessions, session_index);
1010   rx_buf_len = vec_len (utm->rx_buf);
1011   rx_fifo = session->rx_fifo;
1012   tx_fifo = session->tx_fifo;
1013
1014   et += (session->session_index == utm->cut_through_session_index);
1015
1016   max_dequeue = svm_fifo_max_dequeue (rx_fifo);
1017   /* Allow enqueuing of a new event */
1018   svm_fifo_unset_event (rx_fifo);
1019
1020   if (PREDICT_FALSE (!max_dequeue))
1021     return;
1022
1023   /* Read the max_dequeue */
1024   do
1025     {
1026       max_transfer = clib_min (rx_buf_len, max_dequeue);
1027       if (session->is_dgram)
1028         n_read = app_recv_dgram_raw (rx_fifo, utm->rx_buf, max_transfer,
1029                                      &session->transport, 0, 0);
1030       else
1031         n_read = app_recv_stream_raw (rx_fifo, utm->rx_buf, max_transfer, 0,
1032                                       0);
1033
1034       if (n_read > 0)
1035         max_dequeue -= n_read;
1036
1037       /* Reflect if a non-drop session */
1038       if (utm->have_return && n_read > 0)
1039         {
1040           offset = 0;
1041           do
1042             {
1043               if (session->is_dgram)
1044                 rv = app_send_dgram_raw (tx_fifo, &session->transport,
1045                                          session->vpp_evt_q,
1046                                          &utm->rx_buf[offset], n_read, et,
1047                                          SVM_Q_WAIT);
1048               else
1049                 rv = app_send_stream_raw (tx_fifo, session->vpp_evt_q,
1050                                           &utm->rx_buf[offset], n_read, et,
1051                                           SVM_Q_WAIT);
1052               if (rv > 0)
1053                 {
1054                   n_read -= rv;
1055                   offset += rv;
1056                 }
1057             }
1058           while ((rv <= 0 || n_read > 0) && !utm->time_to_stop);
1059
1060           /* If event wasn't set, add one */
1061           if (svm_fifo_set_event (tx_fifo))
1062             app_send_io_evt_to_vpp (session->vpp_evt_q, tx_fifo,
1063                                     et, SVM_Q_WAIT);
1064         }
1065     }
1066   while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop);
1067 }
1068
1069 static void
1070 server_handle_event_queue (udp_echo_main_t * utm)
1071 {
1072   session_event_t *e;
1073   svm_msg_q_msg_t msg;
1074   svm_msg_q_t *mq = utm->our_event_queue;
1075   int i;
1076
1077   while (utm->state != STATE_READY)
1078     sleep (5);
1079
1080   while (1)
1081     {
1082       if (svm_msg_q_sub (mq, &msg, SVM_Q_WAIT, 0))
1083         {
1084           clib_warning ("svm msg q returned");
1085           continue;
1086         }
1087       e = svm_msg_q_msg_data (mq, &msg);
1088       switch (e->event_type)
1089         {
1090         case FIFO_EVENT_APP_RX:
1091           server_handle_fifo_event_rx (utm, e->fifo->client_session_index);
1092           break;
1093         case SESSION_IO_EVT_CT_TX:
1094           break;
1095
1096         default:
1097           handle_mq_event (e);
1098           break;
1099         }
1100       svm_msg_q_free_msg (mq, &msg);
1101       if (PREDICT_FALSE (utm->time_to_stop == 1))
1102         return;
1103       if (PREDICT_FALSE (utm->time_to_print_stats == 1))
1104         {
1105           utm->time_to_print_stats = 0;
1106           fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
1107         }
1108     }
1109 }
1110
1111 static void
1112 server_unbind (udp_echo_main_t * utm)
1113 {
1114   vl_api_unbind_uri_t *ump;
1115
1116   ump = vl_msg_api_alloc (sizeof (*ump));
1117   clib_memset (ump, 0, sizeof (*ump));
1118
1119   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1120   ump->client_index = utm->my_client_index;
1121   memcpy (ump->uri, utm->listen_uri, vec_len (utm->listen_uri));
1122   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
1123 }
1124
1125 static void
1126 server_bind (udp_echo_main_t * utm)
1127 {
1128   vl_api_bind_uri_t *bmp;
1129
1130   bmp = vl_msg_api_alloc (sizeof (*bmp));
1131   clib_memset (bmp, 0, sizeof (*bmp));
1132
1133   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1134   bmp->client_index = utm->my_client_index;
1135   bmp->context = ntohl (0xfeedface);
1136   memcpy (bmp->uri, utm->listen_uri, vec_len (utm->listen_uri));
1137   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
1138 }
1139
1140 void
1141 udp_server_test (udp_echo_main_t * utm)
1142 {
1143   u8 wait_for_state = utm->is_connected ? STATE_BOUND : STATE_READY;
1144   application_send_attach (utm);
1145
1146   /* Bind to uri */
1147   server_bind (utm);
1148
1149   if (wait_for_state_change (utm, wait_for_state))
1150     {
1151       clib_warning ("timeout waiting for state change");
1152       return;
1153     }
1154
1155   server_handle_event_queue (utm);
1156
1157   /* Cleanup */
1158   server_unbind (utm);
1159
1160   if (wait_for_state_change (utm, STATE_START))
1161     {
1162       clib_warning ("timeout waiting for STATE_START");
1163       return;
1164     }
1165
1166   application_detach (utm);
1167
1168   fformat (stdout, "Test complete...\n");
1169 }
1170
1171 int
1172 main (int argc, char **argv)
1173 {
1174   udp_echo_main_t *utm = &udp_echo_main;
1175   svm_fifo_segment_main_t *sm = &utm->segment_main;
1176   u8 *uri = (u8 *) "udp://6.0.1.1/1234";
1177   unformat_input_t _argv, *a = &_argv;
1178   int i_am_server = 1;
1179   app_session_t *session;
1180   u8 *chroot_prefix;
1181   char *app_name;
1182   u32 tmp;
1183   int i;
1184
1185   clib_mem_init_thread_safe (0, 256 << 20);
1186
1187   svm_fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20);
1188
1189   vec_validate (utm->rx_buf, 128 << 10);
1190   utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1191   utm->my_pid = getpid ();
1192   utm->configured_segment_size = 1 << 20;
1193   utm->have_return = 1;
1194   utm->bytes_to_send = 1024;
1195   utm->fifo_size = 128 << 10;
1196   utm->cut_through_session_index = ~0;
1197   clib_time_init (&utm->clib_time);
1198
1199   init_error_string_table (utm);
1200   unformat_init_command_line (a, argv);
1201
1202   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1203     {
1204       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1205         {
1206           vl_set_memory_root_path ((char *) chroot_prefix);
1207         }
1208       else if (unformat (a, "uri %s", &uri))
1209         ;
1210       else if (unformat (a, "segment-size %dM", &tmp))
1211         utm->configured_segment_size = tmp << 20;
1212       else if (unformat (a, "segment-size %dG", &tmp))
1213         utm->configured_segment_size = tmp << 30;
1214       else if (unformat (a, "server"))
1215         i_am_server = 1;
1216       else if (unformat (a, "client"))
1217         i_am_server = 0;
1218       else if (unformat (a, "no-return"))
1219         utm->have_return = 0;
1220       else if (unformat (a, "mbytes %d", &tmp))
1221         utm->bytes_to_send = (u64) tmp << 20;
1222       else if (unformat (a, "fifo-size %d", &tmp))
1223         utm->fifo_size = tmp << 10;
1224       else
1225         {
1226           fformat (stderr, "%s: usage [server|client]\n");
1227           exit (1);
1228         }
1229     }
1230
1231   utm->i_am_server = i_am_server;
1232
1233   setup_signal_handlers ();
1234   tcp_echo_api_hookup (utm);
1235
1236   if (i_am_server)
1237     {
1238       utm->listen_uri = format (0, "%s%c", uri, 0);
1239       utm->is_connected = (utm->listen_uri[4] == 'c');
1240       app_name = "udp_echo_server";
1241     }
1242   else
1243     {
1244       app_name = "udp_echo_client";
1245       utm->connect_uri = format (0, "%s%c", uri, 0);
1246       utm->is_connected = (utm->connect_uri[4] == 'c');
1247     }
1248   if (connect_to_vpp (app_name) < 0)
1249     {
1250       svm_region_exit ();
1251       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1252       exit (1);
1253     }
1254
1255   if (i_am_server == 0)
1256     {
1257       client_test (utm);
1258       goto done;
1259     }
1260
1261   /* $$$$ hack preallocation */
1262   for (i = 0; i < 200000; i++)
1263     {
1264       pool_get (utm->sessions, session);
1265       clib_memset (session, 0, sizeof (*session));
1266     }
1267   for (i = 0; i < 200000; i++)
1268     pool_put_index (utm->sessions, i);
1269
1270   udp_server_test (utm);
1271
1272 done:
1273   vl_client_disconnect_from_vlib ();
1274   exit (0);
1275 }
1276
1277 #undef vl_api_version
1278 #define vl_api_version(n,v) static u32 vpe_api_version = v;
1279 #include <vpp/api/vpe.api.h>
1280 #undef vl_api_version
1281
1282 void
1283 vl_client_add_api_signatures (vl_api_memclnt_create_t * mp)
1284 {
1285   /*
1286    * Send the main API signature in slot 0. This bit of code must
1287    * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
1288    */
1289   mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
1290 }
1291
1292 u32
1293 vl (void *p)
1294 {
1295   return vec_len (p);
1296 }
1297
1298 /*
1299  * fd.io coding-style-patch-verification: ON
1300  *
1301  * Local Variables:
1302  * eval: (c-set-style "gnu")
1303  * End:
1304  */