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