session/vcl: improve fifo tx notifications
[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 <svm/svm_fifo_segment.h>
19 #include <vcl/vppcom.h>
20 #include <vcl/vcl_debug.h>
21 #include <vcl/vcl_private.h>
22
23 __thread uword __vcl_worker_index = ~0;
24
25 static int
26 vcl_wait_for_segment (u64 segment_handle)
27 {
28   vcl_worker_t *wrk = vcl_worker_get_current ();
29   u32 wait_for_seconds = 10, segment_index;
30   f64 timeout;
31
32   if (segment_handle == VCL_INVALID_SEGMENT_HANDLE)
33     return 1;
34
35   timeout = clib_time_now (&wrk->clib_time) + wait_for_seconds;
36   while (clib_time_now (&wrk->clib_time) < timeout)
37     {
38       segment_index = vcl_segment_table_lookup (segment_handle);
39       if (segment_index != VCL_INVALID_SEGMENT_INDEX)
40         return 0;
41       usleep (10);
42     }
43   return 1;
44 }
45
46 static inline int
47 vcl_mq_dequeue_batch (vcl_worker_t * wrk, svm_msg_q_t * mq)
48 {
49   svm_msg_q_msg_t *msg;
50   u32 n_msgs;
51   int i;
52
53   n_msgs = svm_msg_q_size (mq);
54   for (i = 0; i < n_msgs; i++)
55     {
56       vec_add2 (wrk->mq_msg_vector, msg, 1);
57       svm_msg_q_sub_w_lock (mq, msg);
58     }
59   return n_msgs;
60 }
61
62 const char *
63 vppcom_session_state_str (session_state_t state)
64 {
65   char *st;
66
67   switch (state)
68     {
69     case STATE_START:
70       st = "STATE_START";
71       break;
72
73     case STATE_CONNECT:
74       st = "STATE_CONNECT";
75       break;
76
77     case STATE_LISTEN:
78       st = "STATE_LISTEN";
79       break;
80
81     case STATE_ACCEPT:
82       st = "STATE_ACCEPT";
83       break;
84
85     case STATE_VPP_CLOSING:
86       st = "STATE_VPP_CLOSING";
87       break;
88
89     case STATE_DISCONNECT:
90       st = "STATE_DISCONNECT";
91       break;
92
93     case STATE_FAILED:
94       st = "STATE_FAILED";
95       break;
96
97     default:
98       st = "UNKNOWN_STATE";
99       break;
100     }
101
102   return st;
103 }
104
105 u8 *
106 format_ip4_address (u8 * s, va_list * args)
107 {
108   u8 *a = va_arg (*args, u8 *);
109   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
110 }
111
112 u8 *
113 format_ip6_address (u8 * s, va_list * args)
114 {
115   ip6_address_t *a = va_arg (*args, ip6_address_t *);
116   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
117
118   i_max_n_zero = ARRAY_LEN (a->as_u16);
119   max_n_zeros = 0;
120   i_first_zero = i_max_n_zero;
121   n_zeros = 0;
122   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
123     {
124       u32 is_zero = a->as_u16[i] == 0;
125       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
126         {
127           i_first_zero = i;
128           n_zeros = 0;
129         }
130       n_zeros += is_zero;
131       if ((!is_zero && n_zeros > max_n_zeros)
132           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
133         {
134           i_max_n_zero = i_first_zero;
135           max_n_zeros = n_zeros;
136           i_first_zero = ARRAY_LEN (a->as_u16);
137           n_zeros = 0;
138         }
139     }
140
141   last_double_colon = 0;
142   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
143     {
144       if (i == i_max_n_zero && max_n_zeros > 1)
145         {
146           s = format (s, "::");
147           i += max_n_zeros - 1;
148           last_double_colon = 1;
149         }
150       else
151         {
152           s = format (s, "%s%x",
153                       (last_double_colon || i == 0) ? "" : ":",
154                       clib_net_to_host_u16 (a->as_u16[i]));
155           last_double_colon = 0;
156         }
157     }
158
159   return s;
160 }
161
162 /* Format an IP46 address. */
163 u8 *
164 format_ip46_address (u8 * s, va_list * args)
165 {
166   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
167   ip46_type_t type = va_arg (*args, ip46_type_t);
168   int is_ip4 = 1;
169
170   switch (type)
171     {
172     case IP46_TYPE_ANY:
173       is_ip4 = ip46_address_is_ip4 (ip46);
174       break;
175     case IP46_TYPE_IP4:
176       is_ip4 = 1;
177       break;
178     case IP46_TYPE_IP6:
179       is_ip4 = 0;
180       break;
181     }
182
183   return is_ip4 ?
184     format (s, "%U", format_ip4_address, &ip46->ip4) :
185     format (s, "%U", format_ip6_address, &ip46->ip6);
186 }
187
188 /*
189  * VPPCOM Utility Functions
190  */
191
192
193 static void
194 vcl_send_session_accepted_reply (svm_msg_q_t * mq, u32 context,
195                                  session_handle_t handle, int retval)
196 {
197   app_session_evt_t _app_evt, *app_evt = &_app_evt;
198   session_accepted_reply_msg_t *rmp;
199   app_alloc_ctrl_evt_to_vpp (mq, app_evt, SESSION_CTRL_EVT_ACCEPTED_REPLY);
200   rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
201   rmp->handle = handle;
202   rmp->context = context;
203   rmp->retval = retval;
204   app_send_ctrl_evt_to_vpp (mq, app_evt);
205 }
206
207 static void
208 vcl_send_session_disconnected_reply (svm_msg_q_t * mq, u32 context,
209                                      session_handle_t handle, int retval)
210 {
211   app_session_evt_t _app_evt, *app_evt = &_app_evt;
212   session_disconnected_reply_msg_t *rmp;
213   app_alloc_ctrl_evt_to_vpp (mq, app_evt,
214                              SESSION_CTRL_EVT_DISCONNECTED_REPLY);
215   rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
216   rmp->handle = handle;
217   rmp->context = context;
218   rmp->retval = retval;
219   app_send_ctrl_evt_to_vpp (mq, app_evt);
220 }
221
222 static void
223 vcl_send_session_reset_reply (svm_msg_q_t * mq, u32 context,
224                               session_handle_t handle, int retval)
225 {
226   app_session_evt_t _app_evt, *app_evt = &_app_evt;
227   session_reset_reply_msg_t *rmp;
228   app_alloc_ctrl_evt_to_vpp (mq, app_evt, SESSION_CTRL_EVT_RESET_REPLY);
229   rmp = (session_reset_reply_msg_t *) app_evt->evt->data;
230   rmp->handle = handle;
231   rmp->context = context;
232   rmp->retval = retval;
233   app_send_ctrl_evt_to_vpp (mq, app_evt);
234 }
235
236 void
237 vcl_send_session_worker_update (vcl_worker_t * wrk, vcl_session_t * s,
238                                 u32 wrk_index)
239 {
240   app_session_evt_t _app_evt, *app_evt = &_app_evt;
241   session_worker_update_msg_t *mp;
242   svm_msg_q_t *mq;
243
244   mq = vcl_session_vpp_evt_q (wrk, s);
245   app_alloc_ctrl_evt_to_vpp (mq, app_evt, SESSION_CTRL_EVT_WORKER_UPDATE);
246   mp = (session_worker_update_msg_t *) app_evt->evt->data;
247   mp->client_index = wrk->my_client_index;
248   mp->handle = s->vpp_handle;
249   mp->req_wrk_index = wrk->vpp_wrk_index;
250   mp->wrk_index = wrk_index;
251   app_send_ctrl_evt_to_vpp (mq, app_evt);
252 }
253
254 static u32
255 vcl_session_accepted_handler (vcl_worker_t * wrk, session_accepted_msg_t * mp)
256 {
257   vcl_session_t *session, *listen_session;
258   svm_fifo_t *rx_fifo, *tx_fifo;
259   u32 vpp_wrk_index;
260   svm_msg_q_t *evt_q;
261
262   session = vcl_session_alloc (wrk);
263
264   listen_session = vcl_session_table_lookup_listener (wrk,
265                                                       mp->listener_handle);
266   if (!listen_session)
267     {
268       svm_msg_q_t *evt_q;
269       evt_q = uword_to_pointer (mp->vpp_event_queue_address, svm_msg_q_t *);
270       clib_warning ("VCL<%d>: ERROR: couldn't find listen session: "
271                     "unknown vpp listener handle %llx",
272                     getpid (), mp->listener_handle);
273       vcl_send_session_accepted_reply (evt_q, mp->context, mp->handle,
274                                        VNET_API_ERROR_INVALID_ARGUMENT);
275       vcl_session_free (wrk, session);
276       return VCL_INVALID_SESSION_INDEX;
277     }
278
279   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
280   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
281
282   if (mp->server_event_queue_address)
283     {
284       session->vpp_evt_q = uword_to_pointer (mp->client_event_queue_address,
285                                              svm_msg_q_t *);
286       session->our_evt_q = uword_to_pointer (mp->server_event_queue_address,
287                                              svm_msg_q_t *);
288       if (vcl_wait_for_segment (mp->segment_handle))
289         {
290           clib_warning ("segment for session %u couldn't be mounted!",
291                         session->session_index);
292           return VCL_INVALID_SESSION_INDEX;
293         }
294       rx_fifo->master_session_index = session->session_index;
295       tx_fifo->master_session_index = session->session_index;
296       rx_fifo->master_thread_index = vcl_get_worker_index ();
297       tx_fifo->master_thread_index = vcl_get_worker_index ();
298       vec_validate (wrk->vpp_event_queues, 0);
299       evt_q = uword_to_pointer (mp->vpp_event_queue_address, svm_msg_q_t *);
300       wrk->vpp_event_queues[0] = evt_q;
301     }
302   else
303     {
304       session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
305                                              svm_msg_q_t *);
306       rx_fifo->client_session_index = session->session_index;
307       tx_fifo->client_session_index = session->session_index;
308       rx_fifo->client_thread_index = vcl_get_worker_index ();
309       tx_fifo->client_thread_index = vcl_get_worker_index ();
310       vpp_wrk_index = tx_fifo->master_thread_index;
311       vec_validate (wrk->vpp_event_queues, vpp_wrk_index);
312       wrk->vpp_event_queues[vpp_wrk_index] = session->vpp_evt_q;
313     }
314
315   session->vpp_handle = mp->handle;
316   session->vpp_thread_index = rx_fifo->master_thread_index;
317   session->client_context = mp->context;
318   session->rx_fifo = rx_fifo;
319   session->tx_fifo = tx_fifo;
320
321   session->session_state = STATE_ACCEPT;
322   session->transport.rmt_port = mp->port;
323   session->transport.is_ip4 = mp->is_ip4;
324   clib_memcpy_fast (&session->transport.rmt_ip, mp->ip,
325                     sizeof (ip46_address_t));
326
327   vcl_session_table_add_vpp_handle (wrk, mp->handle, session->session_index);
328   session->transport.lcl_port = listen_session->transport.lcl_port;
329   session->transport.lcl_ip = listen_session->transport.lcl_ip;
330   session->session_type = listen_session->session_type;
331   session->is_dgram = session->session_type == VPPCOM_PROTO_UDP;
332
333   VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: client accept request from %s"
334         " address %U port %d queue %p!", getpid (), mp->handle,
335         session->session_index,
336         mp->is_ip4 ? "IPv4" : "IPv6", format_ip46_address, &mp->ip,
337         mp->is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
338         clib_net_to_host_u16 (mp->port), session->vpp_evt_q);
339   vcl_evt (VCL_EVT_ACCEPT, session, listen_session, session_index);
340
341   return session->session_index;
342 }
343
344 static u32
345 vcl_session_connected_handler (vcl_worker_t * wrk,
346                                session_connected_msg_t * mp)
347 {
348   u32 session_index, vpp_wrk_index;
349   svm_fifo_t *rx_fifo, *tx_fifo;
350   vcl_session_t *session = 0;
351   svm_msg_q_t *evt_q;
352
353   session_index = mp->context;
354   session = vcl_session_get (wrk, session_index);
355   if (!session)
356     {
357       clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
358                     "Invalid session index (%u)!",
359                     getpid (), mp->handle, session_index);
360       return VCL_INVALID_SESSION_INDEX;
361     }
362   if (mp->retval)
363     {
364       clib_warning ("VCL<%d>: ERROR: sid %u: connect failed! %U", getpid (),
365                     session_index, format_api_error, ntohl (mp->retval));
366       session->session_state = STATE_FAILED;
367       session->vpp_handle = mp->handle;
368       return session_index;
369     }
370
371   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
372   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
373   if (vcl_wait_for_segment (mp->segment_handle))
374     {
375       clib_warning ("segment for session %u couldn't be mounted!",
376                     session->session_index);
377       return VCL_INVALID_SESSION_INDEX;
378     }
379
380   rx_fifo->client_session_index = session_index;
381   tx_fifo->client_session_index = session_index;
382   rx_fifo->client_thread_index = vcl_get_worker_index ();
383   tx_fifo->client_thread_index = vcl_get_worker_index ();
384
385   if (mp->client_event_queue_address)
386     {
387       session->vpp_evt_q = uword_to_pointer (mp->server_event_queue_address,
388                                              svm_msg_q_t *);
389       session->our_evt_q = uword_to_pointer (mp->client_event_queue_address,
390                                              svm_msg_q_t *);
391
392       vec_validate (wrk->vpp_event_queues, 0);
393       evt_q = uword_to_pointer (mp->vpp_event_queue_address, svm_msg_q_t *);
394       wrk->vpp_event_queues[0] = evt_q;
395     }
396   else
397     {
398       session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
399                                              svm_msg_q_t *);
400       vpp_wrk_index = tx_fifo->master_thread_index;
401       vec_validate (wrk->vpp_event_queues, vpp_wrk_index);
402       wrk->vpp_event_queues[vpp_wrk_index] = session->vpp_evt_q;
403     }
404
405   session->rx_fifo = rx_fifo;
406   session->tx_fifo = tx_fifo;
407   session->vpp_handle = mp->handle;
408   session->vpp_thread_index = rx_fifo->master_thread_index;
409   session->transport.is_ip4 = mp->is_ip4;
410   clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip,
411                     sizeof (session->transport.lcl_ip));
412   session->transport.lcl_port = mp->lcl_port;
413   session->session_state = STATE_CONNECT;
414
415   /* Add it to lookup table */
416   vcl_session_table_add_vpp_handle (wrk, mp->handle, session_index);
417
418   VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: connect succeeded! "
419         "session_rx_fifo %p, refcnt %d, session_tx_fifo %p, refcnt %d",
420         getpid (), mp->handle, session_index, session->rx_fifo,
421         session->rx_fifo->refcnt, session->tx_fifo, session->tx_fifo->refcnt);
422
423   return session_index;
424 }
425
426 static int
427 vcl_flag_accepted_session (vcl_session_t * session, u64 handle, u32 flags)
428 {
429   vcl_session_msg_t *accepted_msg;
430   int i;
431
432   for (i = 0; i < vec_len (session->accept_evts_fifo); i++)
433     {
434       accepted_msg = &session->accept_evts_fifo[i];
435       if (accepted_msg->accepted_msg.handle == handle)
436         {
437           accepted_msg->flags |= flags;
438           return 1;
439         }
440     }
441   return 0;
442 }
443
444 static u32
445 vcl_session_reset_handler (vcl_worker_t * wrk,
446                            session_reset_msg_t * reset_msg)
447 {
448   vcl_session_t *session;
449   u32 sid;
450
451   sid = vcl_session_index_from_vpp_handle (wrk, reset_msg->handle);
452   session = vcl_session_get (wrk, sid);
453   if (!session)
454     {
455       VDBG (0, "request to reset unknown handle 0x%llx", reset_msg->handle);
456       return VCL_INVALID_SESSION_INDEX;
457     }
458
459   /* Caught a reset before actually accepting the session */
460   if (session->session_state == STATE_LISTEN)
461     {
462
463       if (!vcl_flag_accepted_session (session, reset_msg->handle,
464                                       VCL_ACCEPTED_F_RESET))
465         VDBG (0, "session was not accepted!");
466       return VCL_INVALID_SESSION_INDEX;
467     }
468
469   session->session_state = STATE_DISCONNECT;
470   VDBG (0, "reset session %u [0x%llx]", sid, reset_msg->handle);
471   return sid;
472 }
473
474 static u32
475 vcl_session_bound_handler (vcl_worker_t * wrk, session_bound_msg_t * mp)
476 {
477   vcl_session_t *session;
478   u32 sid = mp->context;
479
480   session = vcl_session_get (wrk, sid);
481   if (mp->retval)
482     {
483       VERR ("vpp handle 0x%llx, sid %u: bind failed: %U", mp->handle, sid,
484             format_api_error, mp->retval);
485       if (session)
486         {
487           session->session_state = STATE_FAILED;
488           session->vpp_handle = mp->handle;
489           return sid;
490         }
491       else
492         {
493           clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
494                         "Invalid session index (%u)!",
495                         getpid (), mp->handle, sid);
496           return VCL_INVALID_SESSION_INDEX;
497         }
498     }
499
500   session->vpp_handle = mp->handle;
501   session->transport.is_ip4 = mp->lcl_is_ip4;
502   clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip,
503                     sizeof (ip46_address_t));
504   session->transport.lcl_port = mp->lcl_port;
505   vcl_session_table_add_listener (wrk, mp->handle, sid);
506   session->session_state = STATE_LISTEN;
507
508   if (session->is_dgram)
509     {
510       svm_fifo_t *rx_fifo, *tx_fifo;
511       session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *);
512       rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *);
513       rx_fifo->client_session_index = sid;
514       tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *);
515       tx_fifo->client_session_index = sid;
516       session->rx_fifo = rx_fifo;
517       session->tx_fifo = tx_fifo;
518     }
519
520   VDBG (0, "session %u [0x%llx]: listen succeeded!", sid, mp->handle);
521   return sid;
522 }
523
524 static vcl_session_t *
525 vcl_session_accepted (vcl_worker_t * wrk, session_accepted_msg_t * msg)
526 {
527   vcl_session_msg_t *vcl_msg;
528   vcl_session_t *session;
529
530   session = vcl_session_get_w_vpp_handle (wrk, msg->handle);
531   if (PREDICT_FALSE (session != 0))
532     VWRN ("session overlap handle %lu state %u!", msg->handle,
533           session->session_state);
534
535   session = vcl_session_table_lookup_listener (wrk, msg->listener_handle);
536   if (!session)
537     {
538       VERR ("couldn't find listen session: listener handle %llx",
539             msg->listener_handle);
540       return 0;
541     }
542
543   clib_fifo_add2 (session->accept_evts_fifo, vcl_msg);
544   vcl_msg->accepted_msg = *msg;
545   /* Session handle points to listener until fully accepted by app */
546   vcl_session_table_add_vpp_handle (wrk, msg->handle, session->session_index);
547
548   return session;
549 }
550
551 static vcl_session_t *
552 vcl_session_disconnected_handler (vcl_worker_t * wrk,
553                                   session_disconnected_msg_t * msg)
554 {
555   vcl_session_t *session;
556
557   session = vcl_session_get_w_vpp_handle (wrk, msg->handle);
558   if (!session)
559     {
560       VDBG (0, "request to disconnect unknown handle 0x%llx", msg->handle);
561       return 0;
562     }
563
564   /* Caught a disconnect before actually accepting the session */
565   if (session->session_state == STATE_LISTEN)
566     {
567       if (!vcl_flag_accepted_session (session, msg->handle,
568                                       VCL_ACCEPTED_F_CLOSED))
569         VDBG (0, "session was not accepted!");
570       return 0;
571     }
572
573   session->session_state = STATE_VPP_CLOSING;
574   return session;
575 }
576
577 static void
578 vcl_session_req_worker_update_handler (vcl_worker_t * wrk, void *data)
579 {
580   session_req_worker_update_msg_t *msg;
581   vcl_session_t *s;
582
583   msg = (session_req_worker_update_msg_t *) data;
584   s = vcl_session_get_w_vpp_handle (wrk, msg->session_handle);
585   if (!s)
586     return;
587
588   vec_add1 (wrk->pending_session_wrk_updates, s->session_index);
589 }
590
591 static void
592 vcl_session_worker_update_reply_handler (vcl_worker_t * wrk, void *data)
593 {
594   session_worker_update_reply_msg_t *msg;
595   vcl_session_t *s;
596
597   msg = (session_worker_update_reply_msg_t *) data;
598   s = vcl_session_get_w_vpp_handle (wrk, msg->handle);
599   if (!s)
600     {
601       VDBG (0, "unknown handle 0x%llx", msg->handle);
602       return;
603     }
604   if (vcl_wait_for_segment (msg->segment_handle))
605     {
606       clib_warning ("segment for session %u couldn't be mounted!",
607                     s->session_index);
608       return;
609     }
610   s->rx_fifo = uword_to_pointer (msg->rx_fifo, svm_fifo_t *);
611   s->tx_fifo = uword_to_pointer (msg->tx_fifo, svm_fifo_t *);
612
613   s->rx_fifo->client_session_index = s->session_index;
614   s->tx_fifo->client_session_index = s->session_index;
615   s->rx_fifo->client_thread_index = wrk->wrk_index;
616   s->tx_fifo->client_thread_index = wrk->wrk_index;
617   s->session_state = STATE_UPDATED;
618
619   if (s->shared_index != VCL_INVALID_SESSION_INDEX)
620     {
621       vcl_shared_session_t *ss;
622       ss = vcl_shared_session_get (s->shared_index);
623       if (vec_len (ss->workers) > 1)
624         VDBG (0, "workers need to be updated");
625     }
626   VDBG (0, "session %u[0x%llx] moved to worker %u", s->session_index,
627         s->vpp_handle, wrk->wrk_index);
628 }
629
630 static int
631 vcl_handle_mq_event (vcl_worker_t * wrk, session_event_t * e)
632 {
633   session_disconnected_msg_t *disconnected_msg;
634   vcl_session_t *session;
635
636   switch (e->event_type)
637     {
638     case FIFO_EVENT_APP_RX:
639     case FIFO_EVENT_APP_TX:
640     case SESSION_IO_EVT_CT_RX:
641     case SESSION_IO_EVT_CT_TX:
642       vec_add1 (wrk->unhandled_evts_vector, *e);
643       break;
644     case SESSION_CTRL_EVT_ACCEPTED:
645       vcl_session_accepted (wrk, (session_accepted_msg_t *) e->data);
646       break;
647     case SESSION_CTRL_EVT_CONNECTED:
648       vcl_session_connected_handler (wrk,
649                                      (session_connected_msg_t *) e->data);
650       break;
651     case SESSION_CTRL_EVT_DISCONNECTED:
652       disconnected_msg = (session_disconnected_msg_t *) e->data;
653       session = vcl_session_disconnected_handler (wrk, disconnected_msg);
654       if (!session)
655         break;
656       session->session_state = STATE_DISCONNECT;
657       VDBG (0, "disconnected session %u [0x%llx]", session->session_index,
658             session->vpp_handle);
659       break;
660     case SESSION_CTRL_EVT_RESET:
661       vcl_session_reset_handler (wrk, (session_reset_msg_t *) e->data);
662       break;
663     case SESSION_CTRL_EVT_BOUND:
664       vcl_session_bound_handler (wrk, (session_bound_msg_t *) e->data);
665       break;
666     case SESSION_CTRL_EVT_REQ_WORKER_UPDATE:
667       vcl_session_req_worker_update_handler (wrk, e->data);
668       break;
669     case SESSION_CTRL_EVT_WORKER_UPDATE_REPLY:
670       vcl_session_worker_update_reply_handler (wrk, e->data);
671       break;
672     default:
673       clib_warning ("unhandled %u", e->event_type);
674     }
675   return VPPCOM_OK;
676 }
677
678 static int
679 vppcom_wait_for_session_state_change (u32 session_index,
680                                       session_state_t state,
681                                       f64 wait_for_time)
682 {
683   vcl_worker_t *wrk = vcl_worker_get_current ();
684   f64 timeout = clib_time_now (&wrk->clib_time) + wait_for_time;
685   vcl_session_t *volatile session;
686   svm_msg_q_msg_t msg;
687   session_event_t *e;
688
689   do
690     {
691       session = vcl_session_get (wrk, session_index);
692       if (PREDICT_FALSE (!session))
693         {
694           return VPPCOM_EBADFD;
695         }
696       if (session->session_state & state)
697         {
698           return VPPCOM_OK;
699         }
700       if (session->session_state & STATE_FAILED)
701         {
702           return VPPCOM_ECONNREFUSED;
703         }
704
705       if (svm_msg_q_sub (wrk->app_event_queue, &msg, SVM_Q_NOWAIT, 0))
706         {
707           usleep (100);
708           continue;
709         }
710       e = svm_msg_q_msg_data (wrk->app_event_queue, &msg);
711       vcl_handle_mq_event (wrk, e);
712       svm_msg_q_free_msg (wrk->app_event_queue, &msg);
713     }
714   while (clib_time_now (&wrk->clib_time) < timeout);
715
716   VDBG (0, "timeout waiting for state 0x%x (%s)", state,
717         vppcom_session_state_str (state));
718   vcl_evt (VCL_EVT_SESSION_TIMEOUT, session, session_state);
719
720   return VPPCOM_ETIMEDOUT;
721 }
722
723 static void
724 vcl_handle_pending_wrk_updates (vcl_worker_t * wrk)
725 {
726   session_state_t state;
727   vcl_session_t *s;
728   u32 *sip;
729
730   if (PREDICT_TRUE (vec_len (wrk->pending_session_wrk_updates) == 0))
731     return;
732
733   vec_foreach (sip, wrk->pending_session_wrk_updates)
734   {
735     s = vcl_session_get (wrk, *sip);
736     vcl_send_session_worker_update (wrk, s, wrk->wrk_index);
737     state = s->session_state;
738     vppcom_wait_for_session_state_change (s->session_index, STATE_UPDATED, 5);
739     s->session_state = state;
740   }
741   vec_reset_length (wrk->pending_session_wrk_updates);
742 }
743
744 static void
745 vcl_flush_mq_events (void)
746 {
747   vcl_worker_t *wrk = vcl_worker_get_current ();
748   svm_msg_q_msg_t *msg;
749   session_event_t *e;
750   svm_msg_q_t *mq;
751   int i;
752
753   mq = wrk->app_event_queue;
754   svm_msg_q_lock (mq);
755   vcl_mq_dequeue_batch (wrk, mq);
756   svm_msg_q_unlock (mq);
757
758   for (i = 0; i < vec_len (wrk->mq_msg_vector); i++)
759     {
760       msg = vec_elt_at_index (wrk->mq_msg_vector, i);
761       e = svm_msg_q_msg_data (mq, msg);
762       vcl_handle_mq_event (wrk, e);
763       svm_msg_q_free_msg (mq, msg);
764     }
765   vec_reset_length (wrk->mq_msg_vector);
766   vcl_handle_pending_wrk_updates (wrk);
767 }
768
769 static int
770 vppcom_app_session_enable (void)
771 {
772   int rv;
773
774   if (vcm->app_state != STATE_APP_ENABLED)
775     {
776       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
777       rv = vcl_wait_for_app_state_change (STATE_APP_ENABLED);
778       if (PREDICT_FALSE (rv))
779         {
780           VDBG (0, "VCL<%d>: application session enable timed out! "
781                 "returning %d (%s)", getpid (), rv, vppcom_retval_str (rv));
782           return rv;
783         }
784     }
785   return VPPCOM_OK;
786 }
787
788 static int
789 vppcom_app_attach (void)
790 {
791   int rv;
792
793   vppcom_app_send_attach ();
794   rv = vcl_wait_for_app_state_change (STATE_APP_ATTACHED);
795   if (PREDICT_FALSE (rv))
796     {
797       VDBG (0, "VCL<%d>: application attach timed out! returning %d (%s)",
798             getpid (), rv, vppcom_retval_str (rv));
799       return rv;
800     }
801
802   return VPPCOM_OK;
803 }
804
805 static int
806 vppcom_session_unbind (u32 session_handle)
807 {
808   vcl_worker_t *wrk = vcl_worker_get_current ();
809   vcl_session_t *session = 0;
810   u64 vpp_handle;
811
812   session = vcl_session_get_w_handle (wrk, session_handle);
813   if (!session)
814     return VPPCOM_EBADFD;
815
816   vpp_handle = session->vpp_handle;
817   vcl_session_table_del_listener (wrk, vpp_handle);
818   session->vpp_handle = ~0;
819   session->session_state = STATE_DISCONNECT;
820
821   VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: sending unbind msg! new state"
822         " 0x%x (%s)", getpid (), vpp_handle, session_handle, STATE_DISCONNECT,
823         vppcom_session_state_str (STATE_DISCONNECT));
824   vcl_evt (VCL_EVT_UNBIND, session);
825   vppcom_send_unbind_sock (vpp_handle);
826
827   return VPPCOM_OK;
828 }
829
830 static int
831 vppcom_session_disconnect (u32 session_handle)
832 {
833   vcl_worker_t *wrk = vcl_worker_get_current ();
834   svm_msg_q_t *vpp_evt_q;
835   vcl_session_t *session;
836   session_state_t state;
837   u64 vpp_handle;
838
839   session = vcl_session_get_w_handle (wrk, session_handle);
840   if (!session)
841     return VPPCOM_EBADFD;
842
843   vpp_handle = session->vpp_handle;
844   state = session->session_state;
845
846   VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u state 0x%x (%s)", getpid (),
847         vpp_handle, session_handle, state, vppcom_session_state_str (state));
848
849   if (PREDICT_FALSE (state & STATE_LISTEN))
850     {
851       clib_warning ("VCL<%d>: ERROR: vpp handle 0x%llx, sid %u: "
852                     "Cannot disconnect a listen socket!",
853                     getpid (), vpp_handle, session_handle);
854       return VPPCOM_EBADFD;
855     }
856
857   if (state & STATE_VPP_CLOSING)
858     {
859       vpp_evt_q = vcl_session_vpp_evt_q (wrk, session);
860       vcl_send_session_disconnected_reply (vpp_evt_q, wrk->my_client_index,
861                                            vpp_handle, 0);
862       VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: sending disconnect "
863             "REPLY...", getpid (), vpp_handle, session_handle);
864     }
865   else
866     {
867       VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: sending disconnect...",
868             getpid (), vpp_handle, session_handle);
869       vppcom_send_disconnect_session (vpp_handle);
870     }
871
872   return VPPCOM_OK;
873 }
874
875 static void
876 vcl_cleanup_bapi (void)
877 {
878   socket_client_main_t *scm = &socket_client_main;
879   api_main_t *am = &api_main;
880
881   am->my_client_index = ~0;
882   am->my_registration = 0;
883   am->vl_input_queue = 0;
884   am->msg_index_by_name_and_crc = 0;
885   scm->socket_fd = 0;
886
887   vl_client_api_unmap ();
888 }
889
890 static void
891 vcl_cleanup_forked_child (vcl_worker_t * wrk, vcl_worker_t * child_wrk)
892 {
893   vcl_worker_t *sub_child;
894   int tries = 0;
895
896   if (child_wrk->forked_child != ~0)
897     {
898       sub_child = vcl_worker_get_if_valid (child_wrk->forked_child);
899       if (sub_child)
900         {
901           /* Wait a bit, maybe the process is going away */
902           while (kill (sub_child->current_pid, 0) >= 0 && tries++ < 50)
903             usleep (1e3);
904           if (kill (sub_child->current_pid, 0) < 0)
905             vcl_cleanup_forked_child (child_wrk, sub_child);
906         }
907     }
908   vcl_worker_cleanup (child_wrk, 1 /* notify vpp */ );
909   VDBG (0, "Cleaned up wrk %u", child_wrk->wrk_index);
910   wrk->forked_child = ~0;
911 }
912
913 static struct sigaction old_sa;
914
915 static void
916 vcl_intercept_sigchld_handler (int signum, siginfo_t * si, void *uc)
917 {
918   vcl_worker_t *wrk, *child_wrk;
919
920   if (vcl_get_worker_index () == ~0)
921     return;
922
923   if (sigaction (SIGCHLD, &old_sa, 0))
924     {
925       VERR ("couldn't restore sigchld");
926       exit (-1);
927     }
928
929   wrk = vcl_worker_get_current ();
930   if (wrk->forked_child == ~0)
931     return;
932
933   child_wrk = vcl_worker_get_if_valid (wrk->forked_child);
934   if (!child_wrk)
935     goto done;
936
937   if (si && si->si_pid != child_wrk->current_pid)
938     {
939       VDBG (0, "unexpected child pid %u", si->si_pid);
940       goto done;
941     }
942   vcl_cleanup_forked_child (wrk, child_wrk);
943
944 done:
945   if (old_sa.sa_flags & SA_SIGINFO)
946     {
947       void (*fn) (int, siginfo_t *, void *) = old_sa.sa_sigaction;
948       fn (signum, si, uc);
949     }
950   else
951     {
952       void (*fn) (int) = old_sa.sa_handler;
953       if (fn)
954         fn (signum);
955     }
956 }
957
958 static void
959 vcl_incercept_sigchld ()
960 {
961   struct sigaction sa;
962   clib_memset (&sa, 0, sizeof (sa));
963   sa.sa_sigaction = vcl_intercept_sigchld_handler;
964   sa.sa_flags = SA_SIGINFO;
965   if (sigaction (SIGCHLD, &sa, &old_sa))
966     {
967       VERR ("couldn't intercept sigchld");
968       exit (-1);
969     }
970 }
971
972 static void
973 vcl_app_pre_fork (void)
974 {
975   vcl_incercept_sigchld ();
976   vcl_flush_mq_events ();
977 }
978
979 static void
980 vcl_app_fork_child_handler (void)
981 {
982   vcl_worker_t *parent_wrk, *wrk;
983   int rv, parent_wrk_index;
984   u8 *child_name;
985
986   parent_wrk_index = vcl_get_worker_index ();
987   VDBG (0, "initializing forked child with parent wrk %u", parent_wrk_index);
988
989   /*
990    * Allocate worker
991    */
992   vcl_set_worker_index (~0);
993   if (!vcl_worker_alloc_and_init ())
994     VERR ("couldn't allocate new worker");
995
996   /*
997    * Attach to binary api
998    */
999   child_name = format (0, "%v-child-%u%c", vcm->app_name, getpid (), 0);
1000   vcl_cleanup_bapi ();
1001   vppcom_api_hookup ();
1002   vcm->app_state = STATE_APP_START;
1003   rv = vppcom_connect_to_vpp ((char *) child_name);
1004   vec_free (child_name);
1005   if (rv)
1006     {
1007       VERR ("couldn't connect to VPP!");
1008       return;
1009     }
1010
1011   /*
1012    * Register worker with vpp and share sessions
1013    */
1014   vcl_worker_register_with_vpp ();
1015   parent_wrk = vcl_worker_get (parent_wrk_index);
1016   wrk = vcl_worker_get_current ();
1017   wrk->vpp_event_queues = vec_dup (parent_wrk->vpp_event_queues);
1018   vcl_worker_share_sessions (parent_wrk);
1019   parent_wrk->forked_child = vcl_get_worker_index ();
1020
1021   VDBG (0, "forked child main worker initialized");
1022   vcm->forking = 0;
1023 }
1024
1025 static void
1026 vcl_app_fork_parent_handler (void)
1027 {
1028   vcm->forking = 1;
1029   while (vcm->forking)
1030     ;
1031 }
1032
1033 /**
1034  * Handle app exit
1035  *
1036  * Notify vpp of the disconnect and mark the worker as free. If we're the
1037  * last worker, do a full cleanup otherwise, since we're probably a forked
1038  * child, avoid syscalls as much as possible. We might've lost privileges.
1039  */
1040 void
1041 vppcom_app_exit (void)
1042 {
1043   if (!pool_elts (vcm->workers))
1044     return;
1045   vcl_worker_cleanup (vcl_worker_get_current (), 1 /* notify vpp */ );
1046   vcl_set_worker_index (~0);
1047   vcl_elog_stop (vcm);
1048   if (vec_len (vcm->workers) == 1)
1049     vl_client_disconnect_from_vlib ();
1050   else
1051     vl_client_send_disconnect (1 /* vpp should cleanup */ );
1052 }
1053
1054 /*
1055  * VPPCOM Public API functions
1056  */
1057 int
1058 vppcom_app_create (char *app_name)
1059 {
1060   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1061   int rv;
1062
1063   if (vcm->is_init)
1064     {
1065       VDBG (1, "already initialized");
1066       return VPPCOM_EEXIST;
1067     }
1068
1069   vcm->is_init = 1;
1070   vppcom_cfg (&vcm->cfg);
1071   vcl_cfg = &vcm->cfg;
1072
1073   vcm->main_cpu = pthread_self ();
1074   vcm->main_pid = getpid ();
1075   vcm->app_name = format (0, "%s", app_name);
1076   vppcom_init_error_string_table ();
1077   svm_fifo_segment_main_init (&vcm->segment_main, vcl_cfg->segment_baseva,
1078                               20 /* timeout in secs */ );
1079   pool_alloc (vcm->workers, vcl_cfg->max_workers);
1080   clib_spinlock_init (&vcm->workers_lock);
1081   clib_rwlock_init (&vcm->segment_table_lock);
1082   pthread_atfork (vcl_app_pre_fork, vcl_app_fork_parent_handler,
1083                   vcl_app_fork_child_handler);
1084   atexit (vppcom_app_exit);
1085
1086   /* Allocate default worker */
1087   vcl_worker_alloc_and_init ();
1088
1089   /* API hookup and connect to VPP */
1090   vppcom_api_hookup ();
1091   vcl_elog_init (vcm);
1092   vcm->app_state = STATE_APP_START;
1093   rv = vppcom_connect_to_vpp (app_name);
1094   if (rv)
1095     {
1096       VERR ("couldn't connect to VPP!");
1097       return rv;
1098     }
1099   VDBG (0, "sending session enable");
1100   rv = vppcom_app_session_enable ();
1101   if (rv)
1102     {
1103       VERR ("vppcom_app_session_enable() failed!");
1104       return rv;
1105     }
1106
1107   VDBG (0, "sending app attach");
1108   rv = vppcom_app_attach ();
1109   if (rv)
1110     {
1111       VERR ("vppcom_app_attach() failed!");
1112       return rv;
1113     }
1114
1115   VDBG (0, "app_name '%s', my_client_index %d (0x%x)", app_name,
1116         vcm->workers[0].my_client_index, vcm->workers[0].my_client_index);
1117
1118   return VPPCOM_OK;
1119 }
1120
1121 void
1122 vppcom_app_destroy (void)
1123 {
1124   int rv;
1125   f64 orig_app_timeout;
1126
1127   if (!pool_elts (vcm->workers))
1128     return;
1129
1130   vcl_evt (VCL_EVT_DETACH, vcm);
1131
1132   if (pool_elts (vcm->workers) == 1)
1133     {
1134       vppcom_app_send_detach ();
1135       orig_app_timeout = vcm->cfg.app_timeout;
1136       vcm->cfg.app_timeout = 2.0;
1137       rv = vcl_wait_for_app_state_change (STATE_APP_ENABLED);
1138       vcm->cfg.app_timeout = orig_app_timeout;
1139       if (PREDICT_FALSE (rv))
1140         VDBG (0, "application detach timed out! returning %d (%s)", rv,
1141               vppcom_retval_str (rv));
1142       vec_free (vcm->app_name);
1143       vcl_worker_cleanup (vcl_worker_get_current (), 0 /* notify vpp */ );
1144     }
1145   else
1146     {
1147       vcl_worker_cleanup (vcl_worker_get_current (), 1 /* notify vpp */ );
1148     }
1149
1150   vcl_set_worker_index (~0);
1151   vcl_elog_stop (vcm);
1152   vl_client_disconnect_from_vlib ();
1153 }
1154
1155 int
1156 vppcom_session_create (u8 proto, u8 is_nonblocking)
1157 {
1158   vcl_worker_t *wrk = vcl_worker_get_current ();
1159   vcl_session_t *session;
1160
1161   session = vcl_session_alloc (wrk);
1162
1163   session->session_type = proto;
1164   session->session_state = STATE_START;
1165   session->vpp_handle = ~0;
1166   session->is_dgram = proto == VPPCOM_PROTO_UDP;
1167
1168   if (is_nonblocking)
1169     VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_NONBLOCK);
1170
1171   vcl_evt (VCL_EVT_CREATE, session, session_type, session->session_state,
1172            is_nonblocking, session_index);
1173
1174   VDBG (0, "created sid %u", session->session_index);
1175
1176   return vcl_session_handle (session);
1177 }
1178
1179 int
1180 vppcom_session_close (uint32_t session_handle)
1181 {
1182   vcl_worker_t *wrk = vcl_worker_get_current ();
1183   u8 is_vep, do_disconnect = 1;
1184   vcl_session_t *session = 0;
1185   session_state_t state;
1186   u32 next_sh, vep_sh;
1187   int rv = VPPCOM_OK;
1188   u64 vpp_handle;
1189
1190   session = vcl_session_get_w_handle (wrk, session_handle);
1191   if (!session)
1192     return VPPCOM_EBADFD;
1193
1194   if (session->shared_index != ~0)
1195     do_disconnect = vcl_worker_unshare_session (wrk, session);
1196
1197   is_vep = session->is_vep;
1198   next_sh = session->vep.next_sh;
1199   vep_sh = session->vep.vep_sh;
1200   state = session->session_state;
1201   vpp_handle = session->vpp_handle;
1202
1203   VDBG (1, "closing session handle %u vpp handle %u", session_handle,
1204         vpp_handle);
1205
1206   if (is_vep)
1207     {
1208       while (next_sh != ~0)
1209         {
1210           rv = vppcom_epoll_ctl (session_handle, EPOLL_CTL_DEL, next_sh, 0);
1211           if (PREDICT_FALSE (rv < 0))
1212             VDBG (0, "vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL vep_idx %u"
1213                   " failed! rv %d (%s)", vpp_handle, next_sh, vep_sh, rv,
1214                   vppcom_retval_str (rv));
1215
1216           next_sh = session->vep.next_sh;
1217         }
1218     }
1219   else
1220     {
1221       if (session->is_vep_session)
1222         {
1223           rv = vppcom_epoll_ctl (vep_sh, EPOLL_CTL_DEL, session_handle, 0);
1224           if (rv < 0)
1225             VDBG (0, "vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL vep_idx %u "
1226                   "failed! rv %d (%s)", vpp_handle, session_handle, vep_sh,
1227                   rv, vppcom_retval_str (rv));
1228         }
1229
1230       if (!do_disconnect)
1231         {
1232           VDBG (0, "session handle %u [0x%llx] disconnect skipped",
1233                 session_handle, vpp_handle);
1234           goto cleanup;
1235         }
1236
1237       if (state & STATE_LISTEN)
1238         {
1239           rv = vppcom_session_unbind (session_handle);
1240           if (PREDICT_FALSE (rv < 0))
1241             VDBG (0, "vpp handle 0x%llx, sid %u: listener unbind failed! "
1242                   "rv %d (%s)", vpp_handle, session_handle, rv,
1243                   vppcom_retval_str (rv));
1244         }
1245       else if (state & STATE_OPEN)
1246         {
1247           rv = vppcom_session_disconnect (session_handle);
1248           if (PREDICT_FALSE (rv < 0))
1249             clib_warning ("VCL<%d>: ERROR: vpp handle 0x%llx, sid %u: "
1250                           "session disconnect failed! rv %d (%s)",
1251                           getpid (), vpp_handle, session_handle,
1252                           rv, vppcom_retval_str (rv));
1253         }
1254       else if (state == STATE_DISCONNECT)
1255         {
1256           svm_msg_q_t *mq = vcl_session_vpp_evt_q (wrk, session);
1257           vcl_send_session_reset_reply (mq, wrk->my_client_index,
1258                                         session->vpp_handle, 0);
1259         }
1260     }
1261
1262 cleanup:
1263
1264   if (vcl_session_is_ct (session))
1265     {
1266       vcl_cut_through_registration_t *ctr;
1267       uword mq_addr;
1268
1269       mq_addr = pointer_to_uword (session->our_evt_q);
1270       ctr = vcl_ct_registration_lock_and_lookup (wrk, mq_addr);
1271       ASSERT (ctr);
1272       if (ctr->epoll_evt_conn_index != ~0)
1273         vcl_mq_epoll_del_evfd (wrk, ctr->epoll_evt_conn_index);
1274       VDBG (0, "Removing ct registration %u",
1275             vcl_ct_registration_index (wrk, ctr));
1276       vcl_ct_registration_del (wrk, ctr);
1277       vcl_ct_registration_lookup_del (wrk, mq_addr);
1278       vcl_ct_registration_unlock (wrk);
1279     }
1280
1281   vcl_session_table_del_vpp_handle (wrk, vpp_handle);
1282   vcl_session_free (wrk, session);
1283
1284   VDBG (0, "session handle %u [0x%llx] removed", session_handle, vpp_handle);
1285
1286   vcl_evt (VCL_EVT_CLOSE, session, rv);
1287
1288   return rv;
1289 }
1290
1291 int
1292 vppcom_session_bind (uint32_t session_handle, vppcom_endpt_t * ep)
1293 {
1294   vcl_worker_t *wrk = vcl_worker_get_current ();
1295   vcl_session_t *session = 0;
1296
1297   if (!ep || !ep->ip)
1298     return VPPCOM_EINVAL;
1299
1300   session = vcl_session_get_w_handle (wrk, session_handle);
1301   if (!session)
1302     return VPPCOM_EBADFD;
1303
1304   if (session->is_vep)
1305     {
1306       clib_warning ("VCL<%d>: ERROR: sid %u: cannot "
1307                     "bind to an epoll session!", getpid (), session_handle);
1308       return VPPCOM_EBADFD;
1309     }
1310
1311   session->transport.is_ip4 = ep->is_ip4;
1312   if (ep->is_ip4)
1313     clib_memcpy_fast (&session->transport.lcl_ip.ip4, ep->ip,
1314                       sizeof (ip4_address_t));
1315   else
1316     clib_memcpy_fast (&session->transport.lcl_ip.ip6, ep->ip,
1317                       sizeof (ip6_address_t));
1318   session->transport.lcl_port = ep->port;
1319
1320   VDBG (0, "VCL<%d>: sid %u: binding to local %s address %U port %u, "
1321         "proto %s", getpid (), session_handle,
1322         session->transport.is_ip4 ? "IPv4" : "IPv6",
1323         format_ip46_address, &session->transport.lcl_ip,
1324         session->transport.is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
1325         clib_net_to_host_u16 (session->transport.lcl_port),
1326         vppcom_proto_str (session->session_type));
1327   vcl_evt (VCL_EVT_BIND, session);
1328
1329   if (session->session_type == VPPCOM_PROTO_UDP)
1330     vppcom_session_listen (session_handle, 10);
1331
1332   return VPPCOM_OK;
1333 }
1334
1335 int
1336 vppcom_session_listen (uint32_t listen_sh, uint32_t q_len)
1337 {
1338   vcl_worker_t *wrk = vcl_worker_get_current ();
1339   vcl_session_t *listen_session = 0;
1340   u64 listen_vpp_handle;
1341   int rv;
1342
1343   listen_session = vcl_session_get_w_handle (wrk, listen_sh);
1344   if (!listen_session || listen_session->is_vep)
1345     return VPPCOM_EBADFD;
1346
1347   if (q_len == 0 || q_len == ~0)
1348     q_len = vcm->cfg.listen_queue_size;
1349
1350   listen_vpp_handle = listen_session->vpp_handle;
1351   if (listen_session->session_state & STATE_LISTEN)
1352     {
1353       VDBG (0, "session %u [0x%llx]: already in listen state!",
1354             listen_sh, listen_vpp_handle);
1355       return VPPCOM_OK;
1356     }
1357
1358   VDBG (0, "session %u [0x%llx]: sending vpp listen request...",
1359         listen_sh, listen_vpp_handle);
1360
1361   /*
1362    * Send listen request to vpp and wait for reply
1363    */
1364   vppcom_send_bind_sock (listen_session);
1365   rv = vppcom_wait_for_session_state_change (listen_session->session_index,
1366                                              STATE_LISTEN,
1367                                              vcm->cfg.session_timeout);
1368
1369   if (PREDICT_FALSE (rv))
1370     {
1371       listen_session = vcl_session_get_w_handle (wrk, listen_sh);
1372       VDBG (0, "session %u [0x%llx]: listen failed! returning %d (%s)",
1373             listen_sh, listen_session->vpp_handle, rv,
1374             vppcom_retval_str (rv));
1375       return rv;
1376     }
1377
1378   return VPPCOM_OK;
1379 }
1380
1381 int
1382 vppcom_session_tls_add_cert (uint32_t session_handle, char *cert,
1383                              uint32_t cert_len)
1384 {
1385
1386   vcl_worker_t *wrk = vcl_worker_get_current ();
1387   vcl_session_t *session = 0;
1388
1389   session = vcl_session_get_w_handle (wrk, session_handle);
1390   if (!session)
1391     return VPPCOM_EBADFD;
1392
1393   if (cert_len == 0 || cert_len == ~0)
1394     return VPPCOM_EBADFD;
1395
1396   /*
1397    * Send listen request to vpp and wait for reply
1398    */
1399   vppcom_send_application_tls_cert_add (session, cert, cert_len);
1400
1401   return VPPCOM_OK;
1402
1403 }
1404
1405 int
1406 vppcom_session_tls_add_key (uint32_t session_handle, char *key,
1407                             uint32_t key_len)
1408 {
1409
1410   vcl_worker_t *wrk = vcl_worker_get_current ();
1411   vcl_session_t *session = 0;
1412
1413   session = vcl_session_get_w_handle (wrk, session_handle);
1414   if (!session)
1415     return VPPCOM_EBADFD;
1416
1417   if (key_len == 0 || key_len == ~0)
1418     return VPPCOM_EBADFD;
1419
1420   /*
1421    * Send listen request to vpp and wait for reply
1422    */
1423   vppcom_send_application_tls_key_add (session, key, key_len);
1424
1425   return VPPCOM_OK;
1426
1427
1428 }
1429
1430 static int
1431 validate_args_session_accept_ (vcl_worker_t * wrk,
1432                                vcl_session_t * listen_session)
1433 {
1434   /* Input validation - expects spinlock on sessions_lockp */
1435   if (listen_session->is_vep)
1436     {
1437       clib_warning ("VCL<%d>: ERROR: sid %u: cannot accept on an "
1438                     "epoll session!", getpid (),
1439                     listen_session->session_index);
1440       return VPPCOM_EBADFD;
1441     }
1442
1443   if (listen_session->session_state != STATE_LISTEN)
1444     {
1445       clib_warning ("VCL<%d>: ERROR: vpp handle 0x%llx, sid %u: "
1446                     "not in listen state! state 0x%x (%s)", getpid (),
1447                     listen_session->vpp_handle, listen_session->session_index,
1448                     listen_session->session_state,
1449                     vppcom_session_state_str (listen_session->session_state));
1450       return VPPCOM_EBADFD;
1451     }
1452   return VPPCOM_OK;
1453 }
1454
1455 int
1456 vppcom_session_accept (uint32_t listen_session_handle, vppcom_endpt_t * ep,
1457                        uint32_t flags)
1458 {
1459   u32 client_session_index = ~0, listen_session_index, accept_flags = 0;
1460   vcl_worker_t *wrk = vcl_worker_get_current ();
1461   session_accepted_msg_t accepted_msg;
1462   vcl_session_t *listen_session = 0;
1463   vcl_session_t *client_session = 0;
1464   svm_msg_q_t *vpp_evt_q;
1465   vcl_session_msg_t *evt;
1466   u64 listen_vpp_handle;
1467   svm_msg_q_msg_t msg;
1468   session_event_t *e;
1469   u8 is_nonblocking;
1470   int rv;
1471
1472   listen_session = vcl_session_get_w_handle (wrk, listen_session_handle);
1473   if (!listen_session)
1474     return VPPCOM_EBADFD;
1475
1476   listen_session_index = listen_session->session_index;
1477   if ((rv = validate_args_session_accept_ (wrk, listen_session)))
1478     return rv;
1479
1480   if (clib_fifo_elts (listen_session->accept_evts_fifo))
1481     {
1482       clib_fifo_sub2 (listen_session->accept_evts_fifo, evt);
1483       accept_flags = evt->flags;
1484       accepted_msg = evt->accepted_msg;
1485       goto handle;
1486     }
1487
1488   is_nonblocking = VCL_SESS_ATTR_TEST (listen_session->attr,
1489                                        VCL_SESS_ATTR_NONBLOCK);
1490   if (svm_msg_q_is_empty (wrk->app_event_queue) && is_nonblocking)
1491     return VPPCOM_EAGAIN;
1492
1493   while (1)
1494     {
1495       if (svm_msg_q_sub (wrk->app_event_queue, &msg, SVM_Q_WAIT, 0))
1496         return VPPCOM_EAGAIN;
1497
1498       e = svm_msg_q_msg_data (wrk->app_event_queue, &msg);
1499       if (e->event_type != SESSION_CTRL_EVT_ACCEPTED)
1500         {
1501           clib_warning ("discarded event: %u", e->event_type);
1502           svm_msg_q_free_msg (wrk->app_event_queue, &msg);
1503           continue;
1504         }
1505       clib_memcpy_fast (&accepted_msg, e->data, sizeof (accepted_msg));
1506       svm_msg_q_free_msg (wrk->app_event_queue, &msg);
1507       break;
1508     }
1509
1510 handle:
1511
1512   client_session_index = vcl_session_accepted_handler (wrk, &accepted_msg);
1513   listen_session = vcl_session_get (wrk, listen_session_index);
1514   client_session = vcl_session_get (wrk, client_session_index);
1515
1516   if (flags & O_NONBLOCK)
1517     VCL_SESS_ATTR_SET (client_session->attr, VCL_SESS_ATTR_NONBLOCK);
1518
1519   listen_vpp_handle = listen_session->vpp_handle;
1520   VDBG (1, "vpp handle 0x%llx, sid %u: Got a client request! "
1521         "vpp handle 0x%llx, sid %u, flags %d, is_nonblocking %u",
1522         listen_vpp_handle, listen_session_handle,
1523         client_session->vpp_handle, client_session_index,
1524         flags, VCL_SESS_ATTR_TEST (client_session->attr,
1525                                    VCL_SESS_ATTR_NONBLOCK));
1526
1527   if (ep)
1528     {
1529       ep->is_ip4 = client_session->transport.is_ip4;
1530       ep->port = client_session->transport.rmt_port;
1531       if (client_session->transport.is_ip4)
1532         clib_memcpy_fast (ep->ip, &client_session->transport.rmt_ip.ip4,
1533                           sizeof (ip4_address_t));
1534       else
1535         clib_memcpy_fast (ep->ip, &client_session->transport.rmt_ip.ip6,
1536                           sizeof (ip6_address_t));
1537     }
1538
1539   if (accepted_msg.server_event_queue_address)
1540     vpp_evt_q = uword_to_pointer (accepted_msg.vpp_event_queue_address,
1541                                   svm_msg_q_t *);
1542   else
1543     vpp_evt_q = client_session->vpp_evt_q;
1544
1545   vcl_send_session_accepted_reply (vpp_evt_q, client_session->client_context,
1546                                    client_session->vpp_handle, 0);
1547
1548   VDBG (0, "listener %u [0x%llx] accepted %u [0x%llx] peer: %U:%u "
1549         "local: %U:%u", listen_session_handle, listen_vpp_handle,
1550         client_session_index, client_session->vpp_handle,
1551         format_ip46_address, &client_session->transport.rmt_ip,
1552         client_session->transport.is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
1553         clib_net_to_host_u16 (client_session->transport.rmt_port),
1554         format_ip46_address, &client_session->transport.lcl_ip,
1555         client_session->transport.is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
1556         clib_net_to_host_u16 (client_session->transport.lcl_port));
1557   vcl_evt (VCL_EVT_ACCEPT, client_session, listen_session,
1558            client_session_index);
1559
1560   /*
1561    * Session might have been closed already
1562    */
1563   if (accept_flags)
1564     {
1565       if (accept_flags & VCL_ACCEPTED_F_CLOSED)
1566         client_session->session_state = STATE_VPP_CLOSING;
1567       else if (accept_flags & VCL_ACCEPTED_F_RESET)
1568         client_session->session_state = STATE_DISCONNECT;
1569     }
1570   return vcl_session_handle (client_session);
1571 }
1572
1573 int
1574 vppcom_session_connect (uint32_t session_handle, vppcom_endpt_t * server_ep)
1575 {
1576   vcl_worker_t *wrk = vcl_worker_get_current ();
1577   vcl_session_t *session = 0;
1578   u32 session_index;
1579   int rv;
1580
1581   session = vcl_session_get_w_handle (wrk, session_handle);
1582   if (!session)
1583     return VPPCOM_EBADFD;
1584   session_index = session->session_index;
1585
1586   if (PREDICT_FALSE (session->is_vep))
1587     {
1588       clib_warning ("VCL<%d>: ERROR: sid %u: cannot "
1589                     "connect on an epoll session!", getpid (),
1590                     session_handle);
1591       return VPPCOM_EBADFD;
1592     }
1593
1594   if (PREDICT_FALSE (session->session_state & CLIENT_STATE_OPEN))
1595     {
1596       VDBG (0, "session handle %u [0x%llx]: session already "
1597             "connected to %s %U port %d proto %s, state 0x%x (%s)",
1598             session_handle, session->vpp_handle,
1599             session->transport.is_ip4 ? "IPv4" : "IPv6",
1600             format_ip46_address,
1601             &session->transport.rmt_ip, session->transport.is_ip4 ?
1602             IP46_TYPE_IP4 : IP46_TYPE_IP6,
1603             clib_net_to_host_u16 (session->transport.rmt_port),
1604             vppcom_proto_str (session->session_type), session->session_state,
1605             vppcom_session_state_str (session->session_state));
1606       return VPPCOM_OK;
1607     }
1608
1609   session->transport.is_ip4 = server_ep->is_ip4;
1610   if (session->transport.is_ip4)
1611     clib_memcpy_fast (&session->transport.rmt_ip.ip4, server_ep->ip,
1612                       sizeof (ip4_address_t));
1613   else
1614     clib_memcpy_fast (&session->transport.rmt_ip.ip6, server_ep->ip,
1615                       sizeof (ip6_address_t));
1616   session->transport.rmt_port = server_ep->port;
1617
1618   VDBG (0, "session handle %u [0x%llx]: connecting to server %s %U "
1619         "port %d proto %s", session_handle, session->vpp_handle,
1620         session->transport.is_ip4 ? "IPv4" : "IPv6",
1621         format_ip46_address,
1622         &session->transport.rmt_ip, session->transport.is_ip4 ?
1623         IP46_TYPE_IP4 : IP46_TYPE_IP6,
1624         clib_net_to_host_u16 (session->transport.rmt_port),
1625         vppcom_proto_str (session->session_type));
1626
1627   /*
1628    * Send connect request and wait for reply from vpp
1629    */
1630   vppcom_send_connect_sock (session);
1631   rv = vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
1632                                              vcm->cfg.session_timeout);
1633
1634   session = vcl_session_get (wrk, session_index);
1635
1636   if (PREDICT_FALSE (rv))
1637     {
1638       if (VPPCOM_DEBUG > 0)
1639         {
1640           if (session)
1641             clib_warning ("VCL<%d>: vpp handle 0x%llx, sid %u: connect "
1642                           "failed! returning %d (%s)", getpid (),
1643                           session->vpp_handle, session_handle, rv,
1644                           vppcom_retval_str (rv));
1645           else
1646             clib_warning ("VCL<%d>: no session for sid %u: connect failed! "
1647                           "returning %d (%s)", getpid (),
1648                           session_handle, rv, vppcom_retval_str (rv));
1649         }
1650     }
1651   else
1652     VDBG (0, "VCL<%d>: vpp handle 0x%llx, sid %u: connected!",
1653           getpid (), session->vpp_handle, session_handle);
1654
1655   return rv;
1656 }
1657
1658 static u8
1659 vcl_is_rx_evt_for_session (session_event_t * e, u32 sid, u8 is_ct)
1660 {
1661   if (!is_ct)
1662     return (e->event_type == FIFO_EVENT_APP_RX
1663             && e->fifo->client_session_index == sid);
1664   else
1665     return (e->event_type == SESSION_IO_EVT_CT_TX);
1666 }
1667
1668 static inline u8
1669 vcl_session_is_readable (vcl_session_t * s)
1670 {
1671   return ((s->session_state & STATE_OPEN)
1672           || (s->session_state == STATE_LISTEN
1673               && s->session_type == VPPCOM_PROTO_UDP));
1674 }
1675
1676 static inline int
1677 vppcom_session_read_internal (uint32_t session_handle, void *buf, int n,
1678                               u8 peek)
1679 {
1680   vcl_worker_t *wrk = vcl_worker_get_current ();
1681   int n_read = 0, rv, is_nonblocking;
1682   vcl_session_t *s = 0;
1683   svm_fifo_t *rx_fifo;
1684   svm_msg_q_msg_t msg;
1685   session_event_t *e;
1686   svm_msg_q_t *mq;
1687   u8 is_ct;
1688
1689   if (PREDICT_FALSE (!buf))
1690     return VPPCOM_EINVAL;
1691
1692   s = vcl_session_get_w_handle (wrk, session_handle);
1693   if (PREDICT_FALSE (!s || s->is_vep))
1694     return VPPCOM_EBADFD;
1695
1696   if (PREDICT_FALSE (!vcl_session_is_readable (s)))
1697     {
1698       session_state_t state = s->session_state;
1699       rv = ((state & STATE_DISCONNECT) ? VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
1700
1701       VDBG (0, "session handle %u[0x%llx] is not open! state 0x%x (%s),"
1702             " returning %d (%s)", session_handle, s->vpp_handle, state,
1703             vppcom_session_state_str (state), rv, vppcom_retval_str (rv));
1704       return rv;
1705     }
1706
1707   is_nonblocking = VCL_SESS_ATTR_TEST (s->attr, VCL_SESS_ATTR_NONBLOCK);
1708   is_ct = vcl_session_is_ct (s);
1709   mq = is_ct ? s->our_evt_q : wrk->app_event_queue;
1710   rx_fifo = s->rx_fifo;
1711   s->has_rx_evt = 0;
1712
1713   if (svm_fifo_is_empty (rx_fifo))
1714     {
1715       if (is_nonblocking)
1716         {
1717           svm_fifo_unset_event (rx_fifo);
1718           return VPPCOM_EWOULDBLOCK;
1719         }
1720       while (svm_fifo_is_empty (rx_fifo))
1721         {
1722           svm_fifo_unset_event (rx_fifo);
1723           svm_msg_q_lock (mq);
1724           if (svm_msg_q_is_empty (mq))
1725             svm_msg_q_wait (mq);
1726
1727           svm_msg_q_sub_w_lock (mq, &msg);
1728           e = svm_msg_q_msg_data (mq, &msg);
1729           svm_msg_q_unlock (mq);
1730           if (!vcl_is_rx_evt_for_session (e, s->session_index, is_ct))
1731             vcl_handle_mq_event (wrk, e);
1732           svm_msg_q_free_msg (mq, &msg);
1733
1734           if (PREDICT_FALSE (s->session_state == STATE_DISCONNECT))
1735             return VPPCOM_ECONNRESET;
1736         }
1737     }
1738
1739   if (s->is_dgram)
1740     n_read = app_recv_dgram_raw (rx_fifo, buf, n, &s->transport, 0, peek);
1741   else
1742     n_read = app_recv_stream_raw (rx_fifo, buf, n, 0, peek);
1743
1744   if (svm_fifo_is_empty (rx_fifo))
1745     svm_fifo_unset_event (rx_fifo);
1746
1747   if (is_ct && svm_fifo_needs_tx_ntf (rx_fifo, n_read))
1748     {
1749       svm_fifo_clear_tx_ntf (s->rx_fifo);
1750       app_send_io_evt_to_vpp (s->vpp_evt_q, s->rx_fifo, SESSION_IO_EVT_CT_RX,
1751                               SVM_Q_WAIT);
1752     }
1753
1754   VDBG (2, "vpp handle 0x%llx, sid %u: read %d bytes from (%p)",
1755         s->vpp_handle, session_handle, n_read, rx_fifo);
1756
1757   return n_read;
1758 }
1759
1760 int
1761 vppcom_session_read (uint32_t session_handle, void *buf, size_t n)
1762 {
1763   return (vppcom_session_read_internal (session_handle, buf, n, 0));
1764 }
1765
1766 static int
1767 vppcom_session_peek (uint32_t session_handle, void *buf, int n)
1768 {
1769   return (vppcom_session_read_internal (session_handle, buf, n, 1));
1770 }
1771
1772 int
1773 vppcom_session_read_segments (uint32_t session_handle,
1774                               vppcom_data_segments_t ds)
1775 {
1776   vcl_worker_t *wrk = vcl_worker_get_current ();
1777   int n_read = 0, rv, is_nonblocking;
1778   vcl_session_t *s = 0;
1779   svm_fifo_t *rx_fifo;
1780   svm_msg_q_msg_t msg;
1781   session_event_t *e;
1782   svm_msg_q_t *mq;
1783   u8 is_ct;
1784
1785   s = vcl_session_get_w_handle (wrk, session_handle);
1786   if (PREDICT_FALSE (!s || s->is_vep))
1787     return VPPCOM_EBADFD;
1788
1789   if (PREDICT_FALSE (!vcl_session_is_readable (s)))
1790     {
1791       session_state_t state = s->session_state;
1792       rv = ((state & STATE_DISCONNECT) ? VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
1793       return rv;
1794     }
1795
1796   is_nonblocking = VCL_SESS_ATTR_TEST (s->attr, VCL_SESS_ATTR_NONBLOCK);
1797   is_ct = vcl_session_is_ct (s);
1798   mq = is_ct ? s->our_evt_q : wrk->app_event_queue;
1799   rx_fifo = s->rx_fifo;
1800   s->has_rx_evt = 0;
1801
1802   if (svm_fifo_is_empty (rx_fifo))
1803     {
1804       if (is_nonblocking)
1805         {
1806           svm_fifo_unset_event (rx_fifo);
1807           return VPPCOM_EWOULDBLOCK;
1808         }
1809       while (svm_fifo_is_empty (rx_fifo))
1810         {
1811           svm_fifo_unset_event (rx_fifo);
1812           svm_msg_q_lock (mq);
1813           if (svm_msg_q_is_empty (mq))
1814             svm_msg_q_wait (mq);
1815
1816           svm_msg_q_sub_w_lock (mq, &msg);
1817           e = svm_msg_q_msg_data (mq, &msg);
1818           svm_msg_q_unlock (mq);
1819           if (!vcl_is_rx_evt_for_session (e, s->session_index, is_ct))
1820             vcl_handle_mq_event (wrk, e);
1821           svm_msg_q_free_msg (mq, &msg);
1822
1823           if (PREDICT_FALSE (s->session_state == STATE_DISCONNECT))
1824             return VPPCOM_ECONNRESET;
1825         }
1826     }
1827
1828   n_read = svm_fifo_segments (rx_fifo, (svm_fifo_segment_t *) ds);
1829   svm_fifo_unset_event (rx_fifo);
1830
1831   if (is_ct && n_read + svm_fifo_max_dequeue (rx_fifo) == rx_fifo->nitems)
1832     {
1833       /* If the peer is not polling send notification */
1834       if (!svm_fifo_has_event (s->rx_fifo))
1835         app_send_io_evt_to_vpp (s->vpp_evt_q, s->rx_fifo,
1836                                 SESSION_IO_EVT_CT_RX, SVM_Q_WAIT);
1837     }
1838
1839   return n_read;
1840 }
1841
1842 void
1843 vppcom_session_free_segments (uint32_t session_handle,
1844                               vppcom_data_segments_t ds)
1845 {
1846   vcl_worker_t *wrk = vcl_worker_get_current ();
1847   vcl_session_t *s;
1848
1849   s = vcl_session_get_w_handle (wrk, session_handle);
1850   if (PREDICT_FALSE (!s || s->is_vep))
1851     return;
1852
1853   svm_fifo_segments_free (s->rx_fifo, (svm_fifo_segment_t *) ds);
1854 }
1855
1856 static inline int
1857 vppcom_session_read_ready (vcl_session_t * session)
1858 {
1859   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1860   if (PREDICT_FALSE (session->is_vep))
1861     {
1862       clib_warning ("VCL<%d>: ERROR: sid %u: cannot read from an "
1863                     "epoll session!", getpid (), session->session_index);
1864       return VPPCOM_EBADFD;
1865     }
1866
1867   if (PREDICT_FALSE (!(session->session_state & (STATE_OPEN | STATE_LISTEN))))
1868     {
1869       session_state_t state = session->session_state;
1870       int rv;
1871
1872       rv = ((state & STATE_DISCONNECT) ? VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
1873
1874       VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: session is not open!"
1875             " state 0x%x (%s), returning %d (%s)", getpid (),
1876             session->vpp_handle, session->session_index, state,
1877             vppcom_session_state_str (state), rv, vppcom_retval_str (rv));
1878       return rv;
1879     }
1880
1881   if (session->session_state & STATE_LISTEN)
1882     return clib_fifo_elts (session->accept_evts_fifo);
1883
1884   return svm_fifo_max_dequeue (session->rx_fifo);
1885 }
1886
1887 int
1888 vppcom_data_segment_copy (void *buf, vppcom_data_segments_t ds, u32 max_bytes)
1889 {
1890   u32 first_copy = clib_min (ds[0].len, max_bytes);
1891   clib_memcpy_fast (buf, ds[0].data, first_copy);
1892   if (first_copy < max_bytes)
1893     {
1894       clib_memcpy_fast (buf + first_copy, ds[1].data,
1895                         clib_min (ds[1].len, max_bytes - first_copy));
1896     }
1897   return 0;
1898 }
1899
1900 static u8
1901 vcl_is_tx_evt_for_session (session_event_t * e, u32 sid, u8 is_ct)
1902 {
1903   if (!is_ct)
1904     return (e->event_type == FIFO_EVENT_APP_TX
1905             && e->fifo->client_session_index == sid);
1906   else
1907     return (e->event_type == SESSION_IO_EVT_CT_RX);
1908 }
1909
1910 static inline int
1911 vppcom_session_write_inline (uint32_t session_handle, void *buf, size_t n,
1912                              u8 is_flush)
1913 {
1914   vcl_worker_t *wrk = vcl_worker_get_current ();
1915   int rv, n_write, is_nonblocking;
1916   vcl_session_t *s = 0;
1917   svm_fifo_t *tx_fifo = 0;
1918   session_evt_type_t et;
1919   svm_msg_q_msg_t msg;
1920   session_event_t *e;
1921   svm_msg_q_t *mq;
1922   u8 is_ct;
1923
1924   if (PREDICT_FALSE (!buf))
1925     return VPPCOM_EINVAL;
1926
1927   s = vcl_session_get_w_handle (wrk, session_handle);
1928   if (PREDICT_FALSE (!s))
1929     return VPPCOM_EBADFD;
1930
1931   if (PREDICT_FALSE (s->is_vep))
1932     {
1933       clib_warning ("VCL<%d>: ERROR: vpp handle 0x%llx, sid %u: "
1934                     "cannot write to an epoll session!",
1935                     getpid (), s->vpp_handle, session_handle);
1936
1937       return VPPCOM_EBADFD;
1938     }
1939
1940   if (PREDICT_FALSE (!(s->session_state & STATE_OPEN)))
1941     {
1942       session_state_t state = s->session_state;
1943       rv = ((state & STATE_DISCONNECT) ? VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
1944       VDBG (1, "VCL<%d>: vpp handle 0x%llx, sid %u: session is not open! "
1945             "state 0x%x (%s)", getpid (), s->vpp_handle, session_handle,
1946             state, vppcom_session_state_str (state));
1947       return rv;
1948     }
1949
1950   tx_fifo = s->tx_fifo;
1951   is_ct = vcl_session_is_ct (s);
1952   is_nonblocking = VCL_SESS_ATTR_TEST (s->attr, VCL_SESS_ATTR_NONBLOCK);
1953   mq = is_ct ? s->our_evt_q : wrk->app_event_queue;
1954   if (svm_fifo_is_full (tx_fifo))
1955     {
1956       if (is_nonblocking)
1957         {
1958           return VPPCOM_EWOULDBLOCK;
1959         }
1960       while (svm_fifo_is_full (tx_fifo))
1961         {
1962           svm_fifo_add_want_tx_ntf (tx_fifo, SVM_FIFO_WANT_TX_NOTIF);
1963           svm_msg_q_lock (mq);
1964           if (svm_msg_q_is_empty (mq))
1965             svm_msg_q_wait (mq);
1966
1967           svm_msg_q_sub_w_lock (mq, &msg);
1968           e = svm_msg_q_msg_data (mq, &msg);
1969           svm_msg_q_unlock (mq);
1970
1971           if (!vcl_is_tx_evt_for_session (e, s->session_index, is_ct))
1972             vcl_handle_mq_event (wrk, e);
1973           svm_msg_q_free_msg (mq, &msg);
1974
1975           if (PREDICT_FALSE (!(s->session_state & STATE_OPEN)))
1976             return VPPCOM_ECONNRESET;
1977         }
1978     }
1979
1980   ASSERT (FIFO_EVENT_APP_TX + 1 == SESSION_IO_EVT_CT_TX);
1981   et = FIFO_EVENT_APP_TX + vcl_session_is_ct (s);
1982   if (is_flush && !vcl_session_is_ct (s))
1983     et = SESSION_IO_EVT_TX_FLUSH;
1984
1985   if (s->is_dgram)
1986     n_write = app_send_dgram_raw (tx_fifo, &s->transport,
1987                                   s->vpp_evt_q, buf, n, et, SVM_Q_WAIT);
1988   else
1989     n_write = app_send_stream_raw (tx_fifo, s->vpp_evt_q, buf, n, et,
1990                                    SVM_Q_WAIT);
1991
1992   ASSERT (n_write > 0);
1993
1994   VDBG (2, "VCL<%d>: vpp handle 0x%llx, sid %u: wrote %d bytes", getpid (),
1995         s->vpp_handle, session_handle, n_write);
1996
1997   return n_write;
1998 }
1999
2000 int
2001 vppcom_session_write (uint32_t session_handle, void *buf, size_t n)
2002 {
2003   return vppcom_session_write_inline (session_handle, buf, n,
2004                                       0 /* is_flush */ );
2005 }
2006
2007 int
2008 vppcom_session_write_msg (uint32_t session_handle, void *buf, size_t n)
2009 {
2010   return vppcom_session_write_inline (session_handle, buf, n,
2011                                       1 /* is_flush */ );
2012 }
2013
2014
2015 static vcl_session_t *
2016 vcl_ct_session_get_from_fifo (vcl_worker_t * wrk, svm_fifo_t * f, u8 type)
2017 {
2018   vcl_session_t *s;
2019   s = vcl_session_get (wrk, f->client_session_index);
2020   if (s)
2021     {
2022       /* rx fifo */
2023       if (type == 0 && s->rx_fifo == f)
2024         return s;
2025       /* tx fifo */
2026       if (type == 1 && s->tx_fifo == f)
2027         return s;
2028     }
2029   s = vcl_session_get (wrk, f->master_session_index);
2030   if (s)
2031     {
2032       if (type == 0 && s->rx_fifo == f)
2033         return s;
2034       if (type == 1 && s->tx_fifo == f)
2035         return s;
2036     }
2037   return 0;
2038 }
2039
2040 static inline int
2041 vppcom_session_write_ready (vcl_session_t * session)
2042 {
2043   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2044   if (PREDICT_FALSE (session->is_vep))
2045     {
2046       VDBG (0, "session %u [0x%llx]: cannot write to an epoll session!",
2047             session->session_index, session->vpp_handle);
2048       return VPPCOM_EBADFD;
2049     }
2050
2051   if (PREDICT_FALSE (session->session_state & STATE_LISTEN))
2052     {
2053       if (session->tx_fifo)
2054         return svm_fifo_max_enqueue (session->tx_fifo);
2055       else
2056         return VPPCOM_EBADFD;
2057     }
2058
2059   if (PREDICT_FALSE (!(session->session_state & STATE_OPEN)))
2060     {
2061       session_state_t state = session->session_state;
2062       int rv;
2063
2064       rv = ((state & STATE_DISCONNECT) ? VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
2065       VDBG (0, "session %u [0x%llx]: session is not open! state 0x%x (%s), "
2066             "returning %d (%s)", session->session_index, session->vpp_handle,
2067             state, vppcom_session_state_str (state), rv,
2068             vppcom_retval_str (rv));
2069       return rv;
2070     }
2071
2072   return svm_fifo_max_enqueue (session->tx_fifo);
2073 }
2074
2075 #define vcl_fifo_rx_evt_valid_or_break(_fifo)                   \
2076 if (PREDICT_FALSE (svm_fifo_is_empty (_fifo)))                  \
2077   {                                                             \
2078     svm_fifo_unset_event (_fifo);                               \
2079     if (svm_fifo_is_empty (_fifo))                              \
2080       break;                                                    \
2081   }                                                             \
2082
2083 static void
2084 vcl_select_handle_mq_event (vcl_worker_t * wrk, session_event_t * e,
2085                             unsigned long n_bits, unsigned long *read_map,
2086                             unsigned long *write_map,
2087                             unsigned long *except_map, u32 * bits_set)
2088 {
2089   session_disconnected_msg_t *disconnected_msg;
2090   session_connected_msg_t *connected_msg;
2091   vcl_session_t *session;
2092   u32 sid;
2093
2094   switch (e->event_type)
2095     {
2096     case FIFO_EVENT_APP_RX:
2097       vcl_fifo_rx_evt_valid_or_break (e->fifo);
2098       sid = e->fifo->client_session_index;
2099       session = vcl_session_get (wrk, sid);
2100       if (!session)
2101         break;
2102       if (sid < n_bits && read_map)
2103         {
2104           clib_bitmap_set_no_check ((uword *) read_map, sid, 1);
2105           *bits_set += 1;
2106         }
2107       break;
2108     case FIFO_EVENT_APP_TX:
2109       sid = e->fifo->client_session_index;
2110       session = vcl_session_get (wrk, sid);
2111       if (!session)
2112         break;
2113       if (sid < n_bits && write_map)
2114         {
2115           clib_bitmap_set_no_check ((uword *) write_map, sid, 1);
2116           *bits_set += 1;
2117         }
2118       break;
2119     case SESSION_IO_EVT_CT_TX:
2120       vcl_fifo_rx_evt_valid_or_break (e->fifo);
2121       session = vcl_ct_session_get_from_fifo (wrk, e->fifo, 0);
2122       if (!session)
2123         break;
2124       sid = session->session_index;
2125       if (sid < n_bits && read_map)
2126         {
2127           clib_bitmap_set_no_check ((uword *) read_map, sid, 1);
2128           *bits_set += 1;
2129         }
2130       break;
2131     case SESSION_IO_EVT_CT_RX:
2132       session = vcl_ct_session_get_from_fifo (wrk, e->fifo, 1);
2133       if (!session)
2134         break;
2135       sid = session->session_index;
2136       if (sid < n_bits && write_map)
2137         {
2138           clib_bitmap_set_no_check ((uword *) write_map, sid, 1);
2139           *bits_set += 1;
2140         }
2141       break;
2142     case SESSION_CTRL_EVT_ACCEPTED:
2143       session = vcl_session_accepted (wrk,
2144                                       (session_accepted_msg_t *) e->data);
2145       if (!session)
2146         break;
2147       sid = session->session_index;
2148       if (sid < n_bits && read_map)
2149         {
2150           clib_bitmap_set_no_check ((uword *) read_map, sid, 1);
2151           *bits_set += 1;
2152         }
2153       break;
2154     case SESSION_CTRL_EVT_CONNECTED:
2155       connected_msg = (session_connected_msg_t *) e->data;
2156       vcl_session_connected_handler (wrk, connected_msg);
2157       break;
2158     case SESSION_CTRL_EVT_DISCONNECTED:
2159       disconnected_msg = (session_disconnected_msg_t *) e->data;
2160       session = vcl_session_disconnected_handler (wrk, disconnected_msg);
2161       if (!session)
2162         break;
2163       sid = session->session_index;
2164       if (sid < n_bits && except_map)
2165         {
2166           clib_bitmap_set_no_check ((uword *) except_map, sid, 1);
2167           *bits_set += 1;
2168         }
2169       break;
2170     case SESSION_CTRL_EVT_RESET:
2171       sid = vcl_session_reset_handler (wrk, (session_reset_msg_t *) e->data);
2172       if (sid < n_bits && except_map)
2173         {
2174           clib_bitmap_set_no_check ((uword *) except_map, sid, 1);
2175           *bits_set += 1;
2176         }
2177       break;
2178     case SESSION_CTRL_EVT_WORKER_UPDATE_REPLY:
2179       vcl_session_worker_update_reply_handler (wrk, e->data);
2180       break;
2181     case SESSION_CTRL_EVT_REQ_WORKER_UPDATE:
2182       vcl_session_req_worker_update_handler (wrk, e->data);
2183       break;
2184     default:
2185       clib_warning ("unhandled: %u", e->event_type);
2186       break;
2187     }
2188 }
2189
2190 static int
2191 vcl_select_handle_mq (vcl_worker_t * wrk, svm_msg_q_t * mq,
2192                       unsigned long n_bits, unsigned long *read_map,
2193                       unsigned long *write_map, unsigned long *except_map,
2194                       double time_to_wait, u32 * bits_set)
2195 {
2196   svm_msg_q_msg_t *msg;
2197   session_event_t *e;
2198   u32 i;
2199
2200   svm_msg_q_lock (mq);
2201   if (svm_msg_q_is_empty (mq))
2202     {
2203       if (*bits_set)
2204         {
2205           svm_msg_q_unlock (mq);
2206           return 0;
2207         }
2208
2209       if (!time_to_wait)
2210         {
2211           svm_msg_q_unlock (mq);
2212           return 0;
2213         }
2214       else if (time_to_wait < 0)
2215         {
2216           svm_msg_q_wait (mq);
2217         }
2218       else
2219         {
2220           if (svm_msg_q_timedwait (mq, time_to_wait))
2221             {
2222               svm_msg_q_unlock (mq);
2223               return 0;
2224             }
2225         }
2226     }
2227   vcl_mq_dequeue_batch (wrk, mq);
2228   svm_msg_q_unlock (mq);
2229
2230   for (i = 0; i < vec_len (wrk->mq_msg_vector); i++)
2231     {
2232       msg = vec_elt_at_index (wrk->mq_msg_vector, i);
2233       e = svm_msg_q_msg_data (mq, msg);
2234       vcl_select_handle_mq_event (wrk, e, n_bits, read_map, write_map,
2235                                   except_map, bits_set);
2236       svm_msg_q_free_msg (mq, msg);
2237     }
2238   vec_reset_length (wrk->mq_msg_vector);
2239   vcl_handle_pending_wrk_updates (wrk);
2240   return *bits_set;
2241 }
2242
2243 static int
2244 vppcom_select_condvar (vcl_worker_t * wrk, int n_bits,
2245                        vcl_si_set * read_map, vcl_si_set * write_map,
2246                        vcl_si_set * except_map, double time_to_wait,
2247                        u32 * bits_set)
2248 {
2249   double total_wait = 0, wait_slice;
2250   vcl_cut_through_registration_t *cr;
2251
2252   time_to_wait = (time_to_wait == -1) ? 1e6 : time_to_wait;
2253   wait_slice = wrk->cut_through_registrations ? 10e-6 : time_to_wait;
2254   do
2255     {
2256       vcl_ct_registration_lock (wrk);
2257       /* *INDENT-OFF* */
2258       pool_foreach (cr, wrk->cut_through_registrations, ({
2259         vcl_select_handle_mq (wrk, cr->mq, n_bits, read_map, write_map, except_map,
2260                               0, bits_set);
2261       }));
2262       /* *INDENT-ON* */
2263       vcl_ct_registration_unlock (wrk);
2264
2265       vcl_select_handle_mq (wrk, wrk->app_event_queue, n_bits, read_map,
2266                             write_map, except_map, wait_slice, bits_set);
2267       total_wait += wait_slice;
2268       if (*bits_set)
2269         return *bits_set;
2270     }
2271   while (total_wait < time_to_wait);
2272
2273   return 0;
2274 }
2275
2276 static int
2277 vppcom_select_eventfd (vcl_worker_t * wrk, int n_bits,
2278                        vcl_si_set * read_map, vcl_si_set * write_map,
2279                        vcl_si_set * except_map, double time_to_wait,
2280                        u32 * bits_set)
2281 {
2282   vcl_mq_evt_conn_t *mqc;
2283   int __clib_unused n_read;
2284   int n_mq_evts, i;
2285   u64 buf;
2286
2287   vec_validate (wrk->mq_events, pool_elts (wrk->mq_evt_conns));
2288   n_mq_evts = epoll_wait (wrk->mqs_epfd, wrk->mq_events,
2289                           vec_len (wrk->mq_events), time_to_wait);
2290   for (i = 0; i < n_mq_evts; i++)
2291     {
2292       mqc = vcl_mq_evt_conn_get (wrk, wrk->mq_events[i].data.u32);
2293       n_read = read (mqc->mq_fd, &buf, sizeof (buf));
2294       vcl_select_handle_mq (wrk, mqc->mq, n_bits, read_map, write_map,
2295                             except_map, 0, bits_set);
2296     }
2297
2298   return (n_mq_evts > 0 ? (int) *bits_set : 0);
2299 }
2300
2301 int
2302 vppcom_select (int n_bits, vcl_si_set * read_map, vcl_si_set * write_map,
2303                vcl_si_set * except_map, double time_to_wait)
2304 {
2305   u32 sid, minbits = clib_max (n_bits, BITS (uword)), bits_set = 0;
2306   vcl_worker_t *wrk = vcl_worker_get_current ();
2307   vcl_session_t *session = 0;
2308   int rv, i;
2309
2310   if (n_bits && read_map)
2311     {
2312       clib_bitmap_validate (wrk->rd_bitmap, minbits);
2313       clib_memcpy_fast (wrk->rd_bitmap, read_map,
2314                         vec_len (wrk->rd_bitmap) * sizeof (vcl_si_set));
2315       memset (read_map, 0, vec_len (wrk->rd_bitmap) * sizeof (vcl_si_set));
2316     }
2317   if (n_bits && write_map)
2318     {
2319       clib_bitmap_validate (wrk->wr_bitmap, minbits);
2320       clib_memcpy_fast (wrk->wr_bitmap, write_map,
2321                         vec_len (wrk->wr_bitmap) * sizeof (vcl_si_set));
2322       memset (write_map, 0, vec_len (wrk->wr_bitmap) * sizeof (vcl_si_set));
2323     }
2324   if (n_bits && except_map)
2325     {
2326       clib_bitmap_validate (wrk->ex_bitmap, minbits);
2327       clib_memcpy_fast (wrk->ex_bitmap, except_map,
2328                         vec_len (wrk->ex_bitmap) * sizeof (vcl_si_set));
2329       memset (except_map, 0, vec_len (wrk->ex_bitmap) * sizeof (vcl_si_set));
2330     }
2331
2332   if (!n_bits)
2333     return 0;
2334
2335   if (!write_map)
2336     goto check_rd;
2337
2338   /* *INDENT-OFF* */
2339   clib_bitmap_foreach (sid, wrk->wr_bitmap, ({
2340     if (!(session = vcl_session_get (wrk, sid)))
2341       {
2342         if (except_map && sid < minbits)
2343           clib_bitmap_set_no_check (except_map, sid, 1);
2344         continue;
2345       }
2346
2347     rv = svm_fifo_is_full (session->tx_fifo);
2348     if (!rv)
2349       {
2350         clib_bitmap_set_no_check ((uword*)write_map, sid, 1);
2351         bits_set++;
2352       }
2353     else
2354       svm_fifo_add_want_tx_ntf (session->tx_fifo, SVM_FIFO_WANT_TX_NOTIF);
2355   }));
2356
2357 check_rd:
2358   if (!read_map)
2359     goto check_mq;
2360
2361   clib_bitmap_foreach (sid, wrk->rd_bitmap, ({
2362     if (!(session = vcl_session_get (wrk, sid)))
2363       {
2364         if (except_map && sid < minbits)
2365           clib_bitmap_set_no_check (except_map, sid, 1);
2366         continue;
2367       }
2368
2369     rv = vppcom_session_read_ready (session);
2370     if (rv)
2371       {
2372         clib_bitmap_set_no_check ((uword*)read_map, sid, 1);
2373         bits_set++;
2374       }
2375   }));
2376   /* *INDENT-ON* */
2377
2378 check_mq:
2379
2380   for (i = 0; i < vec_len (wrk->unhandled_evts_vector); i++)
2381     {
2382       vcl_select_handle_mq_event (wrk, &wrk->unhandled_evts_vector[i], n_bits,
2383                                   read_map, write_map, except_map, &bits_set);
2384     }
2385   vec_reset_length (wrk->unhandled_evts_vector);
2386
2387   if (vcm->cfg.use_mq_eventfd)
2388     vppcom_select_eventfd (wrk, n_bits, read_map, write_map, except_map,
2389                            time_to_wait, &bits_set);
2390   else
2391     vppcom_select_condvar (wrk, n_bits, read_map, write_map, except_map,
2392                            time_to_wait, &bits_set);
2393
2394   return (bits_set);
2395 }
2396
2397 static inline void
2398 vep_verify_epoll_chain (vcl_worker_t * wrk, u32 vep_idx)
2399 {
2400   vcl_session_t *session;
2401   vppcom_epoll_t *vep;
2402   u32 sid = vep_idx;
2403
2404   if (VPPCOM_DEBUG <= 1)
2405     return;
2406
2407   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2408   session = vcl_session_get (wrk, vep_idx);
2409   if (PREDICT_FALSE (!session))
2410     {
2411       clib_warning ("VCL<%d>: ERROR: Invalid vep_idx (%u)!",
2412                     getpid (), vep_idx);
2413       goto done;
2414     }
2415   if (PREDICT_FALSE (!session->is_vep))
2416     {
2417       clib_warning ("VCL<%d>: ERROR: vep_idx (%u) is not a vep!",
2418                     getpid (), vep_idx);
2419       goto done;
2420     }
2421   vep = &session->vep;
2422   clib_warning ("VCL<%d>: vep_idx (%u): Dumping epoll chain\n"
2423                 "{\n"
2424                 "   is_vep         = %u\n"
2425                 "   is_vep_session = %u\n"
2426                 "   next_sid       = 0x%x (%u)\n"
2427                 "   wait_cont_idx  = 0x%x (%u)\n"
2428                 "}\n", getpid (), vep_idx,
2429                 session->is_vep, session->is_vep_session,
2430                 vep->next_sh, vep->next_sh,
2431                 session->wait_cont_idx, session->wait_cont_idx);
2432
2433   for (sid = vep->next_sh; sid != ~0; sid = vep->next_sh)
2434     {
2435       session = vcl_session_get (wrk, sid);
2436       if (PREDICT_FALSE (!session))
2437         {
2438           clib_warning ("VCL<%d>: ERROR: Invalid sid (%u)!", getpid (), sid);
2439           goto done;
2440         }
2441       if (PREDICT_FALSE (session->is_vep))
2442         clib_warning ("VCL<%d>: ERROR: sid (%u) is a vep!",
2443                       getpid (), vep_idx);
2444       else if (PREDICT_FALSE (!session->is_vep_session))
2445         {
2446           clib_warning ("VCL<%d>: ERROR: session (%u) "
2447                         "is not a vep session!", getpid (), sid);
2448           goto done;
2449         }
2450       vep = &session->vep;
2451       if (PREDICT_FALSE (vep->vep_sh != vep_idx))
2452         clib_warning ("VCL<%d>: ERROR: session (%u) vep_idx (%u) != "
2453                       "vep_idx (%u)!", getpid (),
2454                       sid, session->vep.vep_sh, vep_idx);
2455       if (session->is_vep_session)
2456         {
2457           clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
2458                         "{\n"
2459                         "   next_sid       = 0x%x (%u)\n"
2460                         "   prev_sid       = 0x%x (%u)\n"
2461                         "   vep_idx        = 0x%x (%u)\n"
2462                         "   ev.events      = 0x%x\n"
2463                         "   ev.data.u64    = 0x%llx\n"
2464                         "   et_mask        = 0x%x\n"
2465                         "}\n",
2466                         vep_idx, sid, sid,
2467                         vep->next_sh, vep->next_sh,
2468                         vep->prev_sh, vep->prev_sh,
2469                         vep->vep_sh, vep->vep_sh,
2470                         vep->ev.events, vep->ev.data.u64, vep->et_mask);
2471         }
2472     }
2473
2474 done:
2475   clib_warning ("VCL<%d>: vep_idx (%u): Dump complete!\n",
2476                 getpid (), vep_idx);
2477 }
2478
2479 int
2480 vppcom_epoll_create (void)
2481 {
2482   vcl_worker_t *wrk = vcl_worker_get_current ();
2483   vcl_session_t *vep_session;
2484
2485   vep_session = vcl_session_alloc (wrk);
2486
2487   vep_session->is_vep = 1;
2488   vep_session->vep.vep_sh = ~0;
2489   vep_session->vep.next_sh = ~0;
2490   vep_session->vep.prev_sh = ~0;
2491   vep_session->wait_cont_idx = ~0;
2492   vep_session->vpp_handle = ~0;
2493
2494   vcl_evt (VCL_EVT_EPOLL_CREATE, vep_session, vep_session->session_index);
2495   VDBG (0, "Created vep_idx %u", vep_session->session_index);
2496
2497   return vcl_session_handle (vep_session);
2498 }
2499
2500 int
2501 vppcom_epoll_ctl (uint32_t vep_handle, int op, uint32_t session_handle,
2502                   struct epoll_event *event)
2503 {
2504   vcl_worker_t *wrk = vcl_worker_get_current ();
2505   vcl_session_t *vep_session;
2506   vcl_session_t *session;
2507   int rv = VPPCOM_OK;
2508
2509   if (vep_handle == session_handle)
2510     {
2511       VDBG (0, "vep_sh == session handle (%u)!", vep_handle);
2512       return VPPCOM_EINVAL;
2513     }
2514
2515   vep_session = vcl_session_get_w_handle (wrk, vep_handle);
2516   if (PREDICT_FALSE (!vep_session))
2517     {
2518       VDBG (0, "Invalid vep_sh (%u)!", vep_handle);
2519       return VPPCOM_EBADFD;
2520     }
2521   if (PREDICT_FALSE (!vep_session->is_vep))
2522     {
2523       VDBG (0, "vep_sh (%u) is not a vep!", vep_handle);
2524       return VPPCOM_EINVAL;
2525     }
2526
2527   ASSERT (vep_session->vep.vep_sh == ~0);
2528   ASSERT (vep_session->vep.prev_sh == ~0);
2529
2530   session = vcl_session_get_w_handle (wrk, session_handle);
2531   if (PREDICT_FALSE (!session))
2532     {
2533       VDBG (0, "Invalid session_handle (%u)!", session_handle);
2534       return VPPCOM_EBADFD;
2535     }
2536   if (PREDICT_FALSE (session->is_vep))
2537     {
2538       VDBG (0, "session_handle (%u) is a vep!", vep_handle);
2539       return VPPCOM_EINVAL;
2540     }
2541
2542   switch (op)
2543     {
2544     case EPOLL_CTL_ADD:
2545       if (PREDICT_FALSE (!event))
2546         {
2547           VDBG (0, "EPOLL_CTL_ADD: NULL pointer to epoll_event structure!");
2548           return VPPCOM_EINVAL;
2549         }
2550       if (vep_session->vep.next_sh != ~0)
2551         {
2552           vcl_session_t *next_session;
2553           next_session = vcl_session_get_w_handle (wrk,
2554                                                    vep_session->vep.next_sh);
2555           if (PREDICT_FALSE (!next_session))
2556             {
2557               VDBG (0, "EPOLL_CTL_ADD: Invalid vep.next_sid (%u) on "
2558                     "vep_idx (%u)!", vep_session->vep.next_sh, vep_handle);
2559               return VPPCOM_EBADFD;
2560             }
2561           ASSERT (next_session->vep.prev_sh == vep_handle);
2562           next_session->vep.prev_sh = session_handle;
2563         }
2564       session->vep.next_sh = vep_session->vep.next_sh;
2565       session->vep.prev_sh = vep_handle;
2566       session->vep.vep_sh = vep_handle;
2567       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2568       session->vep.ev = *event;
2569       session->is_vep = 0;
2570       session->is_vep_session = 1;
2571       vep_session->vep.next_sh = session_handle;
2572
2573       if (session->tx_fifo)
2574         svm_fifo_add_want_tx_ntf (session->tx_fifo,
2575                                   SVM_FIFO_WANT_TX_NOTIF_IF_FULL);
2576
2577       VDBG (1, "EPOLL_CTL_ADD: vep_sh %u, sh %u, events 0x%x, data 0x%llx!",
2578             vep_handle, session_handle, event->events, event->data.u64);
2579       vcl_evt (VCL_EVT_EPOLL_CTLADD, session, event->events, event->data.u64);
2580       break;
2581
2582     case EPOLL_CTL_MOD:
2583       if (PREDICT_FALSE (!event))
2584         {
2585           VDBG (0, "EPOLL_CTL_MOD: NULL pointer to epoll_event structure!");
2586           rv = VPPCOM_EINVAL;
2587           goto done;
2588         }
2589       else if (PREDICT_FALSE (!session->is_vep_session))
2590         {
2591           VDBG (0, "sid %u EPOLL_CTL_MOD: not a vep session!",
2592                 session_handle);
2593           rv = VPPCOM_EINVAL;
2594           goto done;
2595         }
2596       else if (PREDICT_FALSE (session->vep.vep_sh != vep_handle))
2597         {
2598           VDBG (0, "EPOLL_CTL_MOD: sh %u vep_sh (%u) != vep_sh (%u)!",
2599                 session_handle, session->vep.vep_sh, vep_handle);
2600           rv = VPPCOM_EINVAL;
2601           goto done;
2602         }
2603       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2604       session->vep.ev = *event;
2605       VDBG (1, "EPOLL_CTL_MOD: vep_sh %u, sh %u, events 0x%x, data 0x%llx!",
2606             vep_handle, session_handle, event->events, event->data.u64);
2607       break;
2608
2609     case EPOLL_CTL_DEL:
2610       if (PREDICT_FALSE (!session->is_vep_session))
2611         {
2612           VDBG (0, "EPOLL_CTL_DEL: %u not a vep session!", session_handle);
2613           rv = VPPCOM_EINVAL;
2614           goto done;
2615         }
2616       else if (PREDICT_FALSE (session->vep.vep_sh != vep_handle))
2617         {
2618           VDBG (0, "EPOLL_CTL_DEL: sh %u vep_sh (%u) != vep_sh (%u)!",
2619                 session_handle, session->vep.vep_sh, vep_handle);
2620           rv = VPPCOM_EINVAL;
2621           goto done;
2622         }
2623
2624       vep_session->wait_cont_idx =
2625         (vep_session->wait_cont_idx == session_handle) ?
2626         session->vep.next_sh : vep_session->wait_cont_idx;
2627
2628       if (session->vep.prev_sh == vep_handle)
2629         vep_session->vep.next_sh = session->vep.next_sh;
2630       else
2631         {
2632           vcl_session_t *prev_session;
2633           prev_session = vcl_session_get_w_handle (wrk, session->vep.prev_sh);
2634           if (PREDICT_FALSE (!prev_session))
2635             {
2636               VDBG (0, "EPOLL_CTL_DEL: Invalid prev_sid (%u) on sid (%u)!",
2637                     session->vep.prev_sh, session_handle);
2638               return VPPCOM_EBADFD;
2639             }
2640           ASSERT (prev_session->vep.next_sh == session_handle);
2641           prev_session->vep.next_sh = session->vep.next_sh;
2642         }
2643       if (session->vep.next_sh != ~0)
2644         {
2645           vcl_session_t *next_session;
2646           next_session = vcl_session_get_w_handle (wrk, session->vep.next_sh);
2647           if (PREDICT_FALSE (!next_session))
2648             {
2649               VDBG (0, "EPOLL_CTL_DEL: Invalid next_sid (%u) on sid (%u)!",
2650                     session->vep.next_sh, session_handle);
2651               return VPPCOM_EBADFD;
2652             }
2653           ASSERT (next_session->vep.prev_sh == session_handle);
2654           next_session->vep.prev_sh = session->vep.prev_sh;
2655         }
2656
2657       memset (&session->vep, 0, sizeof (session->vep));
2658       session->vep.next_sh = ~0;
2659       session->vep.prev_sh = ~0;
2660       session->vep.vep_sh = ~0;
2661       session->is_vep_session = 0;
2662
2663       if (session->tx_fifo)
2664         svm_fifo_del_want_tx_ntf (session->tx_fifo, SVM_FIFO_NO_TX_NOTIF);
2665
2666       VDBG (1, "EPOLL_CTL_DEL: vep_idx %u, sid %u!", vep_handle,
2667             session_handle);
2668       vcl_evt (VCL_EVT_EPOLL_CTLDEL, session, vep_sh);
2669       break;
2670
2671     default:
2672       VDBG (0, "Invalid operation (%d)!", op);
2673       rv = VPPCOM_EINVAL;
2674     }
2675
2676   vep_verify_epoll_chain (wrk, vep_handle);
2677
2678 done:
2679   return rv;
2680 }
2681
2682 static inline void
2683 vcl_epoll_wait_handle_mq_event (vcl_worker_t * wrk, session_event_t * e,
2684                                 struct epoll_event *events, u32 * num_ev)
2685 {
2686   session_disconnected_msg_t *disconnected_msg;
2687   session_connected_msg_t *connected_msg;
2688   u32 sid = ~0, session_events;
2689   u64 session_evt_data = ~0;
2690   vcl_session_t *session;
2691   u8 add_event = 0;
2692
2693   switch (e->event_type)
2694     {
2695     case FIFO_EVENT_APP_RX:
2696       ASSERT (e->fifo->client_thread_index == vcl_get_worker_index ());
2697       vcl_fifo_rx_evt_valid_or_break (e->fifo);
2698       sid = e->fifo->client_session_index;
2699       if (!(session = vcl_session_get (wrk, sid)))
2700         break;
2701       session_events = session->vep.ev.events;
2702       if (!(EPOLLIN & session->vep.ev.events) || session->has_rx_evt)
2703         break;
2704       add_event = 1;
2705       events[*num_ev].events |= EPOLLIN;
2706       session_evt_data = session->vep.ev.data.u64;
2707       session->has_rx_evt = 1;
2708       break;
2709     case FIFO_EVENT_APP_TX:
2710       sid = e->fifo->client_session_index;
2711       if (!(session = vcl_session_get (wrk, sid)))
2712         break;
2713       session_events = session->vep.ev.events;
2714       if (!(EPOLLOUT & session_events))
2715         break;
2716       add_event = 1;
2717       events[*num_ev].events |= EPOLLOUT;
2718       session_evt_data = session->vep.ev.data.u64;
2719       svm_fifo_reset_tx_ntf (session->tx_fifo);
2720       break;
2721     case SESSION_IO_EVT_CT_TX:
2722       vcl_fifo_rx_evt_valid_or_break (e->fifo);
2723       session = vcl_ct_session_get_from_fifo (wrk, e->fifo, 0);
2724       if (PREDICT_FALSE (!session))
2725         break;
2726       sid = session->session_index;
2727       session_events = session->vep.ev.events;
2728       if (!(EPOLLIN & session->vep.ev.events) || session->has_rx_evt)
2729         break;
2730       add_event = 1;
2731       events[*num_ev].events |= EPOLLIN;
2732       session_evt_data = session->vep.ev.data.u64;
2733       session->has_rx_evt = 1;
2734       break;
2735     case SESSION_IO_EVT_CT_RX:
2736       session = vcl_ct_session_get_from_fifo (wrk, e->fifo, 1);
2737       if (PREDICT_FALSE (!session))
2738         break;
2739       sid = session->session_index;
2740       session_events = session->vep.ev.events;
2741       if (!(EPOLLOUT & session_events))
2742         break;
2743       add_event = 1;
2744       events[*num_ev].events |= EPOLLOUT;
2745       session_evt_data = session->vep.ev.data.u64;
2746       svm_fifo_reset_tx_ntf (session->tx_fifo);
2747       break;
2748     case SESSION_CTRL_EVT_ACCEPTED:
2749       session = vcl_session_accepted (wrk,
2750                                       (session_accepted_msg_t *) e->data);
2751       if (!session)
2752         break;
2753
2754       session_events = session->vep.ev.events;
2755       if (!(EPOLLIN & session_events))
2756         break;
2757
2758       add_event = 1;
2759       events[*num_ev].events |= EPOLLIN;
2760       session_evt_data = session->vep.ev.data.u64;
2761       break;
2762     case SESSION_CTRL_EVT_CONNECTED:
2763       connected_msg = (session_connected_msg_t *) e->data;
2764       vcl_session_connected_handler (wrk, connected_msg);
2765       /* Generate EPOLLOUT because there's no connected event */
2766       sid = vcl_session_index_from_vpp_handle (wrk, connected_msg->handle);
2767       if (!(session = vcl_session_get (wrk, sid)))
2768         break;
2769       session_events = session->vep.ev.events;
2770       if (EPOLLOUT & session_events)
2771         {
2772           add_event = 1;
2773           events[*num_ev].events |= EPOLLOUT;
2774           session_evt_data = session->vep.ev.data.u64;
2775         }
2776       break;
2777     case SESSION_CTRL_EVT_DISCONNECTED:
2778       disconnected_msg = (session_disconnected_msg_t *) e->data;
2779       session = vcl_session_disconnected_handler (wrk, disconnected_msg);
2780       if (!session)
2781         break;
2782       add_event = 1;
2783       events[*num_ev].events |= EPOLLHUP | EPOLLRDHUP;
2784       session_evt_data = session->vep.ev.data.u64;
2785       session_events = session->vep.ev.events;
2786       break;
2787     case SESSION_CTRL_EVT_RESET:
2788       sid = vcl_session_reset_handler (wrk, (session_reset_msg_t *) e->data);
2789       if (!(session = vcl_session_get (wrk, sid)))
2790         break;
2791       add_event = 1;
2792       events[*num_ev].events |= EPOLLHUP | EPOLLRDHUP;
2793       session_evt_data = session->vep.ev.data.u64;
2794       session_events = session->vep.ev.events;
2795       break;
2796     case SESSION_CTRL_EVT_REQ_WORKER_UPDATE:
2797       vcl_session_req_worker_update_handler (wrk, e->data);
2798       break;
2799     case SESSION_CTRL_EVT_WORKER_UPDATE_REPLY:
2800       vcl_session_worker_update_reply_handler (wrk, e->data);
2801       break;
2802     default:
2803       VDBG (0, "unhandled: %u", e->event_type);
2804       break;
2805     }
2806
2807   if (add_event)
2808     {
2809       events[*num_ev].data.u64 = session_evt_data;
2810       if (EPOLLONESHOT & session_events)
2811         {
2812           session = vcl_session_get (wrk, sid);
2813           session->vep.ev.events = 0;
2814         }
2815       *num_ev += 1;
2816     }
2817 }
2818
2819 static int
2820 vcl_epoll_wait_handle_mq (vcl_worker_t * wrk, svm_msg_q_t * mq,
2821                           struct epoll_event *events, u32 maxevents,
2822                           double wait_for_time, u32 * num_ev)
2823 {
2824   svm_msg_q_msg_t *msg;
2825   session_event_t *e;
2826   int i;
2827
2828   if (vec_len (wrk->mq_msg_vector) && svm_msg_q_is_empty (mq))
2829     goto handle_dequeued;
2830
2831   svm_msg_q_lock (mq);
2832   if (svm_msg_q_is_empty (mq))
2833     {
2834       if (!wait_for_time)
2835         {
2836           svm_msg_q_unlock (mq);
2837           return 0;
2838         }
2839       else if (wait_for_time < 0)
2840         {
2841           svm_msg_q_wait (mq);
2842         }
2843       else
2844         {
2845           if (svm_msg_q_timedwait (mq, wait_for_time / 1e3))
2846             {
2847               svm_msg_q_unlock (mq);
2848               return 0;
2849             }
2850         }
2851     }
2852   vcl_mq_dequeue_batch (wrk, mq);
2853   svm_msg_q_unlock (mq);
2854
2855 handle_dequeued:
2856   for (i = 0; i < vec_len (wrk->mq_msg_vector); i++)
2857     {
2858       msg = vec_elt_at_index (wrk->mq_msg_vector, i);
2859       e = svm_msg_q_msg_data (mq, msg);
2860       if (*num_ev < maxevents)
2861         vcl_epoll_wait_handle_mq_event (wrk, e, events, num_ev);
2862       else
2863         vec_add1 (wrk->unhandled_evts_vector, *e);
2864       svm_msg_q_free_msg (mq, msg);
2865     }
2866   vec_reset_length (wrk->mq_msg_vector);
2867   vcl_handle_pending_wrk_updates (wrk);
2868   return *num_ev;
2869 }
2870
2871 static int
2872 vppcom_epoll_wait_condvar (vcl_worker_t * wrk, struct epoll_event *events,
2873                            int maxevents, u32 n_evts, double wait_for_time)
2874 {
2875   vcl_cut_through_registration_t *cr;
2876   double total_wait = 0, wait_slice;
2877   int rv;
2878
2879   wait_for_time = (wait_for_time == -1) ? (double) 10e9 : wait_for_time;
2880   wait_slice = wrk->cut_through_registrations ? 10e-6 : wait_for_time;
2881
2882   do
2883     {
2884       vcl_ct_registration_lock (wrk);
2885       /* *INDENT-OFF* */
2886       pool_foreach (cr, wrk->cut_through_registrations, ({
2887         vcl_epoll_wait_handle_mq (wrk, cr->mq, events, maxevents, 0, &n_evts);
2888       }));
2889       /* *INDENT-ON* */
2890       vcl_ct_registration_unlock (wrk);
2891
2892       rv = vcl_epoll_wait_handle_mq (wrk, wrk->app_event_queue, events,
2893                                      maxevents, n_evts ? 0 : wait_slice,
2894                                      &n_evts);
2895       if (rv)
2896         total_wait += wait_slice;
2897       if (n_evts)
2898         return n_evts;
2899     }
2900   while (total_wait < wait_for_time);
2901   return n_evts;
2902 }
2903
2904 static int
2905 vppcom_epoll_wait_eventfd (vcl_worker_t * wrk, struct epoll_event *events,
2906                            int maxevents, u32 n_evts, double wait_for_time)
2907 {
2908   vcl_mq_evt_conn_t *mqc;
2909   int __clib_unused n_read;
2910   int n_mq_evts, i;
2911   u64 buf;
2912
2913   vec_validate (wrk->mq_events, pool_elts (wrk->mq_evt_conns));
2914 again:
2915   n_mq_evts = epoll_wait (wrk->mqs_epfd, wrk->mq_events,
2916                           vec_len (wrk->mq_events), wait_for_time);
2917   for (i = 0; i < n_mq_evts; i++)
2918     {
2919       mqc = vcl_mq_evt_conn_get (wrk, wrk->mq_events[i].data.u32);
2920       n_read = read (mqc->mq_fd, &buf, sizeof (buf));
2921       vcl_epoll_wait_handle_mq (wrk, mqc->mq, events, maxevents, 0, &n_evts);
2922     }
2923   if (!n_evts && n_mq_evts > 0)
2924     goto again;
2925
2926   return (int) n_evts;
2927 }
2928
2929 int
2930 vppcom_epoll_wait (uint32_t vep_handle, struct epoll_event *events,
2931                    int maxevents, double wait_for_time)
2932 {
2933   vcl_worker_t *wrk = vcl_worker_get_current ();
2934   vcl_session_t *vep_session;
2935   u32 n_evts = 0;
2936   int i;
2937
2938   if (PREDICT_FALSE (maxevents <= 0))
2939     {
2940       clib_warning ("VCL<%d>: ERROR: Invalid maxevents (%d)!",
2941                     getpid (), maxevents);
2942       return VPPCOM_EINVAL;
2943     }
2944
2945   vep_session = vcl_session_get_w_handle (wrk, vep_handle);
2946   if (!vep_session)
2947     return VPPCOM_EBADFD;
2948
2949   if (PREDICT_FALSE (!vep_session->is_vep))
2950     {
2951       clib_warning ("VCL<%d>: ERROR: vep_idx (%u) is not a vep!",
2952                     getpid (), vep_handle);
2953       return VPPCOM_EINVAL;
2954     }
2955
2956   memset (events, 0, sizeof (*events) * maxevents);
2957
2958   if (vec_len (wrk->unhandled_evts_vector))
2959     {
2960       for (i = 0; i < vec_len (wrk->unhandled_evts_vector); i++)
2961         {
2962           vcl_epoll_wait_handle_mq_event (wrk, &wrk->unhandled_evts_vector[i],
2963                                           events, &n_evts);
2964           if (n_evts == maxevents)
2965             {
2966               i += 1;
2967               break;
2968             }
2969         }
2970
2971       vec_delete (wrk->unhandled_evts_vector, i, 0);
2972     }
2973
2974   if (vcm->cfg.use_mq_eventfd)
2975     return vppcom_epoll_wait_eventfd (wrk, events, maxevents, n_evts,
2976                                       wait_for_time);
2977
2978   return vppcom_epoll_wait_condvar (wrk, events, maxevents, n_evts,
2979                                     wait_for_time);
2980 }
2981
2982 int
2983 vppcom_session_attr (uint32_t session_handle, uint32_t op,
2984                      void *buffer, uint32_t * buflen)
2985 {
2986   vcl_worker_t *wrk = vcl_worker_get_current ();
2987   vcl_session_t *session;
2988   int rv = VPPCOM_OK;
2989   u32 *flags = buffer, tmp_flags = 0;
2990   vppcom_endpt_t *ep = buffer;
2991
2992   session = vcl_session_get_w_handle (wrk, session_handle);
2993   if (!session)
2994     return VPPCOM_EBADFD;
2995
2996   switch (op)
2997     {
2998     case VPPCOM_ATTR_GET_NREAD:
2999       rv = vppcom_session_read_ready (session);
3000       VDBG (2, "VPPCOM_ATTR_GET_NREAD: sid %u, nread = %d", rv);
3001       break;
3002
3003     case VPPCOM_ATTR_GET_NWRITE:
3004       rv = vppcom_session_write_ready (session);
3005       VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_NWRITE: sid %u, nwrite = %d",
3006             getpid (), session_handle, rv);
3007       break;
3008
3009     case VPPCOM_ATTR_GET_FLAGS:
3010       if (PREDICT_TRUE (buffer && buflen && (*buflen >= sizeof (*flags))))
3011         {
3012           *flags = O_RDWR | (VCL_SESS_ATTR_TEST (session->attr,
3013                                                  VCL_SESS_ATTR_NONBLOCK));
3014           *buflen = sizeof (*flags);
3015           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_FLAGS: sid %u, flags = 0x%08x, "
3016                 "is_nonblocking = %u", getpid (),
3017                 session_handle, *flags,
3018                 VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_NONBLOCK));
3019         }
3020       else
3021         rv = VPPCOM_EINVAL;
3022       break;
3023
3024     case VPPCOM_ATTR_SET_FLAGS:
3025       if (PREDICT_TRUE (buffer && buflen && (*buflen == sizeof (*flags))))
3026         {
3027           if (*flags & O_NONBLOCK)
3028             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_NONBLOCK);
3029           else
3030             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_NONBLOCK);
3031
3032           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_FLAGS: sid %u, flags = 0x%08x,"
3033                 " is_nonblocking = %u",
3034                 getpid (), session_handle, *flags,
3035                 VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_NONBLOCK));
3036         }
3037       else
3038         rv = VPPCOM_EINVAL;
3039       break;
3040
3041     case VPPCOM_ATTR_GET_PEER_ADDR:
3042       if (PREDICT_TRUE (buffer && buflen &&
3043                         (*buflen >= sizeof (*ep)) && ep->ip))
3044         {
3045           ep->is_ip4 = session->transport.is_ip4;
3046           ep->port = session->transport.rmt_port;
3047           if (session->transport.is_ip4)
3048             clib_memcpy_fast (ep->ip, &session->transport.rmt_ip.ip4,
3049                               sizeof (ip4_address_t));
3050           else
3051             clib_memcpy_fast (ep->ip, &session->transport.rmt_ip.ip6,
3052                               sizeof (ip6_address_t));
3053           *buflen = sizeof (*ep);
3054           VDBG (1, "VCL<%d>: VPPCOM_ATTR_GET_PEER_ADDR: sid %u, is_ip4 = %u, "
3055                 "addr = %U, port %u", getpid (),
3056                 session_handle, ep->is_ip4, format_ip46_address,
3057                 &session->transport.rmt_ip,
3058                 ep->is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
3059                 clib_net_to_host_u16 (ep->port));
3060         }
3061       else
3062         rv = VPPCOM_EINVAL;
3063       break;
3064
3065     case VPPCOM_ATTR_GET_LCL_ADDR:
3066       if (PREDICT_TRUE (buffer && buflen &&
3067                         (*buflen >= sizeof (*ep)) && ep->ip))
3068         {
3069           ep->is_ip4 = session->transport.is_ip4;
3070           ep->port = session->transport.lcl_port;
3071           if (session->transport.is_ip4)
3072             clib_memcpy_fast (ep->ip, &session->transport.lcl_ip.ip4,
3073                               sizeof (ip4_address_t));
3074           else
3075             clib_memcpy_fast (ep->ip, &session->transport.lcl_ip.ip6,
3076                               sizeof (ip6_address_t));
3077           *buflen = sizeof (*ep);
3078           VDBG (1, "VCL<%d>: VPPCOM_ATTR_GET_LCL_ADDR: sid %u, is_ip4 = %u,"
3079                 " addr = %U port %d", getpid (),
3080                 session_handle, ep->is_ip4, format_ip46_address,
3081                 &session->transport.lcl_ip,
3082                 ep->is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
3083                 clib_net_to_host_u16 (ep->port));
3084         }
3085       else
3086         rv = VPPCOM_EINVAL;
3087       break;
3088
3089     case VPPCOM_ATTR_GET_LIBC_EPFD:
3090       rv = session->libc_epfd;
3091       VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_LIBC_EPFD: libc_epfd %d",
3092             getpid (), rv);
3093       break;
3094
3095     case VPPCOM_ATTR_SET_LIBC_EPFD:
3096       if (PREDICT_TRUE (buffer && buflen &&
3097                         (*buflen == sizeof (session->libc_epfd))))
3098         {
3099           session->libc_epfd = *(int *) buffer;
3100           *buflen = sizeof (session->libc_epfd);
3101
3102           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_LIBC_EPFD: libc_epfd %d, "
3103                 "buflen %d", getpid (), session->libc_epfd, *buflen);
3104         }
3105       else
3106         rv = VPPCOM_EINVAL;
3107       break;
3108
3109     case VPPCOM_ATTR_GET_PROTOCOL:
3110       if (buffer && buflen && (*buflen >= sizeof (int)))
3111         {
3112           *(int *) buffer = session->session_type;
3113           *buflen = sizeof (int);
3114
3115           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_PROTOCOL: %d (%s), buflen %d",
3116                 getpid (), *(int *) buffer, *(int *) buffer ? "UDP" : "TCP",
3117                 *buflen);
3118         }
3119       else
3120         rv = VPPCOM_EINVAL;
3121       break;
3122
3123     case VPPCOM_ATTR_GET_LISTEN:
3124       if (buffer && buflen && (*buflen >= sizeof (int)))
3125         {
3126           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3127                                                 VCL_SESS_ATTR_LISTEN);
3128           *buflen = sizeof (int);
3129
3130           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_LISTEN: %d, buflen %d",
3131                 getpid (), *(int *) buffer, *buflen);
3132         }
3133       else
3134         rv = VPPCOM_EINVAL;
3135       break;
3136
3137     case VPPCOM_ATTR_GET_ERROR:
3138       if (buffer && buflen && (*buflen >= sizeof (int)))
3139         {
3140           *(int *) buffer = 0;
3141           *buflen = sizeof (int);
3142
3143           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_ERROR: %d, buflen %d, #VPP-TBD#",
3144                 getpid (), *(int *) buffer, *buflen);
3145         }
3146       else
3147         rv = VPPCOM_EINVAL;
3148       break;
3149
3150     case VPPCOM_ATTR_GET_TX_FIFO_LEN:
3151       if (buffer && buflen && (*buflen >= sizeof (u32)))
3152         {
3153
3154           /* VPP-TBD */
3155           *(size_t *) buffer = (session->sndbuf_size ? session->sndbuf_size :
3156                                 session->tx_fifo ? session->tx_fifo->nitems :
3157                                 vcm->cfg.tx_fifo_size);
3158           *buflen = sizeof (u32);
3159
3160           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_TX_FIFO_LEN: %u (0x%x), "
3161                 "buflen %d, #VPP-TBD#", getpid (),
3162                 *(size_t *) buffer, *(size_t *) buffer, *buflen);
3163         }
3164       else
3165         rv = VPPCOM_EINVAL;
3166       break;
3167
3168     case VPPCOM_ATTR_SET_TX_FIFO_LEN:
3169       if (buffer && buflen && (*buflen == sizeof (u32)))
3170         {
3171           /* VPP-TBD */
3172           session->sndbuf_size = *(u32 *) buffer;
3173           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_TX_FIFO_LEN: %u (0x%x), "
3174                 "buflen %d, #VPP-TBD#", getpid (),
3175                 session->sndbuf_size, session->sndbuf_size, *buflen);
3176         }
3177       else
3178         rv = VPPCOM_EINVAL;
3179       break;
3180
3181     case VPPCOM_ATTR_GET_RX_FIFO_LEN:
3182       if (buffer && buflen && (*buflen >= sizeof (u32)))
3183         {
3184
3185           /* VPP-TBD */
3186           *(size_t *) buffer = (session->rcvbuf_size ? session->rcvbuf_size :
3187                                 session->rx_fifo ? session->rx_fifo->nitems :
3188                                 vcm->cfg.rx_fifo_size);
3189           *buflen = sizeof (u32);
3190
3191           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_RX_FIFO_LEN: %u (0x%x), "
3192                 "buflen %d, #VPP-TBD#", getpid (),
3193                 *(size_t *) buffer, *(size_t *) buffer, *buflen);
3194         }
3195       else
3196         rv = VPPCOM_EINVAL;
3197       break;
3198
3199     case VPPCOM_ATTR_SET_RX_FIFO_LEN:
3200       if (buffer && buflen && (*buflen == sizeof (u32)))
3201         {
3202           /* VPP-TBD */
3203           session->rcvbuf_size = *(u32 *) buffer;
3204           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_RX_FIFO_LEN: %u (0x%x), "
3205                 "buflen %d, #VPP-TBD#", getpid (),
3206                 session->sndbuf_size, session->sndbuf_size, *buflen);
3207         }
3208       else
3209         rv = VPPCOM_EINVAL;
3210       break;
3211
3212     case VPPCOM_ATTR_GET_REUSEADDR:
3213       if (buffer && buflen && (*buflen >= sizeof (int)))
3214         {
3215           /* VPP-TBD */
3216           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3217                                                 VCL_SESS_ATTR_REUSEADDR);
3218           *buflen = sizeof (int);
3219
3220           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_REUSEADDR: %d, "
3221                 "buflen %d, #VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3222         }
3223       else
3224         rv = VPPCOM_EINVAL;
3225       break;
3226
3227     case VPPCOM_ATTR_SET_REUSEADDR:
3228       if (buffer && buflen && (*buflen == sizeof (int)) &&
3229           !VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_LISTEN))
3230         {
3231           /* VPP-TBD */
3232           if (*(int *) buffer)
3233             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_REUSEADDR);
3234           else
3235             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_REUSEADDR);
3236
3237           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_REUSEADDR: %d, buflen %d,"
3238                 " #VPP-TBD#", getpid (),
3239                 VCL_SESS_ATTR_TEST (session->attr,
3240                                     VCL_SESS_ATTR_REUSEADDR), *buflen);
3241         }
3242       else
3243         rv = VPPCOM_EINVAL;
3244       break;
3245
3246     case VPPCOM_ATTR_GET_REUSEPORT:
3247       if (buffer && buflen && (*buflen >= sizeof (int)))
3248         {
3249           /* VPP-TBD */
3250           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3251                                                 VCL_SESS_ATTR_REUSEPORT);
3252           *buflen = sizeof (int);
3253
3254           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_REUSEPORT: %d, buflen %d,"
3255                 " #VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3256         }
3257       else
3258         rv = VPPCOM_EINVAL;
3259       break;
3260
3261     case VPPCOM_ATTR_SET_REUSEPORT:
3262       if (buffer && buflen && (*buflen == sizeof (int)) &&
3263           !VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_LISTEN))
3264         {
3265           /* VPP-TBD */
3266           if (*(int *) buffer)
3267             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_REUSEPORT);
3268           else
3269             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_REUSEPORT);
3270
3271           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_REUSEPORT: %d, buflen %d,"
3272                 " #VPP-TBD#", getpid (),
3273                 VCL_SESS_ATTR_TEST (session->attr,
3274                                     VCL_SESS_ATTR_REUSEPORT), *buflen);
3275         }
3276       else
3277         rv = VPPCOM_EINVAL;
3278       break;
3279
3280     case VPPCOM_ATTR_GET_BROADCAST:
3281       if (buffer && buflen && (*buflen >= sizeof (int)))
3282         {
3283           /* VPP-TBD */
3284           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3285                                                 VCL_SESS_ATTR_BROADCAST);
3286           *buflen = sizeof (int);
3287
3288           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_BROADCAST: %d, buflen %d,"
3289                 " #VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3290         }
3291       else
3292         rv = VPPCOM_EINVAL;
3293       break;
3294
3295     case VPPCOM_ATTR_SET_BROADCAST:
3296       if (buffer && buflen && (*buflen == sizeof (int)))
3297         {
3298           /* VPP-TBD */
3299           if (*(int *) buffer)
3300             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_BROADCAST);
3301           else
3302             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_BROADCAST);
3303
3304           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_BROADCAST: %d, buflen %d, "
3305                 "#VPP-TBD#", getpid (),
3306                 VCL_SESS_ATTR_TEST (session->attr,
3307                                     VCL_SESS_ATTR_BROADCAST), *buflen);
3308         }
3309       else
3310         rv = VPPCOM_EINVAL;
3311       break;
3312
3313     case VPPCOM_ATTR_GET_V6ONLY:
3314       if (buffer && buflen && (*buflen >= sizeof (int)))
3315         {
3316           /* VPP-TBD */
3317           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3318                                                 VCL_SESS_ATTR_V6ONLY);
3319           *buflen = sizeof (int);
3320
3321           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_V6ONLY: %d, buflen %d, "
3322                 "#VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3323         }
3324       else
3325         rv = VPPCOM_EINVAL;
3326       break;
3327
3328     case VPPCOM_ATTR_SET_V6ONLY:
3329       if (buffer && buflen && (*buflen == sizeof (int)))
3330         {
3331           /* VPP-TBD */
3332           if (*(int *) buffer)
3333             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_V6ONLY);
3334           else
3335             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_V6ONLY);
3336
3337           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_V6ONLY: %d, buflen %d, "
3338                 "#VPP-TBD#", getpid (),
3339                 VCL_SESS_ATTR_TEST (session->attr,
3340                                     VCL_SESS_ATTR_V6ONLY), *buflen);
3341         }
3342       else
3343         rv = VPPCOM_EINVAL;
3344       break;
3345
3346     case VPPCOM_ATTR_GET_KEEPALIVE:
3347       if (buffer && buflen && (*buflen >= sizeof (int)))
3348         {
3349           /* VPP-TBD */
3350           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3351                                                 VCL_SESS_ATTR_KEEPALIVE);
3352           *buflen = sizeof (int);
3353
3354           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_KEEPALIVE: %d, buflen %d, "
3355                 "#VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3356         }
3357       else
3358         rv = VPPCOM_EINVAL;
3359       break;
3360
3361     case VPPCOM_ATTR_SET_KEEPALIVE:
3362       if (buffer && buflen && (*buflen == sizeof (int)))
3363         {
3364           /* VPP-TBD */
3365           if (*(int *) buffer)
3366             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_KEEPALIVE);
3367           else
3368             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_KEEPALIVE);
3369
3370           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_KEEPALIVE: %d, buflen %d, "
3371                 "#VPP-TBD#", getpid (),
3372                 VCL_SESS_ATTR_TEST (session->attr,
3373                                     VCL_SESS_ATTR_KEEPALIVE), *buflen);
3374         }
3375       else
3376         rv = VPPCOM_EINVAL;
3377       break;
3378
3379     case VPPCOM_ATTR_GET_TCP_NODELAY:
3380       if (buffer && buflen && (*buflen >= sizeof (int)))
3381         {
3382           /* VPP-TBD */
3383           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3384                                                 VCL_SESS_ATTR_TCP_NODELAY);
3385           *buflen = sizeof (int);
3386
3387           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_TCP_NODELAY: %d, buflen %d, "
3388                 "#VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3389         }
3390       else
3391         rv = VPPCOM_EINVAL;
3392       break;
3393
3394     case VPPCOM_ATTR_SET_TCP_NODELAY:
3395       if (buffer && buflen && (*buflen == sizeof (int)))
3396         {
3397           /* VPP-TBD */
3398           if (*(int *) buffer)
3399             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_TCP_NODELAY);
3400           else
3401             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_TCP_NODELAY);
3402
3403           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_TCP_NODELAY: %d, buflen %d, "
3404                 "#VPP-TBD#", getpid (),
3405                 VCL_SESS_ATTR_TEST (session->attr,
3406                                     VCL_SESS_ATTR_TCP_NODELAY), *buflen);
3407         }
3408       else
3409         rv = VPPCOM_EINVAL;
3410       break;
3411
3412     case VPPCOM_ATTR_GET_TCP_KEEPIDLE:
3413       if (buffer && buflen && (*buflen >= sizeof (int)))
3414         {
3415           /* VPP-TBD */
3416           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3417                                                 VCL_SESS_ATTR_TCP_KEEPIDLE);
3418           *buflen = sizeof (int);
3419
3420           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_TCP_KEEPIDLE: %d, buflen %d, "
3421                 "#VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3422         }
3423       else
3424         rv = VPPCOM_EINVAL;
3425       break;
3426
3427     case VPPCOM_ATTR_SET_TCP_KEEPIDLE:
3428       if (buffer && buflen && (*buflen == sizeof (int)))
3429         {
3430           /* VPP-TBD */
3431           if (*(int *) buffer)
3432             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_TCP_KEEPIDLE);
3433           else
3434             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_TCP_KEEPIDLE);
3435
3436           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_TCP_KEEPIDLE: %d, buflen %d, "
3437                 "#VPP-TBD#", getpid (),
3438                 VCL_SESS_ATTR_TEST (session->attr,
3439                                     VCL_SESS_ATTR_TCP_KEEPIDLE), *buflen);
3440         }
3441       else
3442         rv = VPPCOM_EINVAL;
3443       break;
3444
3445     case VPPCOM_ATTR_GET_TCP_KEEPINTVL:
3446       if (buffer && buflen && (*buflen >= sizeof (int)))
3447         {
3448           /* VPP-TBD */
3449           *(int *) buffer = VCL_SESS_ATTR_TEST (session->attr,
3450                                                 VCL_SESS_ATTR_TCP_KEEPINTVL);
3451           *buflen = sizeof (int);
3452
3453           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_TCP_KEEPINTVL: %d, buflen %d, "
3454                 "#VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3455         }
3456       else
3457         rv = VPPCOM_EINVAL;
3458       break;
3459
3460     case VPPCOM_ATTR_SET_TCP_KEEPINTVL:
3461       if (buffer && buflen && (*buflen == sizeof (int)))
3462         {
3463           /* VPP-TBD */
3464           if (*(int *) buffer)
3465             VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_TCP_KEEPINTVL);
3466           else
3467             VCL_SESS_ATTR_CLR (session->attr, VCL_SESS_ATTR_TCP_KEEPINTVL);
3468
3469           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_TCP_KEEPINTVL: %d, buflen %d, "
3470                 "#VPP-TBD#", getpid (),
3471                 VCL_SESS_ATTR_TEST (session->attr,
3472                                     VCL_SESS_ATTR_TCP_KEEPINTVL), *buflen);
3473         }
3474       else
3475         rv = VPPCOM_EINVAL;
3476       break;
3477
3478     case VPPCOM_ATTR_GET_TCP_USER_MSS:
3479       if (buffer && buflen && (*buflen >= sizeof (u32)))
3480         {
3481           /* VPP-TBD */
3482           *(u32 *) buffer = session->user_mss;
3483           *buflen = sizeof (int);
3484
3485           VDBG (2, "VCL<%d>: VPPCOM_ATTR_GET_TCP_USER_MSS: %d, buflen %d,"
3486                 " #VPP-TBD#", getpid (), *(int *) buffer, *buflen);
3487         }
3488       else
3489         rv = VPPCOM_EINVAL;
3490       break;
3491
3492     case VPPCOM_ATTR_SET_TCP_USER_MSS:
3493       if (buffer && buflen && (*buflen == sizeof (u32)))
3494         {
3495           /* VPP-TBD */
3496           session->user_mss = *(u32 *) buffer;
3497
3498           VDBG (2, "VCL<%d>: VPPCOM_ATTR_SET_TCP_USER_MSS: %u, buflen %d, "
3499                 "#VPP-TBD#", getpid (), session->user_mss, *buflen);
3500         }
3501       else
3502         rv = VPPCOM_EINVAL;
3503       break;
3504
3505     case VPPCOM_ATTR_GET_REFCNT:
3506       rv = vcl_session_get_refcnt (session);
3507       break;
3508
3509     case VPPCOM_ATTR_SET_SHUT:
3510       if (*flags == SHUT_RD || *flags == SHUT_RDWR)
3511         VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_SHUT_RD);
3512       if (*flags == SHUT_WR || *flags == SHUT_RDWR)
3513         VCL_SESS_ATTR_SET (session->attr, VCL_SESS_ATTR_SHUT_WR);
3514       break;
3515
3516     case VPPCOM_ATTR_GET_SHUT:
3517       if (VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_SHUT_RD))
3518         tmp_flags = 1;
3519       if (VCL_SESS_ATTR_TEST (session->attr, VCL_SESS_ATTR_SHUT_WR))
3520         tmp_flags |= 2;
3521       if (tmp_flags == 1)
3522         *(int *) buffer = SHUT_RD;
3523       else if (tmp_flags == 2)
3524         *(int *) buffer = SHUT_WR;
3525       else if (tmp_flags == 3)
3526         *(int *) buffer = SHUT_RDWR;
3527       *buflen = sizeof (int);
3528       break;
3529     default:
3530       rv = VPPCOM_EINVAL;
3531       break;
3532     }
3533
3534   return rv;
3535 }
3536
3537 int
3538 vppcom_session_recvfrom (uint32_t session_handle, void *buffer,
3539                          uint32_t buflen, int flags, vppcom_endpt_t * ep)
3540 {
3541   vcl_worker_t *wrk = vcl_worker_get_current ();
3542   int rv = VPPCOM_OK;
3543   vcl_session_t *session = 0;
3544
3545   if (ep)
3546     {
3547       session = vcl_session_get_w_handle (wrk, session_handle);
3548       if (PREDICT_FALSE (!session))
3549         {
3550           VDBG (0, "VCL<%d>: invalid session, sid (%u) has been closed!",
3551                 getpid (), session_handle);
3552           return VPPCOM_EBADFD;
3553         }
3554       ep->is_ip4 = session->transport.is_ip4;
3555       ep->port = session->transport.rmt_port;
3556     }
3557
3558   if (flags == 0)
3559     rv = vppcom_session_read (session_handle, buffer, buflen);
3560   else if (flags & MSG_PEEK)
3561     rv = vppcom_session_peek (session_handle, buffer, buflen);
3562   else
3563     {
3564       VDBG (0, "Unsupport flags for recvfrom %d", flags);
3565       return VPPCOM_EAFNOSUPPORT;
3566     }
3567
3568   if (ep)
3569     {
3570       if (session->transport.is_ip4)
3571         clib_memcpy_fast (ep->ip, &session->transport.rmt_ip.ip4,
3572                           sizeof (ip4_address_t));
3573       else
3574         clib_memcpy_fast (ep->ip, &session->transport.rmt_ip.ip6,
3575                           sizeof (ip6_address_t));
3576     }
3577
3578   return rv;
3579 }
3580
3581 int
3582 vppcom_session_sendto (uint32_t session_handle, void *buffer,
3583                        uint32_t buflen, int flags, vppcom_endpt_t * ep)
3584 {
3585   if (!buffer)
3586     return VPPCOM_EINVAL;
3587
3588   if (ep)
3589     {
3590       // TBD
3591       return VPPCOM_EINVAL;
3592     }
3593
3594   if (flags)
3595     {
3596       // TBD check the flags and do the right thing
3597       VDBG (2, "VCL<%d>: handling flags 0x%u (%d) not implemented yet.",
3598             getpid (), flags, flags);
3599     }
3600
3601   return (vppcom_session_write_inline (session_handle, buffer, buflen, 1));
3602 }
3603
3604 int
3605 vppcom_poll (vcl_poll_t * vp, uint32_t n_sids, double wait_for_time)
3606 {
3607   vcl_worker_t *wrk = vcl_worker_get_current ();
3608   f64 timeout = clib_time_now (&wrk->clib_time) + wait_for_time;
3609   u32 i, keep_trying = 1;
3610   svm_msg_q_msg_t msg;
3611   session_event_t *e;
3612   int rv, num_ev = 0;
3613
3614   VDBG (3, "VCL<%d>: vp %p, nsids %u, wait_for_time %f",
3615         getpid (), vp, n_sids, wait_for_time);
3616
3617   if (!vp)
3618     return VPPCOM_EFAULT;
3619
3620   do
3621     {
3622       vcl_session_t *session;
3623
3624       /* Dequeue all events and drop all unhandled io events */
3625       while (svm_msg_q_sub (wrk->app_event_queue, &msg, SVM_Q_NOWAIT, 0) == 0)
3626         {
3627           e = svm_msg_q_msg_data (wrk->app_event_queue, &msg);
3628           vcl_handle_mq_event (wrk, e);
3629           svm_msg_q_free_msg (wrk->app_event_queue, &msg);
3630         }
3631       vec_reset_length (wrk->unhandled_evts_vector);
3632
3633       for (i = 0; i < n_sids; i++)
3634         {
3635           session = vcl_session_get (wrk, vp[i].sh);
3636           if (!session)
3637             {
3638               vp[i].revents = POLLHUP;
3639               num_ev++;
3640               continue;
3641             }
3642
3643           vp[i].revents = 0;
3644
3645           if (POLLIN & vp[i].events)
3646             {
3647               rv = vppcom_session_read_ready (session);
3648               if (rv > 0)
3649                 {
3650                   vp[i].revents |= POLLIN;
3651                   num_ev++;
3652                 }
3653               else if (rv < 0)
3654                 {
3655                   switch (rv)
3656                     {
3657                     case VPPCOM_ECONNRESET:
3658                       vp[i].revents = POLLHUP;
3659                       break;
3660
3661                     default:
3662                       vp[i].revents = POLLERR;
3663                       break;
3664                     }
3665                   num_ev++;
3666                 }
3667             }
3668
3669           if (POLLOUT & vp[i].events)
3670             {
3671               rv = vppcom_session_write_ready (session);
3672               if (rv > 0)
3673                 {
3674                   vp[i].revents |= POLLOUT;
3675                   num_ev++;
3676                 }
3677               else if (rv < 0)
3678                 {
3679                   switch (rv)
3680                     {
3681                     case VPPCOM_ECONNRESET:
3682                       vp[i].revents = POLLHUP;
3683                       break;
3684
3685                     default:
3686                       vp[i].revents = POLLERR;
3687                       break;
3688                     }
3689                   num_ev++;
3690                 }
3691             }
3692
3693           if (0)                // Note "done:" label used by VCL_SESSION_LOCK_AND_GET()
3694             {
3695               vp[i].revents = POLLNVAL;
3696               num_ev++;
3697             }
3698         }
3699       if (wait_for_time != -1)
3700         keep_trying = (clib_time_now (&wrk->clib_time) <= timeout) ? 1 : 0;
3701     }
3702   while ((num_ev == 0) && keep_trying);
3703
3704   if (VPPCOM_DEBUG > 3)
3705     {
3706       clib_warning ("VCL<%d>: returning %d", getpid (), num_ev);
3707       for (i = 0; i < n_sids; i++)
3708         {
3709           clib_warning ("VCL<%d>: vp[%d].sid %d (0x%x), .events 0x%x, "
3710                         ".revents 0x%x", getpid (), i, vp[i].sh, vp[i].sh,
3711                         vp[i].events, vp[i].revents);
3712         }
3713     }
3714   return num_ev;
3715 }
3716
3717 int
3718 vppcom_mq_epoll_fd (void)
3719 {
3720   vcl_worker_t *wrk = vcl_worker_get_current ();
3721   return wrk->mqs_epfd;
3722 }
3723
3724 int
3725 vppcom_session_index (vcl_session_handle_t session_handle)
3726 {
3727   return session_handle & 0xFFFFFF;
3728 }
3729
3730 int
3731 vppcom_session_worker (vcl_session_handle_t session_handle)
3732 {
3733   return session_handle >> 24;
3734 }
3735
3736 int
3737 vppcom_session_handle (uint32_t session_index)
3738 {
3739   return (vcl_get_worker_index () << 24) | session_index;
3740 }
3741
3742 int
3743 vppcom_worker_register (void)
3744 {
3745   if (!vcl_worker_alloc_and_init ())
3746     return VPPCOM_EEXIST;
3747
3748   if (vcl_worker_set_bapi ())
3749     return VPPCOM_EEXIST;
3750
3751   if (vcl_worker_register_with_vpp ())
3752     return VPPCOM_EEXIST;
3753
3754   return VPPCOM_OK;
3755 }
3756
3757 int
3758 vppcom_worker_index (void)
3759 {
3760   return vcl_get_worker_index ();
3761 }
3762
3763 /*
3764  * fd.io coding-style-patch-verification: ON
3765  *
3766  * Local Variables:
3767  * eval: (c-set-style "gnu")
3768  * End:
3769  */