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