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