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