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