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