api: refactor vlibmemory
[vpp.git] / src / tests / vnet / session / tcp_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 <signal.h>
18
19 #include <vnet/session/application_interface.h>
20 #include <svm/svm_fifo_segment.h>
21 #include <vlibmemory/api.h>
22
23 #include <vpp/api/vpe_msg_enum.h>
24
25 #define vl_typedefs             /* define message structures */
26 #include <vpp/api/vpe_all_api_h.h>
27 #undef vl_typedefs
28
29 /* declare message handlers for each api */
30
31 #define vl_endianfun            /* define message structures */
32 #include <vpp/api/vpe_all_api_h.h>
33 #undef vl_endianfun
34
35 /* instantiate all the print functions we know about */
36 #define vl_print(handle, ...)
37 #define vl_printfun
38 #include <vpp/api/vpe_all_api_h.h>
39 #undef vl_printfun
40
41 typedef struct
42 {
43   svm_fifo_t *server_rx_fifo;
44   svm_fifo_t *server_tx_fifo;
45
46   u64 vpp_session_handle;
47   u64 bytes_received;
48   f64 start;
49 } session_t;
50
51 typedef enum
52 {
53   STATE_START,
54   STATE_ATTACHED,
55   STATE_READY,
56   STATE_DISCONNECTING,
57   STATE_FAILED
58 } connection_state_t;
59
60 typedef struct
61 {
62   /* vpe input queue */
63   svm_queue_t *vl_input_queue;
64
65   /* API client handle */
66   u32 my_client_index;
67
68   /* The URI we're playing with */
69   u8 *uri;
70
71   /* Session pool */
72   session_t *sessions;
73
74   /* Hash table for disconnect processing */
75   uword *session_index_by_vpp_handles;
76
77   /* intermediate rx buffer */
78   u8 *rx_buf;
79
80   /* URI for slave's connect */
81   u8 *connect_uri;
82
83   u32 connected_session_index;
84
85   int i_am_master;
86
87   /* drop all packets */
88   int drop_packets;
89
90   /* Our event queue */
91   svm_queue_t *our_event_queue;
92
93   /* $$$ single thread only for the moment */
94   svm_queue_t *vpp_event_queue;
95
96   u8 *socket_name;
97
98   pid_t my_pid;
99
100   /* For deadman timers */
101   clib_time_t clib_time;
102
103   /* State of the connection, shared between msg RX thread and main thread */
104   volatile connection_state_t state;
105
106   /* Signal variables */
107   volatile int time_to_stop;
108   volatile int time_to_print_stats;
109
110   u32 configured_segment_size;
111
112   /* VNET_API_ERROR_FOO -> "Foo" hash table */
113   uword *error_string_by_error_number;
114
115   u8 *connect_test_data;
116   pthread_t client_rx_thread_handle;
117   u32 client_bytes_received;
118   u8 test_return_packets;
119   u64 bytes_to_send;
120
121   /** Flag that decides if socket, instead of svm, api is used to connect to
122    * vpp. If sock api is used, shm binary api is subsequently bootstrapped
123    * and all other messages are exchanged using shm IPC. */
124   u8 use_sock_api;
125
126   /* convenience */
127   svm_fifo_segment_main_t *segment_main;
128 } uri_tcp_test_main_t;
129
130 uri_tcp_test_main_t uri_tcp_test_main;
131
132 #if CLIB_DEBUG > 0
133 #define NITER 10000
134 #else
135 #define NITER 4000000
136 #endif
137
138 static u8 *
139 format_api_error (u8 * s, va_list * args)
140 {
141   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
142   i32 error = va_arg (*args, u32);
143   uword *p;
144
145   p = hash_get (utm->error_string_by_error_number, -error);
146
147   if (p)
148     s = format (s, "%s", p[0]);
149   else
150     s = format (s, "%d", error);
151   return s;
152 }
153
154 static void
155 init_error_string_table (uri_tcp_test_main_t * utm)
156 {
157   utm->error_string_by_error_number = hash_create (0, sizeof (uword));
158
159 #define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
160   foreach_vnet_api_error;
161 #undef _
162
163   hash_set (utm->error_string_by_error_number, 99, "Misc");
164 }
165
166 int
167 wait_for_state_change (uri_tcp_test_main_t * utm, connection_state_t state)
168 {
169 #if CLIB_DEBUG > 0
170 #define TIMEOUT 600.0
171 #else
172 #define TIMEOUT 600.0
173 #endif
174
175   f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
176
177   while (clib_time_now (&utm->clib_time) < timeout)
178     {
179       if (utm->state == state)
180         return 0;
181       if (utm->state == STATE_FAILED)
182         return -1;
183       if (utm->time_to_stop == 1)
184         return 0;
185     }
186   clib_warning ("timeout waiting for STATE_READY");
187   return -1;
188 }
189
190 void
191 application_send_attach (uri_tcp_test_main_t * utm)
192 {
193   vl_api_application_attach_t *bmp;
194   u32 fifo_size = 4 << 20;
195   bmp = vl_msg_api_alloc (sizeof (*bmp));
196   memset (bmp, 0, sizeof (*bmp));
197
198   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
199   bmp->client_index = utm->my_client_index;
200   bmp->context = ntohl (0xfeedface);
201   bmp->options[APP_OPTIONS_FLAGS] =
202     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT;
203   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16;
204   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
205   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
206   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
207   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
208   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
209 }
210
211 int
212 application_attach (uri_tcp_test_main_t * utm)
213 {
214   application_send_attach (utm);
215   if (wait_for_state_change (utm, STATE_ATTACHED))
216     {
217       clib_warning ("timeout waiting for STATE_ATTACHED");
218       return -1;
219     }
220   return 0;
221 }
222
223 void
224 application_detach (uri_tcp_test_main_t * utm)
225 {
226   vl_api_application_detach_t *bmp;
227   bmp = vl_msg_api_alloc (sizeof (*bmp));
228   memset (bmp, 0, sizeof (*bmp));
229
230   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
231   bmp->client_index = utm->my_client_index;
232   bmp->context = ntohl (0xfeedface);
233   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
234 }
235
236 static void
237 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
238                                            mp)
239 {
240   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
241   svm_fifo_segment_create_args_t _a, *a = &_a;
242   int rv;
243
244   if (mp->retval)
245     {
246       clib_warning ("attach failed: %U", format_api_error,
247                     clib_net_to_host_u32 (mp->retval));
248       utm->state = STATE_FAILED;
249       return;
250     }
251
252   if (mp->segment_name_length == 0)
253     {
254       clib_warning ("segment_name_length zero");
255       return;
256     }
257
258   memset (a, 0, sizeof (*a));
259   a->segment_name = (char *) mp->segment_name;
260   a->segment_size = mp->segment_size;
261
262   ASSERT (mp->app_event_queue_address);
263
264   /* Attach to the segment vpp created */
265   rv = svm_fifo_segment_attach (a);
266   if (rv)
267     {
268       clib_warning ("svm_fifo_segment_attach ('%s') failed",
269                     mp->segment_name);
270       return;
271     }
272
273   utm->our_event_queue =
274     uword_to_pointer (mp->app_event_queue_address, svm_queue_t *);
275   utm->state = STATE_ATTACHED;
276 }
277
278 static void
279 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
280                                            mp)
281 {
282   if (mp->retval)
283     clib_warning ("detach returned with err: %d", mp->retval);
284 }
285
286 static void
287 stop_signal (int signum)
288 {
289   uri_tcp_test_main_t *um = &uri_tcp_test_main;
290
291   um->time_to_stop = 1;
292 }
293
294 static void
295 stats_signal (int signum)
296 {
297   uri_tcp_test_main_t *um = &uri_tcp_test_main;
298
299   um->time_to_print_stats = 1;
300 }
301
302 static clib_error_t *
303 setup_signal_handlers (void)
304 {
305   signal (SIGINT, stats_signal);
306   signal (SIGQUIT, stop_signal);
307   signal (SIGTERM, stop_signal);
308
309   return 0;
310 }
311
312 void
313 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
314 {
315   clib_warning ("BUG");
316 }
317
318 int
319 connect_to_vpp (char *name)
320 {
321   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
322   api_main_t *am = &api_main;
323
324   if (utm->use_sock_api)
325     {
326       if (vl_socket_client_connect ((char *) utm->socket_name, name,
327                                     0 /* default rx, tx buffer */ ))
328         return -1;
329
330       return vl_socket_client_init_shm (0);
331     }
332   else
333     {
334       if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
335         return -1;
336       utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
337       utm->my_client_index = am->my_client_index;
338     }
339   return 0;
340 }
341
342 void
343 disconnect_from_vpp (uri_tcp_test_main_t * utm)
344 {
345   if (utm->use_sock_api)
346     vl_socket_client_disconnect ();
347   else
348     vl_client_disconnect_from_vlib ();
349 }
350
351 static void
352 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
353 {
354   svm_fifo_segment_create_args_t _a, *a = &_a;
355   int rv;
356
357   memset (a, 0, sizeof (*a));
358   a->segment_name = (char *) mp->segment_name;
359   a->segment_size = mp->segment_size;
360   /* Attach to the segment vpp created */
361   rv = svm_fifo_segment_attach (a);
362   if (rv)
363     {
364       clib_warning ("svm_fifo_segment_attach ('%s') failed",
365                     mp->segment_name);
366       return;
367     }
368   clib_warning ("Mapped new segment '%s' size %d", mp->segment_name,
369                 mp->segment_size);
370 }
371
372 static void
373 session_print_stats (uri_tcp_test_main_t * utm, session_t * session)
374 {
375   f64 deltat;
376   u64 bytes;
377
378   deltat = clib_time_now (&utm->clib_time) - session->start;
379   bytes = utm->i_am_master ? session->bytes_received : utm->bytes_to_send;
380   fformat (stdout, "Finished in %.6f\n", deltat);
381   fformat (stdout, "%.4f Gbit/second\n", (bytes * 8.0) / deltat / 1e9);
382 }
383
384 static void
385 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
386 {
387   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
388   session_t *session = 0;
389   vl_api_disconnect_session_reply_t *rmp;
390   uword *p;
391   int rv = 0;
392
393   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
394
395   if (p)
396     {
397       session = pool_elt_at_index (utm->sessions, p[0]);
398       hash_unset (utm->session_index_by_vpp_handles, mp->handle);
399       pool_put (utm->sessions, session);
400     }
401   else
402     {
403       clib_warning ("couldn't find session key %llx", mp->handle);
404       rv = -11;
405     }
406
407 //  utm->time_to_stop = 1;
408
409   rmp = vl_msg_api_alloc (sizeof (*rmp));
410   memset (rmp, 0, sizeof (*rmp));
411
412   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
413   rmp->retval = rv;
414   rmp->handle = mp->handle;
415   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
416
417   if (session)
418     session_print_stats (utm, session);
419 }
420
421 static void
422 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
423 {
424   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
425   vl_api_reset_session_reply_t *rmp;
426   uword *p;
427   int rv = 0;
428
429   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
430
431   if (p)
432     {
433       clib_warning ("got reset");
434       /* Cleanup later */
435       utm->time_to_stop = 1;
436     }
437   else
438     {
439       clib_warning ("couldn't find session key %llx", mp->handle);
440       rv = -11;
441     }
442
443   rmp = vl_msg_api_alloc (sizeof (*rmp));
444   memset (rmp, 0, sizeof (*rmp));
445   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
446   rmp->retval = rv;
447   rmp->handle = mp->handle;
448   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
449 }
450
451 void
452 client_handle_fifo_event_rx (uri_tcp_test_main_t * utm,
453                              session_fifo_event_t * e)
454 {
455   svm_fifo_t *rx_fifo;
456   int n_read, bytes, i;
457
458   rx_fifo = e->fifo;
459
460   bytes = svm_fifo_max_dequeue (rx_fifo);
461   /* Allow enqueuing of new event */
462   svm_fifo_unset_event (rx_fifo);
463
464   /* Read the bytes */
465   do
466     {
467       n_read = svm_fifo_dequeue_nowait (rx_fifo,
468                                         clib_min (vec_len (utm->rx_buf),
469                                                   bytes), utm->rx_buf);
470       if (n_read > 0)
471         {
472           bytes -= n_read;
473           if (utm->test_return_packets)
474             {
475               for (i = 0; i < n_read; i++)
476                 {
477                   if (utm->rx_buf[i]
478                       != ((utm->client_bytes_received + i) & 0xff))
479                     {
480                       clib_warning ("error at byte %lld, 0x%x not 0x%x",
481                                     utm->client_bytes_received + i,
482                                     utm->rx_buf[i],
483                                     ((utm->client_bytes_received +
484                                       i) & 0xff));
485                     }
486                 }
487             }
488           utm->client_bytes_received += n_read;
489         }
490       else
491         {
492           if (n_read == -2)
493             {
494 //            clib_warning ("weird!");
495               break;
496             }
497         }
498
499     }
500   while (bytes > 0);
501 }
502
503 void
504 client_handle_event_queue (uri_tcp_test_main_t * utm)
505 {
506   session_fifo_event_t _e, *e = &_e;;
507
508   svm_queue_sub (utm->our_event_queue, (u8 *) e, 0 /* nowait */ );
509   switch (e->event_type)
510     {
511     case FIFO_EVENT_APP_RX:
512       client_handle_fifo_event_rx (utm, e);
513       break;
514
515     case FIFO_EVENT_DISCONNECT:
516       return;
517
518     default:
519       clib_warning ("unknown event type %d", e->event_type);
520       break;
521     }
522 }
523
524 static void *
525 client_rx_thread_fn (void *arg)
526 {
527   session_fifo_event_t _e, *e = &_e;
528   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
529
530   utm->client_bytes_received = 0;
531   while (1)
532     {
533       svm_queue_sub (utm->our_event_queue, (u8 *) e, 0 /* nowait */ );
534       switch (e->event_type)
535         {
536         case FIFO_EVENT_APP_RX:
537           client_handle_fifo_event_rx (utm, e);
538           break;
539
540         case FIFO_EVENT_DISCONNECT:
541           return 0;
542         default:
543           clib_warning ("unknown event type %d", e->event_type);
544           break;
545         }
546
547       if (PREDICT_FALSE (utm->time_to_stop == 1))
548         break;
549     }
550   pthread_exit (0);
551 }
552
553
554 static void
555 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
556 {
557   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
558   session_t *session;
559   u32 session_index;
560   svm_fifo_t *rx_fifo, *tx_fifo;
561   int rv;
562
563   if (mp->retval)
564     {
565       clib_warning ("connection failed with code: %U", format_api_error,
566                     clib_net_to_host_u32 (mp->retval));
567       utm->state = STATE_FAILED;
568       return;
569     }
570   else
571     {
572       clib_warning ("connected with local ip %U port %d", format_ip46_address,
573                     mp->lcl_ip, mp->is_ip4,
574                     clib_net_to_host_u16 (mp->lcl_port));
575     }
576
577   utm->vpp_event_queue =
578     uword_to_pointer (mp->vpp_event_queue_address, svm_queue_t *);
579
580   /*
581    * Setup session
582    */
583
584   pool_get (utm->sessions, session);
585   session_index = session - utm->sessions;
586
587   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
588   rx_fifo->client_session_index = session_index;
589   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
590   tx_fifo->client_session_index = session_index;
591
592   session->server_rx_fifo = rx_fifo;
593   session->server_tx_fifo = tx_fifo;
594   session->vpp_session_handle = mp->handle;
595   session->start = clib_time_now (&utm->clib_time);
596
597   /* Save handle */
598   utm->connected_session_index = session_index;
599   utm->state = STATE_READY;
600
601   /* Add it to lookup table */
602   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
603
604   /* Start RX thread */
605   rv = pthread_create (&utm->client_rx_thread_handle,
606                        NULL /*attr */ , client_rx_thread_fn, 0);
607   if (rv)
608     {
609       clib_warning ("pthread_create returned %d", rv);
610       rv = VNET_API_ERROR_SYSCALL_ERROR_1;
611     }
612 }
613
614 static void
615 send_test_chunk (uri_tcp_test_main_t * utm, svm_fifo_t * tx_fifo, int mypid,
616                  u32 bytes)
617 {
618   u8 *test_data = utm->connect_test_data;
619   u64 bytes_sent = 0;
620   int test_buf_offset = 0;
621   u32 bytes_to_snd;
622   u32 queue_max_chunk = 128 << 10, actual_write;
623   session_fifo_event_t evt;
624   int rv;
625
626   bytes_to_snd = (bytes == 0) ? vec_len (test_data) : bytes;
627   if (bytes_to_snd > vec_len (test_data))
628     bytes_to_snd = vec_len (test_data);
629
630   while (bytes_to_snd > 0 && !utm->time_to_stop)
631     {
632       actual_write = (bytes_to_snd > queue_max_chunk) ?
633         queue_max_chunk : bytes_to_snd;
634       rv = svm_fifo_enqueue_nowait (tx_fifo, actual_write,
635                                     test_data + test_buf_offset);
636
637       if (rv > 0)
638         {
639           bytes_to_snd -= rv;
640           test_buf_offset += rv;
641           bytes_sent += rv;
642
643           if (svm_fifo_set_event (tx_fifo))
644             {
645               /* Fabricate TX event, send to vpp */
646               evt.fifo = tx_fifo;
647               evt.event_type = FIFO_EVENT_APP_TX;
648
649               svm_queue_add (utm->vpp_event_queue,
650                              (u8 *) & evt, 0 /* do wait for mutex */ );
651             }
652         }
653     }
654 }
655
656 void
657 client_send_data (uri_tcp_test_main_t * utm)
658 {
659   u8 *test_data = utm->connect_test_data;
660   int mypid = getpid ();
661   session_t *session;
662   svm_fifo_t *tx_fifo;
663   u32 n_iterations, leftover;
664   int i;
665
666   session = pool_elt_at_index (utm->sessions, utm->connected_session_index);
667   tx_fifo = session->server_tx_fifo;
668
669   ASSERT (vec_len (test_data) > 0);
670
671   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
672   n_iterations = utm->bytes_to_send / vec_len (test_data);
673
674   for (i = 0; i < n_iterations; i++)
675     {
676       send_test_chunk (utm, tx_fifo, mypid, 0);
677       if (utm->time_to_stop)
678         break;
679     }
680
681   leftover = utm->bytes_to_send % vec_len (test_data);
682   if (leftover)
683     send_test_chunk (utm, tx_fifo, mypid, leftover);
684
685   if (!utm->drop_packets)
686     {
687       f64 timeout = clib_time_now (&utm->clib_time) + 10;
688
689       /* Wait for the outstanding packets */
690       while (utm->client_bytes_received <
691              vec_len (test_data) * n_iterations + leftover)
692         {
693           if (clib_time_now (&utm->clib_time) > timeout)
694             {
695               clib_warning ("timed out waiting for the missing packets");
696               break;
697             }
698         }
699     }
700   utm->time_to_stop = 1;
701 }
702
703 void
704 client_send_connect (uri_tcp_test_main_t * utm)
705 {
706   vl_api_connect_uri_t *cmp;
707   cmp = vl_msg_api_alloc (sizeof (*cmp));
708   memset (cmp, 0, sizeof (*cmp));
709
710   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
711   cmp->client_index = utm->my_client_index;
712   cmp->context = ntohl (0xfeedface);
713   memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
714   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
715 }
716
717 int
718 client_connect (uri_tcp_test_main_t * utm)
719 {
720   client_send_connect (utm);
721   if (wait_for_state_change (utm, STATE_READY))
722     {
723       clib_warning ("Connect failed");
724       return -1;
725     }
726   return 0;
727 }
728
729 void
730 client_send_disconnect (uri_tcp_test_main_t * utm)
731 {
732   session_t *connected_session;
733   vl_api_disconnect_session_t *dmp;
734   connected_session = pool_elt_at_index (utm->sessions,
735                                          utm->connected_session_index);
736   dmp = vl_msg_api_alloc (sizeof (*dmp));
737   memset (dmp, 0, sizeof (*dmp));
738   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
739   dmp->client_index = utm->my_client_index;
740   dmp->handle = connected_session->vpp_session_handle;
741   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & dmp);
742 }
743
744 int
745 client_disconnect (uri_tcp_test_main_t * utm)
746 {
747   client_send_disconnect (utm);
748   clib_warning ("Sent disconnect");
749   if (wait_for_state_change (utm, STATE_START))
750     {
751       clib_warning ("Disconnect failed");
752       return -1;
753     }
754   return 0;
755 }
756
757 static void
758 client_run (uri_tcp_test_main_t * utm)
759 {
760   int i;
761
762   if (application_attach (utm))
763     return;
764
765   if (client_connect (utm))
766     {
767       application_detach (utm);
768       return;
769     }
770
771   /* Init test data */
772   vec_validate (utm->connect_test_data, 128 * 1024 - 1);
773   for (i = 0; i < vec_len (utm->connect_test_data); i++)
774     utm->connect_test_data[i] = i & 0xff;
775
776   /* Start send */
777   client_send_data (utm);
778
779   /* Disconnect */
780   client_disconnect (utm);
781
782   application_detach (utm);
783 }
784
785 static void
786 vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
787 {
788   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
789
790   if (mp->retval)
791     {
792       clib_warning ("bind failed: %U", format_api_error,
793                     clib_net_to_host_u32 (mp->retval));
794       utm->state = STATE_FAILED;
795       return;
796     }
797
798   utm->state = STATE_READY;
799 }
800
801 static void
802 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
803 {
804   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
805
806   if (mp->retval != 0)
807     clib_warning ("returned %d", ntohl (mp->retval));
808
809   utm->state = STATE_START;
810 }
811
812 u8 *
813 format_ip4_address (u8 * s, va_list * args)
814 {
815   u8 *a = va_arg (*args, u8 *);
816   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
817 }
818
819 u8 *
820 format_ip6_address (u8 * s, va_list * args)
821 {
822   ip6_address_t *a = va_arg (*args, ip6_address_t *);
823   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
824
825   i_max_n_zero = ARRAY_LEN (a->as_u16);
826   max_n_zeros = 0;
827   i_first_zero = i_max_n_zero;
828   n_zeros = 0;
829   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
830     {
831       u32 is_zero = a->as_u16[i] == 0;
832       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
833         {
834           i_first_zero = i;
835           n_zeros = 0;
836         }
837       n_zeros += is_zero;
838       if ((!is_zero && n_zeros > max_n_zeros)
839           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
840         {
841           i_max_n_zero = i_first_zero;
842           max_n_zeros = n_zeros;
843           i_first_zero = ARRAY_LEN (a->as_u16);
844           n_zeros = 0;
845         }
846     }
847
848   last_double_colon = 0;
849   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
850     {
851       if (i == i_max_n_zero && max_n_zeros > 1)
852         {
853           s = format (s, "::");
854           i += max_n_zeros - 1;
855           last_double_colon = 1;
856         }
857       else
858         {
859           s = format (s, "%s%x",
860                       (last_double_colon || i == 0) ? "" : ":",
861                       clib_net_to_host_u16 (a->as_u16[i]));
862           last_double_colon = 0;
863         }
864     }
865
866   return s;
867 }
868
869 /* Format an IP46 address. */
870 u8 *
871 format_ip46_address (u8 * s, va_list * args)
872 {
873   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
874   ip46_type_t type = va_arg (*args, ip46_type_t);
875   int is_ip4 = 1;
876
877   switch (type)
878     {
879     case IP46_TYPE_ANY:
880       is_ip4 = ip46_address_is_ip4 (ip46);
881       break;
882     case IP46_TYPE_IP4:
883       is_ip4 = 1;
884       break;
885     case IP46_TYPE_IP6:
886       is_ip4 = 0;
887       break;
888     }
889
890   return is_ip4 ?
891     format (s, "%U", format_ip4_address, &ip46->ip4) :
892     format (s, "%U", format_ip6_address, &ip46->ip6);
893 }
894
895 static void
896 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
897 {
898   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
899   vl_api_accept_session_reply_t *rmp;
900   svm_fifo_t *rx_fifo, *tx_fifo;
901   session_t *session;
902   static f64 start_time;
903   u32 session_index;
904   u8 *ip_str;
905
906   if (start_time == 0.0)
907     start_time = clib_time_now (&utm->clib_time);
908
909   ip_str = format (0, "%U", format_ip46_address, &mp->ip, mp->is_ip4);
910   clib_warning ("Accepted session from: %s:%d", ip_str,
911                 clib_net_to_host_u16 (mp->port));
912   utm->vpp_event_queue =
913     uword_to_pointer (mp->vpp_event_queue_address, svm_queue_t *);
914
915   /* Allocate local session and set it up */
916   pool_get (utm->sessions, session);
917   session_index = session - utm->sessions;
918
919   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
920   rx_fifo->client_session_index = session_index;
921   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
922   tx_fifo->client_session_index = session_index;
923
924   session->server_rx_fifo = rx_fifo;
925   session->server_tx_fifo = tx_fifo;
926
927   /* Add it to lookup table */
928   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
929
930   utm->state = STATE_READY;
931
932   /* Stats printing */
933   if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
934     {
935       f64 now = clib_time_now (&utm->clib_time);
936       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
937                pool_elts (utm->sessions), now - start_time,
938                (f64) pool_elts (utm->sessions) / (now - start_time));
939     }
940
941   /*
942    * Send accept reply to vpp
943    */
944   rmp = vl_msg_api_alloc (sizeof (*rmp));
945   memset (rmp, 0, sizeof (*rmp));
946   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
947   rmp->handle = mp->handle;
948   rmp->context = mp->context;
949   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
950
951   session->bytes_received = 0;
952   session->start = clib_time_now (&utm->clib_time);
953 }
954
955 void
956 server_handle_fifo_event_rx (uri_tcp_test_main_t * utm,
957                              session_fifo_event_t * e)
958 {
959   svm_fifo_t *rx_fifo, *tx_fifo;
960   int n_read;
961   session_fifo_event_t evt;
962   svm_queue_t *q;
963   session_t *session;
964   int rv;
965   u32 max_dequeue, offset, max_transfer, rx_buf_len;
966
967   rx_buf_len = vec_len (utm->rx_buf);
968   rx_fifo = e->fifo;
969   session = &utm->sessions[rx_fifo->client_session_index];
970   tx_fifo = session->server_tx_fifo;
971
972   max_dequeue = svm_fifo_max_dequeue (rx_fifo);
973   /* Allow enqueuing of a new event */
974   svm_fifo_unset_event (rx_fifo);
975
976   if (PREDICT_FALSE (max_dequeue == 0))
977     {
978       return;
979     }
980
981   /* Read the max_dequeue */
982   do
983     {
984       max_transfer = clib_min (rx_buf_len, max_dequeue);
985       n_read = svm_fifo_dequeue_nowait (rx_fifo, max_transfer, utm->rx_buf);
986       if (n_read > 0)
987         {
988           max_dequeue -= n_read;
989           session->bytes_received += n_read;
990         }
991
992       /* Reflect if a non-drop session */
993       if (!utm->drop_packets && n_read > 0)
994         {
995           offset = 0;
996           do
997             {
998               rv = svm_fifo_enqueue_nowait (tx_fifo, n_read,
999                                             &utm->rx_buf[offset]);
1000               if (rv > 0)
1001                 {
1002                   n_read -= rv;
1003                   offset += rv;
1004                 }
1005             }
1006           while ((rv <= 0 || n_read > 0) && !utm->time_to_stop);
1007
1008           /* If event wasn't set, add one */
1009           if (svm_fifo_set_event (tx_fifo))
1010             {
1011               /* Fabricate TX event, send to vpp */
1012               evt.fifo = tx_fifo;
1013               evt.event_type = FIFO_EVENT_APP_TX;
1014
1015               q = utm->vpp_event_queue;
1016               svm_queue_add (q, (u8 *) & evt, 1 /* do wait for mutex */ );
1017             }
1018         }
1019     }
1020   while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop);
1021 }
1022
1023 void
1024 server_handle_event_queue (uri_tcp_test_main_t * utm)
1025 {
1026   session_fifo_event_t _e, *e = &_e;
1027
1028   while (1)
1029     {
1030       svm_queue_sub (utm->our_event_queue, (u8 *) e, 0 /* nowait */ );
1031       switch (e->event_type)
1032         {
1033         case FIFO_EVENT_APP_RX:
1034           server_handle_fifo_event_rx (utm, e);
1035           break;
1036
1037         case FIFO_EVENT_DISCONNECT:
1038           return;
1039
1040         default:
1041           clib_warning ("unknown event type %d", e->event_type);
1042           break;
1043         }
1044       if (PREDICT_FALSE (utm->time_to_stop == 1))
1045         break;
1046       if (PREDICT_FALSE (utm->time_to_print_stats == 1))
1047         {
1048           utm->time_to_print_stats = 0;
1049           fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
1050         }
1051     }
1052 }
1053
1054 void
1055 server_send_listen (uri_tcp_test_main_t * utm)
1056 {
1057   vl_api_bind_uri_t *bmp;
1058   bmp = vl_msg_api_alloc (sizeof (*bmp));
1059   memset (bmp, 0, sizeof (*bmp));
1060
1061   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1062   bmp->client_index = utm->my_client_index;
1063   bmp->context = ntohl (0xfeedface);
1064   memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
1065   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
1066 }
1067
1068 int
1069 server_listen (uri_tcp_test_main_t * utm)
1070 {
1071   server_send_listen (utm);
1072   if (wait_for_state_change (utm, STATE_READY))
1073     {
1074       clib_warning ("timeout waiting for STATE_READY");
1075       return -1;
1076     }
1077   return 0;
1078 }
1079
1080 void
1081 server_send_unbind (uri_tcp_test_main_t * utm)
1082 {
1083   vl_api_unbind_uri_t *ump;
1084
1085   ump = vl_msg_api_alloc (sizeof (*ump));
1086   memset (ump, 0, sizeof (*ump));
1087
1088   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1089   ump->client_index = utm->my_client_index;
1090   memcpy (ump->uri, utm->uri, vec_len (utm->uri));
1091   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
1092 }
1093
1094 int
1095 server_unbind (uri_tcp_test_main_t * utm)
1096 {
1097   server_send_unbind (utm);
1098   if (wait_for_state_change (utm, STATE_START))
1099     {
1100       clib_warning ("timeout waiting for STATE_START");
1101       return -1;
1102     }
1103   return 0;
1104 }
1105
1106 void
1107 server_run (uri_tcp_test_main_t * utm)
1108 {
1109   session_t *session;
1110   int i;
1111
1112   /* $$$$ hack preallocation */
1113   for (i = 0; i < 200000; i++)
1114     {
1115       pool_get (utm->sessions, session);
1116       memset (session, 0, sizeof (*session));
1117     }
1118   for (i = 0; i < 200000; i++)
1119     pool_put_index (utm->sessions, i);
1120
1121   if (application_attach (utm))
1122     return;
1123
1124   /* Bind to uri */
1125   if (server_listen (utm))
1126     return;
1127
1128   /* Enter handle event loop */
1129   server_handle_event_queue (utm);
1130
1131   /* Cleanup */
1132   server_send_unbind (utm);
1133
1134   application_detach (utm);
1135
1136   fformat (stdout, "Test complete...\n");
1137 }
1138
1139 static void
1140 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
1141                                            mp)
1142 {
1143   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
1144   session_t *session;
1145
1146   if (mp->retval)
1147     {
1148       clib_warning ("vpp complained about disconnect: %d",
1149                     ntohl (mp->retval));
1150     }
1151
1152   utm->state = STATE_START;
1153   session = pool_elt_at_index (utm->sessions, utm->connected_session_index);
1154   if (session)
1155     session_print_stats (utm, session);
1156 }
1157
1158 #define foreach_uri_msg                                         \
1159 _(BIND_URI_REPLY, bind_uri_reply)                               \
1160 _(UNBIND_URI_REPLY, unbind_uri_reply)                           \
1161 _(ACCEPT_SESSION, accept_session)                               \
1162 _(CONNECT_SESSION_REPLY, connect_session_reply)                 \
1163 _(DISCONNECT_SESSION, disconnect_session)                       \
1164 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1165 _(RESET_SESSION, reset_session)                                 \
1166 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1167 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1168 _(MAP_ANOTHER_SEGMENT, map_another_segment)                     \
1169
1170 void
1171 uri_api_hookup (uri_tcp_test_main_t * utm)
1172 {
1173 #define _(N,n)                                                  \
1174     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1175                            vl_api_##n##_t_handler,              \
1176                            vl_noop_handler,                     \
1177                            vl_api_##n##_t_endian,               \
1178                            vl_api_##n##_t_print,                \
1179                            sizeof(vl_api_##n##_t), 1);
1180   foreach_uri_msg;
1181 #undef _
1182 }
1183
1184 int
1185 main (int argc, char **argv)
1186 {
1187   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
1188   unformat_input_t _argv, *a = &_argv;
1189   u8 *chroot_prefix;
1190   u8 *heap, *uri = 0;
1191   u8 *bind_uri = (u8 *) "tcp://0.0.0.0/1234";
1192   u8 *connect_uri = (u8 *) "tcp://6.0.1.2/1234";
1193   u64 bytes_to_send = 64 << 10, mbytes;
1194   u32 tmp;
1195   mheap_t *h;
1196   int i_am_master = 1, drop_packets = 0, test_return_packets = 0;
1197
1198   clib_mem_init (0, 256 << 20);
1199
1200   heap = clib_mem_get_per_cpu_heap ();
1201   h = mheap_header (heap);
1202
1203   /* make the main heap thread-safe */
1204   h->flags |= MHEAP_FLAG_THREAD_SAFE;
1205
1206   vec_validate (utm->rx_buf, 128 << 10);
1207
1208   utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1209
1210   utm->my_pid = getpid ();
1211   utm->configured_segment_size = 1 << 20;
1212   utm->socket_name = 0;
1213   utm->use_sock_api = 1;
1214
1215   clib_time_init (&utm->clib_time);
1216   init_error_string_table (utm);
1217   svm_fifo_segment_init (0x200000000ULL, 20);
1218   unformat_init_command_line (a, argv);
1219
1220   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1221     {
1222       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1223         {
1224           vl_set_memory_root_path ((char *) chroot_prefix);
1225         }
1226       else if (unformat (a, "uri %s", &uri))
1227         ;
1228       else if (unformat (a, "segment-size %dM", &tmp))
1229         utm->configured_segment_size = tmp << 20;
1230       else if (unformat (a, "segment-size %dG", &tmp))
1231         utm->configured_segment_size = tmp << 30;
1232       else if (unformat (a, "master"))
1233         i_am_master = 1;
1234       else if (unformat (a, "slave"))
1235         i_am_master = 0;
1236       else if (unformat (a, "drop"))
1237         drop_packets = 1;
1238       else if (unformat (a, "test"))
1239         test_return_packets = 1;
1240       else if (unformat (a, "mbytes %lld", &mbytes))
1241         {
1242           bytes_to_send = mbytes << 20;
1243         }
1244       else if (unformat (a, "gbytes %lld", &mbytes))
1245         {
1246           bytes_to_send = mbytes << 30;
1247         }
1248       else if (unformat (a, "socket-name %s", &utm->socket_name))
1249         ;
1250       else if (unformat (a, "use-svm-api"))
1251         utm->use_sock_api = 0;
1252       else
1253         {
1254           fformat (stderr, "%s: usage [master|slave]\n");
1255           exit (1);
1256         }
1257     }
1258
1259   if (!utm->socket_name)
1260     utm->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0);
1261
1262   if (uri)
1263     {
1264       utm->uri = format (0, "%s%c", uri, 0);
1265       utm->connect_uri = format (0, "%s%c", uri, 0);
1266     }
1267   else
1268     {
1269       utm->uri = format (0, "%s%c", bind_uri, 0);
1270       utm->connect_uri = format (0, "%s%c", connect_uri, 0);
1271     }
1272
1273   utm->i_am_master = i_am_master;
1274   utm->segment_main = &svm_fifo_segment_main;
1275   utm->drop_packets = drop_packets;
1276   utm->test_return_packets = test_return_packets;
1277   utm->bytes_to_send = bytes_to_send;
1278   utm->time_to_stop = 0;
1279
1280   setup_signal_handlers ();
1281   uri_api_hookup (utm);
1282
1283   if (connect_to_vpp (i_am_master ? "tcp_echo_server" : "tcp_echo_client") <
1284       0)
1285     {
1286       svm_region_exit ();
1287       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1288       exit (1);
1289     }
1290
1291   if (i_am_master == 0)
1292     client_run (utm);
1293   else
1294     server_run (utm);
1295
1296   disconnect_from_vpp (utm);
1297   exit (0);
1298 }
1299
1300 /*
1301  * fd.io coding-style-patch-verification: ON
1302  *
1303  * Local Variables:
1304  * eval: (c-set-style "gnu")
1305  * End:
1306  */