44208cc0d823a1221fd093384af2b5bb12420964
[vpp.git] / src / uri / vppcom.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
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 <stdlib.h>
18 #include <signal.h>
19 #include <svm/svm_fifo_segment.h>
20 #include <vlibmemory/api.h>
21 #include <vpp/api/vpe_msg_enum.h>
22 #include <vnet/session/application_interface.h>
23 #include <uri/vppcom.h>
24 #include <vlib/unix/unix.h>
25 #include <vppinfra/vec_bootstrap.h>
26
27 #define vl_typedefs             /* define message structures */
28 #include <vpp/api/vpe_all_api_h.h>
29 #undef vl_typedefs
30
31 /* declare message handlers for each api */
32
33 #define vl_endianfun            /* define message structures */
34 #include <vpp/api/vpe_all_api_h.h>
35 #undef vl_endianfun
36
37 /* instantiate all the print functions we know about */
38 #define vl_print(handle, ...)
39 #define vl_printfun
40 #include <vpp/api/vpe_all_api_h.h>
41 #undef vl_printfun
42
43 #if (CLIB_DEBUG > 0)
44 /* Set VPPCOM_DEBUG 2 for connection debug, 3 for read/write debug output */
45 #define VPPCOM_DEBUG 1
46 #else
47 #define VPPCOM_DEBUG 0
48 #endif
49
50 /*
51  * VPPCOM Private definitions and functions.
52  */
53 typedef enum
54 {
55   STATE_APP_START,
56   STATE_APP_CONN_VPP,
57   STATE_APP_ENABLED,
58   STATE_APP_ATTACHED,
59 } app_state_t;
60
61 typedef enum
62 {
63   STATE_START,
64   STATE_CONNECT,
65   STATE_LISTEN,
66   STATE_ACCEPT,
67   STATE_DISCONNECT,
68   STATE_FAILED
69 } session_state_t;
70
71 typedef struct
72 {
73   volatile session_state_t state;
74
75   svm_fifo_t *server_rx_fifo;
76   svm_fifo_t *server_tx_fifo;
77   u32 sm_seg_index;
78   u64 vpp_session_handle;
79   unix_shared_memory_queue_t *event_queue;
80
81   /* Socket configuration state */
82   u8 is_server;
83   u8 is_listen;
84   u8 is_cut_thru;
85   u8 is_nonblocking;
86   u32 vrf;
87   u8 is_ip4;
88   u8 ip[16];
89   u16 port;
90   u8 proto;
91   u64 client_queue_address;
92   u64 options[16];
93 } session_t;
94
95 typedef struct vppcom_cfg_t_
96 {
97   u64 heapsize;
98   u64 segment_baseva;
99   u32 segment_size;
100   u32 add_segment_size;
101   u32 preallocated_fifo_pairs;
102   u32 rx_fifo_size;
103   u32 tx_fifo_size;
104   u32 event_queue_size;
105   u32 listen_queue_size;
106   f64 app_timeout;
107   f64 session_timeout;
108   f64 accept_timeout;
109 } vppcom_cfg_t;
110
111 typedef struct vppcom_main_t_
112 {
113   u8 init;
114   u32 *client_session_index_fifo;
115   volatile u32 bind_session_index;
116   u32 tx_event_id;
117   int main_cpu;
118
119   /* vpe input queue */
120   unix_shared_memory_queue_t *vl_input_queue;
121
122   /* API client handle */
123   u32 my_client_index;
124
125   /* Session pool */
126   clib_spinlock_t sessions_lockp;
127   session_t *sessions;
128
129   /* Hash table for disconnect processing */
130   uword *session_index_by_vpp_handles;
131
132   /* Select bitmaps */
133   clib_bitmap_t *rd_bitmap;
134   clib_bitmap_t *wr_bitmap;
135   clib_bitmap_t *ex_bitmap;
136
137   /* Our event queue */
138   unix_shared_memory_queue_t *app_event_queue;
139
140   /* unique segment name counter */
141   u32 unique_segment_index;
142
143   pid_t my_pid;
144
145   /* For deadman timers */
146   clib_time_t clib_time;
147
148   /* State of the connection, shared between msg RX thread and main thread */
149   volatile app_state_t app_state;
150
151   vppcom_cfg_t cfg;
152
153   /* VNET_API_ERROR_FOO -> "Foo" hash table */
154   uword *error_string_by_error_number;
155 } vppcom_main_t;
156
157 vppcom_main_t vppcom_main = {.my_client_index = ~0 };
158
159 static const char *
160 vppcom_app_state_str (app_state_t state)
161 {
162   char *st;
163
164   switch (state)
165     {
166     case STATE_APP_START:
167       st = "STATE_APP_START";
168       break;
169
170     case STATE_APP_CONN_VPP:
171       st = "STATE_APP_CONN_VPP";
172       break;
173
174     case STATE_APP_ENABLED:
175       st = "STATE_APP_ENABLED";
176       break;
177
178     case STATE_APP_ATTACHED:
179       st = "STATE_APP_ATTACHED";
180       break;
181
182     default:
183       st = "UNKNOWN_APP_STATE";
184       break;
185     }
186
187   return st;
188 }
189
190 static const char *
191 vppcom_session_state_str (session_state_t state)
192 {
193   char *st;
194
195   switch (state)
196     {
197     case STATE_START:
198       st = "STATE_START";
199       break;
200
201     case STATE_CONNECT:
202       st = "STATE_CONNECT";
203       break;
204
205     case STATE_LISTEN:
206       st = "STATE_LISTEN";
207       break;
208
209     case STATE_ACCEPT:
210       st = "STATE_ACCEPT";
211       break;
212
213     case STATE_DISCONNECT:
214       st = "STATE_DISCONNECT";
215       break;
216
217     case STATE_FAILED:
218       st = "STATE_FAILED";
219       break;
220
221     default:
222       st = "UNKNOWN_STATE";
223       break;
224     }
225
226   return st;
227 }
228
229 /*
230  * VPPCOM Utility Functions
231  */
232 static inline int
233 vppcom_session_at_index (u32 session_index, session_t * volatile *sess)
234 {
235   vppcom_main_t *vcm = &vppcom_main;
236
237   /* Assumes that caller has acquired spinlock: vcm->sessions_lockp */
238   if (PREDICT_FALSE ((session_index == ~0) ||
239                      pool_is_free_index (vcm->sessions, session_index)))
240     {
241       clib_warning ("[%d] invalid session, sid (%d) has been closed!",
242                     vcm->my_pid, session_index);
243       return VPPCOM_EBADFD;
244     }
245   *sess = pool_elt_at_index (vcm->sessions, session_index);
246   return VPPCOM_OK;
247 }
248
249 static int
250 vppcom_connect_to_vpp (char *app_name)
251 {
252   api_main_t *am = &api_main;
253   vppcom_main_t *vcm = &vppcom_main;
254
255   if (VPPCOM_DEBUG > 0)
256     printf ("\nConnecting to VPP api...");
257   if (vl_client_connect_to_vlib ("/vpe-api", app_name, 32) < 0)
258     {
259       clib_warning ("[%d] connect to vpp (%s) failed!",
260                     vcm->my_pid, app_name);
261       return VPPCOM_ECONNREFUSED;
262     }
263
264   vcm->vl_input_queue = am->shmem_hdr->vl_input_queue;
265   vcm->my_client_index = am->my_client_index;
266   if (VPPCOM_DEBUG > 0)
267     printf (" connected!\n");
268
269   vcm->app_state = STATE_APP_CONN_VPP;
270   return VPPCOM_OK;
271 }
272
273 static u8 *
274 format_api_error (u8 * s, va_list * args)
275 {
276   vppcom_main_t *vcm = &vppcom_main;
277   i32 error = va_arg (*args, u32);
278   uword *p;
279
280   p = hash_get (vcm->error_string_by_error_number, -error);
281
282   if (p)
283     s = format (s, "%s (%d)", p[0], error);
284   else
285     s = format (s, "%d", error);
286   return s;
287 }
288
289 static void
290 vppcom_init_error_string_table (void)
291 {
292   vppcom_main_t *vcm = &vppcom_main;
293
294   vcm->error_string_by_error_number = hash_create (0, sizeof (uword));
295
296 #define _(n,v,s) hash_set (vcm->error_string_by_error_number, -v, s);
297   foreach_vnet_api_error;
298 #undef _
299
300   hash_set (vcm->error_string_by_error_number, 99, "Misc");
301 }
302
303 static inline int
304 vppcom_wait_for_app_state_change (app_state_t app_state)
305 {
306   vppcom_main_t *vcm = &vppcom_main;
307   f64 timeout = clib_time_now (&vcm->clib_time) + vcm->cfg.app_timeout;
308
309   while (clib_time_now (&vcm->clib_time) < timeout)
310     {
311       if (vcm->app_state == app_state)
312         return VPPCOM_OK;
313     }
314   if (VPPCOM_DEBUG > 0)
315     clib_warning ("[%d] timeout waiting for state %s (%d)", vcm->my_pid,
316                   vppcom_app_state_str (app_state), app_state);
317   return VPPCOM_ETIMEDOUT;
318 }
319
320 static inline int
321 vppcom_wait_for_session_state_change (u32 session_index,
322                                       session_state_t state,
323                                       f64 wait_for_time)
324 {
325   vppcom_main_t *vcm = &vppcom_main;
326   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
327   session_t *volatile session;
328   int rv;
329
330   do
331     {
332       clib_spinlock_lock (&vcm->sessions_lockp);
333       rv = vppcom_session_at_index (session_index, &session);
334       if (PREDICT_FALSE (rv))
335         {
336           clib_spinlock_unlock (&vcm->sessions_lockp);
337           return rv;
338         }
339       if (session->state == state)
340         {
341           clib_spinlock_unlock (&vcm->sessions_lockp);
342           return VPPCOM_OK;
343         }
344       clib_spinlock_unlock (&vcm->sessions_lockp);
345     }
346   while (clib_time_now (&vcm->clib_time) < timeout);
347
348   if (VPPCOM_DEBUG > 0)
349     clib_warning ("[%d] timeout waiting for state %s (%d)", vcm->my_pid,
350                   vppcom_session_state_str (state), state);
351   return VPPCOM_ETIMEDOUT;
352 }
353
354 static inline int
355 vppcom_wait_for_client_session_index (f64 wait_for_time)
356 {
357   vppcom_main_t *vcm = &vppcom_main;
358   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
359
360   do
361     {
362       if (clib_fifo_elts (vcm->client_session_index_fifo))
363         return VPPCOM_OK;
364     }
365   while (clib_time_now (&vcm->clib_time) < timeout);
366
367   if (wait_for_time == 0)
368     return VPPCOM_EAGAIN;
369
370   if (VPPCOM_DEBUG > 0)
371     clib_warning ("[%d] timeout waiting for client_session_index",
372                   vcm->my_pid);
373   return VPPCOM_ETIMEDOUT;
374 }
375
376 /*
377  * VPP-API message functions
378  */
379 static void
380 vppcom_send_session_enable_disable (u8 is_enable)
381 {
382   vppcom_main_t *vcm = &vppcom_main;
383   vl_api_session_enable_disable_t *bmp;
384   bmp = vl_msg_api_alloc (sizeof (*bmp));
385   memset (bmp, 0, sizeof (*bmp));
386
387   bmp->_vl_msg_id = ntohs (VL_API_SESSION_ENABLE_DISABLE);
388   bmp->client_index = vcm->my_client_index;
389   bmp->context = htonl (0xfeedface);
390   bmp->is_enable = is_enable;
391   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
392 }
393
394 static int
395 vppcom_app_session_enable (void)
396 {
397   vppcom_main_t *vcm = &vppcom_main;
398   int rv;
399
400   if (vcm->app_state != STATE_APP_ENABLED)
401     {
402       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
403       rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
404       if (PREDICT_FALSE (rv))
405         {
406           if (VPPCOM_DEBUG > 0)
407             clib_warning ("[%d] Session enable timed out, rv = %s (%d)",
408                           vcm->my_pid, vppcom_retval_str (rv), rv);
409           return rv;
410         }
411     }
412   return VPPCOM_OK;
413 }
414
415 static void
416   vl_api_session_enable_disable_reply_t_handler
417   (vl_api_session_enable_disable_reply_t * mp)
418 {
419   vppcom_main_t *vcm = &vppcom_main;
420
421   if (mp->retval)
422     {
423       clib_warning ("[%d] session_enable_disable failed: %U", vcm->my_pid,
424                     format_api_error, ntohl (mp->retval));
425     }
426   else
427     vcm->app_state = STATE_APP_ENABLED;
428 }
429
430 static void
431 vppcom_app_send_attach (void)
432 {
433   vppcom_main_t *vcm = &vppcom_main;
434   vl_api_application_attach_t *bmp;
435   bmp = vl_msg_api_alloc (sizeof (*bmp));
436   memset (bmp, 0, sizeof (*bmp));
437
438   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
439   bmp->client_index = vcm->my_client_index;
440   bmp->context = htonl (0xfeedface);
441   bmp->options[APP_OPTIONS_FLAGS] =
442     APP_OPTIONS_FLAGS_USE_FIFO | APP_OPTIONS_FLAGS_ADD_SEGMENT;
443   bmp->options[SESSION_OPTIONS_SEGMENT_SIZE] = vcm->cfg.segment_size;
444   bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = vcm->cfg.add_segment_size;
445   bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = vcm->cfg.rx_fifo_size;
446   bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = vcm->cfg.tx_fifo_size;
447   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
448 }
449
450 static int
451 vppcom_app_attach (void)
452 {
453   vppcom_main_t *vcm = &vppcom_main;
454   int rv;
455
456   vppcom_app_send_attach ();
457   rv = vppcom_wait_for_app_state_change (STATE_APP_ATTACHED);
458   if (PREDICT_FALSE (rv))
459     {
460       if (VPPCOM_DEBUG > 0)
461         clib_warning ("[%d] application attach timed out, rv = %s (%d)",
462                       vcm->my_pid, vppcom_retval_str (rv), rv);
463       return rv;
464     }
465   return VPPCOM_OK;
466 }
467
468 static void
469 vppcom_app_detach (void)
470 {
471   vppcom_main_t *vcm = &vppcom_main;
472   vl_api_application_detach_t *bmp;
473   bmp = vl_msg_api_alloc (sizeof (*bmp));
474   memset (bmp, 0, sizeof (*bmp));
475
476   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
477   bmp->client_index = vcm->my_client_index;
478   bmp->context = htonl (0xfeedface);
479   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
480 }
481
482 static void
483 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
484                                            mp)
485 {
486   vppcom_main_t *vcm = &vppcom_main;
487   static svm_fifo_segment_create_args_t _a;
488   svm_fifo_segment_create_args_t *a = &_a;
489   int rv;
490
491   memset (a, 0, sizeof (*a));
492   if (mp->retval)
493     {
494       clib_warning ("[%d] attach failed: %U", vcm->my_pid,
495                     format_api_error, ntohl (mp->retval));
496       return;
497     }
498
499   if (mp->segment_name_length == 0)
500     {
501       clib_warning ("[%d] segment_name_length zero", vcm->my_pid);
502       return;
503     }
504
505   a->segment_name = (char *) mp->segment_name;
506   a->segment_size = mp->segment_size;
507
508   ASSERT (mp->app_event_queue_address);
509
510   /* Attach to the segment vpp created */
511   rv = svm_fifo_segment_attach (a);
512   vec_reset_length (a->new_segment_indices);
513   if (PREDICT_FALSE (rv))
514     {
515       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed", vcm->my_pid,
516                     mp->segment_name);
517       return;
518     }
519
520   vcm->app_event_queue =
521     uword_to_pointer (mp->app_event_queue_address,
522                       unix_shared_memory_queue_t *);
523
524   vcm->app_state = STATE_APP_ATTACHED;
525 }
526
527 static void
528 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
529                                            mp)
530 {
531   vppcom_main_t *vcm = &vppcom_main;
532
533   if (mp->retval)
534     clib_warning ("[%d] detach failed: %U", vcm->my_pid, format_api_error,
535                   ntohl (mp->retval));
536
537   vcm->app_state = STATE_APP_ENABLED;
538 }
539
540 static void
541 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
542                                            mp)
543 {
544   vppcom_main_t *vcm = &vppcom_main;
545   uword *p;
546
547   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
548   if (p)
549     {
550       session_t *session = 0;
551       int rv;
552       clib_spinlock_lock (&vcm->sessions_lockp);
553       rv = vppcom_session_at_index (p[0], &session);
554       if (PREDICT_FALSE (rv))
555         {
556           if (VPPCOM_DEBUG > 1)
557             clib_warning ("[%d] invalid session, sid (%d) has been closed!",
558                           vcm->my_pid, p[0]);
559         }
560       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
561       session->state = STATE_DISCONNECT;
562       clib_spinlock_unlock (&vcm->sessions_lockp);
563     }
564   else
565     {
566       if (VPPCOM_DEBUG > 1)
567         clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
568                       mp->handle);
569     }
570
571   if (mp->retval)
572     clib_warning ("[%d] disconnect_session failed: %U", vcm->my_pid,
573                   format_api_error, ntohl (mp->retval));
574 }
575
576 static void
577 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
578 {
579   vppcom_main_t *vcm = &vppcom_main;
580   static svm_fifo_segment_create_args_t _a;
581   svm_fifo_segment_create_args_t *a = &_a;
582   int rv;
583
584   memset (a, 0, sizeof (*a));
585   a->segment_name = (char *) mp->segment_name;
586   a->segment_size = mp->segment_size;
587   /* Attach to the segment vpp created */
588   rv = svm_fifo_segment_attach (a);
589   vec_reset_length (a->new_segment_indices);
590   if (PREDICT_FALSE (rv))
591     {
592       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed",
593                     vcm->my_pid, mp->segment_name);
594       return;
595     }
596   if (VPPCOM_DEBUG > 1)
597     clib_warning ("[%d] mapped new segment '%s' size %d", vcm->my_pid,
598                   mp->segment_name, mp->segment_size);
599 }
600
601 static void
602 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
603 {
604   vppcom_main_t *vcm = &vppcom_main;
605   session_t *session = 0;
606   vl_api_disconnect_session_reply_t *rmp;
607   uword *p;
608   int rv = 0;
609
610   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
611   if (p)
612     {
613       int rval;
614       clib_spinlock_lock (&vcm->sessions_lockp);
615       rval = vppcom_session_at_index (p[0], &session);
616       if (PREDICT_FALSE (rval))
617         {
618           if (VPPCOM_DEBUG > 1)
619             clib_warning ("[%d] invalid session, sid (%d) has been closed!",
620                           vcm->my_pid, p[0]);
621         }
622       else
623         pool_put (vcm->sessions, session);
624       clib_spinlock_unlock (&vcm->sessions_lockp);
625       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
626     }
627   else
628     {
629       clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
630                     mp->handle);
631       rv = -11;
632     }
633
634   rmp = vl_msg_api_alloc (sizeof (*rmp));
635   memset (rmp, 0, sizeof (*rmp));
636
637   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
638   rmp->retval = htonl (rv);
639   rmp->handle = mp->handle;
640   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
641 }
642
643 static void
644 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
645 {
646   vppcom_main_t *vcm = &vppcom_main;
647   session_t *session = 0;
648   vl_api_reset_session_reply_t *rmp;
649   uword *p;
650   int rv = 0;
651
652   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
653   if (p)
654     {
655       int rval;
656       clib_spinlock_lock (&vcm->sessions_lockp);
657       rval = vppcom_session_at_index (p[0], &session);
658       if (PREDICT_FALSE (rval))
659         {
660           if (VPPCOM_DEBUG > 1)
661             clib_warning ("[%d] invalid session, sid (%d) has been closed!",
662                           vcm->my_pid, p[0]);
663         }
664       else
665         pool_put (vcm->sessions, session);
666       clib_spinlock_unlock (&vcm->sessions_lockp);
667       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
668     }
669   else
670     {
671       clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
672                     mp->handle);
673       rv = -11;
674     }
675
676   rmp = vl_msg_api_alloc (sizeof (*rmp));
677   memset (rmp, 0, sizeof (*rmp));
678   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
679   rmp->retval = htonl (rv);
680   rmp->handle = mp->handle;
681   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
682 }
683
684 static void
685 vl_api_connect_sock_reply_t_handler (vl_api_connect_sock_reply_t * mp)
686 {
687   vppcom_main_t *vcm = &vppcom_main;
688   session_t *session;
689   u32 session_index;
690   svm_fifo_t *rx_fifo, *tx_fifo;
691   u8 is_cut_thru = 0;
692   int rv;
693
694   if (mp->retval)
695     {
696       clib_warning ("[%d] connect failed: %U", vcm->my_pid, format_api_error,
697                     ntohl (mp->retval));
698       return;
699     }
700
701   session_index = ntohl (mp->app_connect);
702   if (VPPCOM_DEBUG > 1)
703     clib_warning ("[%d] app_connect = %d 0x%08x", vcm->my_pid,
704                   session_index, session_index);
705
706   clib_spinlock_lock (&vcm->sessions_lockp);
707   if (pool_is_free_index (vcm->sessions, session_index))
708     {
709       clib_spinlock_unlock (&vcm->sessions_lockp);
710       if (VPPCOM_DEBUG > 1)
711         clib_warning ("[%d] invalid session, sid %d is closed!",
712                       vcm->my_pid, session_index);
713       return;
714     }
715
716   /* We've been redirected */
717   if (mp->segment_name_length > 0)
718     {
719       static svm_fifo_segment_create_args_t _a;
720       svm_fifo_segment_create_args_t *a = &_a;
721
722       is_cut_thru = 1;
723       memset (a, 0, sizeof (*a));
724       a->segment_name = (char *) mp->segment_name;
725       if (VPPCOM_DEBUG > 1)
726         clib_warning ("[%d] cut-thru segment: %s", vcm->my_pid,
727                       a->segment_name);
728       rv = svm_fifo_segment_attach (a);
729       vec_reset_length (a->new_segment_indices);
730       if (PREDICT_FALSE (rv))
731         {
732           clib_warning ("[%d] sm_fifo_segment_attach ('%s') failed",
733                         vcm->my_pid, a->segment_name);
734           return;
735         }
736     }
737
738   /*
739    * Setup session
740    */
741   if (VPPCOM_DEBUG > 1)
742     clib_warning ("[%d] client sid %d", vcm->my_pid, session_index);
743
744   session = pool_elt_at_index (vcm->sessions, session_index);
745   session->is_cut_thru = is_cut_thru;
746   session->event_queue = uword_to_pointer (mp->vpp_event_queue_address,
747                                            unix_shared_memory_queue_t *);
748
749   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
750   rx_fifo->client_session_index = session_index;
751   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
752   tx_fifo->client_session_index = session_index;
753
754   session->server_rx_fifo = rx_fifo;
755   session->server_tx_fifo = tx_fifo;
756   session->vpp_session_handle = mp->handle;
757   session->state = STATE_CONNECT;
758
759   /* Add it to lookup table */
760   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
761   clib_spinlock_unlock (&vcm->sessions_lockp);
762 }
763
764 static void
765 vppcom_send_connect_sock (session_t * session, u32 session_index)
766 {
767   vppcom_main_t *vcm = &vppcom_main;
768   vl_api_connect_sock_t *cmp;
769
770   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
771   session->is_server = 0;
772   cmp = vl_msg_api_alloc (sizeof (*cmp));
773   memset (cmp, 0, sizeof (*cmp));
774   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK);
775   cmp->client_index = vcm->my_client_index;
776   cmp->context = htonl (0xfeedface);
777   cmp->app_connect = session_index;
778
779   if (VPPCOM_DEBUG > 1)
780     clib_warning ("[%d] session_index = %d 0x%08x, app_connect = %d 0x%08x",
781                   vcm->my_pid, session_index, session_index,
782                   cmp->app_connect, cmp->app_connect);
783
784   cmp->vrf = session->vrf;
785   cmp->is_ip4 = session->is_ip4;
786   clib_memcpy (cmp->ip, session->ip, (session->is_ip4 ?
787                                       sizeof (ip4_address_t) :
788                                       sizeof (ip6_address_t)));
789   cmp->port = session->port;
790   cmp->proto = session->proto;
791   clib_memcpy (cmp->options, session->options, sizeof (cmp->options));
792   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & cmp);
793 }
794
795 static int
796 vppcom_send_disconnect (u32 session_index)
797 {
798   vppcom_main_t *vcm = &vppcom_main;
799   vl_api_disconnect_session_t *dmp;
800   session_t *session = 0;
801   int rv;
802
803   clib_spinlock_lock (&vcm->sessions_lockp);
804   rv = vppcom_session_at_index (session_index, &session);
805   if (PREDICT_FALSE (rv))
806     {
807       clib_spinlock_unlock (&vcm->sessions_lockp);
808       if (VPPCOM_DEBUG > 1)
809         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
810                       vcm->my_pid, session_index);
811       return rv;
812     }
813
814   dmp = vl_msg_api_alloc (sizeof (*dmp));
815   memset (dmp, 0, sizeof (*dmp));
816   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
817   dmp->client_index = vcm->my_client_index;
818   dmp->handle = session->vpp_session_handle;
819   clib_spinlock_unlock (&vcm->sessions_lockp);
820   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & dmp);
821   return VPPCOM_OK;
822 }
823
824 static void
825 vl_api_bind_sock_reply_t_handler (vl_api_bind_sock_reply_t * mp)
826 {
827   vppcom_main_t *vcm = &vppcom_main;
828   session_t *session = 0;
829   int rv;
830
831   if (mp->retval)
832     clib_warning ("[%d] bind failed: %U", vcm->my_pid, format_api_error,
833                   ntohl (mp->retval));
834
835   ASSERT (vcm->bind_session_index != ~0);
836
837   clib_spinlock_lock (&vcm->sessions_lockp);
838   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
839   if (rv == VPPCOM_OK)
840     {
841       session->vpp_session_handle = mp->handle;
842       hash_set (vcm->session_index_by_vpp_handles, mp->handle,
843                 vcm->bind_session_index);
844       session->state = mp->retval ? STATE_FAILED : STATE_LISTEN;
845       vcm->bind_session_index = ~0;
846     }
847   clib_spinlock_unlock (&vcm->sessions_lockp);
848 }
849
850 static void
851 vl_api_unbind_sock_reply_t_handler (vl_api_unbind_sock_reply_t * mp)
852 {
853   vppcom_main_t *vcm = &vppcom_main;
854   session_t *session = 0;
855   int rv;
856
857   clib_spinlock_lock (&vcm->sessions_lockp);
858   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
859   if (PREDICT_FALSE (rv))
860     {
861       if (VPPCOM_DEBUG > 1)
862         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
863                       vcm->my_pid, vcm->bind_session_index);
864     }
865
866   if (mp->retval)
867     clib_warning ("[%d] unbind failed: %U", vcm->my_pid, format_api_error,
868                   ntohl (mp->retval));
869
870   vcm->bind_session_index = ~0;
871   session->state = STATE_START;
872   clib_spinlock_unlock (&vcm->sessions_lockp);
873 }
874
875 u8 *
876 format_ip4_address (u8 * s, va_list * args)
877 {
878   u8 *a = va_arg (*args, u8 *);
879   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
880 }
881
882 u8 *
883 format_ip6_address (u8 * s, va_list * args)
884 {
885   ip6_address_t *a = va_arg (*args, ip6_address_t *);
886   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
887
888   i_max_n_zero = ARRAY_LEN (a->as_u16);
889   max_n_zeros = 0;
890   i_first_zero = i_max_n_zero;
891   n_zeros = 0;
892   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
893     {
894       u32 is_zero = a->as_u16[i] == 0;
895       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
896         {
897           i_first_zero = i;
898           n_zeros = 0;
899         }
900       n_zeros += is_zero;
901       if ((!is_zero && n_zeros > max_n_zeros)
902           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
903         {
904           i_max_n_zero = i_first_zero;
905           max_n_zeros = n_zeros;
906           i_first_zero = ARRAY_LEN (a->as_u16);
907           n_zeros = 0;
908         }
909     }
910
911   last_double_colon = 0;
912   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
913     {
914       if (i == i_max_n_zero && max_n_zeros > 1)
915         {
916           s = format (s, "::");
917           i += max_n_zeros - 1;
918           last_double_colon = 1;
919         }
920       else
921         {
922           s = format (s, "%s%x",
923                       (last_double_colon || i == 0) ? "" : ":",
924                       clib_net_to_host_u16 (a->as_u16[i]));
925           last_double_colon = 0;
926         }
927     }
928
929   return s;
930 }
931
932 /* Format an IP46 address. */
933 u8 *
934 format_ip46_address (u8 * s, va_list * args)
935 {
936   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
937   ip46_type_t type = va_arg (*args, ip46_type_t);
938   int is_ip4 = 1;
939
940   switch (type)
941     {
942     case IP46_TYPE_ANY:
943       is_ip4 = ip46_address_is_ip4 (ip46);
944       break;
945     case IP46_TYPE_IP4:
946       is_ip4 = 1;
947       break;
948     case IP46_TYPE_IP6:
949       is_ip4 = 0;
950       break;
951     }
952
953   return is_ip4 ?
954     format (s, "%U", format_ip4_address, &ip46->ip4) :
955     format (s, "%U", format_ip6_address, &ip46->ip6);
956 }
957
958 static void
959 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
960 {
961   vppcom_main_t *vcm = &vppcom_main;
962   vl_api_accept_session_reply_t *rmp;
963   svm_fifo_t *rx_fifo, *tx_fifo;
964   session_t *session;
965   u32 session_index;
966   int rv = 0;
967
968   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
969     {
970       clib_warning ("[%d] client session queue is full!", vcm->my_pid);
971       rv = VNET_API_ERROR_QUEUE_FULL;
972       goto send_reply;
973     }
974
975   if (VPPCOM_DEBUG > 1)
976     {
977       u8 *ip_str = format (0, "%U", format_ip46_address, &mp->ip, mp->is_ip4);
978       clib_warning ("[%d] accepted session from: %s:%d", vcm->my_pid, ip_str,
979                     clib_net_to_host_u16 (mp->port));
980       vec_free (ip_str);
981     }
982
983   clib_spinlock_lock (&vcm->sessions_lockp);
984   /* Allocate local session and set it up */
985   pool_get (vcm->sessions, session);
986   memset (session, 0, sizeof (*session));
987   session_index = session - vcm->sessions;
988
989   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
990   rx_fifo->client_session_index = session_index;
991   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
992   tx_fifo->client_session_index = session_index;
993
994   session->server_rx_fifo = rx_fifo;
995   session->server_tx_fifo = tx_fifo;
996   session->event_queue = uword_to_pointer (mp->vpp_event_queue_address,
997                                            unix_shared_memory_queue_t *);
998   session->state = STATE_ACCEPT;
999   session->is_cut_thru = 0;
1000   session->port = ntohs (mp->port);
1001   session->is_ip4 = mp->is_ip4;
1002   clib_memcpy (session->ip, mp->ip, (mp->is_ip4 ?
1003                                      sizeof (ip4_address_t) :
1004                                      sizeof (ip6_address_t)));
1005   clib_spinlock_unlock (&vcm->sessions_lockp);
1006
1007   /* Add it to lookup table */
1008   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
1009
1010   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1011
1012   /*
1013    * Send accept reply to vpp
1014    */
1015 send_reply:
1016   rmp = vl_msg_api_alloc (sizeof (*rmp));
1017   memset (rmp, 0, sizeof (*rmp));
1018   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
1019   rmp->retval = htonl (rv);
1020   rmp->handle = mp->handle;
1021   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1022 }
1023
1024 /*
1025  * Acting as server for redirected connect requests
1026  */
1027 static void
1028 vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
1029 {
1030   static svm_fifo_segment_create_args_t _a;
1031   svm_fifo_segment_create_args_t *a = &_a;
1032   vppcom_main_t *vcm = &vppcom_main;
1033   u32 session_index;
1034   svm_fifo_segment_private_t *seg;
1035   unix_shared_memory_queue_t *client_q;
1036   vl_api_connect_sock_reply_t *rmp;
1037   session_t *session = 0;
1038   int rv = 0;
1039   svm_fifo_t *rx_fifo;
1040   svm_fifo_t *tx_fifo;
1041   unix_shared_memory_queue_t *event_q = 0;
1042
1043   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1044     {
1045       if (VPPCOM_DEBUG > 1)
1046         clib_warning ("[%d] client session queue is full!", vcm->my_pid);
1047       rv = VNET_API_ERROR_QUEUE_FULL;
1048       goto send_reply;
1049     }
1050
1051   /* Create the segment */
1052   memset (a, 0, sizeof (*a));
1053   a->segment_name = (char *) format ((u8 *) a->segment_name, "%d:segment%d%c",
1054                                      vcm->my_pid, vcm->unique_segment_index++,
1055                                      0);
1056   a->segment_size = vcm->cfg.segment_size;
1057   a->preallocated_fifo_pairs = vcm->cfg.preallocated_fifo_pairs;
1058   a->rx_fifo_size = vcm->cfg.rx_fifo_size;
1059   a->tx_fifo_size = vcm->cfg.tx_fifo_size;
1060
1061   rv = svm_fifo_segment_create (a);
1062   if (PREDICT_FALSE (rv))
1063     {
1064       if (VPPCOM_DEBUG > 1)
1065         clib_warning ("[%d] svm_fifo_segment_create ('%s') failed",
1066                       vcm->my_pid, a->segment_name);
1067       vec_reset_length (a->new_segment_indices);
1068       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1069       goto send_reply;
1070     }
1071
1072   if (VPPCOM_DEBUG > 1)
1073     clib_warning ("[%d] created segment '%s'", vcm->my_pid, a->segment_name);
1074
1075   clib_spinlock_lock (&vcm->sessions_lockp);
1076   pool_get (vcm->sessions, session);
1077   memset (session, 0, sizeof (*session));
1078   session_index = session - vcm->sessions;
1079
1080   session->sm_seg_index = a->new_segment_indices[0];
1081   vec_reset_length (a->new_segment_indices);
1082
1083   seg = svm_fifo_get_segment (session->sm_seg_index);
1084   rx_fifo = session->server_rx_fifo =
1085     svm_fifo_segment_alloc_fifo (seg, vcm->cfg.rx_fifo_size,
1086                                  FIFO_SEGMENT_RX_FREELIST);
1087   if (PREDICT_FALSE (!session->server_rx_fifo))
1088     {
1089       svm_fifo_segment_delete (seg);
1090       clib_warning ("[%d] rx fifo alloc failed, size %ld (0x%lx)",
1091                     vcm->my_pid, vcm->cfg.rx_fifo_size,
1092                     vcm->cfg.rx_fifo_size);
1093       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1094       clib_spinlock_unlock (&vcm->sessions_lockp);
1095       goto send_reply;
1096     }
1097
1098   tx_fifo = session->server_tx_fifo =
1099     svm_fifo_segment_alloc_fifo (seg, vcm->cfg.tx_fifo_size,
1100                                  FIFO_SEGMENT_TX_FREELIST);
1101   if (PREDICT_FALSE (!session->server_tx_fifo))
1102     {
1103       svm_fifo_segment_delete (seg);
1104       if (VPPCOM_DEBUG > 1)
1105         clib_warning ("[%d] tx fifo alloc failed, size %ld (0x%lx)",
1106                       vcm->my_pid, vcm->cfg.tx_fifo_size,
1107                       vcm->cfg.tx_fifo_size);
1108       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1109       clib_spinlock_unlock (&vcm->sessions_lockp);
1110       goto send_reply;
1111     }
1112
1113   session->server_rx_fifo->master_session_index = session_index;
1114   session->server_tx_fifo->master_session_index = session_index;
1115   session->client_queue_address = mp->client_queue_address;
1116   session->is_cut_thru = 1;
1117   session->is_server = 1;
1118   session->is_ip4 = mp->is_ip4;
1119   session->port = mp->port;
1120   {
1121     void *oldheap;
1122     ssvm_shared_header_t *sh = seg->ssvm.sh;
1123
1124     ssvm_lock_non_recursive (sh, 1);
1125     oldheap = ssvm_push_heap (sh);
1126     event_q = session->event_queue =
1127       unix_shared_memory_queue_init (vcm->cfg.event_queue_size,
1128                                      sizeof (session_fifo_event_t),
1129                                      vcm->my_pid, 0 /* signal not sent */ );
1130     ssvm_pop_heap (oldheap);
1131     ssvm_unlock_non_recursive (sh);
1132   }
1133   clib_memcpy (session->ip, mp->ip, (mp->is_ip4 ?
1134                                      sizeof (ip4_address_t) :
1135                                      sizeof (ip6_address_t)));
1136   session->state = STATE_ACCEPT;
1137   if (VPPCOM_DEBUG > 1)
1138     clib_warning ("[%d] Connected cut-thru to client: sid %d",
1139                   vcm->my_pid, session_index);
1140   clib_spinlock_unlock (&vcm->sessions_lockp);
1141   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1142
1143 send_reply:
1144   rmp = vl_msg_api_alloc (sizeof (*rmp));
1145   memset (rmp, 0, sizeof (*rmp));
1146
1147   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK_REPLY);
1148   rmp->context = mp->context;
1149   rmp->app_connect = htonl (mp->app_connect);
1150   rmp->retval = htonl (rv);
1151   rmp->segment_name_length = vec_len (a->segment_name);
1152   clib_memcpy (rmp->segment_name, a->segment_name, vec_len (a->segment_name));
1153   vec_reset_length (a->segment_name);
1154
1155   if (event_q)
1156     {
1157       rmp->vpp_event_queue_address = pointer_to_uword (event_q);
1158       rmp->server_rx_fifo = pointer_to_uword (rx_fifo);
1159       rmp->server_tx_fifo = pointer_to_uword (tx_fifo);
1160     }
1161   client_q =
1162     uword_to_pointer (mp->client_queue_address, unix_shared_memory_queue_t *);
1163
1164   ASSERT (client_q);
1165   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
1166 }
1167
1168 static void
1169 vppcom_send_bind_sock (session_t * session)
1170 {
1171   vppcom_main_t *vcm = &vppcom_main;
1172   vl_api_bind_sock_t *bmp;
1173
1174   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1175   session->is_server = 1;
1176   bmp = vl_msg_api_alloc (sizeof (*bmp));
1177   memset (bmp, 0, sizeof (*bmp));
1178
1179   bmp->_vl_msg_id = ntohs (VL_API_BIND_SOCK);
1180   bmp->client_index = vcm->my_client_index;
1181   bmp->context = htonl (0xfeedface);
1182   bmp->vrf = session->vrf;
1183   bmp->is_ip4 = session->is_ip4;
1184   clib_memcpy (bmp->ip, session->ip, (session->is_ip4 ?
1185                                       sizeof (ip4_address_t) :
1186                                       sizeof (ip6_address_t)));
1187   bmp->port = session->port;
1188   bmp->proto = session->proto;
1189   clib_memcpy (bmp->options, session->options, sizeof (bmp->options));
1190   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
1191 }
1192
1193 static void
1194 vppcom_send_unbind_sock (u32 session_index)
1195 {
1196   vppcom_main_t *vcm = &vppcom_main;
1197   vl_api_unbind_sock_t *ump;
1198   session_t *session = 0;
1199   int rv;
1200
1201   clib_spinlock_lock (&vcm->sessions_lockp);
1202   rv = vppcom_session_at_index (session_index, &session);
1203   if (PREDICT_FALSE (rv))
1204     {
1205       clib_spinlock_unlock (&vcm->sessions_lockp);
1206       if (VPPCOM_DEBUG > 0)
1207         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1208                       vcm->my_pid, session_index);
1209       return;
1210     }
1211
1212   ump = vl_msg_api_alloc (sizeof (*ump));
1213   memset (ump, 0, sizeof (*ump));
1214
1215   ump->_vl_msg_id = ntohs (VL_API_UNBIND_SOCK);
1216   ump->client_index = vcm->my_client_index;
1217   ump->handle = session->vpp_session_handle;
1218   clib_spinlock_unlock (&vcm->sessions_lockp);
1219   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & ump);
1220 }
1221
1222 static int
1223 vppcom_session_unbind_cut_thru (session_t * session)
1224 {
1225   svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
1226   svm_fifo_segment_private_t *seg;
1227   int rv = VPPCOM_OK;
1228
1229   seg = vec_elt_at_index (sm->segments, session->sm_seg_index);
1230   svm_fifo_segment_free_fifo (seg, session->server_rx_fifo,
1231                               FIFO_SEGMENT_RX_FREELIST);
1232   svm_fifo_segment_free_fifo (seg, session->server_tx_fifo,
1233                               FIFO_SEGMENT_TX_FREELIST);
1234   svm_fifo_segment_delete (seg);
1235
1236   return rv;
1237 }
1238
1239 static int
1240 vppcom_session_unbind (u32 session_index)
1241 {
1242   vppcom_main_t *vcm = &vppcom_main;
1243   int rv;
1244
1245   clib_spinlock_lock (&vcm->sessions_lockp);
1246   if (PREDICT_FALSE (pool_is_free_index (vcm->sessions, session_index)))
1247     {
1248       clib_spinlock_unlock (&vcm->sessions_lockp);
1249       if (VPPCOM_DEBUG > 1)
1250         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1251                       vcm->my_pid, session_index);
1252       return VPPCOM_EBADFD;
1253     }
1254   clib_spinlock_unlock (&vcm->sessions_lockp);
1255
1256   vcm->bind_session_index = session_index;
1257   vppcom_send_unbind_sock (session_index);
1258   rv = vppcom_wait_for_session_state_change (session_index, STATE_START,
1259                                              vcm->cfg.session_timeout);
1260   if (PREDICT_FALSE (rv))
1261     {
1262       vcm->bind_session_index = ~0;
1263       if (VPPCOM_DEBUG > 0)
1264         clib_warning ("[%d] server unbind timed out, rv = %s (%d)",
1265                       vcm->my_pid, vppcom_retval_str (rv), rv);
1266       return rv;
1267     }
1268   return VPPCOM_OK;
1269 }
1270
1271 static int
1272 vppcom_session_disconnect (u32 session_index)
1273 {
1274   vppcom_main_t *vcm = &vppcom_main;
1275   int rv;
1276
1277   rv = vppcom_send_disconnect (session_index);
1278   if (PREDICT_FALSE (rv))
1279     return rv;
1280
1281   rv = vppcom_wait_for_session_state_change (session_index, STATE_DISCONNECT,
1282                                              vcm->cfg.session_timeout);
1283   if (PREDICT_FALSE (rv))
1284     {
1285       if (VPPCOM_DEBUG > 0)
1286         clib_warning ("[%d] client disconnect timed out, rv = %s (%d)",
1287                       vcm->my_pid, vppcom_retval_str (rv), rv);
1288       return rv;
1289     }
1290
1291   clib_spinlock_lock (&vcm->sessions_lockp);
1292   pool_put_index (vcm->sessions, session_index);
1293   clib_spinlock_unlock (&vcm->sessions_lockp);
1294   return VPPCOM_OK;
1295 }
1296
1297 #define foreach_sock_msg                                        \
1298 _(SESSION_ENABLE_DISABLE_REPLY, session_enable_disable_reply)   \
1299 _(BIND_SOCK_REPLY, bind_sock_reply)                             \
1300 _(UNBIND_SOCK_REPLY, unbind_sock_reply)                         \
1301 _(ACCEPT_SESSION, accept_session)                               \
1302 _(CONNECT_SOCK, connect_sock)                                   \
1303 _(CONNECT_SOCK_REPLY, connect_sock_reply)                       \
1304 _(DISCONNECT_SESSION, disconnect_session)                       \
1305 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1306 _(RESET_SESSION, reset_session)                                 \
1307 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1308 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1309 _(MAP_ANOTHER_SEGMENT, map_another_segment)
1310
1311 static void
1312 vppcom_api_hookup (void)
1313 {
1314 #define _(N,n)                                                  \
1315     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1316                            vl_api_##n##_t_handler,              \
1317                            vl_noop_handler,                     \
1318                            vl_api_##n##_t_endian,               \
1319                            vl_api_##n##_t_print,                \
1320                            sizeof(vl_api_##n##_t), 1);
1321   foreach_sock_msg;
1322 #undef _
1323 }
1324
1325 static void
1326 vppcom_cfg_init (vppcom_cfg_t * vcl_cfg)
1327 {
1328   ASSERT (vcl_cfg);
1329
1330   vcl_cfg->heapsize = (256ULL << 20);
1331   vcl_cfg->segment_baseva = 0x200000000ULL;
1332   vcl_cfg->segment_size = (256 << 20);
1333   vcl_cfg->add_segment_size = (128 << 20);
1334   vcl_cfg->preallocated_fifo_pairs = 8;
1335   vcl_cfg->rx_fifo_size = (1 << 20);
1336   vcl_cfg->tx_fifo_size = (1 << 20);
1337   vcl_cfg->event_queue_size = 2048;
1338   vcl_cfg->listen_queue_size = CLIB_CACHE_LINE_BYTES / sizeof (u32);
1339   vcl_cfg->app_timeout = 10 * 60.0;
1340   vcl_cfg->session_timeout = 10 * 60.0;
1341   vcl_cfg->accept_timeout = 60.0;
1342 }
1343
1344 static void
1345 vppcom_cfg_heapsize (char *conf_fname)
1346 {
1347   vppcom_main_t *vcm = &vppcom_main;
1348   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1349   FILE *fp;
1350   char inbuf[4096];
1351   int argc = 1;
1352   char **argv = NULL;
1353   char *arg = NULL;
1354   char *p;
1355   int i;
1356   u8 *sizep;
1357   u32 size;
1358
1359   fp = fopen (conf_fname, "r");
1360   if (fp == NULL)
1361     {
1362       if (VPPCOM_DEBUG > 0)
1363         fprintf (stderr, "open configuration file '%s' failed\n", conf_fname);
1364       goto defaulted;
1365     }
1366   argv = calloc (1, sizeof (char *));
1367   if (argv == NULL)
1368     goto defaulted;
1369
1370   while (1)
1371     {
1372       if (fgets (inbuf, 4096, fp) == 0)
1373         break;
1374       p = strtok (inbuf, " \t\n");
1375       while (p != NULL)
1376         {
1377           if (*p == '#')
1378             break;
1379           argc++;
1380           char **tmp = realloc (argv, argc * sizeof (char *));
1381           if (tmp == NULL)
1382             {
1383               fclose (fp);
1384               goto defaulted;
1385             }
1386           argv = tmp;
1387           arg = strndup (p, 1024);
1388           if (arg == NULL)
1389             {
1390               fclose (fp);
1391               goto defaulted;
1392             }
1393           argv[argc - 1] = arg;
1394           p = strtok (NULL, " \t\n");
1395         }
1396     }
1397
1398   fclose (fp);
1399
1400   char **tmp = realloc (argv, (argc + 1) * sizeof (char *));
1401   if (tmp == NULL)
1402     goto defaulted;
1403   argv = tmp;
1404   argv[argc] = NULL;
1405
1406   /*
1407    * Look for and parse the "heapsize" config parameter.
1408    * Manual since none of the clib infra has been bootstrapped yet.
1409    *
1410    * Format: heapsize <nn>[mM][gG]
1411    */
1412
1413   for (i = 1; i < (argc - 1); i++)
1414     {
1415       if (!strncmp (argv[i], "heapsize", 8))
1416         {
1417           sizep = (u8 *) argv[i + 1];
1418           size = 0;
1419           while (*sizep >= '0' && *sizep <= '9')
1420             {
1421               size *= 10;
1422               size += *sizep++ - '0';
1423             }
1424           if (size == 0)
1425             {
1426               if (VPPCOM_DEBUG > 0)
1427                 clib_warning ("[%d] parse error '%s %s', "
1428                               "using default heapsize %lld (0x%llx)",
1429                               vcm->my_pid, argv[i], argv[i + 1],
1430                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1431               goto defaulted;
1432             }
1433
1434           if (*sizep == 'g' || *sizep == 'G')
1435             vcl_cfg->heapsize = size << 30;
1436           else if (*sizep == 'm' || *sizep == 'M')
1437             vcl_cfg->heapsize = size << 20;
1438           else
1439             {
1440               if (VPPCOM_DEBUG > 0)
1441                 clib_warning ("[%d] parse error '%s %s', "
1442                               "using default heapsize %lld (0x%llx)",
1443                               vcm->my_pid, argv[i], argv[i + 1],
1444                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1445               goto defaulted;
1446             }
1447         }
1448     }
1449
1450 defaulted:
1451   if (!clib_mem_init (0, vcl_cfg->heapsize))
1452     clib_warning ("[%d] vppcom heap allocation failure!", vcm->my_pid);
1453   else if (VPPCOM_DEBUG > 0)
1454     clib_warning ("[%d] allocated vppcom heapsize %lld (0x%llx)",
1455                   vcm->my_pid, vcl_cfg->heapsize, vcl_cfg->heapsize);
1456 }
1457
1458 static void
1459 vppcom_cfg_read (char *conf_fname)
1460 {
1461   vppcom_main_t *vcm = &vppcom_main;
1462   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1463   int fd;
1464   unformat_input_t _input, *input = &_input;
1465   unformat_input_t _line_input, *line_input = &_line_input;
1466   u8 vc_cfg_input = 0;
1467   u8 *chroot_path;
1468   struct stat s;
1469   u32 uid, gid;
1470
1471   fd = open (conf_fname, O_RDONLY);
1472   if (fd < 0)
1473     {
1474       if (VPPCOM_DEBUG > 0)
1475         clib_warning ("[%d] open configuration file '%s' failed!",
1476                       vcm->my_pid, conf_fname);
1477       goto file_done;
1478     }
1479
1480   if (fstat (fd, &s) < 0)
1481     {
1482       if (VPPCOM_DEBUG > 0)
1483         clib_warning ("[%d] failed to stat `%s'", vcm->my_pid, conf_fname);
1484       goto file_done;
1485     }
1486
1487   if (!(S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
1488     {
1489       if (VPPCOM_DEBUG > 0)
1490         clib_warning ("[%d] not a regular file `%s'", vcm->my_pid,
1491                       conf_fname);
1492       goto file_done;
1493     }
1494
1495   unformat_init_unix_file (input, fd);
1496
1497   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1498     {
1499       unformat_user (input, unformat_line_input, line_input);
1500       unformat_skip_white_space (line_input);
1501
1502       if (unformat (line_input, "vppcom {"))
1503         {
1504           vc_cfg_input = 1;
1505           continue;
1506         }
1507
1508       if (vc_cfg_input)
1509         {
1510           if (unformat (line_input, "heapsize %s", &chroot_path))
1511             {
1512               vec_terminate_c_string (chroot_path);
1513               if (VPPCOM_DEBUG > 0)
1514                 clib_warning ("[%d] configured heapsize %s, "
1515                               "actual heapsize %lld (0x%llx)",
1516                               vcm->my_pid, chroot_path, vcl_cfg->heapsize,
1517                               vcl_cfg->heapsize);
1518               vec_free (chroot_path);
1519             }
1520           else if (unformat (line_input, "api-prefix %s", &chroot_path))
1521             {
1522               vec_terminate_c_string (chroot_path);
1523               vl_set_memory_root_path ((char *) chroot_path);
1524               if (VPPCOM_DEBUG > 0)
1525                 clib_warning ("[%d] configured api-prefix %s",
1526                               vcm->my_pid, chroot_path);
1527               chroot_path = 0;  /* Don't vec_free() it! */
1528             }
1529           else if (unformat (line_input, "uid %d", &uid))
1530             {
1531               vl_set_memory_uid (uid);
1532               if (VPPCOM_DEBUG > 0)
1533                 clib_warning ("[%d] configured uid %d", vcm->my_pid, uid);
1534             }
1535           else if (unformat (line_input, "gid %d", &gid))
1536             {
1537               vl_set_memory_gid (gid);
1538               if (VPPCOM_DEBUG > 0)
1539                 clib_warning ("[%d] configured gid %d", vcm->my_pid, gid);
1540             }
1541           else if (unformat (line_input, "segment-baseva 0x%llx",
1542                              &vcl_cfg->segment_baseva))
1543             {
1544               if (VPPCOM_DEBUG > 0)
1545                 clib_warning ("[%d] configured segment_baseva 0x%llx",
1546                               vcm->my_pid, vcl_cfg->segment_baseva);
1547             }
1548           else if (unformat (line_input, "segment-size 0x%lx",
1549                              &vcl_cfg->segment_size))
1550             {
1551               if (VPPCOM_DEBUG > 0)
1552                 clib_warning ("[%d] configured segment_size 0x%lx (%ld)",
1553                               vcm->my_pid, vcl_cfg->segment_size,
1554                               vcl_cfg->segment_size);
1555             }
1556           else if (unformat (line_input, "segment-size %ld",
1557                              &vcl_cfg->segment_size))
1558             {
1559               if (VPPCOM_DEBUG > 0)
1560                 clib_warning ("[%d] configured segment_size %ld (0x%lx)",
1561                               vcm->my_pid, vcl_cfg->segment_size,
1562                               vcl_cfg->segment_size);
1563             }
1564           else if (unformat (line_input, "add-segment-size 0x%lx",
1565                              &vcl_cfg->add_segment_size))
1566             {
1567               if (VPPCOM_DEBUG > 0)
1568                 clib_warning
1569                   ("[%d] configured add_segment_size 0x%lx (%ld)",
1570                    vcm->my_pid, vcl_cfg->add_segment_size,
1571                    vcl_cfg->add_segment_size);
1572             }
1573           else if (unformat (line_input, "add-segment-size %ld",
1574                              &vcl_cfg->add_segment_size))
1575             {
1576               if (VPPCOM_DEBUG > 0)
1577                 clib_warning
1578                   ("[%d] configured add_segment_size %ld (0x%lx)",
1579                    vcm->my_pid, vcl_cfg->add_segment_size,
1580                    vcl_cfg->add_segment_size);
1581             }
1582           else if (unformat (line_input, "preallocated-fifo-pairs %d",
1583                              &vcl_cfg->preallocated_fifo_pairs))
1584             {
1585               if (VPPCOM_DEBUG > 0)
1586                 clib_warning ("[%d] configured preallocated_fifo_pairs "
1587                               "%d (0x%x)", vcm->my_pid,
1588                               vcl_cfg->preallocated_fifo_pairs,
1589                               vcl_cfg->preallocated_fifo_pairs);
1590             }
1591           else if (unformat (line_input, "rx-fifo-size 0x%lx",
1592                              &vcl_cfg->rx_fifo_size))
1593             {
1594               if (VPPCOM_DEBUG > 0)
1595                 clib_warning ("[%d] configured rx_fifo_size 0x%lx (%ld)",
1596                               vcm->my_pid, vcl_cfg->rx_fifo_size,
1597                               vcl_cfg->rx_fifo_size);
1598             }
1599           else if (unformat (line_input, "rx-fifo-size %ld",
1600                              &vcl_cfg->rx_fifo_size))
1601             {
1602               if (VPPCOM_DEBUG > 0)
1603                 clib_warning ("[%d] configured rx_fifo_size %ld (0x%lx)",
1604                               vcm->my_pid, vcl_cfg->rx_fifo_size,
1605                               vcl_cfg->rx_fifo_size);
1606             }
1607           else if (unformat (line_input, "tx-fifo-size 0x%lx",
1608                              &vcl_cfg->tx_fifo_size))
1609             {
1610               if (VPPCOM_DEBUG > 0)
1611                 clib_warning ("[%d] configured tx_fifo_size 0x%lx (%ld)",
1612                               vcm->my_pid, vcl_cfg->tx_fifo_size,
1613                               vcl_cfg->tx_fifo_size);
1614             }
1615           else if (unformat (line_input, "tx-fifo-size %ld",
1616                              &vcl_cfg->tx_fifo_size))
1617             {
1618               if (VPPCOM_DEBUG > 0)
1619                 clib_warning ("[%d] configured tx_fifo_size %ld (0x%lx)",
1620                               vcm->my_pid, vcl_cfg->tx_fifo_size,
1621                               vcl_cfg->tx_fifo_size);
1622             }
1623           else if (unformat (line_input, "event-queue-size 0x%lx",
1624                              &vcl_cfg->event_queue_size))
1625             {
1626               if (VPPCOM_DEBUG > 0)
1627                 clib_warning ("[%d] configured event_queue_size 0x%lx (%ld)",
1628                               vcm->my_pid, vcl_cfg->event_queue_size,
1629                               vcl_cfg->event_queue_size);
1630             }
1631           else if (unformat (line_input, "event-queue-size %ld",
1632                              &vcl_cfg->event_queue_size))
1633             {
1634               if (VPPCOM_DEBUG > 0)
1635                 clib_warning ("[%d] configured event_queue_size %ld (0x%lx)",
1636                               vcm->my_pid, vcl_cfg->event_queue_size,
1637                               vcl_cfg->event_queue_size);
1638             }
1639           else if (unformat (line_input, "listen-queue-size 0x%lx",
1640                              &vcl_cfg->listen_queue_size))
1641             {
1642               if (VPPCOM_DEBUG > 0)
1643                 clib_warning ("[%d] configured listen_queue_size 0x%lx (%ld)",
1644                               vcm->my_pid, vcl_cfg->listen_queue_size,
1645                               vcl_cfg->listen_queue_size);
1646             }
1647           else if (unformat (line_input, "listen-queue-size %ld",
1648                              &vcl_cfg->listen_queue_size))
1649             {
1650               if (VPPCOM_DEBUG > 0)
1651                 clib_warning ("[%d] configured listen_queue_size %ld (0x%lx)",
1652                               vcm->my_pid, vcl_cfg->listen_queue_size,
1653                               vcl_cfg->listen_queue_size);
1654             }
1655           else if (unformat (line_input, "app-timeout %f",
1656                              &vcl_cfg->app_timeout))
1657             {
1658               if (VPPCOM_DEBUG > 0)
1659                 clib_warning ("[%d] configured app_timeout %f",
1660                               vcm->my_pid, vcl_cfg->app_timeout);
1661             }
1662           else if (unformat (line_input, "session-timeout %f",
1663                              &vcl_cfg->session_timeout))
1664             {
1665               if (VPPCOM_DEBUG > 0)
1666                 clib_warning ("[%d] configured session_timeout %f",
1667                               vcm->my_pid, vcl_cfg->session_timeout);
1668             }
1669           else if (unformat (line_input, "accept-timeout %f",
1670                              &vcl_cfg->accept_timeout))
1671             {
1672               if (VPPCOM_DEBUG > 0)
1673                 clib_warning ("[%d] configured accept_timeout %f",
1674                               vcm->my_pid, vcl_cfg->accept_timeout);
1675             }
1676           else if (unformat (line_input, "}"))
1677             {
1678               vc_cfg_input = 0;
1679               if (VPPCOM_DEBUG > 0)
1680                 clib_warning ("[%d] completed parsing vppcom config!",
1681                               vcm->my_pid);
1682               goto input_done;
1683             }
1684           else
1685             {
1686               if (line_input->buffer[line_input->index] != '#')
1687                 {
1688                   clib_warning ("[%d] Unknown vppcom config option: '%s'",
1689                                 vcm->my_pid, (char *)
1690                                 &line_input->buffer[line_input->index]);
1691                 }
1692             }
1693         }
1694     }
1695
1696 input_done:
1697   unformat_free (input);
1698
1699 file_done:
1700   if (fd > 0)
1701     close (fd);
1702 }
1703
1704 /*
1705  * VPPCOM Public API functions
1706  */
1707 int
1708 vppcom_app_create (char *app_name)
1709 {
1710   vppcom_main_t *vcm = &vppcom_main;
1711   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1712   u8 *heap;
1713   mheap_t *h;
1714   int rv;
1715
1716   if (!vcm->init)
1717     {
1718       char *conf_fname;
1719
1720       vcm->init = 1;
1721       vcm->my_pid = getpid ();
1722       clib_fifo_validate (vcm->client_session_index_fifo,
1723                           vcm->cfg.listen_queue_size);
1724       vppcom_cfg_init (vcl_cfg);
1725       conf_fname = getenv (VPPCOM_CONF_ENV);
1726       if (!conf_fname)
1727         {
1728           conf_fname = VPPCOM_CONF_DEFAULT;
1729           if (VPPCOM_DEBUG > 0)
1730             clib_warning ("[%d] getenv '%s' failed!", vcm->my_pid,
1731                           VPPCOM_CONF_ENV);
1732         }
1733       vppcom_cfg_heapsize (conf_fname);
1734       vppcom_cfg_read (conf_fname);
1735       vcm->bind_session_index = ~0;
1736       vcm->main_cpu = os_get_thread_index ();
1737       heap = clib_mem_get_per_cpu_heap ();
1738       h = mheap_header (heap);
1739
1740       /* make the main heap thread-safe */
1741       h->flags |= MHEAP_FLAG_THREAD_SAFE;
1742
1743       vcm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1744
1745       clib_time_init (&vcm->clib_time);
1746       vppcom_init_error_string_table ();
1747       svm_fifo_segment_init (vcl_cfg->segment_baseva,
1748                              20 /* timeout in secs */ );
1749       clib_spinlock_init (&vcm->sessions_lockp);
1750       vppcom_api_hookup ();
1751     }
1752
1753   if (vcm->my_client_index == ~0)
1754     {
1755       vcm->app_state = STATE_APP_START;
1756       rv = vppcom_connect_to_vpp (app_name);
1757       if (rv)
1758         {
1759           clib_warning ("[%s] couldn't connect to VPP.", vcm->my_pid);
1760           return rv;
1761         }
1762
1763       if (VPPCOM_DEBUG > 0)
1764         clib_warning ("[%d] sending session enable", vcm->my_pid);
1765
1766       rv = vppcom_app_session_enable ();
1767       if (rv)
1768         {
1769           clib_warning ("[%d] vppcom_app_session_enable() failed!",
1770                         vcm->my_pid);
1771           return rv;
1772         }
1773
1774       if (VPPCOM_DEBUG > 0)
1775         clib_warning ("[%d] sending app attach", vcm->my_pid);
1776
1777       rv = vppcom_app_attach ();
1778       if (rv)
1779         {
1780           clib_warning ("[%d] vppcom_app_attach() failed!", vcm->my_pid);
1781           return rv;
1782         }
1783     }
1784
1785   if (VPPCOM_DEBUG > 0)
1786     clib_warning ("[%d] app_name '%s', my_client_index %d (0x%x)",
1787                   vcm->my_pid, app_name, vcm->my_client_index,
1788                   vcm->my_client_index);
1789
1790   return VPPCOM_OK;
1791 }
1792
1793 void
1794 vppcom_app_destroy (void)
1795 {
1796   vppcom_main_t *vcm = &vppcom_main;
1797   int rv;
1798
1799   if (vcm->my_client_index == ~0)
1800     return;
1801
1802   if (VPPCOM_DEBUG > 0)
1803     clib_warning ("[%d] detaching from VPP, my_client_index %d (0x%x)",
1804                   vcm->my_pid, vcm->my_client_index, vcm->my_client_index);
1805
1806   vppcom_app_detach ();
1807   rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
1808   if (PREDICT_FALSE (rv))
1809     {
1810       if (VPPCOM_DEBUG > 0)
1811         clib_warning ("[%d] application detach timed out, rv = %s (%d)",
1812                       vcm->my_pid, vppcom_retval_str (rv), rv);
1813     }
1814   vl_client_disconnect_from_vlib ();
1815   vcm->my_client_index = ~0;
1816   vcm->app_state = STATE_APP_START;
1817 }
1818
1819 int
1820 vppcom_session_create (u32 vrf, u8 proto, u8 is_nonblocking)
1821 {
1822   vppcom_main_t *vcm = &vppcom_main;
1823   session_t *session;
1824   u32 session_index;
1825
1826   clib_spinlock_lock (&vcm->sessions_lockp);
1827   pool_get (vcm->sessions, session);
1828   session_index = session - vcm->sessions;
1829
1830   session->vrf = vrf;
1831   session->proto = proto;
1832   session->state = STATE_START;
1833   session->is_nonblocking = is_nonblocking;
1834   clib_spinlock_unlock (&vcm->sessions_lockp);
1835
1836   if (VPPCOM_DEBUG > 0)
1837     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1838
1839   return (int) session_index;
1840 }
1841
1842 int
1843 vppcom_session_close (uint32_t session_index)
1844 {
1845   vppcom_main_t *vcm = &vppcom_main;
1846   session_t *session = 0;
1847   int rv;
1848
1849   clib_spinlock_lock (&vcm->sessions_lockp);
1850   rv = vppcom_session_at_index (session_index, &session);
1851   if (PREDICT_FALSE (rv))
1852     {
1853       clib_spinlock_unlock (&vcm->sessions_lockp);
1854       if (VPPCOM_DEBUG > 0)
1855         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1856                       vcm->my_pid, session_index);
1857       return rv;
1858     }
1859   clib_spinlock_unlock (&vcm->sessions_lockp);
1860
1861   if (VPPCOM_DEBUG > 0)
1862     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1863
1864   if (session->is_cut_thru)
1865     {
1866       if (session->is_server)
1867         rv = vppcom_session_unbind_cut_thru (session);
1868     }
1869   else
1870     {
1871       rv = (session->is_server) ?
1872         vppcom_session_unbind (session_index) :
1873         vppcom_session_disconnect (session_index);
1874     }
1875
1876   clib_spinlock_lock (&vcm->sessions_lockp);
1877   pool_put_index (vcm->sessions, session_index);
1878   clib_spinlock_unlock (&vcm->sessions_lockp);
1879   return rv;
1880 }
1881
1882 int
1883 vppcom_session_bind (uint32_t session_index, vppcom_endpt_t * ep)
1884 {
1885   vppcom_main_t *vcm = &vppcom_main;
1886   session_t *session = 0;
1887   int rv;
1888
1889   if (!ep || !ep->ip)
1890     return VPPCOM_EINVAL;
1891
1892   clib_spinlock_lock (&vcm->sessions_lockp);
1893   rv = vppcom_session_at_index (session_index, &session);
1894   if (PREDICT_FALSE (rv))
1895     {
1896       clib_spinlock_unlock (&vcm->sessions_lockp);
1897       if (VPPCOM_DEBUG > 0)
1898         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1899                       vcm->my_pid, session_index);
1900       return rv;
1901     }
1902
1903   if (VPPCOM_DEBUG > 0)
1904     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1905
1906   session->vrf = ep->vrf;
1907   session->is_ip4 = ep->is_ip4;
1908   memset (session->ip, 0, sizeof (*session->ip));
1909   clib_memcpy (session->ip, ep->ip, (ep->is_ip4 ?
1910                                      sizeof (ip4_address_t) :
1911                                      sizeof (ip6_address_t)));
1912   session->port = ep->port;
1913
1914   clib_spinlock_unlock (&vcm->sessions_lockp);
1915   return VPPCOM_OK;
1916 }
1917
1918 int
1919 vppcom_session_listen (uint32_t session_index, uint32_t q_len)
1920 {
1921   vppcom_main_t *vcm = &vppcom_main;
1922   session_t *session = 0;
1923   int rv;
1924
1925   clib_spinlock_lock (&vcm->sessions_lockp);
1926   rv = vppcom_session_at_index (session_index, &session);
1927   if (PREDICT_FALSE (rv))
1928     {
1929       clib_spinlock_unlock (&vcm->sessions_lockp);
1930       if (VPPCOM_DEBUG > 0)
1931         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1932                       vcm->my_pid, session_index);
1933       return rv;
1934     }
1935
1936   if (VPPCOM_DEBUG > 0)
1937     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1938
1939   ASSERT (vcm->bind_session_index == ~0);
1940   vcm->bind_session_index = session_index;
1941   vppcom_send_bind_sock (session);
1942   clib_spinlock_unlock (&vcm->sessions_lockp);
1943   rv = vppcom_wait_for_session_state_change (session_index, STATE_LISTEN,
1944                                              vcm->cfg.session_timeout);
1945   if (PREDICT_FALSE (rv))
1946     {
1947       vcm->bind_session_index = ~0;
1948       if (VPPCOM_DEBUG > 0)
1949         clib_warning ("[%d] server listen timed out, rv = %d (%d)",
1950                       vcm->my_pid, vppcom_retval_str (rv), rv);
1951       return rv;
1952     }
1953
1954   clib_spinlock_lock (&vcm->sessions_lockp);
1955   rv = vppcom_session_at_index (session_index, &session);
1956   if (PREDICT_FALSE (rv))
1957     {
1958       clib_spinlock_unlock (&vcm->sessions_lockp);
1959       if (VPPCOM_DEBUG > 0)
1960         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1961                       vcm->my_pid, session_index);
1962       return rv;
1963     }
1964   session->is_listen = 1;
1965   clib_spinlock_unlock (&vcm->sessions_lockp);
1966   clib_fifo_validate (vcm->client_session_index_fifo, q_len);
1967
1968   return VPPCOM_OK;
1969 }
1970
1971 int
1972 vppcom_session_accept (uint32_t listen_session_index, vppcom_endpt_t * ep,
1973                        double wait_for_time)
1974 {
1975   vppcom_main_t *vcm = &vppcom_main;
1976   session_t *session = 0;
1977   u32 client_session_index;
1978   int rv;
1979   f64 wait_for;
1980
1981   clib_spinlock_lock (&vcm->sessions_lockp);
1982   rv = vppcom_session_at_index (listen_session_index, &session);
1983   if (PREDICT_FALSE (rv))
1984     {
1985       clib_spinlock_unlock (&vcm->sessions_lockp);
1986       if (VPPCOM_DEBUG > 0)
1987         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
1988                       vcm->my_pid, listen_session_index);
1989       return rv;
1990     }
1991
1992   if (session->state != STATE_LISTEN)
1993     {
1994       clib_spinlock_unlock (&vcm->sessions_lockp);
1995       if (VPPCOM_DEBUG > 0)
1996         clib_warning ("[%d] session not in listen state, state = %s",
1997                       vcm->my_pid, vppcom_session_state_str (session->state));
1998       return VPPCOM_EBADFD;
1999     }
2000   wait_for = session->is_nonblocking ? 0 :
2001     (wait_for_time < 0) ? vcm->cfg.accept_timeout : wait_for_time;
2002
2003   if (VPPCOM_DEBUG > 0)
2004     clib_warning ("[%d] sid %d, state %s (%d)", vcm->my_pid,
2005                   listen_session_index,
2006                   vppcom_session_state_str (session->state), session->state);
2007   clib_spinlock_unlock (&vcm->sessions_lockp);
2008
2009   while (1)
2010     {
2011       rv = vppcom_wait_for_client_session_index (wait_for);
2012       if (rv)
2013         {
2014           if ((VPPCOM_DEBUG > 0))
2015             clib_warning ("[%d] sid %d, accept timed out, rv = %s (%d)",
2016                           vcm->my_pid, listen_session_index,
2017                           vppcom_retval_str (rv), rv);
2018           if ((wait_for == 0) || (wait_for_time > 0))
2019             return rv;
2020         }
2021       else
2022         break;
2023     }
2024
2025   clib_fifo_sub1 (vcm->client_session_index_fifo, client_session_index);
2026
2027   session = 0;
2028   clib_spinlock_lock (&vcm->sessions_lockp);
2029   rv = vppcom_session_at_index (client_session_index, &session);
2030   ASSERT (rv == VPPCOM_OK);
2031   ASSERT (session->is_server);
2032
2033   if (VPPCOM_DEBUG > 0)
2034     clib_warning ("[%d] Got a request: client sid %d", vcm->my_pid,
2035                   client_session_index);
2036
2037   ep->vrf = session->vrf;
2038   ep->is_cut_thru = session->is_cut_thru;
2039   ep->is_ip4 = session->is_ip4;
2040   ep->port = session->port;
2041   memset (ep->ip, 0, sizeof (ip6_address_t));
2042   clib_memcpy (ep->ip, session->ip, (session->is_ip4 ?
2043                                      sizeof (ip4_address_t) :
2044                                      sizeof (ip6_address_t)));
2045   session->state = STATE_LISTEN;
2046   clib_spinlock_unlock (&vcm->sessions_lockp);
2047   return (int) client_session_index;
2048 }
2049
2050 int
2051 vppcom_session_connect (uint32_t session_index, vppcom_endpt_t * server_ep)
2052 {
2053   vppcom_main_t *vcm = &vppcom_main;
2054   session_t *session = 0;
2055   int rv;
2056   ip46_address_t *ip46;
2057
2058   clib_spinlock_lock (&vcm->sessions_lockp);
2059   rv = vppcom_session_at_index (session_index, &session);
2060   if (PREDICT_FALSE (rv))
2061     {
2062       clib_spinlock_unlock (&vcm->sessions_lockp);
2063       if (VPPCOM_DEBUG > 0)
2064         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
2065                       vcm->my_pid, session_index);
2066       return rv;
2067     }
2068
2069   if (session->state == STATE_CONNECT)
2070     {
2071       clib_spinlock_unlock (&vcm->sessions_lockp);
2072       if (VPPCOM_DEBUG > 0)
2073         clib_warning ("[%d] session, sid (%d) already connected!",
2074                       vcm->my_pid, session_index);
2075       return VPPCOM_OK;
2076     }
2077
2078   session->vrf = server_ep->vrf;
2079   session->is_ip4 = server_ep->is_ip4;
2080   ip46 = (ip46_address_t *) session->ip;
2081   *ip46 = to_ip46 (!server_ep->is_ip4, server_ep->ip);
2082   session->port = server_ep->port;
2083
2084   if (VPPCOM_DEBUG > 0)
2085     {
2086       u8 *ip_str = format (0, "%U", format_ip46_address,
2087                            &session->ip, session->is_ip4);
2088       clib_warning ("[%d] connect sid %d to %s server port %d",
2089                     vcm->my_pid, session_index, ip_str,
2090                     clib_net_to_host_u16 (session->port));
2091       vec_free (ip_str);
2092     }
2093
2094   vppcom_send_connect_sock (session, session_index);
2095   clib_spinlock_unlock (&vcm->sessions_lockp);
2096   rv = vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
2097                                              vcm->cfg.session_timeout);
2098   if (PREDICT_FALSE (rv))
2099     {
2100       if (VPPCOM_DEBUG > 0)
2101         clib_warning ("[%d] connect timed out, rv = %s (%d)",
2102                       vcm->my_pid, vppcom_retval_str (rv), rv);
2103       return rv;
2104     }
2105   return VPPCOM_OK;
2106 }
2107
2108 int
2109 vppcom_session_read (uint32_t session_index, void *buf, int n)
2110 {
2111   session_fifo_event_t _e, *e = &_e;
2112   vppcom_main_t *vcm = &vppcom_main;
2113   session_t *session = 0;
2114   svm_fifo_t *rx_fifo;
2115   int n_read = 0;
2116   int rv;
2117   char *fifo_str;
2118
2119   ASSERT (buf);
2120
2121   clib_spinlock_lock (&vcm->sessions_lockp);
2122   rv = vppcom_session_at_index (session_index, &session);
2123   if (PREDICT_FALSE (rv))
2124     {
2125       clib_spinlock_unlock (&vcm->sessions_lockp);
2126       if (VPPCOM_DEBUG > 0)
2127         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
2128                       vcm->my_pid, session_index);
2129       return rv;
2130     }
2131
2132   if (session->is_cut_thru)
2133     {
2134       rx_fifo = session->is_server ? session->server_rx_fifo :
2135         session->server_tx_fifo;
2136       fifo_str = session->is_server ? "server_rx_fifo" : "server_tx_fifo";
2137       clib_spinlock_unlock (&vcm->sessions_lockp);
2138
2139       n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2140
2141       if (n_read <= 0)
2142         return VPPCOM_EAGAIN;
2143
2144     }
2145   else
2146     {
2147       rv = unix_shared_memory_queue_sub (session->event_queue, (u8 *) e,
2148                                          1 /* nowait */ );
2149       clib_spinlock_unlock (&vcm->sessions_lockp);
2150       if (rv < 0)
2151         return VPPCOM_EAGAIN;
2152
2153       switch (e->event_type)
2154         {
2155         case FIFO_EVENT_APP_RX:
2156           rx_fifo = e->fifo;
2157           fifo_str = "app_rx_fifo";
2158           n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2159           break;
2160
2161         case FIFO_EVENT_DISCONNECT:
2162           return VPPCOM_ECONNRESET;
2163
2164         default:
2165           if (VPPCOM_DEBUG > 0)
2166             clib_warning ("[%d] unknown event type %d", vcm->my_pid,
2167                           e->event_type);
2168           return VPPCOM_EAGAIN;
2169         }
2170     }
2171
2172   if (VPPCOM_DEBUG > 2)
2173     clib_warning ("[%d] sid %d, read %d bytes from %s (%p)", vcm->my_pid,
2174                   session_index, n_read, fifo_str, rx_fifo);
2175   return n_read;
2176 }
2177
2178 static inline int
2179 vppcom_session_read_ready (session_t * session, u32 session_index)
2180 {
2181   session_fifo_event_t _e, *e = &_e;
2182   vppcom_main_t *vcm = &vppcom_main;
2183   svm_fifo_t *rx_fifo;
2184   int rv;
2185   int ready = 0;
2186
2187   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2188   if (session->is_cut_thru)
2189     {
2190       rx_fifo = session->is_server ? session->server_rx_fifo :
2191         session->server_tx_fifo;
2192
2193       ready = svm_fifo_max_dequeue (rx_fifo);
2194     }
2195   else if (session->is_listen)
2196     ready = clib_fifo_elts (vcm->client_session_index_fifo);
2197   else
2198     {
2199       rv = unix_shared_memory_queue_sub (vcm->app_event_queue, (u8 *) e,
2200                                          1 /* nowait */ );
2201       if (rv >= 0)
2202         {
2203           switch (e->event_type)
2204             {
2205             case FIFO_EVENT_APP_RX:
2206               rx_fifo = e->fifo;
2207               ready = svm_fifo_max_dequeue (rx_fifo);
2208               break;
2209
2210             case FIFO_EVENT_DISCONNECT:
2211               return VPPCOM_ECONNRESET;
2212
2213             default:
2214               clib_warning ("[%d] unknown event type %d", vcm->my_pid,
2215                             e->event_type);
2216             }
2217         }
2218     }
2219
2220   if (VPPCOM_DEBUG > 2)
2221     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2222                   session_index,
2223                   session->is_server ? "server_rx_fifo" : "server_tx_fifo",
2224                   rx_fifo, ready);
2225
2226   return ready;
2227 }
2228
2229 int
2230 vppcom_session_write (uint32_t session_index, void *buf, int n)
2231 {
2232   vppcom_main_t *vcm = &vppcom_main;
2233   session_t *session = 0;
2234   svm_fifo_t *tx_fifo;
2235   unix_shared_memory_queue_t *q;
2236   session_fifo_event_t evt;
2237   int rv;
2238   char *fifo_str;
2239   u8 is_nonblocking;
2240
2241   ASSERT (buf);
2242
2243   clib_spinlock_lock (&vcm->sessions_lockp);
2244   rv = vppcom_session_at_index (session_index, &session);
2245   if (PREDICT_FALSE (rv))
2246     {
2247       clib_spinlock_unlock (&vcm->sessions_lockp);
2248       if (VPPCOM_DEBUG > 0)
2249         clib_warning ("[%d] invalid session, sid (%d) has been closed!",
2250                       vcm->my_pid, session_index);
2251       return rv;
2252     }
2253
2254   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2255              session->server_tx_fifo : session->server_rx_fifo);
2256   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2257               "server_tx_fifo" : "server_rx_fifo");
2258   is_nonblocking = session->is_nonblocking;
2259   clib_spinlock_unlock (&vcm->sessions_lockp);
2260
2261   do
2262     {
2263       rv = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
2264     }
2265   while (!is_nonblocking && (rv <= 0));
2266
2267   /* If event wasn't set, add one */
2268   if ((rv > 0) && svm_fifo_set_event (tx_fifo))
2269     {
2270       int rval;
2271
2272       /* Fabricate TX event, send to vpp */
2273       evt.fifo = tx_fifo;
2274       evt.event_type = FIFO_EVENT_APP_TX;
2275       evt.event_id = vcm->tx_event_id++;
2276
2277       clib_spinlock_lock (&vcm->sessions_lockp);
2278       rval = vppcom_session_at_index (session_index, &session);
2279       if (PREDICT_FALSE (rval))
2280         {
2281           clib_spinlock_unlock (&vcm->sessions_lockp);
2282           if (VPPCOM_DEBUG > 1)
2283             clib_warning ("[%d] invalid session, sid (%d) has been closed!",
2284                           vcm->my_pid, session_index);
2285           return rval;
2286         }
2287       q = session->event_queue;
2288       clib_spinlock_unlock (&vcm->sessions_lockp);
2289       ASSERT (q);
2290       unix_shared_memory_queue_add (q, (u8 *) & evt,
2291                                     0 /* do wait for mutex */ );
2292     }
2293
2294   if (VPPCOM_DEBUG > 2)
2295     clib_warning ("[%d] sid %d, wrote %d bytes to %s (%p)", vcm->my_pid,
2296                   session_index, rv, fifo_str, tx_fifo);
2297
2298   return rv;
2299 }
2300
2301 static inline int
2302 vppcom_session_write_ready (session_t * session, u32 session_index)
2303 {
2304   vppcom_main_t *vcm = &vppcom_main;
2305   svm_fifo_t *tx_fifo;
2306   int rv;
2307
2308   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2309   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2310              session->server_tx_fifo : session->server_rx_fifo);
2311
2312   rv = svm_fifo_max_enqueue (tx_fifo);
2313
2314   if (VPPCOM_DEBUG > 2)
2315     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2316                   session_index,
2317                   session->is_server ? "server_tx_fifo" : "server_rx_fifo",
2318                   tx_fifo, rv);
2319   return rv;
2320 }
2321
2322 int
2323 vppcom_select (unsigned long n_bits, unsigned long *read_map,
2324                unsigned long *write_map, unsigned long *except_map,
2325                double time_to_wait)
2326 {
2327   vppcom_main_t *vcm = &vppcom_main;
2328   u32 session_index;
2329   session_t *session = 0;
2330   int rv, bits_set = 0;
2331   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
2332   u32 minbits = clib_max (n_bits, BITS (uword));
2333
2334   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
2335
2336   if (read_map)
2337     {
2338       clib_bitmap_validate (vcm->rd_bitmap, minbits);
2339       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
2340       memset (read_map, 0, vec_len (vcm->rd_bitmap));
2341     }
2342   if (write_map)
2343     {
2344       clib_bitmap_validate (vcm->wr_bitmap, minbits);
2345       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
2346       memset (write_map, 0, vec_len (vcm->wr_bitmap));
2347     }
2348   if (except_map)
2349     {
2350       clib_bitmap_validate (vcm->ex_bitmap, minbits);
2351       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
2352       memset (except_map, 0, vec_len (vcm->ex_bitmap));
2353     }
2354
2355   do
2356     {
2357       /* *INDENT-OFF* */
2358       clib_bitmap_foreach (session_index, vcm->rd_bitmap,
2359         ({
2360           clib_spinlock_lock (&vcm->sessions_lockp);
2361           rv = vppcom_session_at_index (session_index, &session);
2362           if (rv < 0)
2363             {
2364               clib_spinlock_unlock (&vcm->sessions_lockp);
2365               if (VPPCOM_DEBUG > 1)
2366                 clib_warning ("[%d] session %d specified in "
2367                               "read_map is closed.", vcm->my_pid,
2368                               session_index);
2369               bits_set = VPPCOM_EBADFD;
2370               goto select_done;
2371             }
2372
2373           rv = vppcom_session_read_ready (session, session_index);
2374           clib_spinlock_unlock (&vcm->sessions_lockp);
2375           if (vcm->ex_bitmap &&
2376               clib_bitmap_get (vcm->ex_bitmap, session_index) && (rv < 0))
2377             {
2378               // TBD: clib_warning
2379               clib_bitmap_set_no_check (except_map, session_index, 1);
2380               bits_set++;
2381             }
2382           else if (rv > 0)
2383             {
2384               // TBD: clib_warning
2385               clib_bitmap_set_no_check (read_map, session_index, 1);
2386               bits_set++;
2387             }
2388         }));
2389
2390       clib_bitmap_foreach (session_index, vcm->wr_bitmap,
2391         ({
2392           clib_spinlock_lock (&vcm->sessions_lockp);
2393           rv = vppcom_session_at_index (session_index, &session);
2394           if (rv < 0)
2395             {
2396               clib_spinlock_unlock (&vcm->sessions_lockp);
2397               if (VPPCOM_DEBUG > 0)
2398                 clib_warning ("[%d] session %d specified in "
2399                               "write_map is closed.", vcm->my_pid,
2400                               session_index);
2401               bits_set = VPPCOM_EBADFD;
2402               goto select_done;
2403             }
2404
2405           rv = vppcom_session_write_ready (session, session_index);
2406           clib_spinlock_unlock (&vcm->sessions_lockp);
2407           if (rv > 0)
2408             {
2409               // TBD: clib_warning
2410               clib_bitmap_set_no_check (write_map, session_index, 1);
2411               bits_set++;
2412             }
2413         }));
2414
2415       clib_bitmap_foreach (session_index, vcm->ex_bitmap,
2416         ({
2417           clib_spinlock_lock (&vcm->sessions_lockp);
2418           rv = vppcom_session_at_index (session_index, &session);
2419           if (rv < 0)
2420             {
2421               clib_spinlock_unlock (&vcm->sessions_lockp);
2422               if (VPPCOM_DEBUG > 1)
2423                 clib_warning ("[%d] session %d specified in "
2424                               "except_map is closed.", vcm->my_pid,
2425                               session_index);
2426               bits_set = VPPCOM_EBADFD;
2427               goto select_done;
2428             }
2429
2430           rv = vppcom_session_read_ready (session, session_index);
2431           clib_spinlock_unlock (&vcm->sessions_lockp);
2432           if (rv < 0)
2433             {
2434               // TBD: clib_warning
2435               clib_bitmap_set_no_check (except_map, session_index, 1);
2436               bits_set++;
2437             }
2438         }));
2439       /* *INDENT-ON* */
2440     }
2441   while (clib_time_now (&vcm->clib_time) < timeout);
2442
2443 select_done:
2444   return (bits_set);
2445 }
2446
2447 /*
2448  * fd.io coding-style-patch-verification: ON
2449  *
2450  * Local Variables:
2451  * eval: (c-set-style "gnu")
2452  * End:
2453  */