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