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