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