VCL: drain the vpp app event queue.
[vpp.git] / src / vcl / vppcom.c
1 /*
2  * Copyright (c) 2017 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 <vcl/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_INIT 2 for connection debug,
45  *                       3 for read/write debug output
46  * or
47  *    export VCL_DEBUG=<#> to set dynamically.
48  */
49 #define VPPCOM_DEBUG_INIT 1
50 #else
51 #define VPPCOM_DEBUG_INIT 0
52 #endif
53
54 #define VPPCOM_DEBUG vcm->debug
55
56 /*
57  * VPPCOM Private definitions and functions.
58  */
59 typedef enum
60 {
61   STATE_APP_START,
62   STATE_APP_CONN_VPP,
63   STATE_APP_ENABLED,
64   STATE_APP_ATTACHED,
65 } app_state_t;
66
67 typedef enum
68 {
69   STATE_START = 0x01,
70   STATE_CONNECT = 0x02,
71   STATE_LISTEN = 0x04,
72   STATE_ACCEPT = 0x08,
73   STATE_CLOSE_ON_EMPTY = 0x10,
74   STATE_DISCONNECT = 0x20,
75   STATE_FAILED = 0x40
76 } session_state_t;
77
78 #define SERVER_STATE_OPEN  (STATE_ACCEPT|STATE_CLOSE_ON_EMPTY)
79 #define CLIENT_STATE_OPEN  (STATE_CONNECT|STATE_CLOSE_ON_EMPTY)
80
81 typedef struct epoll_event vppcom_epoll_event_t;
82
83 typedef struct
84 {
85   u32 next_sid;
86   u32 prev_sid;
87   u32 vep_idx;
88   vppcom_epoll_event_t ev;
89 #define VEP_DEFAULT_ET_MASK  (EPOLLIN|EPOLLOUT)
90 #define VEP_UNSUPPORTED_EVENTS (EPOLLONESHOT|EPOLLEXCLUSIVE)
91   u32 et_mask;
92 } vppcom_epoll_t;
93
94 typedef struct
95 {
96   u8 is_ip4;
97   ip46_address_t ip46;
98 } vppcom_ip46_t;
99
100 typedef struct
101 {
102   volatile session_state_t state;
103
104   svm_fifo_t *server_rx_fifo;
105   svm_fifo_t *server_tx_fifo;
106   u8 *segment_name;
107   u32 sm_seg_index;
108   u32 client_context;
109   u64 vpp_handle;
110   unix_shared_memory_queue_t *vpp_event_queue;
111
112   /* Socket configuration state */
113   /* TBD: covert 'is_*' vars to bit in u8 flags; */
114   u8 is_server;
115   u8 is_listen;
116   u8 is_cut_thru;
117   u8 is_nonblocking;
118   u8 is_vep;
119   u8 is_vep_session;
120   u32 wait_cont_idx;
121   vppcom_epoll_t vep;
122   u32 vrf;
123   vppcom_ip46_t lcl_addr;
124   vppcom_ip46_t peer_addr;
125   u16 lcl_port;                 // network order
126   u16 peer_port;                // network order
127   u8 proto;
128   u64 client_queue_address;
129   u64 options[16];
130 } session_t;
131
132 typedef struct vppcom_cfg_t_
133 {
134   u64 heapsize;
135   u64 segment_baseva;
136   u32 segment_size;
137   u32 add_segment_size;
138   u32 preallocated_fifo_pairs;
139   u32 rx_fifo_size;
140   u32 tx_fifo_size;
141   u32 event_queue_size;
142   u32 listen_queue_size;
143   u8 app_proxy_transport_tcp;
144   u8 app_proxy_transport_udp;
145   u8 app_scope_local;
146   u8 app_scope_global;
147   u8 *namespace_id;
148   u64 namespace_secret;
149   f64 app_timeout;
150   f64 session_timeout;
151   f64 accept_timeout;
152 } vppcom_cfg_t;
153
154 typedef struct vppcom_main_t_
155 {
156   u8 init;
157   u32 debug;
158   u32 *client_session_index_fifo;
159   int main_cpu;
160
161   /* vpe input queue */
162   unix_shared_memory_queue_t *vl_input_queue;
163
164   /* API client handle */
165   u32 my_client_index;
166
167   /* Session pool */
168   clib_spinlock_t sessions_lockp;
169   session_t *sessions;
170
171   /* Hash table for disconnect processing */
172   uword *session_index_by_vpp_handles;
173
174   /* Select bitmaps */
175   clib_bitmap_t *rd_bitmap;
176   clib_bitmap_t *wr_bitmap;
177   clib_bitmap_t *ex_bitmap;
178
179   /* Our event queue */
180   unix_shared_memory_queue_t *app_event_queue;
181
182   /* unique segment name counter */
183   u32 unique_segment_index;
184
185   /* For deadman timers */
186   clib_time_t clib_time;
187
188   /* State of the connection, shared between msg RX thread and main thread */
189   volatile app_state_t app_state;
190
191   vppcom_cfg_t cfg;
192
193   /* VNET_API_ERROR_FOO -> "Foo" hash table */
194   uword *error_string_by_error_number;
195 } vppcom_main_t;
196
197 /* NOTE: _vppcom_main is only used until the heap is allocated.
198  *       Do not access it directly -- use vcm which will point to
199  *       the heap allocated copy after init.
200  */
201 static vppcom_main_t _vppcom_main = {
202   .debug = VPPCOM_DEBUG_INIT,
203   .my_client_index = ~0
204 };
205
206 static vppcom_main_t *vcm = &_vppcom_main;
207
208 #define VCL_LOCK_AND_GET_SESSION(I, S)                  \
209 do {                                                    \
210   clib_spinlock_lock (&vcm->sessions_lockp);            \
211   rv = vppcom_session_at_index (I, S);                  \
212   if (PREDICT_FALSE (rv))                               \
213     {                                                   \
214       clib_spinlock_unlock (&vcm->sessions_lockp);      \
215       clib_warning ("[%s] ERROR: Invalid ##I (%u)!",    \
216                     getpid (), I);                      \
217       goto done;                                        \
218     }                                                   \
219 } while (0)
220
221 static const char *
222 vppcom_app_state_str (app_state_t state)
223 {
224   char *st;
225
226   switch (state)
227     {
228     case STATE_APP_START:
229       st = "STATE_APP_START";
230       break;
231
232     case STATE_APP_CONN_VPP:
233       st = "STATE_APP_CONN_VPP";
234       break;
235
236     case STATE_APP_ENABLED:
237       st = "STATE_APP_ENABLED";
238       break;
239
240     case STATE_APP_ATTACHED:
241       st = "STATE_APP_ATTACHED";
242       break;
243
244     default:
245       st = "UNKNOWN_APP_STATE";
246       break;
247     }
248
249   return st;
250 }
251
252 static const char *
253 vppcom_session_state_str (session_state_t state)
254 {
255   char *st;
256
257   switch (state)
258     {
259     case STATE_START:
260       st = "STATE_START";
261       break;
262
263     case STATE_CONNECT:
264       st = "STATE_CONNECT";
265       break;
266
267     case STATE_LISTEN:
268       st = "STATE_LISTEN";
269       break;
270
271     case STATE_ACCEPT:
272       st = "STATE_ACCEPT";
273       break;
274
275     case STATE_CLOSE_ON_EMPTY:
276       st = "STATE_CLOSE_ON_EMPTY";
277       break;
278
279     case STATE_DISCONNECT:
280       st = "STATE_DISCONNECT";
281       break;
282
283     case STATE_FAILED:
284       st = "STATE_FAILED";
285       break;
286
287     default:
288       st = "UNKNOWN_STATE";
289       break;
290     }
291
292   return st;
293 }
294
295 /*
296  * VPPCOM Utility Functions
297  */
298 static inline int
299 vppcom_session_at_index (u32 session_index, session_t * volatile *sess)
300 {
301   /* Assumes that caller has acquired spinlock: vcm->sessions_lockp */
302   if (PREDICT_FALSE ((session_index == ~0) ||
303                      pool_is_free_index (vcm->sessions, session_index)))
304     {
305       clib_warning ("[%d] invalid session, sid (%u) has been closed!",
306                     getpid (), session_index);
307       return VPPCOM_EBADFD;
308     }
309   *sess = pool_elt_at_index (vcm->sessions, session_index);
310   return VPPCOM_OK;
311 }
312
313 static inline void
314 vppcom_session_table_add_listener (u64 listener_handle, u32 value)
315 {
316   /* Session and listener handles have different formats. The latter has
317    * the thread index in the upper 32 bits while the former has the session
318    * type. Knowing that, for listeners we just flip the MSB to 1 */
319   listener_handle |= 1ULL << 63;
320   hash_set (vcm->session_index_by_vpp_handles, listener_handle, value);
321 }
322
323 static inline session_t *
324 vppcom_session_table_lookup_listener (u64 listener_handle)
325 {
326   uword *p;
327   u64 handle = listener_handle | (1ULL << 63);
328   session_t *session;
329
330   p = hash_get (vcm->session_index_by_vpp_handles, handle);
331   if (!p)
332     {
333       clib_warning ("[%d] couldn't find listen session: unknown vpp "
334                     "listener handle %llx", getpid (), listener_handle);
335       return 0;
336     }
337   if (pool_is_free_index (vcm->sessions, p[0]))
338     {
339       if (VPPCOM_DEBUG > 1)
340         clib_warning ("[%d] invalid listen session, sid (%u)", getpid (),
341                       p[0]);
342       return 0;
343     }
344
345   session = pool_elt_at_index (vcm->sessions, p[0]);
346   ASSERT (session->is_listen);
347   return session;
348 }
349
350 static inline void
351 vppcom_session_table_del_listener (u64 listener_handle)
352 {
353   listener_handle |= 1ULL << 63;
354   hash_unset (vcm->session_index_by_vpp_handles, listener_handle);
355 }
356
357 static int
358 vppcom_connect_to_vpp (char *app_name)
359 {
360   api_main_t *am = &api_main;
361
362   if (VPPCOM_DEBUG > 0)
363     printf ("\nConnecting to VPP api...");
364   if (vl_client_connect_to_vlib ("/vpe-api", app_name, 32) < 0)
365     {
366       clib_warning ("[%d] connect to vpp (%s) failed!", getpid (), app_name);
367       return VPPCOM_ECONNREFUSED;
368     }
369
370   vcm->vl_input_queue = am->shmem_hdr->vl_input_queue;
371   vcm->my_client_index = am->my_client_index;
372   if (VPPCOM_DEBUG > 0)
373     printf (" connected!\n");
374
375   vcm->app_state = STATE_APP_CONN_VPP;
376   return VPPCOM_OK;
377 }
378
379 static u8 *
380 format_api_error (u8 * s, va_list * args)
381 {
382   i32 error = va_arg (*args, u32);
383   uword *p;
384
385   p = hash_get (vcm->error_string_by_error_number, -error);
386
387   if (p)
388     s = format (s, "%s (%d)", p[0], error);
389   else
390     s = format (s, "%d", error);
391   return s;
392 }
393
394 static void
395 vppcom_init_error_string_table (void)
396 {
397   vcm->error_string_by_error_number = hash_create (0, sizeof (uword));
398
399 #define _(n,v,s) hash_set (vcm->error_string_by_error_number, -v, s);
400   foreach_vnet_api_error;
401 #undef _
402
403   hash_set (vcm->error_string_by_error_number, 99, "Misc");
404 }
405
406 static inline int
407 vppcom_wait_for_app_state_change (app_state_t app_state)
408 {
409   f64 timeout = clib_time_now (&vcm->clib_time) + vcm->cfg.app_timeout;
410
411   while (clib_time_now (&vcm->clib_time) < timeout)
412     {
413       if (vcm->app_state == app_state)
414         return VPPCOM_OK;
415     }
416   if (VPPCOM_DEBUG > 0)
417     clib_warning ("[%d] timeout waiting for state %s (%d)", getpid (),
418                   vppcom_app_state_str (app_state), app_state);
419   return VPPCOM_ETIMEDOUT;
420 }
421
422 static inline int
423 vppcom_wait_for_session_state_change (u32 session_index,
424                                       session_state_t state,
425                                       f64 wait_for_time)
426 {
427   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
428   session_t *volatile session;
429   int rv;
430
431   do
432     {
433       clib_spinlock_lock (&vcm->sessions_lockp);
434       rv = vppcom_session_at_index (session_index, &session);
435       if (PREDICT_FALSE (rv))
436         {
437           clib_spinlock_unlock (&vcm->sessions_lockp);
438           return rv;
439         }
440       if (session->state == state)
441         {
442           clib_spinlock_unlock (&vcm->sessions_lockp);
443           return VPPCOM_OK;
444         }
445       if (session->state == STATE_FAILED)
446         {
447           clib_spinlock_unlock (&vcm->sessions_lockp);
448           return VPPCOM_ECONNREFUSED;
449         }
450
451       clib_spinlock_unlock (&vcm->sessions_lockp);
452     }
453   while (clib_time_now (&vcm->clib_time) < timeout);
454
455   if (VPPCOM_DEBUG > 0)
456     clib_warning ("[%d] timeout waiting for state 0x%x (%s)", getpid (),
457                   state, vppcom_session_state_str (state));
458   return VPPCOM_ETIMEDOUT;
459 }
460
461 static inline int
462 vppcom_wait_for_client_session_index (f64 wait_for_time)
463 {
464   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
465
466   do
467     {
468       if (clib_fifo_elts (vcm->client_session_index_fifo))
469         return VPPCOM_OK;
470     }
471   while (clib_time_now (&vcm->clib_time) < timeout);
472
473   if (wait_for_time == 0)
474     return VPPCOM_EAGAIN;
475
476   if (VPPCOM_DEBUG > 0)
477     clib_warning ("[%d] timeout waiting for client_session_index", getpid ());
478   return VPPCOM_ETIMEDOUT;
479 }
480
481 /*
482  * VPP-API message functions
483  */
484 static void
485 vppcom_send_session_enable_disable (u8 is_enable)
486 {
487   vl_api_session_enable_disable_t *bmp;
488   bmp = vl_msg_api_alloc (sizeof (*bmp));
489   memset (bmp, 0, sizeof (*bmp));
490
491   bmp->_vl_msg_id = ntohs (VL_API_SESSION_ENABLE_DISABLE);
492   bmp->client_index = vcm->my_client_index;
493   bmp->context = htonl (0xfeedface);
494   bmp->is_enable = is_enable;
495   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
496 }
497
498 static int
499 vppcom_app_session_enable (void)
500 {
501   int rv;
502
503   if (vcm->app_state != STATE_APP_ENABLED)
504     {
505       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
506       rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
507       if (PREDICT_FALSE (rv))
508         {
509           if (VPPCOM_DEBUG > 0)
510             clib_warning ("[%d] application session enable timed out! "
511                           "returning %d (%s)",
512                           getpid (), rv, vppcom_retval_str (rv));
513           return rv;
514         }
515     }
516   return VPPCOM_OK;
517 }
518
519 static void
520   vl_api_session_enable_disable_reply_t_handler
521   (vl_api_session_enable_disable_reply_t * mp)
522 {
523   if (mp->retval)
524     {
525       clib_warning ("[%d] session_enable_disable failed: %U", getpid (),
526                     format_api_error, ntohl (mp->retval));
527     }
528   else
529     vcm->app_state = STATE_APP_ENABLED;
530 }
531
532 static void
533 vppcom_app_send_attach (void)
534 {
535   vl_api_application_attach_t *bmp;
536   u8 nsid_len = vec_len (vcm->cfg.namespace_id);
537   u8 app_is_proxy = (vcm->cfg.app_proxy_transport_tcp ||
538                      vcm->cfg.app_proxy_transport_udp);
539
540   bmp = vl_msg_api_alloc (sizeof (*bmp));
541   memset (bmp, 0, sizeof (*bmp));
542
543   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
544   bmp->client_index = vcm->my_client_index;
545   bmp->context = htonl (0xfeedface);
546   bmp->options[APP_OPTIONS_FLAGS] =
547     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT |
548     (vcm->cfg.app_scope_local ? APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE : 0) |
549     (vcm->cfg.app_scope_global ? APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE : 0) |
550     (app_is_proxy ? APP_OPTIONS_FLAGS_IS_PROXY : 0);
551   bmp->options[APP_OPTIONS_PROXY_TRANSPORT] =
552     (vcm->cfg.app_proxy_transport_tcp ? 1 << TRANSPORT_PROTO_TCP : 0) |
553     (vcm->cfg.app_proxy_transport_udp ? 1 << TRANSPORT_PROTO_UDP : 0);
554   bmp->options[SESSION_OPTIONS_SEGMENT_SIZE] = vcm->cfg.segment_size;
555   bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = vcm->cfg.add_segment_size;
556   bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = vcm->cfg.rx_fifo_size;
557   bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = vcm->cfg.tx_fifo_size;
558   if (nsid_len)
559     {
560       bmp->namespace_id_len = nsid_len;
561       clib_memcpy (bmp->namespace_id, vcm->cfg.namespace_id, nsid_len);
562       bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = vcm->cfg.namespace_secret;
563     }
564   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
565 }
566
567 static int
568 vppcom_app_attach (void)
569 {
570   int rv;
571
572   vppcom_app_send_attach ();
573   rv = vppcom_wait_for_app_state_change (STATE_APP_ATTACHED);
574   if (PREDICT_FALSE (rv))
575     {
576       if (VPPCOM_DEBUG > 0)
577         clib_warning ("[%d] application attach timed out! returning %d (%s)",
578                       getpid (), rv, vppcom_retval_str (rv));
579       return rv;
580     }
581   return VPPCOM_OK;
582 }
583
584 static void
585 vppcom_app_detach (void)
586 {
587   vl_api_application_detach_t *bmp;
588   bmp = vl_msg_api_alloc (sizeof (*bmp));
589   memset (bmp, 0, sizeof (*bmp));
590
591   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
592   bmp->client_index = vcm->my_client_index;
593   bmp->context = htonl (0xfeedface);
594   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
595 }
596
597 static void
598 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
599                                            mp)
600 {
601   static svm_fifo_segment_create_args_t _a;
602   svm_fifo_segment_create_args_t *a = &_a;
603   int rv;
604
605   memset (a, 0, sizeof (*a));
606   if (mp->retval)
607     {
608       clib_warning ("[%d] attach failed: %U", getpid (),
609                     format_api_error, ntohl (mp->retval));
610       return;
611     }
612
613   if (mp->segment_name_length == 0)
614     {
615       clib_warning ("[%d] segment_name_length zero", getpid ());
616       return;
617     }
618
619   a->segment_name = (char *) mp->segment_name;
620   a->segment_size = mp->segment_size;
621
622   ASSERT (mp->app_event_queue_address);
623
624   /* Attach to the segment vpp created */
625   rv = svm_fifo_segment_attach (a);
626   vec_reset_length (a->new_segment_indices);
627   if (PREDICT_FALSE (rv))
628     {
629       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed", getpid (),
630                     mp->segment_name);
631       return;
632     }
633
634   vcm->app_event_queue =
635     uword_to_pointer (mp->app_event_queue_address,
636                       unix_shared_memory_queue_t *);
637
638   vcm->app_state = STATE_APP_ATTACHED;
639 }
640
641 static void
642 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
643                                            mp)
644 {
645   if (mp->retval)
646     clib_warning ("[%d] detach failed: %U", getpid (), format_api_error,
647                   ntohl (mp->retval));
648
649   vcm->app_state = STATE_APP_ENABLED;
650 }
651
652 static void
653 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
654                                            mp)
655 {
656   if (mp->retval)
657     clib_warning ("[%d] vpp handle 0x%llx: disconnect session failed: %U",
658                   getpid (), mp->handle, format_api_error,
659                   ntohl (mp->retval));
660 }
661
662 static void
663 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
664 {
665   static svm_fifo_segment_create_args_t _a;
666   svm_fifo_segment_create_args_t *a = &_a;
667   int rv;
668
669   memset (a, 0, sizeof (*a));
670   a->segment_name = (char *) mp->segment_name;
671   a->segment_size = mp->segment_size;
672   /* Attach to the segment vpp created */
673   rv = svm_fifo_segment_attach (a);
674   vec_reset_length (a->new_segment_indices);
675   if (PREDICT_FALSE (rv))
676     {
677       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed",
678                     getpid (), mp->segment_name);
679       return;
680     }
681   if (VPPCOM_DEBUG > 1)
682     clib_warning ("[%d] mapped new segment '%s' size %d", getpid (),
683                   mp->segment_name, mp->segment_size);
684 }
685
686 static void
687 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
688 {
689   uword *p;
690
691   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
692   if (p)
693     {
694       int rv;
695       session_t *session = 0;
696       u32 session_index = p[0];
697
698       VCL_LOCK_AND_GET_SESSION (session_index, &session);
699       session->state = STATE_CLOSE_ON_EMPTY;
700
701       if (VPPCOM_DEBUG > 1)
702         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
703                       "setting state to 0x%x (%s)",
704                       getpid (), mp->handle, session_index, session->state,
705                       vppcom_session_state_str (session->state));
706       clib_spinlock_unlock (&vcm->sessions_lockp);
707       return;
708
709     done:
710       if (VPPCOM_DEBUG > 1)
711         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
712                       "session lookup failed!",
713                       getpid (), mp->handle, session_index);
714     }
715   else
716     clib_warning ("[%d] vpp handle 0x%llx: session lookup by "
717                   "handle failed!", getpid (), mp->handle);
718 }
719
720 static void
721 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
722 {
723   session_t *session = 0;
724   vl_api_reset_session_reply_t *rmp;
725   uword *p;
726   int rv = 0;
727
728   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
729   if (p)
730     {
731       int rval;
732       clib_spinlock_lock (&vcm->sessions_lockp);
733       rval = vppcom_session_at_index (p[0], &session);
734       if (PREDICT_FALSE (rval))
735         {
736           rv = VNET_API_ERROR_INVALID_VALUE_2;
737           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
738                         "session lookup failed! returning %d %U",
739                         getpid (), mp->handle, p[0],
740                         rv, format_api_error, rv);
741         }
742       else
743         {
744           /* TBD: should this disconnect immediately and
745            * flush the fifos?
746            */
747           session->state = STATE_CLOSE_ON_EMPTY;
748
749           if (VPPCOM_DEBUG > 1)
750             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
751                           "state set to %d (%s)!", getpid (),
752                           mp->handle, p[0], session->state,
753                           vppcom_session_state_str (session->state));
754         }
755       clib_spinlock_unlock (&vcm->sessions_lockp);
756     }
757   else
758     {
759       rv = VNET_API_ERROR_INVALID_VALUE;
760       clib_warning ("[%d] ERROR: vpp handle 0x%llx: session lookup "
761                     "failed! returning %d %U",
762                     getpid (), mp->handle, rv, format_api_error, rv);
763     }
764
765   rmp = vl_msg_api_alloc (sizeof (*rmp));
766   memset (rmp, 0, sizeof (*rmp));
767   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
768   rmp->retval = htonl (rv);
769   rmp->handle = mp->handle;
770   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
771 }
772
773 static void
774 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
775 {
776   session_t *session = 0;
777   u32 session_index;
778   svm_fifo_t *rx_fifo, *tx_fifo;
779   u8 is_cut_thru = 0;
780   int rv;
781
782   session_index = mp->context;
783   VCL_LOCK_AND_GET_SESSION (session_index, &session);
784 done:
785   if (mp->retval)
786     {
787       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
788                     "connect failed! %U",
789                     getpid (), mp->handle, session_index,
790                     format_api_error, ntohl (mp->retval));
791       if (rv == VPPCOM_OK)
792         {
793           session->state = STATE_FAILED;
794           session->vpp_handle = mp->handle;
795         }
796       else
797         {
798           clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
799                         "Invalid session index (%u)!",
800                         getpid (), mp->handle, session_index);
801         }
802       goto done_unlock;
803     }
804
805   if (rv)
806     goto done_unlock;
807
808   /* We've been redirected */
809   if (mp->segment_name_length > 0)
810     {
811       static svm_fifo_segment_create_args_t _a;
812       svm_fifo_segment_create_args_t *a = &_a;
813
814       is_cut_thru = 1;
815       memset (a, 0, sizeof (*a));
816       a->segment_name = (char *) mp->segment_name;
817       if (VPPCOM_DEBUG > 1)
818         clib_warning ("[%d] cut-thru segment: %s\n",
819                       getpid (), a->segment_name);
820
821       rv = svm_fifo_segment_attach (a);
822       vec_reset_length (a->new_segment_indices);
823       if (PREDICT_FALSE (rv))
824         {
825           clib_warning ("[%d] sm_fifo_segment_attach ('%s') failed",
826                         getpid (), a->segment_name);
827           goto done_unlock;
828         }
829     }
830
831   /*
832    * Setup session
833    */
834   session->is_cut_thru = is_cut_thru;
835   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
836                                                unix_shared_memory_queue_t *);
837
838   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
839   rx_fifo->client_session_index = session_index;
840   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
841   tx_fifo->client_session_index = session_index;
842
843   session->server_rx_fifo = rx_fifo;
844   session->server_tx_fifo = tx_fifo;
845   session->vpp_handle = mp->handle;
846   session->lcl_addr.is_ip4 = mp->is_ip4;
847   clib_memcpy (&session->lcl_addr.ip46, mp->lcl_ip,
848                sizeof (session->peer_addr.ip46));
849   session->lcl_port = mp->lcl_port;
850   session->state = STATE_CONNECT;
851
852   /* Add it to lookup table */
853   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
854
855   if (VPPCOM_DEBUG > 1)
856     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connect succeeded!"
857                   " session_rx_fifo %p, refcnt %d,"
858                   " session_tx_fifo %p, refcnt %d",
859                   getpid (), mp->handle, session_index,
860                   session->server_rx_fifo,
861                   session->server_rx_fifo->refcnt,
862                   session->server_tx_fifo, session->server_tx_fifo->refcnt);
863 done_unlock:
864   clib_spinlock_unlock (&vcm->sessions_lockp);
865 }
866
867 static void
868 vppcom_send_connect_sock (session_t * session, u32 session_index)
869 {
870   vl_api_connect_sock_t *cmp;
871
872   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
873   session->is_server = 0;
874   cmp = vl_msg_api_alloc (sizeof (*cmp));
875   memset (cmp, 0, sizeof (*cmp));
876   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK);
877   cmp->client_index = vcm->my_client_index;
878   cmp->context = session_index;
879
880   cmp->vrf = session->vrf;
881   cmp->is_ip4 = session->peer_addr.is_ip4;
882   clib_memcpy (cmp->ip, &session->peer_addr.ip46, sizeof (cmp->ip));
883   cmp->port = session->peer_port;
884   cmp->proto = session->proto;
885   clib_memcpy (cmp->options, session->options, sizeof (cmp->options));
886   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & cmp);
887 }
888
889 static inline void
890 vppcom_send_disconnect_session_reply (u64 vpp_handle, u32 session_index,
891                                       int rv)
892 {
893   vl_api_disconnect_session_reply_t *rmp;
894
895   if (VPPCOM_DEBUG > 1)
896     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending disconnect msg",
897                   getpid (), vpp_handle, session_index);
898
899   rmp = vl_msg_api_alloc (sizeof (*rmp));
900   memset (rmp, 0, sizeof (*rmp));
901
902   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
903   rmp->retval = htonl (rv);
904   rmp->handle = vpp_handle;
905   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
906 }
907
908 static inline void
909 vppcom_send_disconnect_session (u64 vpp_handle, u32 session_index)
910 {
911   vl_api_disconnect_session_t *dmp;
912
913   if (VPPCOM_DEBUG > 1)
914     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending disconnect msg",
915                   getpid (), vpp_handle, session_index);
916
917   dmp = vl_msg_api_alloc (sizeof (*dmp));
918   memset (dmp, 0, sizeof (*dmp));
919   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
920   dmp->client_index = vcm->my_client_index;
921   dmp->handle = vpp_handle;
922   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & dmp);
923 }
924
925 static void
926 vl_api_bind_sock_reply_t_handler (vl_api_bind_sock_reply_t * mp)
927 {
928   session_t *session = 0;
929   u32 session_index = mp->context;
930   int rv;
931
932   VCL_LOCK_AND_GET_SESSION (session_index, &session);
933 done:
934   if (mp->retval)
935     {
936       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: bind failed: %U",
937                     getpid (), mp->handle, session_index, format_api_error,
938                     ntohl (mp->retval));
939       rv = vppcom_session_at_index (session_index, &session);
940       if (rv == VPPCOM_OK)
941         {
942           session->state = STATE_FAILED;
943           session->vpp_handle = mp->handle;
944         }
945       else
946         {
947           clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
948                         "Invalid session index (%u)!",
949                         getpid (), mp->handle, session_index);
950         }
951       goto done_unlock;
952     }
953
954   session->vpp_handle = mp->handle;
955   session->lcl_addr.is_ip4 = mp->lcl_is_ip4;
956   clib_memcpy (&session->lcl_addr.ip46, mp->lcl_ip,
957                sizeof (session->peer_addr.ip46));
958   session->lcl_port = mp->lcl_port;
959   vppcom_session_table_add_listener (mp->handle, session_index);
960   session->is_listen = 1;
961   session->state = STATE_LISTEN;
962
963   if (VPPCOM_DEBUG > 1)
964     clib_warning ("[%d] vpp handle 0x%llx, sid %u: bind succeeded!",
965                   getpid (), mp->handle, mp->context);
966 done_unlock:
967   clib_spinlock_unlock (&vcm->sessions_lockp);
968 }
969
970 static void
971 vl_api_unbind_sock_reply_t_handler (vl_api_unbind_sock_reply_t * mp)
972 {
973   if (mp->retval)
974     clib_warning ("[%d] ERROR: sid %u: unbind failed: %U",
975                   getpid (), mp->context, format_api_error,
976                   ntohl (mp->retval));
977
978   else if (VPPCOM_DEBUG > 1)
979     clib_warning ("[%d] sid %u: unbind succeeded!", getpid (), mp->context);
980 }
981
982 u8 *
983 format_ip4_address (u8 * s, va_list * args)
984 {
985   u8 *a = va_arg (*args, u8 *);
986   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
987 }
988
989 u8 *
990 format_ip6_address (u8 * s, va_list * args)
991 {
992   ip6_address_t *a = va_arg (*args, ip6_address_t *);
993   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
994
995   i_max_n_zero = ARRAY_LEN (a->as_u16);
996   max_n_zeros = 0;
997   i_first_zero = i_max_n_zero;
998   n_zeros = 0;
999   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1000     {
1001       u32 is_zero = a->as_u16[i] == 0;
1002       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
1003         {
1004           i_first_zero = i;
1005           n_zeros = 0;
1006         }
1007       n_zeros += is_zero;
1008       if ((!is_zero && n_zeros > max_n_zeros)
1009           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
1010         {
1011           i_max_n_zero = i_first_zero;
1012           max_n_zeros = n_zeros;
1013           i_first_zero = ARRAY_LEN (a->as_u16);
1014           n_zeros = 0;
1015         }
1016     }
1017
1018   last_double_colon = 0;
1019   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1020     {
1021       if (i == i_max_n_zero && max_n_zeros > 1)
1022         {
1023           s = format (s, "::");
1024           i += max_n_zeros - 1;
1025           last_double_colon = 1;
1026         }
1027       else
1028         {
1029           s = format (s, "%s%x",
1030                       (last_double_colon || i == 0) ? "" : ":",
1031                       clib_net_to_host_u16 (a->as_u16[i]));
1032           last_double_colon = 0;
1033         }
1034     }
1035
1036   return s;
1037 }
1038
1039 /* Format an IP46 address. */
1040 u8 *
1041 format_ip46_address (u8 * s, va_list * args)
1042 {
1043   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
1044   ip46_type_t type = va_arg (*args, ip46_type_t);
1045   int is_ip4 = 1;
1046
1047   switch (type)
1048     {
1049     case IP46_TYPE_ANY:
1050       is_ip4 = ip46_address_is_ip4 (ip46);
1051       break;
1052     case IP46_TYPE_IP4:
1053       is_ip4 = 1;
1054       break;
1055     case IP46_TYPE_IP6:
1056       is_ip4 = 0;
1057       break;
1058     }
1059
1060   return is_ip4 ?
1061     format (s, "%U", format_ip4_address, &ip46->ip4) :
1062     format (s, "%U", format_ip6_address, &ip46->ip6);
1063 }
1064
1065 static inline void
1066 vppcom_send_accept_session_reply (u64 handle, u32 context, int retval)
1067 {
1068   vl_api_accept_session_reply_t *rmp;
1069
1070   rmp = vl_msg_api_alloc (sizeof (*rmp));
1071   memset (rmp, 0, sizeof (*rmp));
1072   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
1073   rmp->retval = htonl (retval);
1074   rmp->context = context;
1075   rmp->handle = handle;
1076   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1077 }
1078
1079 static void
1080 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
1081 {
1082   svm_fifo_t *rx_fifo, *tx_fifo;
1083   session_t *session, *listen_session;
1084   u32 session_index;
1085
1086   clib_spinlock_lock (&vcm->sessions_lockp);
1087   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1088     {
1089       clib_warning ("[%d] client session queue is full!", getpid ());
1090       vppcom_send_accept_session_reply (mp->handle, mp->context,
1091                                         VNET_API_ERROR_QUEUE_FULL);
1092       clib_spinlock_unlock (&vcm->sessions_lockp);
1093       return;
1094     }
1095
1096   listen_session = vppcom_session_table_lookup_listener (mp->listener_handle);
1097   if (!listen_session)
1098     {
1099       clib_warning ("[%d] ERROR: couldn't find listen session: unknown vpp "
1100                     "listener handle %llx", getpid (), mp->listener_handle);
1101       clib_spinlock_unlock (&vcm->sessions_lockp);
1102       return;
1103     }
1104
1105   /* Allocate local session and set it up */
1106   pool_get (vcm->sessions, session);
1107   memset (session, 0, sizeof (*session));
1108   session_index = session - vcm->sessions;
1109
1110   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
1111   rx_fifo->client_session_index = session_index;
1112   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
1113   tx_fifo->client_session_index = session_index;
1114
1115   session->vpp_handle = mp->handle;
1116   session->client_context = mp->context;
1117   session->server_rx_fifo = rx_fifo;
1118   session->server_tx_fifo = tx_fifo;
1119   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
1120                                                unix_shared_memory_queue_t *);
1121   session->state = STATE_ACCEPT;
1122   session->is_cut_thru = 0;
1123   session->is_server = 1;
1124   session->peer_port = mp->port;
1125   session->peer_addr.is_ip4 = mp->is_ip4;
1126   clib_memcpy (&session->peer_addr.ip46, mp->ip,
1127                sizeof (session->peer_addr.ip46));
1128
1129   /* Add it to lookup table */
1130   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
1131   session->lcl_port = listen_session->lcl_port;
1132   session->lcl_addr = listen_session->lcl_addr;
1133
1134   /* TBD: move client_session_index_fifo into listener session */
1135   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1136
1137   clib_spinlock_unlock (&vcm->sessions_lockp);
1138
1139   if (VPPCOM_DEBUG > 1)
1140     clib_warning ("[%d] vpp handle 0x%llx, sid %u: client accept "
1141                   "request from %s address %U port %d queue %p!", getpid (),
1142                   mp->handle, session_index, mp->is_ip4 ? "IPv4" : "IPv6",
1143                   format_ip46_address, &mp->ip, mp->is_ip4,
1144                   clib_net_to_host_u16 (mp->port), session->vpp_event_queue);
1145 }
1146
1147 static void
1148 vppcom_send_connect_session_reply (session_t * session, u32 session_index,
1149                                    u64 vpp_handle, u32 context, int retval)
1150 {
1151   vl_api_connect_session_reply_t *rmp;
1152   u32 len;
1153   unix_shared_memory_queue_t *client_q;
1154
1155   rmp = vl_msg_api_alloc (sizeof (*rmp));
1156   memset (rmp, 0, sizeof (*rmp));
1157   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SESSION_REPLY);
1158
1159   if (!session)
1160     {
1161       rmp->context = context;
1162       rmp->handle = vpp_handle;
1163       rmp->retval = htonl (retval);
1164       vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1165       return;
1166     }
1167
1168   rmp->context = session->client_context;
1169   rmp->retval = htonl (retval);
1170   rmp->handle = session->vpp_handle;
1171   rmp->server_rx_fifo = pointer_to_uword (session->server_rx_fifo);
1172   rmp->server_tx_fifo = pointer_to_uword (session->server_tx_fifo);
1173   rmp->vpp_event_queue_address = pointer_to_uword (session->vpp_event_queue);
1174   rmp->segment_size = vcm->cfg.segment_size;
1175   len = vec_len (session->segment_name);
1176   rmp->segment_name_length = clib_min (len, sizeof (rmp->segment_name));
1177   clib_memcpy (rmp->segment_name, session->segment_name,
1178                rmp->segment_name_length - 1);
1179   clib_memcpy (rmp->lcl_ip, session->peer_addr.ip46.as_u8,
1180                sizeof (rmp->lcl_ip));
1181   rmp->is_ip4 = session->peer_addr.is_ip4;
1182   rmp->lcl_port = session->peer_port;
1183   client_q = uword_to_pointer (session->client_queue_address,
1184                                unix_shared_memory_queue_t *);
1185   ASSERT (client_q);
1186   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
1187 }
1188
1189 /*
1190  * Acting as server for redirected connect requests
1191  */
1192 static void
1193 vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
1194 {
1195   u32 session_index;
1196   session_t *session = 0;
1197
1198   clib_spinlock_lock (&vcm->sessions_lockp);
1199   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1200     {
1201       clib_spinlock_unlock (&vcm->sessions_lockp);
1202
1203       if (VPPCOM_DEBUG > 1)
1204         clib_warning ("[%d] client session queue is full!", getpid ());
1205
1206       /* TBD: Fix api to include vpp handle */
1207       vppcom_send_connect_session_reply (0 /* session */ , 0 /* sid */ ,
1208                                          0 /* handle */ , mp->context,
1209                                          VNET_API_ERROR_QUEUE_FULL);
1210       return;
1211     }
1212
1213   pool_get (vcm->sessions, session);
1214   memset (session, 0, sizeof (*session));
1215   session_index = session - vcm->sessions;
1216
1217   session->client_context = mp->context;
1218   session->vpp_handle = session_index;
1219   session->client_queue_address = mp->client_queue_address;
1220   session->is_cut_thru = 1;
1221   session->is_server = 1;
1222   session->lcl_port = mp->port;
1223   session->lcl_addr.is_ip4 = mp->is_ip4;
1224   clib_memcpy (&session->lcl_addr.ip46, mp->ip,
1225                sizeof (session->lcl_addr.ip46));
1226
1227   /* TBD: missing peer info in api msg.
1228    */
1229   session->peer_addr.is_ip4 = mp->is_ip4;
1230   ASSERT (session->lcl_addr.is_ip4 == session->peer_addr.is_ip4);
1231
1232   session->state = STATE_ACCEPT;
1233   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1234   if (VPPCOM_DEBUG > 1)
1235     clib_warning ("[%d] sid %u: Got a cut-thru connect request! "
1236                   "clib_fifo_elts %u!\n", getpid (), session_index,
1237                   clib_fifo_elts (vcm->client_session_index_fifo));
1238   clib_spinlock_unlock (&vcm->sessions_lockp);
1239 }
1240
1241 static void
1242 vppcom_send_bind_sock (session_t * session, u32 session_index)
1243 {
1244   vl_api_bind_sock_t *bmp;
1245
1246   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1247   session->is_server = 1;
1248   bmp = vl_msg_api_alloc (sizeof (*bmp));
1249   memset (bmp, 0, sizeof (*bmp));
1250
1251   bmp->_vl_msg_id = ntohs (VL_API_BIND_SOCK);
1252   bmp->client_index = vcm->my_client_index;
1253   bmp->context = session_index;
1254   bmp->vrf = session->vrf;
1255   bmp->is_ip4 = session->lcl_addr.is_ip4;
1256   clib_memcpy (bmp->ip, &session->lcl_addr.ip46, sizeof (bmp->ip));
1257   bmp->port = session->lcl_port;
1258   bmp->proto = session->proto;
1259   clib_memcpy (bmp->options, session->options, sizeof (bmp->options));
1260   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
1261 }
1262
1263 static void
1264 vppcom_send_unbind_sock (u64 vpp_handle)
1265 {
1266   vl_api_unbind_sock_t *ump;
1267
1268   ump = vl_msg_api_alloc (sizeof (*ump));
1269   memset (ump, 0, sizeof (*ump));
1270
1271   ump->_vl_msg_id = ntohs (VL_API_UNBIND_SOCK);
1272   ump->client_index = vcm->my_client_index;
1273   ump->handle = vpp_handle;
1274   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & ump);
1275 }
1276
1277 static int
1278 vppcom_session_unbind (u32 session_index)
1279 {
1280   session_t *session = 0;
1281   int rv;
1282   u64 vpp_handle;
1283
1284   VCL_LOCK_AND_GET_SESSION (session_index, &session);
1285
1286   vpp_handle = session->vpp_handle;
1287   vppcom_session_table_del_listener (vpp_handle);
1288   session->vpp_handle = ~0;
1289   session->state = STATE_DISCONNECT;
1290
1291   clib_spinlock_unlock (&vcm->sessions_lockp);
1292
1293   if (VPPCOM_DEBUG > 1)
1294     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1295                   "sending unbind msg! new state 0x%x (%s)",
1296                   getpid (), vpp_handle, session_index,
1297                   session->state, vppcom_session_state_str (session->state));
1298
1299   vppcom_send_unbind_sock (vpp_handle);
1300
1301 done:
1302   return rv;
1303 }
1304
1305 static inline int
1306 vppcom_session_disconnect (u32 session_index)
1307 {
1308   int rv;
1309   session_t *session;
1310   u8 is_cut_thru, is_listen, is_server;
1311   u64 vpp_handle;
1312   session_state_t state;
1313
1314   VCL_LOCK_AND_GET_SESSION (session_index, &session);
1315
1316   vpp_handle = session->vpp_handle;
1317   is_server = session->is_server;
1318   is_listen = session->is_listen;
1319   is_cut_thru = session->is_cut_thru;
1320   state = session->state;
1321   clib_spinlock_unlock (&vcm->sessions_lockp);
1322
1323   if (VPPCOM_DEBUG > 1)
1324     {
1325       clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s state 0x%x (%s), "
1326                     "is_cut_thru %d, is_listen %d",
1327                     getpid (), vpp_handle, session_index,
1328                     is_server ? "server" : "client",
1329                     state, vppcom_session_state_str (state),
1330                     is_cut_thru, is_listen);
1331     }
1332
1333   if (PREDICT_FALSE (is_listen))
1334     {
1335       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
1336                     "Cannot disconnect a listen socket!",
1337                     getpid (), vpp_handle, session_index);
1338       rv = VPPCOM_EBADFD;
1339       goto done;
1340     }
1341
1342   /* Through the VPP host stack...
1343    */
1344   else if (!is_cut_thru)
1345     {
1346       /* The peer has already initiated the close,
1347        * so send the disconnect session reply.
1348        */
1349       if (state & STATE_CLOSE_ON_EMPTY)
1350         {
1351           vppcom_send_disconnect_session_reply (vpp_handle,
1352                                                 session_index, 0 /* rv */ );
1353           if (VPPCOM_DEBUG > 1)
1354             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1355                           "sending disconnect REPLY...",
1356                           getpid (), vpp_handle, session_index);
1357         }
1358
1359       /* Otherwise, send a disconnect session msg...
1360        */
1361       else
1362         {
1363           if (VPPCOM_DEBUG > 1)
1364             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1365                           "sending disconnect...",
1366                           getpid (), vpp_handle, session_index);
1367
1368           vppcom_send_disconnect_session (vpp_handle, session_index);
1369         }
1370     }
1371
1372   /* Cut-thru connections...
1373    *
1374    *   server: free fifos and segment allocated during connect/redirect
1375    *   client: no cleanup required
1376    */
1377   else
1378     {
1379       if (is_server)
1380         {
1381           svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
1382           svm_fifo_segment_private_t *seg;
1383
1384           VCL_LOCK_AND_GET_SESSION (session_index, &session);
1385
1386           if (VPPCOM_DEBUG > 1)
1387             clib_warning ("[%d] sid %d: freeing cut-thru fifos in "
1388                           "sm_seg_index %d! "
1389                           " server_rx_fifo %p, refcnt = %d"
1390                           " server_tx_fifo %p, refcnt = %d",
1391                           getpid (), session_index, session->sm_seg_index,
1392                           session->server_rx_fifo,
1393                           session->server_rx_fifo->refcnt,
1394                           session->server_tx_fifo,
1395                           session->server_tx_fifo->refcnt);
1396
1397           seg = vec_elt_at_index (sm->segments, session->sm_seg_index);
1398           svm_fifo_segment_free_fifo (seg, session->server_rx_fifo,
1399                                       FIFO_SEGMENT_RX_FREELIST);
1400           svm_fifo_segment_free_fifo (seg, session->server_tx_fifo,
1401                                       FIFO_SEGMENT_TX_FREELIST);
1402           svm_fifo_segment_delete (seg);
1403
1404           /* TBD: Send cut-thru disconnect event to client */
1405
1406           clib_spinlock_unlock (&vcm->sessions_lockp);
1407         }
1408       else
1409         {
1410           /* TBD: Send cut-thru disconnect event to server */
1411         }
1412     }
1413
1414 done:
1415   return rv;
1416 }
1417
1418 #define foreach_sock_msg                                        \
1419 _(SESSION_ENABLE_DISABLE_REPLY, session_enable_disable_reply)   \
1420 _(BIND_SOCK_REPLY, bind_sock_reply)                             \
1421 _(UNBIND_SOCK_REPLY, unbind_sock_reply)                         \
1422 _(ACCEPT_SESSION, accept_session)                               \
1423 _(CONNECT_SOCK, connect_sock)                                   \
1424 _(CONNECT_SESSION_REPLY, connect_session_reply)                 \
1425 _(DISCONNECT_SESSION, disconnect_session)                       \
1426 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1427 _(RESET_SESSION, reset_session)                                 \
1428 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1429 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1430 _(MAP_ANOTHER_SEGMENT, map_another_segment)
1431
1432 static void
1433 vppcom_api_hookup (void)
1434 {
1435 #define _(N,n)                                                  \
1436     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1437                            vl_api_##n##_t_handler,              \
1438                            vl_noop_handler,                     \
1439                            vl_api_##n##_t_endian,               \
1440                            vl_api_##n##_t_print,                \
1441                            sizeof(vl_api_##n##_t), 1);
1442   foreach_sock_msg;
1443 #undef _
1444 }
1445
1446 static void
1447 vppcom_cfg_init (vppcom_cfg_t * vcl_cfg)
1448 {
1449   ASSERT (vcl_cfg);
1450
1451   vcl_cfg->heapsize = (256ULL << 20);
1452   vcl_cfg->segment_baseva = 0x200000000ULL;
1453   vcl_cfg->segment_size = (256 << 20);
1454   vcl_cfg->add_segment_size = (128 << 20);
1455   vcl_cfg->preallocated_fifo_pairs = 8;
1456   vcl_cfg->rx_fifo_size = (1 << 20);
1457   vcl_cfg->tx_fifo_size = (1 << 20);
1458   vcl_cfg->event_queue_size = 2048;
1459   vcl_cfg->listen_queue_size = CLIB_CACHE_LINE_BYTES / sizeof (u32);
1460   vcl_cfg->app_timeout = 10 * 60.0;
1461   vcl_cfg->session_timeout = 10 * 60.0;
1462   vcl_cfg->accept_timeout = 60.0;
1463 }
1464
1465 static void
1466 vppcom_cfg_heapsize (char *conf_fname)
1467 {
1468   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1469   FILE *fp;
1470   char inbuf[4096];
1471   int argc = 1;
1472   char **argv = NULL;
1473   char *arg = NULL;
1474   char *p;
1475   int i;
1476   u8 *sizep;
1477   u32 size;
1478   void *vcl_mem;
1479   void *heap;
1480
1481   fp = fopen (conf_fname, "r");
1482   if (fp == NULL)
1483     {
1484       if (VPPCOM_DEBUG > 0)
1485         fprintf (stderr, "open configuration file '%s' failed\n", conf_fname);
1486       goto defaulted;
1487     }
1488   argv = calloc (1, sizeof (char *));
1489   if (argv == NULL)
1490     goto defaulted;
1491
1492   while (1)
1493     {
1494       if (fgets (inbuf, 4096, fp) == 0)
1495         break;
1496       p = strtok (inbuf, " \t\n");
1497       while (p != NULL)
1498         {
1499           if (*p == '#')
1500             break;
1501           argc++;
1502           char **tmp = realloc (argv, argc * sizeof (char *));
1503           if (tmp == NULL)
1504             goto defaulted;
1505           argv = tmp;
1506           arg = strndup (p, 1024);
1507           if (arg == NULL)
1508             goto defaulted;
1509           argv[argc - 1] = arg;
1510           p = strtok (NULL, " \t\n");
1511         }
1512     }
1513
1514   fclose (fp);
1515   fp = NULL;
1516
1517   char **tmp = realloc (argv, (argc + 1) * sizeof (char *));
1518   if (tmp == NULL)
1519     goto defaulted;
1520   argv = tmp;
1521   argv[argc] = NULL;
1522
1523   /*
1524    * Look for and parse the "heapsize" config parameter.
1525    * Manual since none of the clib infra has been bootstrapped yet.
1526    *
1527    * Format: heapsize <nn>[mM][gG]
1528    */
1529
1530   for (i = 1; i < (argc - 1); i++)
1531     {
1532       if (!strncmp (argv[i], "heapsize", 8))
1533         {
1534           sizep = (u8 *) argv[i + 1];
1535           size = 0;
1536           while (*sizep >= '0' && *sizep <= '9')
1537             {
1538               size *= 10;
1539               size += *sizep++ - '0';
1540             }
1541           if (size == 0)
1542             {
1543               if (VPPCOM_DEBUG > 0)
1544                 clib_warning ("[%d] parse error '%s %s', "
1545                               "using default heapsize %lld (0x%llx)",
1546                               getpid (), argv[i], argv[i + 1],
1547                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1548               goto defaulted;
1549             }
1550
1551           if (*sizep == 'g' || *sizep == 'G')
1552             vcl_cfg->heapsize = size << 30;
1553           else if (*sizep == 'm' || *sizep == 'M')
1554             vcl_cfg->heapsize = size << 20;
1555           else
1556             {
1557               if (VPPCOM_DEBUG > 0)
1558                 clib_warning ("[%d] parse error '%s %s', "
1559                               "using default heapsize %lld (0x%llx)",
1560                               getpid (), argv[i], argv[i + 1],
1561                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1562               goto defaulted;
1563             }
1564         }
1565     }
1566
1567 defaulted:
1568   if (fp != NULL)
1569     fclose (fp);
1570   if (argv != NULL)
1571     free (argv);
1572
1573   vcl_mem = mmap (0, vcl_cfg->heapsize, PROT_READ | PROT_WRITE,
1574                   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1575   if (vcl_mem == MAP_FAILED)
1576     {
1577       clib_unix_error ("[%d] ERROR: mmap(0, %lld == 0x%llx, "
1578                        "PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, "
1579                        "-1, 0) failed!",
1580                        getpid (), vcl_cfg->heapsize, vcl_cfg->heapsize);
1581       return;
1582     }
1583   heap = clib_mem_init (vcl_mem, vcl_cfg->heapsize);
1584   if (!heap)
1585     {
1586       clib_warning ("[%d] ERROR: clib_mem_init() failed!", getpid ());
1587       return;
1588     }
1589   vcl_mem = clib_mem_alloc (sizeof (_vppcom_main));
1590   if (!vcl_mem)
1591     {
1592       clib_warning ("[%d] ERROR: clib_mem_alloc() failed!", getpid ());
1593       return;
1594     }
1595
1596   clib_memcpy (vcl_mem, &_vppcom_main, sizeof (_vppcom_main));
1597   vcm = vcl_mem;
1598
1599   if (VPPCOM_DEBUG > 0)
1600     clib_warning ("[%d] allocated VCL heap = %p, size %lld (0x%llx)",
1601                   getpid (), heap, vcl_cfg->heapsize, vcl_cfg->heapsize);
1602 }
1603
1604 static void
1605 vppcom_cfg_read (char *conf_fname)
1606 {
1607   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1608   int fd;
1609   unformat_input_t _input, *input = &_input;
1610   unformat_input_t _line_input, *line_input = &_line_input;
1611   u8 vc_cfg_input = 0;
1612   u8 *chroot_path;
1613   struct stat s;
1614   u32 uid, gid;
1615
1616   fd = open (conf_fname, O_RDONLY);
1617   if (fd < 0)
1618     {
1619       if (VPPCOM_DEBUG > 0)
1620         clib_warning ("[%d] open configuration file '%s' failed!",
1621                       getpid (), conf_fname);
1622       goto file_done;
1623     }
1624
1625   if (fstat (fd, &s) < 0)
1626     {
1627       if (VPPCOM_DEBUG > 0)
1628         clib_warning ("[%d] failed to stat `%s'", getpid (), conf_fname);
1629       goto file_done;
1630     }
1631
1632   if (!(S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
1633     {
1634       if (VPPCOM_DEBUG > 0)
1635         clib_warning ("[%d] not a regular file `%s'", getpid (), conf_fname);
1636       goto file_done;
1637     }
1638
1639   unformat_init_clib_file (input, fd);
1640
1641   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1642     {
1643       (void) unformat_user (input, unformat_line_input, line_input);
1644       unformat_skip_white_space (line_input);
1645
1646       if (unformat (line_input, "vcl {"))
1647         {
1648           vc_cfg_input = 1;
1649           continue;
1650         }
1651
1652       if (vc_cfg_input)
1653         {
1654           if (unformat (line_input, "heapsize %s", &chroot_path))
1655             {
1656               vec_terminate_c_string (chroot_path);
1657               if (VPPCOM_DEBUG > 0)
1658                 clib_warning ("[%d] configured heapsize %s, "
1659                               "actual heapsize %lld (0x%llx)",
1660                               getpid (), chroot_path, vcl_cfg->heapsize,
1661                               vcl_cfg->heapsize);
1662               vec_free (chroot_path);
1663             }
1664           else if (unformat (line_input, "api-prefix %s", &chroot_path))
1665             {
1666               vec_terminate_c_string (chroot_path);
1667               vl_set_memory_root_path ((char *) chroot_path);
1668               if (VPPCOM_DEBUG > 0)
1669                 clib_warning ("[%d] configured api-prefix %s",
1670                               getpid (), chroot_path);
1671               chroot_path = 0;  /* Don't vec_free() it! */
1672             }
1673           else if (unformat (line_input, "uid %d", &uid))
1674             {
1675               vl_set_memory_uid (uid);
1676               if (VPPCOM_DEBUG > 0)
1677                 clib_warning ("[%d] configured uid %d", getpid (), uid);
1678             }
1679           else if (unformat (line_input, "gid %d", &gid))
1680             {
1681               vl_set_memory_gid (gid);
1682               if (VPPCOM_DEBUG > 0)
1683                 clib_warning ("[%d] configured gid %d", getpid (), gid);
1684             }
1685           else if (unformat (line_input, "segment-baseva 0x%lx",
1686                              &vcl_cfg->segment_baseva))
1687             {
1688               if (VPPCOM_DEBUG > 0)
1689                 clib_warning ("[%d] configured segment_baseva 0x%lx",
1690                               getpid (), vcl_cfg->segment_baseva);
1691             }
1692           else if (unformat (line_input, "segment-size 0x%lx",
1693                              &vcl_cfg->segment_size))
1694             {
1695               if (VPPCOM_DEBUG > 0)
1696                 clib_warning ("[%d] configured segment_size 0x%lx (%ld)",
1697                               getpid (), vcl_cfg->segment_size,
1698                               vcl_cfg->segment_size);
1699             }
1700           else if (unformat (line_input, "segment-size %ld",
1701                              &vcl_cfg->segment_size))
1702             {
1703               if (VPPCOM_DEBUG > 0)
1704                 clib_warning ("[%d] configured segment_size %ld (0x%lx)",
1705                               getpid (), vcl_cfg->segment_size,
1706                               vcl_cfg->segment_size);
1707             }
1708           else if (unformat (line_input, "add-segment-size 0x%lx",
1709                              &vcl_cfg->add_segment_size))
1710             {
1711               if (VPPCOM_DEBUG > 0)
1712                 clib_warning
1713                   ("[%d] configured add_segment_size 0x%lx (%ld)",
1714                    getpid (), vcl_cfg->add_segment_size,
1715                    vcl_cfg->add_segment_size);
1716             }
1717           else if (unformat (line_input, "add-segment-size %ld",
1718                              &vcl_cfg->add_segment_size))
1719             {
1720               if (VPPCOM_DEBUG > 0)
1721                 clib_warning
1722                   ("[%d] configured add_segment_size %ld (0x%lx)",
1723                    getpid (), vcl_cfg->add_segment_size,
1724                    vcl_cfg->add_segment_size);
1725             }
1726           else if (unformat (line_input, "preallocated-fifo-pairs %d",
1727                              &vcl_cfg->preallocated_fifo_pairs))
1728             {
1729               if (VPPCOM_DEBUG > 0)
1730                 clib_warning ("[%d] configured preallocated_fifo_pairs "
1731                               "%d (0x%x)", getpid (),
1732                               vcl_cfg->preallocated_fifo_pairs,
1733                               vcl_cfg->preallocated_fifo_pairs);
1734             }
1735           else if (unformat (line_input, "rx-fifo-size 0x%lx",
1736                              &vcl_cfg->rx_fifo_size))
1737             {
1738               if (VPPCOM_DEBUG > 0)
1739                 clib_warning ("[%d] configured rx_fifo_size 0x%lx (%ld)",
1740                               getpid (), vcl_cfg->rx_fifo_size,
1741                               vcl_cfg->rx_fifo_size);
1742             }
1743           else if (unformat (line_input, "rx-fifo-size %ld",
1744                              &vcl_cfg->rx_fifo_size))
1745             {
1746               if (VPPCOM_DEBUG > 0)
1747                 clib_warning ("[%d] configured rx_fifo_size %ld (0x%lx)",
1748                               getpid (), vcl_cfg->rx_fifo_size,
1749                               vcl_cfg->rx_fifo_size);
1750             }
1751           else if (unformat (line_input, "tx-fifo-size 0x%lx",
1752                              &vcl_cfg->tx_fifo_size))
1753             {
1754               if (VPPCOM_DEBUG > 0)
1755                 clib_warning ("[%d] configured tx_fifo_size 0x%lx (%ld)",
1756                               getpid (), vcl_cfg->tx_fifo_size,
1757                               vcl_cfg->tx_fifo_size);
1758             }
1759           else if (unformat (line_input, "tx-fifo-size %ld",
1760                              &vcl_cfg->tx_fifo_size))
1761             {
1762               if (VPPCOM_DEBUG > 0)
1763                 clib_warning ("[%d] configured tx_fifo_size %ld (0x%lx)",
1764                               getpid (), vcl_cfg->tx_fifo_size,
1765                               vcl_cfg->tx_fifo_size);
1766             }
1767           else if (unformat (line_input, "event-queue-size 0x%lx",
1768                              &vcl_cfg->event_queue_size))
1769             {
1770               if (VPPCOM_DEBUG > 0)
1771                 clib_warning ("[%d] configured event_queue_size 0x%lx (%ld)",
1772                               getpid (), vcl_cfg->event_queue_size,
1773                               vcl_cfg->event_queue_size);
1774             }
1775           else if (unformat (line_input, "event-queue-size %ld",
1776                              &vcl_cfg->event_queue_size))
1777             {
1778               if (VPPCOM_DEBUG > 0)
1779                 clib_warning ("[%d] configured event_queue_size %ld (0x%lx)",
1780                               getpid (), vcl_cfg->event_queue_size,
1781                               vcl_cfg->event_queue_size);
1782             }
1783           else if (unformat (line_input, "listen-queue-size 0x%lx",
1784                              &vcl_cfg->listen_queue_size))
1785             {
1786               if (VPPCOM_DEBUG > 0)
1787                 clib_warning ("[%d] configured listen_queue_size 0x%lx (%ld)",
1788                               getpid (), vcl_cfg->listen_queue_size,
1789                               vcl_cfg->listen_queue_size);
1790             }
1791           else if (unformat (line_input, "listen-queue-size %ld",
1792                              &vcl_cfg->listen_queue_size))
1793             {
1794               if (VPPCOM_DEBUG > 0)
1795                 clib_warning ("[%d] configured listen_queue_size %ld (0x%lx)",
1796                               getpid (), vcl_cfg->listen_queue_size,
1797                               vcl_cfg->listen_queue_size);
1798             }
1799           else if (unformat (line_input, "app-timeout %f",
1800                              &vcl_cfg->app_timeout))
1801             {
1802               if (VPPCOM_DEBUG > 0)
1803                 clib_warning ("[%d] configured app_timeout %f",
1804                               getpid (), vcl_cfg->app_timeout);
1805             }
1806           else if (unformat (line_input, "session-timeout %f",
1807                              &vcl_cfg->session_timeout))
1808             {
1809               if (VPPCOM_DEBUG > 0)
1810                 clib_warning ("[%d] configured session_timeout %f",
1811                               getpid (), vcl_cfg->session_timeout);
1812             }
1813           else if (unformat (line_input, "accept-timeout %f",
1814                              &vcl_cfg->accept_timeout))
1815             {
1816               if (VPPCOM_DEBUG > 0)
1817                 clib_warning ("[%d] configured accept_timeout %f",
1818                               getpid (), vcl_cfg->accept_timeout);
1819             }
1820           else if (unformat (line_input, "app-proxy-transport-tcp"))
1821             {
1822               vcl_cfg->app_proxy_transport_tcp = 1;
1823               if (VPPCOM_DEBUG > 0)
1824                 clib_warning ("[%d] configured app_proxy_transport_tcp (%d)",
1825                               getpid (), vcl_cfg->app_proxy_transport_tcp);
1826             }
1827           else if (unformat (line_input, "app-proxy-transport-udp"))
1828             {
1829               vcl_cfg->app_proxy_transport_udp = 1;
1830               if (VPPCOM_DEBUG > 0)
1831                 clib_warning ("[%d] configured app_proxy_transport_udp (%d)",
1832                               getpid (), vcl_cfg->app_proxy_transport_udp);
1833             }
1834           else if (unformat (line_input, "app-scope-local"))
1835             {
1836               vcl_cfg->app_scope_local = 1;
1837               if (VPPCOM_DEBUG > 0)
1838                 clib_warning ("[%d] configured app_scope_local (%d)",
1839                               getpid (), vcl_cfg->app_scope_local);
1840             }
1841           else if (unformat (line_input, "app-scope-global"))
1842             {
1843               vcl_cfg->app_scope_global = 1;
1844               if (VPPCOM_DEBUG > 0)
1845                 clib_warning ("[%d] configured app_scope_global (%d)",
1846                               getpid (), vcl_cfg->app_scope_global);
1847             }
1848           else if (unformat (line_input, "namespace-secret %lu",
1849                              &vcl_cfg->namespace_secret))
1850             {
1851               if (VPPCOM_DEBUG > 0)
1852                 clib_warning
1853                   ("[%d] configured namespace_secret %lu (0x%lx)",
1854                    getpid (), vcl_cfg->namespace_secret,
1855                    vcl_cfg->namespace_secret);
1856             }
1857           else if (unformat (line_input, "namespace-id %v",
1858                              &vcl_cfg->namespace_id))
1859             {
1860               vl_api_application_attach_t *mp;
1861               u32 max_nsid_vec_len = sizeof (mp->namespace_id) - 1;
1862               u32 nsid_vec_len = vec_len (vcl_cfg->namespace_id);
1863               if (nsid_vec_len > max_nsid_vec_len)
1864                 {
1865                   _vec_len (vcl_cfg->namespace_id) = max_nsid_vec_len;
1866                   if (VPPCOM_DEBUG > 0)
1867                     clib_warning ("[%d] configured namespace_id is too long,"
1868                                   " truncated to %d characters!", getpid (),
1869                                   max_nsid_vec_len);
1870                 }
1871
1872               if (VPPCOM_DEBUG > 0)
1873                 clib_warning ("[%d] configured namespace_id %v",
1874                               getpid (), vcl_cfg->namespace_id);
1875             }
1876           else if (unformat (line_input, "}"))
1877             {
1878               vc_cfg_input = 0;
1879               if (VPPCOM_DEBUG > 0)
1880                 clib_warning ("[%d] completed parsing vppcom config!",
1881                               getpid ());
1882               goto input_done;
1883             }
1884           else
1885             {
1886               if (line_input->buffer[line_input->index] != '#')
1887                 {
1888                   clib_warning ("[%d] Unknown vppcom config option: '%s'",
1889                                 getpid (), (char *)
1890                                 &line_input->buffer[line_input->index]);
1891                 }
1892             }
1893         }
1894     }
1895
1896 input_done:
1897   unformat_free (input);
1898
1899 file_done:
1900   if (fd >= 0)
1901     close (fd);
1902 }
1903
1904 /*
1905  * VPPCOM Public API functions
1906  */
1907 int
1908 vppcom_app_create (char *app_name)
1909 {
1910   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1911   u8 *heap;
1912   mheap_t *h;
1913   int rv;
1914
1915   if (!vcm->init)
1916     {
1917       char *conf_fname;
1918       char *env_var_str;
1919
1920       vcm->init = 1;
1921       vppcom_cfg_init (vcl_cfg);
1922       env_var_str = getenv (VPPCOM_ENV_DEBUG);
1923       if (env_var_str)
1924         {
1925           u32 tmp;
1926           if (sscanf (env_var_str, "%u", &tmp) != 1)
1927             clib_warning ("[%d] Invalid debug level specified in "
1928                           "the environment variable "
1929                           VPPCOM_ENV_DEBUG
1930                           " (%s)!\n", getpid (), env_var_str);
1931           else
1932             {
1933               vcm->debug = tmp;
1934               clib_warning ("[%d] configured debug level (%u) from "
1935                             VPPCOM_ENV_DEBUG "!", getpid (), vcm->debug);
1936             }
1937         }
1938       conf_fname = getenv (VPPCOM_ENV_CONF);
1939       if (!conf_fname)
1940         {
1941           conf_fname = VPPCOM_CONF_DEFAULT;
1942           if (VPPCOM_DEBUG > 0)
1943             clib_warning ("[%d] getenv '%s' failed!", getpid (),
1944                           VPPCOM_ENV_CONF);
1945         }
1946       vppcom_cfg_heapsize (conf_fname);
1947       clib_fifo_validate (vcm->client_session_index_fifo,
1948                           vcm->cfg.listen_queue_size);
1949       vppcom_cfg_read (conf_fname);
1950       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_ID);
1951       if (env_var_str)
1952         {
1953           u32 ns_id_vec_len = strlen (env_var_str);
1954
1955           vec_reset_length (vcm->cfg.namespace_id);
1956           vec_validate (vcm->cfg.namespace_id, ns_id_vec_len - 1);
1957           clib_memcpy (vcm->cfg.namespace_id, env_var_str, ns_id_vec_len);
1958
1959           if (VPPCOM_DEBUG > 0)
1960             clib_warning ("[%d] configured namespace_id (%v) from "
1961                           VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
1962                           vcm->cfg.namespace_id);
1963         }
1964       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_SECRET);
1965       if (env_var_str)
1966         {
1967           u64 tmp;
1968           if (sscanf (env_var_str, "%lu", &tmp) != 1)
1969             clib_warning ("[%d] Invalid namespace secret specified in "
1970                           "the environment variable "
1971                           VPPCOM_ENV_APP_NAMESPACE_SECRET
1972                           " (%s)!\n", getpid (), env_var_str);
1973           else
1974             {
1975               vcm->cfg.namespace_secret = tmp;
1976               if (VPPCOM_DEBUG > 0)
1977                 clib_warning ("[%d] configured namespace secret (%lu) from "
1978                               VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
1979                               vcm->cfg.namespace_secret);
1980             }
1981         }
1982       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP))
1983         {
1984           vcm->cfg.app_proxy_transport_tcp = 1;
1985           if (VPPCOM_DEBUG > 0)
1986             clib_warning ("[%d] configured app_proxy_transport_tcp (%u) from "
1987                           VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP "!", getpid (),
1988                           vcm->cfg.app_proxy_transport_tcp);
1989         }
1990       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP))
1991         {
1992           vcm->cfg.app_proxy_transport_udp = 1;
1993           if (VPPCOM_DEBUG > 0)
1994             clib_warning ("[%d] configured app_proxy_transport_udp (%u) from "
1995                           VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP "!", getpid (),
1996                           vcm->cfg.app_proxy_transport_udp);
1997         }
1998       if (getenv (VPPCOM_ENV_APP_SCOPE_LOCAL))
1999         {
2000           vcm->cfg.app_scope_local = 1;
2001           if (VPPCOM_DEBUG > 0)
2002             clib_warning ("[%d] configured app_scope_local (%u) from "
2003                           VPPCOM_ENV_APP_SCOPE_LOCAL "!", getpid (),
2004                           vcm->cfg.app_scope_local);
2005         }
2006       if (getenv (VPPCOM_ENV_APP_SCOPE_GLOBAL))
2007         {
2008           vcm->cfg.app_scope_global = 1;
2009           if (VPPCOM_DEBUG > 0)
2010             clib_warning ("[%d] configured app_scope_global (%u) from "
2011                           VPPCOM_ENV_APP_SCOPE_GLOBAL "!", getpid (),
2012                           vcm->cfg.app_scope_global);
2013         }
2014
2015       vcm->main_cpu = os_get_thread_index ();
2016       heap = clib_mem_get_per_cpu_heap ();
2017       h = mheap_header (heap);
2018
2019       /* make the main heap thread-safe */
2020       h->flags |= MHEAP_FLAG_THREAD_SAFE;
2021
2022       vcm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
2023
2024       clib_time_init (&vcm->clib_time);
2025       vppcom_init_error_string_table ();
2026       svm_fifo_segment_init (vcl_cfg->segment_baseva,
2027                              20 /* timeout in secs */ );
2028       clib_spinlock_init (&vcm->sessions_lockp);
2029       vppcom_api_hookup ();
2030     }
2031
2032   if (vcm->my_client_index == ~0)
2033     {
2034       vcm->app_state = STATE_APP_START;
2035       rv = vppcom_connect_to_vpp (app_name);
2036       if (rv)
2037         {
2038           clib_warning ("[%d] ERROR: couldn't connect to VPP!", getpid ());
2039           return rv;
2040         }
2041
2042       if (VPPCOM_DEBUG > 0)
2043         clib_warning ("[%d] sending session enable", getpid ());
2044
2045       rv = vppcom_app_session_enable ();
2046       if (rv)
2047         {
2048           clib_warning ("[%d] ERROR: vppcom_app_session_enable() failed!",
2049                         getpid ());
2050           return rv;
2051         }
2052
2053       if (VPPCOM_DEBUG > 0)
2054         clib_warning ("[%d] sending app attach", getpid ());
2055
2056       rv = vppcom_app_attach ();
2057       if (rv)
2058         {
2059           clib_warning ("[%d] ERROR: vppcom_app_attach() failed!", getpid ());
2060           return rv;
2061         }
2062
2063       if (VPPCOM_DEBUG > 0)
2064         clib_warning ("[%d] app_name '%s', my_client_index %d (0x%x)",
2065                       getpid (), app_name, vcm->my_client_index,
2066                       vcm->my_client_index);
2067     }
2068
2069   return VPPCOM_OK;
2070 }
2071
2072 void
2073 vppcom_app_destroy (void)
2074 {
2075   int rv;
2076
2077   if (vcm->my_client_index == ~0)
2078     return;
2079
2080   if (VPPCOM_DEBUG > 0)
2081     clib_warning ("[%d] detaching from VPP, my_client_index %d (0x%x)",
2082                   getpid (), vcm->my_client_index, vcm->my_client_index);
2083
2084   vppcom_app_detach ();
2085   rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
2086   if (PREDICT_FALSE (rv))
2087     {
2088       if (VPPCOM_DEBUG > 0)
2089         clib_warning ("[%d] application detach timed out! returning %d (%s)",
2090                       getpid (), rv, vppcom_retval_str (rv));
2091     }
2092   vl_client_disconnect_from_vlib ();
2093   vcm->my_client_index = ~0;
2094   vcm->app_state = STATE_APP_START;
2095 }
2096
2097 int
2098 vppcom_session_create (u32 vrf, u8 proto, u8 is_nonblocking)
2099 {
2100   session_t *session;
2101   u32 session_index;
2102
2103   clib_spinlock_lock (&vcm->sessions_lockp);
2104   pool_get (vcm->sessions, session);
2105   memset (session, 0, sizeof (*session));
2106   session_index = session - vcm->sessions;
2107
2108   session->vrf = vrf;
2109   session->proto = proto;
2110   session->state = STATE_START;
2111   session->is_nonblocking = is_nonblocking ? 1 : 0;
2112   session->vpp_handle = ~0;
2113   clib_spinlock_unlock (&vcm->sessions_lockp);
2114
2115   if (VPPCOM_DEBUG > 0)
2116     clib_warning ("[%d] sid %u", getpid (), session_index);
2117
2118   return (int) session_index;
2119 }
2120
2121 int
2122 vppcom_session_close (uint32_t session_index)
2123 {
2124   session_t *session = 0;
2125   int rv;
2126   u8 is_listen;
2127   u8 is_vep;
2128   u8 is_vep_session;
2129   u32 next_sid;
2130   u32 vep_idx;
2131   u64 vpp_handle;
2132   uword *p;
2133   session_state_t state;
2134
2135   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2136   is_listen = session->is_listen;
2137   is_vep = session->is_vep;
2138   is_vep_session = session->is_vep_session;
2139   next_sid = session->vep.next_sid;
2140   vep_idx = session->vep.vep_idx;
2141   state = session->state;
2142   vpp_handle = session->vpp_handle;
2143   clib_spinlock_unlock (&vcm->sessions_lockp);
2144
2145   if (VPPCOM_DEBUG > 0)
2146     {
2147       if (is_vep)
2148         clib_warning ("[%d] vep_idx %u / sid %u: closing epoll session...",
2149                       getpid (), session_index, session_index);
2150       else
2151         clib_warning ("[%d] vpp handle 0x%llx, sid %d: closing session...",
2152                       getpid (), vpp_handle, session_index);
2153     }
2154
2155   if (is_vep)
2156     {
2157       while (next_sid != ~0)
2158         {
2159           rv = vppcom_epoll_ctl (session_index, EPOLL_CTL_DEL, next_sid, 0);
2160           if ((VPPCOM_DEBUG > 0) && PREDICT_FALSE (rv < 0))
2161             clib_warning ("[%d] vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL "
2162                           "vep_idx %u failed! rv %d (%s)", getpid (),
2163                           vpp_handle, next_sid, vep_idx,
2164                           rv, vppcom_retval_str (rv));
2165
2166           VCL_LOCK_AND_GET_SESSION (session_index, &session);
2167           next_sid = session->vep.next_sid;
2168           clib_spinlock_unlock (&vcm->sessions_lockp);
2169         }
2170     }
2171   else
2172     {
2173       if (is_vep_session)
2174         {
2175           rv = vppcom_epoll_ctl (vep_idx, EPOLL_CTL_DEL, session_index, 0);
2176           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2177             clib_warning ("[%d] vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL "
2178                           "vep_idx %u failed! rv %d (%s)",
2179                           getpid (), vpp_handle, session_index,
2180                           vep_idx, rv, vppcom_retval_str (rv));
2181         }
2182
2183       if (is_listen)
2184         {
2185           if (state == STATE_LISTEN)
2186             {
2187               rv = vppcom_session_unbind (session_index);
2188               if (PREDICT_FALSE (rv < 0))
2189                 {
2190                   if (VPPCOM_DEBUG > 0)
2191                     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2192                                   "listener unbind failed! rv %d (%s)",
2193                                   getpid (), vpp_handle, session_index,
2194                                   rv, vppcom_retval_str (rv));
2195                 }
2196             }
2197         }
2198
2199       else if (state & (CLIENT_STATE_OPEN | SERVER_STATE_OPEN))
2200         {
2201           rv = vppcom_session_disconnect (session_index);
2202           if (PREDICT_FALSE (rv < 0))
2203             clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2204                           "session disconnect failed! rv %d (%s)",
2205                           getpid (), vpp_handle, session_index,
2206                           rv, vppcom_retval_str (rv));
2207         }
2208     }
2209
2210   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2211   vpp_handle = session->vpp_handle;
2212   if (vpp_handle != ~0)
2213     {
2214       p = hash_get (vcm->session_index_by_vpp_handles, vpp_handle);
2215       if (p)
2216         hash_unset (vcm->session_index_by_vpp_handles, vpp_handle);
2217     }
2218   pool_put_index (vcm->sessions, session_index);
2219   clib_spinlock_unlock (&vcm->sessions_lockp);
2220
2221   if (VPPCOM_DEBUG > 0)
2222     {
2223       if (is_vep)
2224         clib_warning ("[%d] vep_idx %u / sid %u: epoll session removed.",
2225                       getpid (), session_index, session_index);
2226       else
2227         clib_warning ("[%d] vpp handle 0x%llx, sid %u: session removed.",
2228                       getpid (), vpp_handle, session_index);
2229     }
2230 done:
2231   return rv;
2232 }
2233
2234 int
2235 vppcom_session_bind (uint32_t session_index, vppcom_endpt_t * ep)
2236 {
2237   session_t *session = 0;
2238   int rv;
2239
2240   if (!ep || !ep->ip)
2241     return VPPCOM_EINVAL;
2242
2243   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2244
2245   if (session->is_vep)
2246     {
2247       clib_spinlock_unlock (&vcm->sessions_lockp);
2248       clib_warning ("[%d] ERROR: sid %u: cannot bind to an epoll session!",
2249                     getpid (), session_index);
2250       rv = VPPCOM_EBADFD;
2251       goto done;
2252     }
2253
2254   session->vrf = ep->vrf;
2255   session->lcl_addr.is_ip4 = ep->is_ip4;
2256   session->lcl_addr.ip46 = to_ip46 (!ep->is_ip4, ep->ip);
2257   session->lcl_port = ep->port;
2258
2259   if (VPPCOM_DEBUG > 0)
2260     clib_warning ("[%d] sid %u: binding to local %s address %U "
2261                   "port %u, proto %s", getpid (), session_index,
2262                   session->lcl_addr.is_ip4 ? "IPv4" : "IPv6",
2263                   format_ip46_address, &session->lcl_addr.ip46,
2264                   session->lcl_addr.is_ip4,
2265                   clib_net_to_host_u16 (session->lcl_port),
2266                   session->proto ? "UDP" : "TCP");
2267
2268   clib_spinlock_unlock (&vcm->sessions_lockp);
2269 done:
2270   return rv;
2271 }
2272
2273 int
2274 vppcom_session_listen (uint32_t listen_session_index, uint32_t q_len)
2275 {
2276   session_t *listen_session = 0;
2277   u64 listen_vpp_handle;
2278   int rv, retval;
2279
2280   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2281
2282   if (listen_session->is_vep)
2283     {
2284       clib_spinlock_unlock (&vcm->sessions_lockp);
2285       clib_warning ("[%d] ERROR: sid %u: cannot listen on an "
2286                     "epoll session!", getpid (), listen_session_index);
2287       rv = VPPCOM_EBADFD;
2288       goto done;
2289     }
2290
2291   listen_vpp_handle = listen_session->vpp_handle;
2292   if (listen_session->is_listen)
2293     {
2294       clib_spinlock_unlock (&vcm->sessions_lockp);
2295       if (VPPCOM_DEBUG > 0)
2296         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2297                       "already in listen state!",
2298                       getpid (), listen_vpp_handle, listen_session_index);
2299       rv = VPPCOM_OK;
2300       goto done;
2301     }
2302
2303   if (VPPCOM_DEBUG > 0)
2304     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending bind request...",
2305                   getpid (), listen_vpp_handle, listen_session_index);
2306
2307   vppcom_send_bind_sock (listen_session, listen_session_index);
2308   clib_spinlock_unlock (&vcm->sessions_lockp);
2309   retval =
2310     vppcom_wait_for_session_state_change (listen_session_index, STATE_LISTEN,
2311                                           vcm->cfg.session_timeout);
2312
2313   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2314   if (PREDICT_FALSE (retval))
2315     {
2316       if (VPPCOM_DEBUG > 0)
2317         clib_warning ("[%d] vpp handle 0x%llx, sid %u: bind failed! "
2318                       "returning %d (%s)", getpid (),
2319                       listen_session->vpp_handle, listen_session_index,
2320                       retval, vppcom_retval_str (retval));
2321       clib_spinlock_unlock (&vcm->sessions_lockp);
2322       rv = retval;
2323       goto done;
2324     }
2325
2326   clib_fifo_validate (vcm->client_session_index_fifo, q_len);
2327   clib_spinlock_unlock (&vcm->sessions_lockp);
2328 done:
2329   return rv;
2330 }
2331
2332 int
2333 vppcom_session_accept (uint32_t listen_session_index, vppcom_endpt_t * ep,
2334                        uint32_t flags, double wait_for_time)
2335 {
2336   session_t *listen_session = 0;
2337   session_t *client_session = 0;
2338   u32 client_session_index = ~0;
2339   int rv;
2340   f64 wait_for;
2341   char *cut_thru_str;
2342   u64 listen_vpp_handle;
2343
2344   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2345
2346   if (listen_session->is_vep)
2347     {
2348       clib_spinlock_unlock (&vcm->sessions_lockp);
2349       clib_warning ("[%d] ERROR: sid %u: cannot accept on an "
2350                     "epoll session!", getpid (), listen_session_index);
2351       rv = VPPCOM_EBADFD;
2352       goto done;
2353     }
2354
2355   listen_vpp_handle = listen_session->vpp_handle;
2356   if (listen_session->state != STATE_LISTEN)
2357     {
2358       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2359                     "not in listen state! state 0x%x (%s)", getpid (),
2360                     listen_vpp_handle, listen_session_index,
2361                     listen_session->state,
2362                     vppcom_session_state_str (listen_session->state));
2363       clib_spinlock_unlock (&vcm->sessions_lockp);
2364       rv = VPPCOM_EBADFD;
2365       goto done;
2366     }
2367   wait_for = ((listen_session->is_nonblocking) ? 0 :
2368               (wait_for_time < 0) ? vcm->cfg.accept_timeout : wait_for_time);
2369
2370   clib_spinlock_unlock (&vcm->sessions_lockp);
2371
2372   while (1)
2373     {
2374       rv = vppcom_wait_for_client_session_index (wait_for);
2375       if (rv)
2376         {
2377           if ((VPPCOM_DEBUG > 0))
2378             clib_warning ("[%d] vpp handle 0x%llx, sid %u: accept failed! "
2379                           "returning %d (%s)", getpid (),
2380                           listen_vpp_handle, listen_session_index,
2381                           rv, vppcom_retval_str (rv));
2382           if ((wait_for == 0) || (wait_for_time > 0))
2383             goto done;
2384         }
2385       else
2386         break;
2387     }
2388
2389   clib_spinlock_lock (&vcm->sessions_lockp);
2390   clib_fifo_sub1 (vcm->client_session_index_fifo, client_session_index);
2391   rv = vppcom_session_at_index (client_session_index, &client_session);
2392   if (PREDICT_FALSE (rv))
2393     {
2394       rv = VPPCOM_ECONNABORTED;
2395       clib_warning ("[%d] vpp handle 0x%llx, sid %u: client sid %u "
2396                     "lookup failed! returning %d (%s)", getpid (),
2397                     listen_vpp_handle, listen_session_index,
2398                     client_session_index, rv, vppcom_retval_str (rv));
2399       goto done;
2400     }
2401
2402   client_session->is_nonblocking = (flags & O_NONBLOCK) ? 1 : 0;
2403   if (VPPCOM_DEBUG > 0)
2404     clib_warning ("[%d] vpp handle 0x%llx, sid %u: Got a client request! "
2405                   "vpp handle 0x%llx, sid %u, flags %d, is_nonblocking %u",
2406                   getpid (), listen_vpp_handle, listen_session_index,
2407                   client_session->vpp_handle, client_session_index,
2408                   flags, client_session->is_nonblocking);
2409
2410   ep->vrf = client_session->vrf;
2411   ep->is_cut_thru = client_session->is_cut_thru;
2412   ep->is_ip4 = client_session->peer_addr.is_ip4;
2413   ep->port = client_session->peer_port;
2414   if (client_session->peer_addr.is_ip4)
2415     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip4,
2416                  sizeof (ip4_address_t));
2417   else
2418     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip6,
2419                  sizeof (ip6_address_t));
2420
2421   if (client_session->is_server && client_session->is_cut_thru)
2422     {
2423       static svm_fifo_segment_create_args_t _a;
2424       svm_fifo_segment_create_args_t *a = &_a;
2425       svm_fifo_segment_private_t *seg;
2426
2427       cut_thru_str = " cut-thru ";
2428
2429       /* Create the segment */
2430       memset (a, 0, sizeof (*a));
2431       a->segment_name = (char *)
2432         format ((u8 *) a->segment_name, "%d:segment%d%c",
2433                 getpid (), vcm->unique_segment_index++, 0);
2434       a->segment_size = vcm->cfg.segment_size;
2435       a->preallocated_fifo_pairs = vcm->cfg.preallocated_fifo_pairs;
2436       a->rx_fifo_size = vcm->cfg.rx_fifo_size;
2437       a->tx_fifo_size = vcm->cfg.tx_fifo_size;
2438
2439       rv = svm_fifo_segment_create (a);
2440       if (PREDICT_FALSE (rv))
2441         {
2442           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2443                         "client sid %u svm_fifo_segment_create ('%s') "
2444                         "failed! rv %d", getpid (), listen_vpp_handle,
2445                         listen_session_index, client_session_index,
2446                         a->segment_name, rv);
2447           vec_reset_length (a->new_segment_indices);
2448           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2449           vppcom_send_connect_session_reply (client_session,
2450                                              client_session_index,
2451                                              client_session->vpp_handle,
2452                                              client_session->client_context,
2453                                              rv);
2454           clib_spinlock_unlock (&vcm->sessions_lockp);
2455           rv = VPPCOM_ENOMEM;
2456           goto done;
2457         }
2458
2459       client_session->segment_name = vec_dup ((u8 *) a->segment_name);
2460       client_session->sm_seg_index = a->new_segment_indices[0];
2461       vec_free (a->new_segment_indices);
2462
2463       seg = svm_fifo_segment_get_segment (client_session->sm_seg_index);
2464       client_session->server_rx_fifo =
2465         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.rx_fifo_size,
2466                                      FIFO_SEGMENT_RX_FREELIST);
2467       if (PREDICT_FALSE (!client_session->server_rx_fifo))
2468         {
2469           svm_fifo_segment_delete (seg);
2470           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2471                         "client sid %u rx fifo alloc failed! "
2472                         "size %ld (0x%lx)", getpid (), listen_vpp_handle,
2473                         listen_session_index, client_session_index,
2474                         vcm->cfg.rx_fifo_size, vcm->cfg.rx_fifo_size);
2475           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2476           vppcom_send_connect_session_reply (client_session,
2477                                              client_session_index,
2478                                              client_session->vpp_handle,
2479                                              client_session->client_context,
2480                                              rv);
2481           clib_spinlock_unlock (&vcm->sessions_lockp);
2482           rv = VPPCOM_ENOMEM;
2483           goto done;
2484         }
2485       client_session->server_rx_fifo->master_session_index =
2486         client_session_index;
2487
2488       client_session->server_tx_fifo =
2489         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.tx_fifo_size,
2490                                      FIFO_SEGMENT_TX_FREELIST);
2491       if (PREDICT_FALSE (!client_session->server_tx_fifo))
2492         {
2493           svm_fifo_segment_delete (seg);
2494           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2495                         "client sid %u tx fifo alloc failed! "
2496                         "size %ld (0x%lx)", getpid (), listen_vpp_handle,
2497                         listen_session_index, client_session_index,
2498                         vcm->cfg.tx_fifo_size, vcm->cfg.tx_fifo_size);
2499           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2500           vppcom_send_connect_session_reply (client_session,
2501                                              client_session_index,
2502                                              client_session->vpp_handle,
2503                                              client_session->client_context,
2504                                              rv);
2505           clib_spinlock_unlock (&vcm->sessions_lockp);
2506           rv = VPPCOM_ENOMEM;
2507           goto done;
2508         }
2509       client_session->server_tx_fifo->master_session_index =
2510         client_session_index;
2511
2512       if (VPPCOM_DEBUG > 1)
2513         clib_warning ("[%d] vpp handle 0x%llx, sid %u: client sid %u "
2514                       "created segment '%s', rx_fifo %p, tx_fifo %p",
2515                       getpid (), listen_vpp_handle, listen_session_index,
2516                       client_session_index, client_session->segment_name,
2517                       client_session->server_rx_fifo,
2518                       client_session->server_tx_fifo);
2519
2520 #ifdef CUT_THRU_EVENT_QUEUE     /* TBD */
2521       {
2522         void *oldheap;
2523         ssvm_shared_header_t *sh = seg->ssvm.sh;
2524
2525         ssvm_lock_non_recursive (sh, 1);
2526         oldheap = ssvm_push_heap (sh);
2527         event_q = client_session->vpp_event_queue =
2528           unix_shared_memory_queue_init (vcm->cfg.event_queue_size,
2529                                          sizeof (session_fifo_event_t),
2530                                          getpid (), 0 /* signal not sent */ );
2531         ssvm_pop_heap (oldheap);
2532         ssvm_unlock_non_recursive (sh);
2533       }
2534 #endif
2535       vppcom_send_connect_session_reply (client_session,
2536                                          client_session_index,
2537                                          client_session->vpp_handle,
2538                                          client_session->client_context,
2539                                          0 /* retval OK */ );
2540     }
2541   else
2542     {
2543       cut_thru_str = " ";
2544       vppcom_send_accept_session_reply (client_session->vpp_handle,
2545                                         client_session->client_context,
2546                                         0 /* retval OK */ );
2547     }
2548
2549   if (VPPCOM_DEBUG > 0)
2550     clib_warning ("[%d] vpp handle 0x%llx, sid %u: accepted vpp handle "
2551                   "0x%llx, sid %u%sconnection to local %s address "
2552                   "%U port %u", getpid (), listen_vpp_handle,
2553                   listen_session_index, client_session->vpp_handle,
2554                   client_session_index, cut_thru_str,
2555                   client_session->lcl_addr.is_ip4 ? "IPv4" : "IPv6",
2556                   format_ip46_address, &client_session->lcl_addr.ip46,
2557                   client_session->lcl_addr.is_ip4,
2558                   clib_net_to_host_u16 (client_session->lcl_port));
2559
2560   clib_spinlock_unlock (&vcm->sessions_lockp);
2561   rv = (int) client_session_index;
2562 done:
2563   return rv;
2564 }
2565
2566 int
2567 vppcom_session_connect (uint32_t session_index, vppcom_endpt_t * server_ep)
2568 {
2569   session_t *session = 0;
2570   int rv, retval = VPPCOM_OK;
2571   u64 vpp_handle = ~0;
2572
2573   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2574
2575   if (PREDICT_FALSE (session->is_vep))
2576     {
2577       clib_spinlock_unlock (&vcm->sessions_lockp);
2578       clib_warning ("[%d] ERROR: sid %u: cannot connect on an epoll session!",
2579                     getpid (), session_index);
2580       rv = VPPCOM_EBADFD;
2581       goto done;
2582     }
2583
2584   vpp_handle = session->vpp_handle;
2585   if (PREDICT_FALSE (session->is_server))
2586     {
2587       clib_spinlock_unlock (&vcm->sessions_lockp);
2588       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: is in use "
2589                     "as a server session!", getpid (), vpp_handle,
2590                     session_index);
2591       rv = VPPCOM_EBADFD;
2592       goto done;
2593     }
2594
2595   if (PREDICT_FALSE (session->state & CLIENT_STATE_OPEN))
2596     {
2597       if (VPPCOM_DEBUG > 0)
2598         clib_warning ("[%d] vpp handle 0x%llx, sid %u: session already "
2599                       "connected to %s %U port %d proto %s, state 0x%x (%s)",
2600                       getpid (), vpp_handle, session_index,
2601                       session->peer_addr.is_ip4 ? "IPv4" : "IPv6",
2602                       format_ip46_address,
2603                       &session->peer_addr.ip46, session->peer_addr.is_ip4,
2604                       clib_net_to_host_u16 (session->peer_port),
2605                       session->proto ? "UDP" : "TCP", session->state,
2606                       vppcom_session_state_str (session->state));
2607
2608       clib_spinlock_unlock (&vcm->sessions_lockp);
2609       goto done;
2610     }
2611
2612   session->vrf = server_ep->vrf;
2613   session->peer_addr.is_ip4 = server_ep->is_ip4;
2614   session->peer_addr.ip46 = to_ip46 (!server_ep->is_ip4, server_ep->ip);
2615   session->peer_port = server_ep->port;
2616
2617   if (VPPCOM_DEBUG > 0)
2618     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connecting to server "
2619                   "%s %U port %d proto %s",
2620                   getpid (), vpp_handle, session_index,
2621                   session->peer_addr.is_ip4 ? "IPv4" : "IPv6",
2622                   format_ip46_address,
2623                   &session->peer_addr.ip46, session->peer_addr.is_ip4,
2624                   clib_net_to_host_u16 (session->peer_port),
2625                   session->proto ? "UDP" : "TCP");
2626
2627   vppcom_send_connect_sock (session, session_index);
2628   clib_spinlock_unlock (&vcm->sessions_lockp);
2629
2630   retval =
2631     vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
2632                                           vcm->cfg.session_timeout);
2633
2634   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2635   vpp_handle = session->vpp_handle;
2636   clib_spinlock_unlock (&vcm->sessions_lockp);
2637
2638 done:
2639   if (PREDICT_FALSE (retval))
2640     {
2641       rv = retval;
2642       if (VPPCOM_DEBUG > 0)
2643         clib_warning ("[%d] vpp handle 0x%llx, sid %u: connect failed! "
2644                       "returning %d (%s)", getpid (), vpp_handle,
2645                       session_index, rv, vppcom_retval_str (rv));
2646     }
2647   else if (VPPCOM_DEBUG > 0)
2648     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connected!",
2649                   getpid (), vpp_handle, session_index);
2650
2651   return rv;
2652 }
2653
2654 static inline int
2655 vppcom_session_read_internal (uint32_t session_index, void *buf, int n,
2656                               u8 peek)
2657 {
2658   session_t *session = 0;
2659   svm_fifo_t *rx_fifo;
2660   int n_read = 0;
2661   int rv;
2662   char *fifo_str;
2663   u32 poll_et;
2664   session_state_t state;
2665   u8 is_server;
2666   u8 is_nonblocking;
2667   u64 vpp_handle;
2668
2669   ASSERT (buf);
2670
2671   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2672
2673   if (PREDICT_FALSE (session->is_vep))
2674     {
2675       clib_spinlock_unlock (&vcm->sessions_lockp);
2676       clib_warning ("[%d] ERROR: sid %u: cannot read from an epoll session!",
2677                     getpid (), session_index);
2678       rv = VPPCOM_EBADFD;
2679       goto done;
2680     }
2681
2682   vpp_handle = session->vpp_handle;
2683   is_server = session->is_server;
2684   is_nonblocking = session->is_nonblocking;
2685   state = session->state;
2686   if (PREDICT_FALSE (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN))))
2687     {
2688       clib_spinlock_unlock (&vcm->sessions_lockp);
2689       rv = ((state == STATE_DISCONNECT) ?
2690             VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
2691
2692       if (VPPCOM_DEBUG > 0)
2693         clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s session is "
2694                       "not open! state 0x%x (%s), returning %d (%s)",
2695                       getpid (), vpp_handle, session_index,
2696                       is_server ? "server" : "client", state,
2697                       vppcom_session_state_str (state),
2698                       rv, vppcom_retval_str (rv));
2699       goto done;
2700     }
2701
2702   rx_fifo = ((!session->is_cut_thru || is_server) ?
2703              session->server_rx_fifo : session->server_tx_fifo);
2704   fifo_str = ((!session->is_cut_thru || is_server) ?
2705               "server_rx_fifo" : "server_tx_fifo");
2706   clib_spinlock_unlock (&vcm->sessions_lockp);
2707
2708   do
2709     {
2710       if (peek)
2711         n_read = svm_fifo_peek (rx_fifo, 0, n, buf);
2712       else
2713         n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2714     }
2715   while (!is_nonblocking && (n_read <= 0));
2716
2717   if (n_read <= 0)
2718     {
2719       VCL_LOCK_AND_GET_SESSION (session_index, &session);
2720
2721       poll_et = (((EPOLLET | EPOLLIN) & session->vep.ev.events) ==
2722                  (EPOLLET | EPOLLIN));
2723       if (poll_et)
2724         session->vep.et_mask |= EPOLLIN;
2725
2726       if (state == STATE_CLOSE_ON_EMPTY)
2727         {
2728           session_state_t new_state = STATE_DISCONNECT;
2729           rv = VPPCOM_ECONNRESET;
2730
2731           if (VPPCOM_DEBUG > 1)
2732             {
2733               clib_warning ("[%d] vpp handle 0x%llx, sid %u: Empty fifo "
2734                             "with %s session state 0x%x (%s)!"
2735                             "  Setting state to 0x%x (%s), returning %d (%s)",
2736                             getpid (), vpp_handle, session_index,
2737                             is_server ? "server" : "client",
2738                             state, vppcom_session_state_str (state),
2739                             new_state, vppcom_session_state_str (new_state),
2740                             rv, vppcom_retval_str (rv));
2741             }
2742
2743           session->state = new_state;
2744         }
2745       else
2746         rv = VPPCOM_EAGAIN;
2747
2748       clib_spinlock_unlock (&vcm->sessions_lockp);
2749     }
2750   else
2751     rv = n_read;
2752
2753   if (VPPCOM_DEBUG > 2)
2754     {
2755       if (rv > 0)
2756         clib_warning ("[%d] vpp handle 0x%llx, sid %u: read %d bytes "
2757                       "from %s (%p)", getpid (), vpp_handle,
2758                       session_index, n_read, fifo_str, rx_fifo);
2759       else
2760         clib_warning ("[%d] vpp handle 0x%llx, sid %u: nothing read! "
2761                       "returning %d (%s)", getpid (), vpp_handle,
2762                       session_index, rv, vppcom_retval_str (rv));
2763     }
2764 done:
2765   return rv;
2766 }
2767
2768 int
2769 vppcom_session_read (uint32_t session_index, void *buf, int n)
2770 {
2771   return (vppcom_session_read_internal (session_index, buf, n, 0));
2772 }
2773
2774 static int
2775 vppcom_session_peek (uint32_t session_index, void *buf, int n)
2776 {
2777   return (vppcom_session_read_internal (session_index, buf, n, 1));
2778 }
2779
2780 static inline int
2781 vppcom_session_read_ready (session_t * session, u32 session_index)
2782 {
2783   svm_fifo_t *rx_fifo = 0;
2784   int ready = 0;
2785   u32 poll_et;
2786   int rv;
2787   u8 is_server = session->is_server;
2788   session_state_t state = session->state;
2789   u64 vpp_handle = session->vpp_handle;
2790
2791   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2792   if (PREDICT_FALSE (session->is_vep))
2793     {
2794       clib_warning ("[%d] ERROR: sid %u: cannot read from an "
2795                     "epoll session!", getpid (), session_index);
2796       rv = VPPCOM_EBADFD;
2797       goto done;
2798     }
2799
2800   if (session->is_listen)
2801     ready = clib_fifo_elts (vcm->client_session_index_fifo);
2802   else
2803     {
2804       if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN | STATE_LISTEN)))
2805         {
2806           rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
2807                 VPPCOM_ENOTCONN);
2808
2809           if (VPPCOM_DEBUG > 1)
2810             clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s session is "
2811                           "not open! state 0x%x (%s), returning %d (%s)",
2812                           getpid (), vpp_handle, session_index,
2813                           is_server ? "server" : "client",
2814                           state, vppcom_session_state_str (state),
2815                           rv, vppcom_retval_str (rv));
2816           goto done;
2817         }
2818
2819       rx_fifo = ((!session->is_cut_thru || is_server) ?
2820                  session->server_rx_fifo : session->server_tx_fifo);
2821
2822       ready = svm_fifo_max_dequeue (rx_fifo);
2823     }
2824
2825   if (ready == 0)
2826     {
2827       poll_et =
2828         ((EPOLLET | EPOLLIN) & session->vep.ev.events) == (EPOLLET | EPOLLIN);
2829       if (poll_et)
2830         session->vep.et_mask |= EPOLLIN;
2831
2832       if (state == STATE_CLOSE_ON_EMPTY)
2833         {
2834           rv = VPPCOM_ECONNRESET;
2835           session_state_t new_state = STATE_DISCONNECT;
2836
2837           if (VPPCOM_DEBUG > 1)
2838             {
2839               clib_warning ("[%d] vpp handle 0x%llx, sid %u: Empty fifo with"
2840                             " %s session state 0x%x (%s)! Setting state to "
2841                             "0x%x (%s), returning %d (%s)",
2842                             getpid (), session_index, vpp_handle,
2843                             is_server ? "server" : "client",
2844                             state, vppcom_session_state_str (state),
2845                             new_state, vppcom_session_state_str (new_state),
2846                             rv, vppcom_retval_str (rv));
2847             }
2848           session->state = new_state;
2849           goto done;
2850         }
2851     }
2852   rv = ready;
2853
2854   if (vcm->app_event_queue->cursize &&
2855       !pthread_mutex_trylock (&vcm->app_event_queue->mutex))
2856     {
2857       u32 i, n_to_dequeue = vcm->app_event_queue->cursize;
2858       session_fifo_event_t e;
2859
2860       for (i = 0; i < n_to_dequeue; i++)
2861         unix_shared_memory_queue_sub_raw (vcm->app_event_queue, (u8 *) & e);
2862
2863       pthread_mutex_unlock (&vcm->app_event_queue->mutex);
2864     }
2865
2866 done:
2867   return rv;
2868 }
2869
2870 int
2871 vppcom_session_write (uint32_t session_index, void *buf, int n)
2872 {
2873   session_t *session = 0;
2874   svm_fifo_t *tx_fifo;
2875   unix_shared_memory_queue_t *q;
2876   session_fifo_event_t evt;
2877   int rv, n_write;
2878   char *fifo_str;
2879   u32 poll_et;
2880   u8 is_server;
2881   u8 is_nonblocking;
2882   session_state_t state;
2883   u64 vpp_handle;
2884
2885   ASSERT (buf);
2886
2887   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2888
2889   if (PREDICT_FALSE (session->is_vep))
2890     {
2891       clib_spinlock_unlock (&vcm->sessions_lockp);
2892       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2893                     "cannot write to an epoll session!",
2894                     getpid (), session->vpp_handle, session_index);
2895
2896       rv = VPPCOM_EBADFD;
2897       goto done;
2898     }
2899
2900   is_server = session->is_server;
2901   is_nonblocking = session->is_nonblocking;
2902   vpp_handle = session->vpp_handle;
2903   state = session->state;
2904   if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN)))
2905     {
2906       rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
2907             VPPCOM_ENOTCONN);
2908
2909       clib_spinlock_unlock (&vcm->sessions_lockp);
2910       if (VPPCOM_DEBUG > 1)
2911         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2912                       "%s session is not open! state 0x%x (%s)",
2913                       getpid (), vpp_handle, session_index,
2914                       is_server ? "server" : "client", state,
2915                       vppcom_session_state_str (state));
2916       goto done;
2917     }
2918
2919   tx_fifo = ((!session->is_cut_thru || is_server) ?
2920              session->server_tx_fifo : session->server_rx_fifo);
2921   fifo_str = ((!session->is_cut_thru || is_server) ?
2922               "server_tx_fifo" : "server_rx_fifo");
2923   clib_spinlock_unlock (&vcm->sessions_lockp);
2924
2925   do
2926     {
2927       n_write = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
2928     }
2929   while (!is_nonblocking && (n_write <= 0));
2930
2931   /* If event wasn't set, add one */
2932   if (!session->is_cut_thru && (n_write > 0) && svm_fifo_set_event (tx_fifo))
2933     {
2934       /* Fabricate TX event, send to vpp */
2935       evt.fifo = tx_fifo;
2936       evt.event_type = FIFO_EVENT_APP_TX;
2937
2938       VCL_LOCK_AND_GET_SESSION (session_index, &session);
2939       q = session->vpp_event_queue;
2940       ASSERT (q);
2941       unix_shared_memory_queue_add (q, (u8 *) & evt,
2942                                     0 /* do wait for mutex */ );
2943       clib_spinlock_unlock (&vcm->sessions_lockp);
2944       if (VPPCOM_DEBUG > 1)
2945         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2946                       "added FIFO_EVENT_APP_TX to "
2947                       "vpp_event_q %p, n_write %d", getpid (),
2948                       vpp_handle, session_index, q, n_write);
2949     }
2950
2951   if (n_write <= 0)
2952     {
2953       VCL_LOCK_AND_GET_SESSION (session_index, &session);
2954
2955       poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
2956                  (EPOLLET | EPOLLOUT));
2957       if (poll_et)
2958         session->vep.et_mask |= EPOLLOUT;
2959
2960       if (state == STATE_CLOSE_ON_EMPTY)
2961         {
2962           session_state_t new_state = STATE_DISCONNECT;
2963           rv = VPPCOM_ECONNRESET;
2964
2965           if (VPPCOM_DEBUG > 1)
2966             {
2967               clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2968                             "Empty fifo with %s session state 0x%x (%s)!"
2969                             "  Setting state to 0x%x (%s), returning %d (%s)",
2970                             getpid (), vpp_handle, session_index,
2971                             is_server ? "server" : "client",
2972                             state, vppcom_session_state_str (state),
2973                             new_state, vppcom_session_state_str (new_state),
2974                             rv, vppcom_retval_str (rv));
2975             }
2976
2977           session->state = new_state;
2978         }
2979       else
2980         rv = VPPCOM_EAGAIN;
2981
2982       clib_spinlock_unlock (&vcm->sessions_lockp);
2983     }
2984   else
2985     rv = n_write;
2986
2987   if (VPPCOM_DEBUG > 2)
2988     {
2989       if (n_write <= 0)
2990         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2991                       "FIFO-FULL %s (%p)", getpid (), vpp_handle,
2992                       session_index, fifo_str, tx_fifo);
2993       else
2994         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2995                       "wrote %d bytes to %s (%p)", getpid (), vpp_handle,
2996                       session_index, n_write, fifo_str, tx_fifo);
2997     }
2998 done:
2999   return rv;
3000 }
3001
3002 static inline int
3003 vppcom_session_write_ready (session_t * session, u32 session_index)
3004 {
3005   svm_fifo_t *tx_fifo;
3006   char *fifo_str;
3007   int ready;
3008   u32 poll_et;
3009   int rv;
3010   u8 is_server = session->is_server;
3011   session_state_t state = session->state;
3012
3013   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
3014   if (PREDICT_FALSE (session->is_vep))
3015     {
3016       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3017                     "cannot write to an epoll session!",
3018                     getpid (), session->vpp_handle, session_index);
3019       rv = VPPCOM_EBADFD;
3020       goto done;
3021     }
3022
3023   if (PREDICT_FALSE (session->is_listen))
3024     {
3025       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3026                     "cannot write to a listen session!",
3027                     getpid (), session->vpp_handle, session_index);
3028       rv = VPPCOM_EBADFD;
3029       goto done;
3030     }
3031
3032   if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN)))
3033     {
3034       session_state_t state = session->state;
3035
3036       rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
3037             VPPCOM_ENOTCONN);
3038
3039       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3040                     "%s session is not open! state 0x%x (%s), "
3041                     "returning %d (%s)", getpid (), session->vpp_handle,
3042                     session_index, is_server ? "server" : "client",
3043                     state, vppcom_session_state_str (state),
3044                     rv, vppcom_retval_str (rv));
3045       goto done;
3046     }
3047
3048   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
3049              session->server_tx_fifo : session->server_rx_fifo);
3050   fifo_str = ((!session->is_cut_thru || session->is_server) ?
3051               "server_tx_fifo" : "server_rx_fifo");
3052
3053   ready = svm_fifo_max_enqueue (tx_fifo);
3054
3055   if (VPPCOM_DEBUG > 3)
3056     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3057                   "peek %s (%p), ready = %d", getpid (),
3058                   session->vpp_handle, session_index,
3059                   fifo_str, tx_fifo, ready);
3060
3061   if (ready == 0)
3062     {
3063       poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
3064                  (EPOLLET | EPOLLOUT));
3065       if (poll_et)
3066         session->vep.et_mask |= EPOLLOUT;
3067
3068       if (state == STATE_CLOSE_ON_EMPTY)
3069         {
3070           rv = VPPCOM_ECONNRESET;
3071           session_state_t new_state = STATE_DISCONNECT;
3072
3073           if (VPPCOM_DEBUG > 1)
3074             {
3075               clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3076                             "Empty fifo with %s session "
3077                             "state 0x%x (%s)! Setting state to 0x%x (%s), "
3078                             "returning %d (%s)", getpid (),
3079                             session->vpp_handle, session_index,
3080                             is_server ? "server" : "client",
3081                             state, vppcom_session_state_str (state),
3082                             new_state, vppcom_session_state_str (new_state),
3083                             rv, vppcom_retval_str (rv));
3084             }
3085           session->state = new_state;
3086           goto done;
3087         }
3088     }
3089   rv = ready;
3090 done:
3091   return rv;
3092 }
3093
3094 int
3095 vppcom_select (unsigned long n_bits, unsigned long *read_map,
3096                unsigned long *write_map, unsigned long *except_map,
3097                double time_to_wait)
3098 {
3099   u32 session_index;
3100   session_t *session = 0;
3101   int rv, bits_set = 0;
3102   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
3103   u32 minbits = clib_max (n_bits, BITS (uword));
3104
3105   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
3106
3107   if (n_bits && read_map)
3108     {
3109       clib_bitmap_validate (vcm->rd_bitmap, minbits);
3110       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
3111       memset (read_map, 0, vec_len (vcm->rd_bitmap));
3112     }
3113   if (n_bits && write_map)
3114     {
3115       clib_bitmap_validate (vcm->wr_bitmap, minbits);
3116       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
3117       memset (write_map, 0, vec_len (vcm->wr_bitmap));
3118     }
3119   if (n_bits && except_map)
3120     {
3121       clib_bitmap_validate (vcm->ex_bitmap, minbits);
3122       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
3123       memset (except_map, 0, vec_len (vcm->ex_bitmap));
3124     }
3125
3126   do
3127     {
3128       /* *INDENT-OFF* */
3129       if (n_bits)
3130         {
3131           if (read_map)
3132             {
3133               clib_bitmap_foreach (session_index, vcm->rd_bitmap,
3134                 ({
3135                   clib_spinlock_lock (&vcm->sessions_lockp);
3136                   rv = vppcom_session_at_index (session_index, &session);
3137                   if (rv < 0)
3138                     {
3139                       clib_spinlock_unlock (&vcm->sessions_lockp);
3140                       if (VPPCOM_DEBUG > 1)
3141                         clib_warning ("[%d] session %d specified in "
3142                                       "read_map is closed.", getpid (),
3143                                       session_index);
3144                       bits_set = VPPCOM_EBADFD;
3145                       goto select_done;
3146                     }
3147
3148                   rv = vppcom_session_read_ready (session, session_index);
3149                   clib_spinlock_unlock (&vcm->sessions_lockp);
3150                   if (except_map && vcm->ex_bitmap &&
3151                       clib_bitmap_get (vcm->ex_bitmap, session_index) &&
3152                       (rv < 0))
3153                     {
3154                       // TBD: clib_warning
3155                       clib_bitmap_set_no_check (except_map, session_index, 1);
3156                       bits_set++;
3157                     }
3158                   else if (rv > 0)
3159                     {
3160                       // TBD: clib_warning
3161                       clib_bitmap_set_no_check (read_map, session_index, 1);
3162                       bits_set++;
3163                     }
3164                 }));
3165             }
3166
3167           if (write_map)
3168             {
3169               clib_bitmap_foreach (session_index, vcm->wr_bitmap,
3170                 ({
3171                   clib_spinlock_lock (&vcm->sessions_lockp);
3172                   rv = vppcom_session_at_index (session_index, &session);
3173                   if (rv < 0)
3174                     {
3175                       clib_spinlock_unlock (&vcm->sessions_lockp);
3176                       if (VPPCOM_DEBUG > 0)
3177                         clib_warning ("[%d] session %d specified in "
3178                                       "write_map is closed.", getpid (),
3179                                       session_index);
3180                       bits_set = VPPCOM_EBADFD;
3181                       goto select_done;
3182                     }
3183
3184                   rv = vppcom_session_write_ready (session, session_index);
3185                   clib_spinlock_unlock (&vcm->sessions_lockp);
3186                   if (write_map && (rv > 0))
3187                     {
3188                       // TBD: clib_warning
3189                       clib_bitmap_set_no_check (write_map, session_index, 1);
3190                       bits_set++;
3191                     }
3192                 }));
3193             }
3194
3195           if (except_map)
3196             {
3197               clib_bitmap_foreach (session_index, vcm->ex_bitmap,
3198                 ({
3199                   clib_spinlock_lock (&vcm->sessions_lockp);
3200                   rv = vppcom_session_at_index (session_index, &session);
3201                   if (rv < 0)
3202                     {
3203                       clib_spinlock_unlock (&vcm->sessions_lockp);
3204                       if (VPPCOM_DEBUG > 1)
3205                         clib_warning ("[%d] session %d specified in "
3206                                       "except_map is closed.", getpid (),
3207                                       session_index);
3208                       bits_set = VPPCOM_EBADFD;
3209                       goto select_done;
3210                     }
3211
3212                   rv = vppcom_session_read_ready (session, session_index);
3213                   clib_spinlock_unlock (&vcm->sessions_lockp);
3214                   if (rv < 0)
3215                     {
3216                       // TBD: clib_warning
3217                       clib_bitmap_set_no_check (except_map, session_index, 1);
3218                       bits_set++;
3219                     }
3220                 }));
3221             }
3222         }
3223       /* *INDENT-ON* */
3224     }
3225   while (clib_time_now (&vcm->clib_time) < timeout);
3226
3227 select_done:
3228   return (bits_set);
3229 }
3230
3231 static inline void
3232 vep_verify_epoll_chain (u32 vep_idx)
3233 {
3234   session_t *session;
3235   vppcom_epoll_t *vep;
3236   int rv;
3237   u32 sid = vep_idx;
3238
3239   if (VPPCOM_DEBUG <= 1)
3240     return;
3241
3242   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
3243   rv = vppcom_session_at_index (vep_idx, &session);
3244   if (PREDICT_FALSE (rv))
3245     {
3246       clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", getpid (), vep_idx);
3247       goto done;
3248     }
3249   if (PREDICT_FALSE (!session->is_vep))
3250     {
3251       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!", getpid (),
3252                     vep_idx);
3253       goto done;
3254     }
3255   vep = &session->vep;
3256   clib_warning ("[%d] vep_idx (%u): Dumping epoll chain\n"
3257                 "{\n"
3258                 "   is_vep         = %u\n"
3259                 "   is_vep_session = %u\n"
3260                 "   next_sid       = 0x%x (%u)\n"
3261                 "   wait_cont_idx  = 0x%x (%u)\n"
3262                 "}\n", getpid (), vep_idx,
3263                 session->is_vep, session->is_vep_session,
3264                 vep->next_sid, vep->next_sid,
3265                 session->wait_cont_idx, session->wait_cont_idx);
3266
3267   for (sid = vep->next_sid; sid != ~0; sid = vep->next_sid)
3268     {
3269       rv = vppcom_session_at_index (sid, &session);
3270       if (PREDICT_FALSE (rv))
3271         {
3272           clib_warning ("[%d] ERROR: Invalid sid (%u)!", getpid (), sid);
3273           goto done;
3274         }
3275       if (PREDICT_FALSE (session->is_vep))
3276         clib_warning ("[%d] ERROR: sid (%u) is a vep!", getpid (), vep_idx);
3277       else if (PREDICT_FALSE (!session->is_vep_session))
3278         {
3279           clib_warning ("[%d] ERROR: session (%u) is not a vep session!",
3280                         getpid (), sid);
3281           goto done;
3282         }
3283       vep = &session->vep;
3284       if (PREDICT_FALSE (vep->vep_idx != vep_idx))
3285         clib_warning ("[%d] ERROR: session (%u) vep_idx (%u) != "
3286                       "vep_idx (%u)!", getpid (),
3287                       sid, session->vep.vep_idx, vep_idx);
3288       if (session->is_vep_session)
3289         {
3290           clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
3291                         "{\n"
3292                         "   next_sid       = 0x%x (%u)\n"
3293                         "   prev_sid       = 0x%x (%u)\n"
3294                         "   vep_idx        = 0x%x (%u)\n"
3295                         "   ev.events      = 0x%x\n"
3296                         "   ev.data.u64    = 0x%llx\n"
3297                         "   et_mask        = 0x%x\n"
3298                         "}\n",
3299                         vep_idx, sid, sid,
3300                         vep->next_sid, vep->next_sid,
3301                         vep->prev_sid, vep->prev_sid,
3302                         vep->vep_idx, vep->vep_idx,
3303                         vep->ev.events, vep->ev.data.u64, vep->et_mask);
3304         }
3305     }
3306
3307 done:
3308   clib_warning ("[%d] vep_idx (%u): Dump complete!\n", getpid (), vep_idx);
3309 }
3310
3311 int
3312 vppcom_epoll_create (void)
3313 {
3314   session_t *vep_session;
3315   u32 vep_idx;
3316
3317   clib_spinlock_lock (&vcm->sessions_lockp);
3318   pool_get (vcm->sessions, vep_session);
3319   memset (vep_session, 0, sizeof (*vep_session));
3320   vep_idx = vep_session - vcm->sessions;
3321
3322   vep_session->is_vep = 1;
3323   vep_session->vep.vep_idx = ~0;
3324   vep_session->vep.next_sid = ~0;
3325   vep_session->vep.prev_sid = ~0;
3326   vep_session->wait_cont_idx = ~0;
3327   vep_session->vpp_handle = ~0;
3328   clib_spinlock_unlock (&vcm->sessions_lockp);
3329
3330   if (VPPCOM_DEBUG > 0)
3331     clib_warning ("[%d] Created vep_idx %u / sid %u!",
3332                   getpid (), vep_idx, vep_idx);
3333
3334   return (vep_idx);
3335 }
3336
3337 int
3338 vppcom_epoll_ctl (uint32_t vep_idx, int op, uint32_t session_index,
3339                   struct epoll_event *event)
3340 {
3341   session_t *vep_session;
3342   session_t *session;
3343   int rv;
3344
3345   if (vep_idx == session_index)
3346     {
3347       clib_warning ("[%d] ERROR: vep_idx == session_index (%u)!",
3348                     getpid (), vep_idx);
3349       return VPPCOM_EINVAL;
3350     }
3351
3352   clib_spinlock_lock (&vcm->sessions_lockp);
3353   rv = vppcom_session_at_index (vep_idx, &vep_session);
3354   if (PREDICT_FALSE (rv))
3355     {
3356       clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", vep_idx);
3357       goto done;
3358     }
3359   if (PREDICT_FALSE (!vep_session->is_vep))
3360     {
3361       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3362                     getpid (), vep_idx);
3363       rv = VPPCOM_EINVAL;
3364       goto done;
3365     }
3366
3367   ASSERT (vep_session->vep.vep_idx == ~0);
3368   ASSERT (vep_session->vep.prev_sid == ~0);
3369
3370   rv = vppcom_session_at_index (session_index, &session);
3371   if (PREDICT_FALSE (rv))
3372     {
3373       if (VPPCOM_DEBUG > 0)
3374         clib_warning ("[%d] ERROR: Invalid session_index (%u)!",
3375                       getpid (), session_index);
3376       goto done;
3377     }
3378   if (PREDICT_FALSE (session->is_vep))
3379     {
3380       clib_warning ("ERROR: session_index (%u) is a vep!", vep_idx);
3381       rv = VPPCOM_EINVAL;
3382       goto done;
3383     }
3384
3385   switch (op)
3386     {
3387     case EPOLL_CTL_ADD:
3388       if (PREDICT_FALSE (!event))
3389         {
3390           clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: NULL pointer to "
3391                         "epoll_event structure!", getpid ());
3392           rv = VPPCOM_EINVAL;
3393           goto done;
3394         }
3395       if (vep_session->vep.next_sid != ~0)
3396         {
3397           session_t *next_session;
3398           rv = vppcom_session_at_index (vep_session->vep.next_sid,
3399                                         &next_session);
3400           if (PREDICT_FALSE (rv))
3401             {
3402               clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: Invalid "
3403                             "vep.next_sid (%u) on vep_idx (%u)!",
3404                             getpid (), vep_session->vep.next_sid, vep_idx);
3405               goto done;
3406             }
3407           ASSERT (next_session->vep.prev_sid == vep_idx);
3408           next_session->vep.prev_sid = session_index;
3409         }
3410       session->vep.next_sid = vep_session->vep.next_sid;
3411       session->vep.prev_sid = vep_idx;
3412       session->vep.vep_idx = vep_idx;
3413       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3414       session->vep.ev = *event;
3415       session->is_vep = 0;
3416       session->is_vep_session = 1;
3417       vep_session->vep.next_sid = session_index;
3418       if (VPPCOM_DEBUG > 1)
3419         clib_warning ("[%d] EPOLL_CTL_ADD: vep_idx %u, sid %u, events 0x%x,"
3420                       " data 0x%llx!", getpid (), vep_idx, session_index,
3421                       event->events, event->data.u64);
3422       break;
3423
3424     case EPOLL_CTL_MOD:
3425       if (PREDICT_FALSE (!event))
3426         {
3427           clib_warning ("[%d] ERROR: EPOLL_CTL_MOD: NULL pointer to "
3428                         "epoll_event structure!", getpid ());
3429           rv = VPPCOM_EINVAL;
3430           goto done;
3431         }
3432       else if (PREDICT_FALSE (!session->is_vep_session))
3433         {
3434           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_MOD: "
3435                         "not a vep session!", getpid (), session_index);
3436           rv = VPPCOM_EINVAL;
3437           goto done;
3438         }
3439       else if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
3440         {
3441           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_MOD: "
3442                         "vep_idx (%u) != vep_idx (%u)!",
3443                         getpid (), session_index,
3444                         session->vep.vep_idx, vep_idx);
3445           rv = VPPCOM_EINVAL;
3446           goto done;
3447         }
3448       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3449       session->vep.ev = *event;
3450       if (VPPCOM_DEBUG > 1)
3451         clib_warning ("[%d] EPOLL_CTL_MOD: vep_idx %u, sid %u, events 0x%x,"
3452                       " data 0x%llx!", getpid (), vep_idx, session_index,
3453                       event->events, event->data.u64);
3454       break;
3455
3456     case EPOLL_CTL_DEL:
3457       if (PREDICT_FALSE (!session->is_vep_session))
3458         {
3459           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_DEL: "
3460                         "not a vep session!", getpid (), session_index);
3461           rv = VPPCOM_EINVAL;
3462           goto done;
3463         }
3464       else if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
3465         {
3466           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_DEL: "
3467                         "vep_idx (%u) != vep_idx (%u)!",
3468                         getpid (), session_index,
3469                         session->vep.vep_idx, vep_idx);
3470           rv = VPPCOM_EINVAL;
3471           goto done;
3472         }
3473
3474       vep_session->wait_cont_idx =
3475         (vep_session->wait_cont_idx == session_index) ?
3476         session->vep.next_sid : vep_session->wait_cont_idx;
3477
3478       if (session->vep.prev_sid == vep_idx)
3479         vep_session->vep.next_sid = session->vep.next_sid;
3480       else
3481         {
3482           session_t *prev_session;
3483           rv = vppcom_session_at_index (session->vep.prev_sid, &prev_session);
3484           if (PREDICT_FALSE (rv))
3485             {
3486               clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3487                             "vep.prev_sid (%u) on sid (%u)!",
3488                             getpid (), session->vep.prev_sid, session_index);
3489               goto done;
3490             }
3491           ASSERT (prev_session->vep.next_sid == session_index);
3492           prev_session->vep.next_sid = session->vep.next_sid;
3493         }
3494       if (session->vep.next_sid != ~0)
3495         {
3496           session_t *next_session;
3497           rv = vppcom_session_at_index (session->vep.next_sid, &next_session);
3498           if (PREDICT_FALSE (rv))
3499             {
3500               clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3501                             "vep.next_sid (%u) on sid (%u)!",
3502                             getpid (), session->vep.next_sid, session_index);
3503               goto done;
3504             }
3505           ASSERT (next_session->vep.prev_sid == session_index);
3506           next_session->vep.prev_sid = session->vep.prev_sid;
3507         }
3508
3509       memset (&session->vep, 0, sizeof (session->vep));
3510       session->vep.next_sid = ~0;
3511       session->vep.prev_sid = ~0;
3512       session->vep.vep_idx = ~0;
3513       session->is_vep_session = 0;
3514       if (VPPCOM_DEBUG > 1)
3515         clib_warning ("[%d] EPOLL_CTL_DEL: vep_idx %u, sid %u!",
3516                       getpid (), vep_idx, session_index);
3517       break;
3518
3519     default:
3520       clib_warning ("[%d] ERROR: Invalid operation (%d)!", getpid (), op);
3521       rv = VPPCOM_EINVAL;
3522     }
3523
3524   vep_verify_epoll_chain (vep_idx);
3525
3526 done:
3527   clib_spinlock_unlock (&vcm->sessions_lockp);
3528   return rv;
3529 }
3530
3531 int
3532 vppcom_epoll_wait (uint32_t vep_idx, struct epoll_event *events,
3533                    int maxevents, double wait_for_time)
3534 {
3535   session_t *vep_session;
3536   int rv;
3537   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
3538   u32 keep_trying = 1;
3539   int num_ev = 0;
3540   u32 vep_next_sid, wait_cont_idx;
3541   u8 is_vep;
3542
3543   if (PREDICT_FALSE (maxevents <= 0))
3544     {
3545       clib_warning ("[%d] ERROR: Invalid maxevents (%d)!",
3546                     getpid (), maxevents);
3547       return VPPCOM_EINVAL;
3548     }
3549   memset (events, 0, sizeof (*events) * maxevents);
3550
3551   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3552   vep_next_sid = vep_session->vep.next_sid;
3553   is_vep = vep_session->is_vep;
3554   wait_cont_idx = vep_session->wait_cont_idx;
3555   clib_spinlock_unlock (&vcm->sessions_lockp);
3556
3557   if (PREDICT_FALSE (!is_vep))
3558     {
3559       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3560                     getpid (), vep_idx);
3561       rv = VPPCOM_EINVAL;
3562       goto done;
3563     }
3564   if (PREDICT_FALSE (vep_next_sid == ~0))
3565     {
3566       if (VPPCOM_DEBUG > 0)
3567         clib_warning ("[%d] WARNING: vep_idx (%u) is empty!",
3568                       getpid (), vep_idx);
3569       goto done;
3570     }
3571
3572   do
3573     {
3574       u32 sid;
3575       u32 next_sid = ~0;
3576       session_t *session;
3577
3578       for (sid = (wait_cont_idx == ~0) ? vep_next_sid : wait_cont_idx;
3579            sid != ~0; sid = next_sid)
3580         {
3581           u32 session_events, et_mask, clear_et_mask, session_vep_idx;
3582           u8 add_event, is_vep_session;
3583           int ready;
3584           u64 session_ev_data;
3585
3586           VCL_LOCK_AND_GET_SESSION (sid, &session);
3587           next_sid = session->vep.next_sid;
3588           session_events = session->vep.ev.events;
3589           et_mask = session->vep.et_mask;
3590           is_vep = session->is_vep;
3591           is_vep_session = session->is_vep_session;
3592           session_vep_idx = session->vep.vep_idx;
3593           session_ev_data = session->vep.ev.data.u64;
3594           clib_spinlock_unlock (&vcm->sessions_lockp);
3595
3596           if (PREDICT_FALSE (is_vep))
3597             {
3598               if (VPPCOM_DEBUG > 0)
3599                 clib_warning ("[%d] ERROR: sid (%u) is a vep!",
3600                               getpid (), vep_idx);
3601               rv = VPPCOM_EINVAL;
3602               goto done;
3603             }
3604           if (PREDICT_FALSE (!is_vep_session))
3605             {
3606               if (VPPCOM_DEBUG > 0)
3607                 clib_warning ("[%d] ERROR: session (%u) is not "
3608                               "a vep session!", getpid (), sid);
3609               rv = VPPCOM_EINVAL;
3610               goto done;
3611             }
3612           if (PREDICT_FALSE (session_vep_idx != vep_idx))
3613             {
3614               clib_warning ("[%d] ERROR: session (%u) "
3615                             "vep_idx (%u) != vep_idx (%u)!",
3616                             getpid (), sid, session->vep.vep_idx, vep_idx);
3617               rv = VPPCOM_EINVAL;
3618               goto done;
3619             }
3620
3621           add_event = clear_et_mask = 0;
3622
3623           if (EPOLLIN & session_events)
3624             {
3625               VCL_LOCK_AND_GET_SESSION (sid, &session);
3626               ready = vppcom_session_read_ready (session, sid);
3627               clib_spinlock_unlock (&vcm->sessions_lockp);
3628               if ((ready > 0) && (EPOLLIN & et_mask))
3629                 {
3630                   add_event = 1;
3631                   events[num_ev].events |= EPOLLIN;
3632                   if (((EPOLLET | EPOLLIN) & session_events) ==
3633                       (EPOLLET | EPOLLIN))
3634                     clear_et_mask |= EPOLLIN;
3635                 }
3636               else if (ready < 0)
3637                 {
3638                   add_event = 1;
3639                   switch (ready)
3640                     {
3641                     case VPPCOM_ECONNRESET:
3642                       events[num_ev].events |= EPOLLHUP | EPOLLRDHUP;
3643                       break;
3644
3645                     default:
3646                       events[num_ev].events |= EPOLLERR;
3647                       break;
3648                     }
3649                 }
3650             }
3651
3652           if (EPOLLOUT & session_events)
3653             {
3654               VCL_LOCK_AND_GET_SESSION (sid, &session);
3655               ready = vppcom_session_write_ready (session, sid);
3656               clib_spinlock_unlock (&vcm->sessions_lockp);
3657               if ((ready > 0) && (EPOLLOUT & et_mask))
3658                 {
3659                   add_event = 1;
3660                   events[num_ev].events |= EPOLLOUT;
3661                   if (((EPOLLET | EPOLLOUT) & session_events) ==
3662                       (EPOLLET | EPOLLOUT))
3663                     clear_et_mask |= EPOLLOUT;
3664                 }
3665               else if (ready < 0)
3666                 {
3667                   add_event = 1;
3668                   switch (ready)
3669                     {
3670                     case VPPCOM_ECONNRESET:
3671                       events[num_ev].events |= EPOLLHUP;
3672                       break;
3673
3674                     default:
3675                       events[num_ev].events |= EPOLLERR;
3676                       break;
3677                     }
3678                 }
3679             }
3680
3681           if (add_event)
3682             {
3683               events[num_ev].data.u64 = session_ev_data;
3684               if (EPOLLONESHOT & session_events)
3685                 {
3686                   VCL_LOCK_AND_GET_SESSION (sid, &session);
3687                   session->vep.ev.events = 0;
3688                   clib_spinlock_unlock (&vcm->sessions_lockp);
3689                 }
3690               num_ev++;
3691               if (num_ev == maxevents)
3692                 {
3693                   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3694                   vep_session->wait_cont_idx = next_sid;
3695                   clib_spinlock_unlock (&vcm->sessions_lockp);
3696                   goto done;
3697                 }
3698             }
3699           if (wait_cont_idx != ~0)
3700             {
3701               if (next_sid == ~0)
3702                 next_sid = vep_next_sid;
3703               else if (next_sid == wait_cont_idx)
3704                 next_sid = ~0;
3705             }
3706         }
3707       if (wait_for_time != -1)
3708         keep_trying = (clib_time_now (&vcm->clib_time) <= timeout) ? 1 : 0;
3709     }
3710   while ((num_ev == 0) && keep_trying);
3711
3712   if (wait_cont_idx != ~0)
3713     {
3714       VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3715       vep_session->wait_cont_idx = ~0;
3716       clib_spinlock_unlock (&vcm->sessions_lockp);
3717     }
3718 done:
3719   return (rv != VPPCOM_OK) ? rv : num_ev;
3720 }
3721
3722 int
3723 vppcom_session_attr (uint32_t session_index, uint32_t op,
3724                      void *buffer, uint32_t * buflen)
3725 {
3726   session_t *session;
3727   int rv = VPPCOM_OK;
3728   u32 *flags = buffer;
3729   vppcom_endpt_t *ep = buffer;
3730
3731   VCL_LOCK_AND_GET_SESSION (session_index, &session);
3732   switch (op)
3733     {
3734     case VPPCOM_ATTR_GET_NREAD:
3735       rv = vppcom_session_read_ready (session, session_index);
3736       if (VPPCOM_DEBUG > 2)
3737         clib_warning ("[%d] VPPCOM_ATTR_GET_NREAD: sid %u, nread = %d",
3738                       getpid (), rv);
3739       break;
3740
3741     case VPPCOM_ATTR_GET_NWRITE:
3742       rv = vppcom_session_write_ready (session, session_index);
3743       if (VPPCOM_DEBUG > 2)
3744         clib_warning ("[%d] VPPCOM_ATTR_GET_NWRITE: sid %u, nwrite = %d",
3745                       getpid (), session_index, rv);
3746       break;
3747
3748     case VPPCOM_ATTR_GET_FLAGS:
3749       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3750         {
3751           *flags = O_RDWR | ((session->is_nonblocking) ? O_NONBLOCK : 0);
3752           *buflen = sizeof (*flags);
3753           if (VPPCOM_DEBUG > 2)
3754             clib_warning ("[%d] VPPCOM_ATTR_GET_FLAGS: sid %u, "
3755                           "flags = 0x%08x, is_nonblocking = %u", getpid (),
3756                           session_index, *flags, session->is_nonblocking);
3757         }
3758       else
3759         rv = VPPCOM_EINVAL;
3760       break;
3761
3762     case VPPCOM_ATTR_SET_FLAGS:
3763       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3764         {
3765           session->is_nonblocking = (*flags & O_NONBLOCK) ? 1 : 0;
3766           if (VPPCOM_DEBUG > 2)
3767             clib_warning ("[%d] VPPCOM_ATTR_SET_FLAGS: sid %u, "
3768                           "flags = 0x%08x, is_nonblocking = %u",
3769                           getpid (), session_index, *flags,
3770                           session->is_nonblocking);
3771         }
3772       else
3773         rv = VPPCOM_EINVAL;
3774       break;
3775
3776     case VPPCOM_ATTR_GET_PEER_ADDR:
3777       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3778         {
3779           ep->vrf = session->vrf;
3780           ep->is_ip4 = session->peer_addr.is_ip4;
3781           ep->port = session->peer_port;
3782           if (session->peer_addr.is_ip4)
3783             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3784                          sizeof (ip4_address_t));
3785           else
3786             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3787                          sizeof (ip6_address_t));
3788           *buflen = sizeof (*ep);
3789           if (VPPCOM_DEBUG > 1)
3790             clib_warning ("[%d] VPPCOM_ATTR_GET_PEER_ADDR: sid %u, is_ip4 = "
3791                           "%u, addr = %U, port %u", getpid (),
3792                           session_index, ep->is_ip4, format_ip46_address,
3793                           &session->peer_addr.ip46, ep->is_ip4,
3794                           clib_net_to_host_u16 (ep->port));
3795         }
3796       else
3797         rv = VPPCOM_EINVAL;
3798       break;
3799
3800     case VPPCOM_ATTR_GET_LCL_ADDR:
3801       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3802         {
3803           ep->vrf = session->vrf;
3804           ep->is_ip4 = session->lcl_addr.is_ip4;
3805           ep->port = session->lcl_port;
3806           if (session->lcl_addr.is_ip4)
3807             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip4,
3808                          sizeof (ip4_address_t));
3809           else
3810             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip6,
3811                          sizeof (ip6_address_t));
3812           *buflen = sizeof (*ep);
3813           if (VPPCOM_DEBUG > 1)
3814             clib_warning ("[%d] VPPCOM_ATTR_GET_LCL_ADDR: sid %u, is_ip4 = "
3815                           "%u, addr = %U port %d", getpid (),
3816                           session_index, ep->is_ip4, format_ip46_address,
3817                           &session->lcl_addr.ip46, ep->is_ip4,
3818                           clib_net_to_host_u16 (ep->port));
3819         }
3820       else
3821         rv = VPPCOM_EINVAL;
3822       break;
3823
3824     case VPPCOM_ATTR_SET_REUSEADDR:
3825       break;
3826
3827     case VPPCOM_ATTR_SET_BROADCAST:
3828       break;
3829
3830     case VPPCOM_ATTR_SET_V6ONLY:
3831       break;
3832
3833     case VPPCOM_ATTR_SET_KEEPALIVE:
3834       break;
3835
3836     case VPPCOM_ATTR_SET_TCP_KEEPIDLE:
3837       break;
3838
3839     case VPPCOM_ATTR_SET_TCP_KEEPINTVL:
3840       break;
3841
3842     default:
3843       rv = VPPCOM_EINVAL;
3844       break;
3845     }
3846
3847 done:
3848   clib_spinlock_unlock (&vcm->sessions_lockp);
3849   return rv;
3850 }
3851
3852 int
3853 vppcom_session_recvfrom (uint32_t session_index, void *buffer,
3854                          uint32_t buflen, int flags, vppcom_endpt_t * ep)
3855 {
3856   int rv = VPPCOM_OK;
3857   session_t *session = 0;
3858
3859   if (ep)
3860     {
3861       clib_spinlock_lock (&vcm->sessions_lockp);
3862       rv = vppcom_session_at_index (session_index, &session);
3863       if (PREDICT_FALSE (rv))
3864         {
3865           clib_spinlock_unlock (&vcm->sessions_lockp);
3866           if (VPPCOM_DEBUG > 0)
3867             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
3868                           getpid (), session_index);
3869           rv = VPPCOM_EBADFD;
3870           clib_spinlock_unlock (&vcm->sessions_lockp);
3871           goto done;
3872         }
3873       ep->vrf = session->vrf;
3874       ep->is_ip4 = session->peer_addr.is_ip4;
3875       ep->port = session->peer_port;
3876       if (session->peer_addr.is_ip4)
3877         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3878                      sizeof (ip4_address_t));
3879       else
3880         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3881                      sizeof (ip6_address_t));
3882       clib_spinlock_unlock (&vcm->sessions_lockp);
3883     }
3884
3885   if (flags == 0)
3886     rv = vppcom_session_read (session_index, buffer, buflen);
3887   else if (flags & MSG_PEEK)
3888     rv = vppcom_session_peek (session_index, buffer, buflen);
3889   else
3890     {
3891       clib_warning ("[%d] Unsupport flags for recvfrom %d", getpid (), flags);
3892       rv = VPPCOM_EAFNOSUPPORT;
3893     }
3894
3895 done:
3896   return rv;
3897 }
3898
3899 int
3900 vppcom_session_sendto (uint32_t session_index, void *buffer,
3901                        uint32_t buflen, int flags, vppcom_endpt_t * ep)
3902 {
3903   if (!buffer)
3904     return VPPCOM_EINVAL;
3905
3906   if (ep)
3907     {
3908       // TBD
3909       return VPPCOM_EINVAL;
3910     }
3911
3912   if (flags)
3913     {
3914       // TBD check the flags and do the right thing
3915       if (VPPCOM_DEBUG > 2)
3916         clib_warning ("[%d] handling flags 0x%u (%d) not implemented yet.",
3917                       getpid (), flags, flags);
3918     }
3919
3920   return (vppcom_session_write (session_index, buffer, buflen));
3921 }
3922
3923 /*
3924  * fd.io coding-style-patch-verification: ON
3925  *
3926  * Local Variables:
3927  * eval: (c-set-style "gnu")
3928  * End:
3929  */