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