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