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