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