session_node.c revision 45b7973d
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 file except in compliance with the License.
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 <math.h>
17#include <vlib/vlib.h>
18#include <vnet/vnet.h>
19#include <vppinfra/elog.h>
20#include <vnet/session/transport.h>
21#include <vnet/session/session.h>
22#include <vnet/session/application.h>
23#include <vnet/session/application_interface.h>
24#include <vnet/session/application_local.h>
25#include <vnet/session/session_debug.h>
26#include <svm/queue.h>
27
28#define app_check_thread_and_barrier(_fn, _arg)				\
29  if (!vlib_thread_is_main_w_barrier ())				\
30    {									\
31     vlib_rpc_call_main_thread (_fn, (u8 *) _arg, sizeof(*_arg));	\
32      return;								\
33   }
34
35static void
36session_mq_listen_handler (void *data)
37{
38  session_listen_msg_t *mp = (session_listen_msg_t *) data;
39  vnet_listen_args_t _a, *a = &_a;
40  app_worker_t *app_wrk;
41  application_t *app;
42  int rv;
43
44  app_check_thread_and_barrier (session_mq_listen_handler, mp);
45
46  app = application_lookup (mp->client_index);
47  if (!app)
48    return;
49
50  clib_memset (a, 0, sizeof (*a));
51  a->sep.is_ip4 = mp->is_ip4;
52  clib_memcpy_fast (&a->sep.ip, &mp->ip, sizeof (mp->ip));
53  a->sep.port = mp->port;
54  a->sep.fib_index = mp->vrf;
55  a->sep.sw_if_index = ENDPOINT_INVALID_INDEX;
56  a->sep.transport_proto = mp->proto;
57  a->sep_ext.ckpair_index = mp->ckpair_index;
58  a->app_index = app->app_index;
59  a->wrk_map_index = mp->wrk_index;
60
61  if ((rv = vnet_listen (a)))
62    clib_warning ("listen returned: %d", rv);
63
64  app_wrk = application_get_worker (app, mp->wrk_index);
65  mq_send_session_bound_cb (app_wrk->wrk_index, mp->context, a->handle, rv);
66  return;
67}
68
69static void
70session_mq_listen_uri_handler (void *data)
71{
72  session_listen_uri_msg_t *mp = (session_listen_uri_msg_t *) data;
73  vnet_listen_args_t _a, *a = &_a;
74  app_worker_t *app_wrk;
75  application_t *app;
76  int rv;
77
78  app_check_thread_and_barrier (session_mq_listen_uri_handler, mp);
79
80  app = application_lookup (mp->client_index);
81  if (!app)
82    return;
83
84  clib_memset (a, 0, sizeof (*a));
85  a->uri = (char *) mp->uri;
86  a->app_index = app->app_index;
87  rv = vnet_bind_uri (a);
88
89  app_wrk = application_get_worker (app, 0);
90  mq_send_session_bound_cb (app_wrk->wrk_index, mp->context, a->handle, rv);
91}
92
93static void
94session_mq_connect_handler (void *data)
95{
96  session_connect_msg_t *mp = (session_connect_msg_t *) data;
97  vnet_connect_args_t _a, *a = &_a;
98  app_worker_t *app_wrk;
99  application_t *app;
100  int rv;
101
102  app_check_thread_and_barrier (session_mq_connect_handler, mp);
103
104  app = application_lookup (mp->client_index);
105  if (!app)
106    return;
107
108  clib_memset (a, 0, sizeof (*a));
109  a->sep.is_ip4 = mp->is_ip4;
110  clib_memcpy_fast (&a->sep.ip, &mp->ip, sizeof (mp->ip));
111  a->sep.port = mp->port;
112  a->sep.transport_proto = mp->proto;
113  a->sep.peer.fib_index = mp->vrf;
114  clib_memcpy_fast (&a->sep.peer.ip, &mp->lcl_ip, sizeof (mp->lcl_ip));
115  a->sep.peer.sw_if_index = ENDPOINT_INVALID_INDEX;
116  a->sep_ext.parent_handle = mp->parent_handle;
117  a->sep_ext.ckpair_index = mp->ckpair_index;
118  if (mp->hostname_len)
119    {
120      vec_validate (a->sep_ext.hostname, mp->hostname_len - 1);
121      clib_memcpy_fast (a->sep_ext.hostname, mp->hostname, mp->hostname_len);
122    }
123  a->api_context = mp->context;
124  a->app_index = app->app_index;
125  a->wrk_map_index = mp->wrk_index;
126
127  if ((rv = vnet_connect (a)))
128    {
129      clib_warning ("connect returned: %U", format_vnet_api_errno, rv);
130      app_wrk = application_get_worker (app, mp->wrk_index);
131      mq_send_session_connected_cb (app_wrk->wrk_index, mp->context, 0,
132				    /* is_fail */ 1);
133    }
134
135  vec_free (a->sep_ext.hostname);
136}
137
138static void
139session_mq_connect_uri_handler (void *data)
140{
141  session_connect_uri_msg_t *mp = (session_connect_uri_msg_t *) data;
142  vnet_connect_args_t _a, *a = &_a;
143  app_worker_t *app_wrk;
144  application_t *app;
145  int rv;
146
147  app_check_thread_and_barrier (session_mq_connect_uri_handler, mp);
148
149  app = application_lookup (mp->client_index);
150  if (!app)
151    return;
152
153  clib_memset (a, 0, sizeof (*a));
154  a->uri = (char *) mp->uri;
155  a->api_context = mp->context;
156  a->app_index = app->app_index;
157  if ((rv = vnet_connect_uri (a)))
158    {
159      clib_warning ("connect_uri returned: %d", rv);
160      app_wrk = application_get_worker (app, 0 /* default wrk only */ );
161      mq_send_session_connected_cb (app_wrk->wrk_index, mp->context, 0,
162				    /* is_fail */ 1);
163    }
164}
165
166static void
167session_mq_disconnect_handler (void *data)
168{
169  session_disconnect_msg_t *mp = (session_disconnect_msg_t *) data;
170  vnet_disconnect_args_t _a, *a = &_a;
171  application_t *app;
172
173  app = application_lookup (mp->client_index);
174  if (!app)
175    return;
176
177  a->app_index = app->app_index;
178  a->handle = mp->handle;
179  vnet_disconnect_session (a);
180}
181
182static void
183app_mq_detach_handler (void *data)
184{
185  session_app_detach_msg_t *mp = (session_app_detach_msg_t *) data;
186  vnet_app_detach_args_t _a, *a = &_a;
187  application_t *app;
188
189  app_check_thread_and_barrier (app_mq_detach_handler, mp);
190
191  app = application_lookup (mp->client_index);
192  if (!app)
193    return;
194
195  a->app_index = app->app_index;
196  a->api_client_index = mp->client_index;
197  vnet_application_detach (a);
198}
199
200static void
201session_mq_unlisten_handler (void *data)
202{
203  session_unlisten_msg_t *mp = (session_unlisten_msg_t *) data;
204  vnet_unlisten_args_t _a, *a = &_a;
205  app_worker_t *app_wrk;
206  application_t *app;
207  int rv;
208
209  app_check_thread_and_barrier (session_mq_unlisten_handler, mp);
210
211  app = application_lookup (mp->client_index);
212  if (!app)
213    return;
214
215  clib_memset (a, 0, sizeof (*a));
216  a->app_index = app->app_index;
217  a->handle = mp->handle;
218  a->wrk_map_index = mp->wrk_index;
219  if ((rv = vnet_unlisten (a)))
220    clib_warning ("unlisten returned: %d", rv);
221
222  app_wrk = application_get_worker (app, a->wrk_map_index);
223  if (!app_wrk)
224    return;
225
226  mq_send_unlisten_reply (app_wrk, mp->handle, mp->context, rv);
227}
228
229static void
230session_mq_accepted_reply_handler (void *data)
231{
232  session_accepted_reply_msg_t *mp = (session_accepted_reply_msg_t *) data;
233  vnet_disconnect_args_t _a = { 0 }, *a = &_a;
234  session_state_t old_state;
235  app_worker_t *app_wrk;
236  session_t *s;
237
238  /* Server isn't interested, kill the session */
239  if (mp->retval)
240    {
241      a->app_index = mp->context;
242      a->handle = mp->handle;
243      vnet_disconnect_session (a);
244      return;
245    }
246
247  /* Mail this back from the main thread. We're not polling in main
248   * thread so we're using other workers for notifications. */
249  if (vlib_num_workers () && vlib_get_thread_index () != 0
250      && session_thread_from_handle (mp->handle) == 0)
251    {
252      vlib_rpc_call_main_thread (session_mq_accepted_reply_handler,
253				 (u8 *) mp, sizeof (*mp));
254      return;
255    }
256
257  s = session_get_from_handle_if_valid (mp->handle);
258  if (!s)
259    return;
260
261  app_wrk = app_worker_get (s->app_wrk_index);
262  if (app_wrk->app_index != mp->context)
263    {
264      clib_warning ("app doesn't own session");
265      return;
266    }
267
268  if (!session_has_transport (s))
269    {
270      s->session_state = SESSION_STATE_READY;
271      if (ct_session_connect_notify (s))
272	return;
273    }
274  else
275    {
276      old_state = s->session_state;
277      s->session_state = SESSION_STATE_READY;
278
279      if (!svm_fifo_is_empty_prod (s->rx_fifo))
280	app_worker_lock_and_send_event (app_wrk, s, SESSION_IO_EVT_RX);
281
282      /* Closed while waiting for app to reply. Resend disconnect */
283      if (old_state >= SESSION_STATE_TRANSPORT_CLOSING)
284	{
285	  app_worker_close_notify (app_wrk, s);
286	  s->session_state = old_state;
287	  return;
288	}
289    }
290}
291
292static void
293session_mq_reset_reply_handler (void *data)
294{
295  vnet_disconnect_args_t _a = { 0 }, *a = &_a;
296  session_reset_reply_msg_t *mp;
297  app_worker_t *app_wrk;
298  session_t *s;
299  application_t *app;
300  u32 index, thread_index;
301
302  mp = (session_reset_reply_msg_t *) data;
303  app = application_lookup (mp->context);
304  if (!app)
305    return;
306
307  session_parse_handle (mp->handle, &index, &thread_index);
308  s = session_get_if_valid (index, thread_index);
309
310  /* Session was already closed or already cleaned up */
311  if (!s || s->session_state != SESSION_STATE_TRANSPORT_CLOSING)
312    return;
313
314  app_wrk = app_worker_get (s->app_wrk_index);
315  if (!app_wrk || app_wrk->app_index != app->app_index)
316    {
317      clib_warning ("App %u does not own handle 0x%lx!", app->app_index,
318		    mp->handle);
319      return;
320    }
321
322  /* Client objected to resetting the session, log and continue */
323  if (mp->retval)
324    {
325      clib_warning ("client retval %d", mp->retval);
326      return;
327    }
328
329  /* This comes as a response to a reset, transport only waiting for
330   * confirmation to remove connection state, no need to disconnect */
331  a->handle = mp->handle;
332  a->app_index = app->app_index;
333  vnet_disconnect_session (a);
334}
335
336static void
337session_mq_disconnected_handler (void *data)
338{
339  session_disconnected_reply_msg_t *rmp;
340  vnet_disconnect_args_t _a, *a = &_a;
341  svm_msg_q_msg_t _msg, *msg = &_msg;
342  session_disconnected_msg_t *mp;
343  app_worker_t *app_wrk;
344  session_event_t *evt;
345  session_t *s;
346  application_t *app;
347  int rv = 0;
348
349  mp = (session_disconnected_msg_t *) data;
350  if (!(s = session_get_from_handle_if_valid (mp->handle)))
351    {
352      clib_warning ("could not disconnect handle %llu", mp->handle);
353      return;
354    }
355  app_wrk = app_worker_get (s->app_wrk_index);
356  app = application_lookup (mp->client_index);
357  if (!(app_wrk && app && app->app_index == app_wrk->app_index))
358    {
359      clib_warning ("could not disconnect session: %llu app: %u",
360		    mp->handle, mp->client_index);
361      return;
362    }
363
364  a->handle = mp->handle;
365  a->app_index = app_wrk->wrk_index;
366  rv = vnet_disconnect_session (a);
367
368  svm_msg_q_lock_and_alloc_msg_w_ring (app_wrk->event_queue,
369				       SESSION_MQ_CTRL_EVT_RING,
370				       SVM_Q_WAIT, msg);
371  evt = svm_msg_q_msg_data (app_wrk->event_queue, msg);
372  clib_memset (evt, 0, sizeof (*evt));
373  evt->event_type = SESSION_CTRL_EVT_DISCONNECTED_REPLY;
374  rmp = (session_disconnected_reply_msg_t *) evt->data;
375  rmp->handle = mp->handle;
376  rmp->context = mp->context;
377  rmp->retval = rv;
378  svm_msg_q_add_and_unlock (app_wrk->event_queue, msg);
379}
380
381static void
382session_mq_disconnected_reply_handler (void *data)
383{
384  session_disconnected_reply_msg_t *mp;
385  vnet_disconnect_args_t _a, *a = &_a;
386  application_t *app;
387
388  mp = (session_disconnected_reply_msg_t *) data;
389
390  /* Client objected to disconnecting the session, log and continue */
391  if (mp->retval)
392    {
393      clib_warning ("client retval %d", mp->retval);
394      return;
395    }
396
397  /* Disconnect has been confirmed. Confirm close to transport */
398  app = application_lookup (mp->context);
399  if (app)
400    {
401      a->handle = mp->handle;
402      a->app_index = app->app_index;
403      vnet_disconnect_session (a);
404    }
405}
406
407static void
408session_mq_worker_update_handler (void *data)
409{
410  session_worker_update_msg_t *mp = (session_worker_update_msg_t *) data;
411  session_worker_update_reply_msg_t *rmp;
412  svm_msg_q_msg_t _msg, *msg = &_msg;
413  app_worker_t *app_wrk;
414  u32 owner_app_wrk_map;
415  session_event_t *evt;
416  session_t *s;
417  application_t *app;
418
419  app = application_lookup (mp->client_index);
420  if (!app)
421    return;
422  if (!(s = session_get_from_handle_if_valid (mp->handle)))
423    {
424      clib_warning ("invalid handle %llu", mp->handle);
425      return;
426    }
427  app_wrk = app_worker_get (s->app_wrk_index);
428  if (app_wrk->app_index != app->app_index)
429    {
430      clib_warning ("app %u does not own session %llu", app->app_index,
431		    mp->handle);
432      return;
433    }
434  owner_app_wrk_map = app_wrk->wrk_map_index;
435  app_wrk = application_get_worker (app, mp->wrk_index);
436
437  /* This needs to come from the new owner */
438  if (mp->req_wrk_index == owner_app_wrk_map)
439    {
440      session_req_worker_update_msg_t *wump;
441
442      svm_msg_q_lock_and_alloc_msg_w_ring (app_wrk->event_queue,
443					   SESSION_MQ_CTRL_EVT_RING,
444					   SVM_Q_WAIT, msg);
445      evt = svm_msg_q_msg_data (app_wrk->event_queue, msg);
446      clib_memset (evt, 0, sizeof (*evt));
447      evt->event_type = SESSION_CTRL_EVT_REQ_WORKER_UPDATE;
448      wump = (session_req_worker_update_msg_t *) evt->data;
449      wump->session_handle = mp->handle;
450      svm_msg_q_add_and_unlock (app_wrk->event_queue, msg);
451      return;
452    }
453
454  app_worker_own_session (app_wrk, s);
455
456  /*
457   * Send reply
458   */
459  svm_msg_q_lock_and_alloc_msg_w_ring (app_wrk->event_queue,
460				       SESSION_MQ_CTRL_EVT_RING,
461				       SVM_Q_WAIT, msg);
462  evt = svm_msg_q_msg_data (app_wrk->event_queue, msg);
463  clib_memset (evt, 0, sizeof (*evt));
464  evt->event_type = SESSION_CTRL_EVT_WORKER_UPDATE_REPLY;
465  rmp = (session_worker_update_reply_msg_t *) evt->data;
466  rmp->handle = mp->handle;
467  rmp->rx_fifo = pointer_to_uword (s->rx_fifo);
468  rmp->tx_fifo = pointer_to_uword (s->tx_fifo);
469  rmp->segment_handle = session_segment_handle (s);
470  svm_msg_q_add_and_unlock (app_wrk->event_queue, msg);
471
472  /*
473   * Retransmit messages that may have been lost
474   */
475  if (s->tx_fifo && !svm_fifo_is_empty (s->tx_fifo))
476    session_send_io_evt_to_thread (s->tx_fifo, SESSION_IO_EVT_TX);
477
478  if (s->rx_fifo && !svm_fifo_is_empty (s->rx_fifo))
479    app_worker_lock_and_send_event (app_wrk, s, SESSION_IO_EVT_RX);
480
481  if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
482    app_worker_close_notify (app_wrk, s);
483}
484
485vlib_node_registration_t session_queue_node;
486
487typedef struct
488{
489  u32 session_index;
490  u32 server_thread_index;
491} session_queue_trace_t;
492
493/* packet trace format function */
494static u8 *
495format_session_queue_trace (u8 * s, va_list * args)
496{
497  CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
498  CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
499  session_queue_trace_t *t = va_arg (*args, session_queue_trace_t *);
500
501  s = format (s, "SESSION_QUEUE: session index %d, server thread index %d",
502	      t->session_index, t->server_thread_index);
503  return s;
504}
505
506#define foreach_session_queue_error		\
507_(TX, "Packets transmitted")                  	\
508_(TIMER, "Timer events")			\
509_(NO_BUFFER, "Out of buffers")
510
511typedef enum
512{
513#define _(sym,str) SESSION_QUEUE_ERROR_##sym,
514  foreach_session_queue_error
515#undef _
516    SESSION_QUEUE_N_ERROR,
517} session_queue_error_t;
518
519static char *session_queue_error_strings[] = {
520#define _(sym,string) string,
521  foreach_session_queue_error
522#undef _
523};
524
525enum
526{
527  SESSION_TX_NO_BUFFERS = -2,
528  SESSION_TX_NO_DATA,
529  SESSION_TX_OK
530};
531
532static void
533session_tx_trace_frame (vlib_main_t * vm, vlib_node_runtime_t * node,
534			u32 next_index, u32 * to_next, u16 n_segs,
535			session_t * s, u32 n_trace)
536{
537  session_queue_trace_t *t;
538  vlib_buffer_t *b;
539  int i;
540
541  for (i = 0; i < clib_min (n_trace, n_segs); i++)
542    {
543      b = vlib_get_buffer (vm, to_next[i - n_segs]);
544      vlib_trace_buffer (vm, node, next_index, b, 1 /* follow_chain */ );
545      t = vlib_add_trace (vm, node, b, sizeof (*t));
546      t->session_index = s->session_index;
547      t->server_thread_index = s->thread_index;
548    }
549  vlib_set_trace_count (vm, node, n_trace - i);
550}
551
552always_inline void
553session_tx_fifo_chain_tail (vlib_main_t * vm, session_tx_context_t * ctx,
554			    vlib_buffer_t * b, u16 * n_bufs, u8 peek_data)
555{
556  vlib_buffer_t *chain_b, *prev_b;
557  u32 chain_bi0, to_deq, left_from_seg;
558  session_worker_t *wrk;
559  u16 len_to_deq, n_bytes_read;
560  u8 *data, j;
561
562  wrk = session_main_get_worker (ctx->s->thread_index);
563  b->flags |= VLIB_BUFFER_TOTAL_LENGTH_VALID;
564  b->total_length_not_including_first_buffer = 0;
565
566  chain_b = b;
567  left_from_seg = clib_min (ctx->snd_mss - b->current_length,
568			    ctx->left_to_snd);
569  to_deq = left_from_seg;
570  for (j = 1; j < ctx->n_bufs_per_seg; j++)
571    {
572      prev_b = chain_b;
573      len_to_deq = clib_min (to_deq, ctx->deq_per_buf);
574
575      *n_bufs -= 1;
576      chain_bi0 = wrk->tx_buffers[*n_bufs];
577      chain_b = vlib_get_buffer (vm, chain_bi0);
578      chain_b->current_data = 0;
579      data = vlib_buffer_get_current (chain_b);
580      if (peek_data)
581	{
582	  n_bytes_read = svm_fifo_peek (ctx->s->tx_fifo,
583					ctx->tx_offset, len_to_deq, data);
584	  ctx->tx_offset += n_bytes_read;
585	}
586      else
587	{
588	  if (ctx->transport_vft->transport_options.tx_type ==
589	      TRANSPORT_TX_DGRAM)
590	    {
591	      svm_fifo_t *f = ctx->s->tx_fifo;
592	      session_dgram_hdr_t *hdr = &ctx->hdr;
593	      u16 deq_now;
594	      deq_now = clib_min (hdr->data_length - hdr->data_offset,
595				  len_to_deq);
596	      n_bytes_read = svm_fifo_peek (f, hdr->data_offset, deq_now,
597					    data);
598	      ASSERT (n_bytes_read > 0);
599
600	      hdr->data_offset += n_bytes_read;
601	      if (hdr->data_offset == hdr->data_length)
602		{
603		  u32 offset = hdr->data_length + SESSION_CONN_HDR_LEN;
604		  svm_fifo_dequeue_drop (f, offset);
605		}
606	    }
607	  else
608	    n_bytes_read = svm_fifo_dequeue (ctx->s->tx_fifo,
609					     len_to_deq, data);
610	}
611      ASSERT (n_bytes_read == len_to_deq);
612      chain_b->current_length = n_bytes_read;
613      b->total_length_not_including_first_buffer += chain_b->current_length;
614
615      /* update previous buffer */
616      prev_b->next_buffer = chain_bi0;
617      prev_b->flags |= VLIB_BUFFER_NEXT_PRESENT;
618
619      /* update current buffer */
620      chain_b->next_buffer = 0;
621
622      to_deq -= n_bytes_read;
623      if (to_deq == 0)
624	break;
625    }
626  ASSERT (to_deq == 0
627	  && b->total_length_not_including_first_buffer == left_from_seg);
628  ctx->left_to_snd -= left_from_seg;
629}
630
631always_inline void
632session_tx_fill_buffer (vlib_main_t * vm, session_tx_context_t * ctx,
633			vlib_buffer_t * b, u16 * n_bufs, u8 peek_data)
634{
635  u32 len_to_deq;
636  u8 *data0;
637  int n_bytes_read;
638
639  /*
640   * Start with the first buffer in chain
641   */
642  b->error = 0;
643  b->flags = VNET_BUFFER_F_LOCALLY_ORIGINATED;
644  b->current_data = 0;
645
646  data0 = vlib_buffer_make_headroom (b, TRANSPORT_MAX_HDRS_LEN);
647  len_to_deq = clib_min (ctx->left_to_snd, ctx->deq_per_first_buf);
648
649  if (peek_data)
650    {
651      n_bytes_read = svm_fifo_peek (ctx->s->tx_fifo, ctx->tx_offset,
652				    len_to_deq, data0);
653      ASSERT (n_bytes_read > 0);
654      /* Keep track of progress locally, transport is also supposed to
655       * increment it independently when pushing the header */
656      ctx->tx_offset += n_bytes_read;
657    }
658  else
659    {
660      if (ctx->transport_vft->transport_options.tx_type == TRANSPORT_TX_DGRAM)
661	{
662	  session_dgram_hdr_t *hdr = &ctx->hdr;
663	  svm_fifo_t *f = ctx->s->tx_fifo;
664	  u16 deq_now;
665	  u32 offset;
666
667	  ASSERT (hdr->data_length > hdr->data_offset);
668	  deq_now = clib_min (hdr->data_length - hdr->data_offset,
669			      len_to_deq);
670	  offset = hdr->data_offset + SESSION_CONN_HDR_LEN;
671	  n_bytes_read = svm_fifo_peek (f, offset, deq_now, data0);
672	  ASSERT (n_bytes_read > 0);
673
674	  if (ctx->s->session_state == SESSION_STATE_LISTENING)
675	    {
676	      ip_copy (&ctx->tc->rmt_ip, &hdr->rmt_ip, ctx->tc->is_ip4);
677	      ctx->tc->rmt_port = hdr->rmt_port;
678	    }
679	  hdr->data_offset += n_bytes_read;
680	  if (hdr->data_offset == hdr->data_length)
681	    {
682	      offset = hdr->data_length + SESSION_CONN_HDR_LEN;
683	      svm_fifo_dequeue_drop (f, offset);
684	    }
685	}
686      else
687	{
688	  n_bytes_read = svm_fifo_dequeue (ctx->s->tx_fifo,
689					   len_to_deq, data0);
690	  ASSERT (n_bytes_read > 0);
691	}
692    }
693  b->current_length = n_bytes_read;
694  ctx->left_to_snd -= n_bytes_read;
695
696  /*
697   * Fill in the remaining buffers in the chain, if any
698   */
699  if (PREDICT_FALSE (ctx->n_bufs_per_seg > 1 && ctx->left_to_snd))
700    session_tx_fifo_chain_tail (vm, ctx, b, n_bufs, peek_data);
701}
702
703always_inline u8
704session_tx_not_ready (session_t * s, u8 peek_data)
705{
706  if (peek_data)
707    {
708      if (PREDICT_TRUE (s->session_state == SESSION_STATE_READY))
709	return 0;
710      /* Can retransmit for closed sessions but can't send new data if
711       * session is not ready or closed */
712      else if (s->session_state < SESSION_STATE_READY)
713	return 1;
714      else if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSED)
715	{
716	  /* Allow closed transports to still send custom packets.
717	   * For instance, tcp may want to send acks in time-wait. */
718	  if (s->session_state != SESSION_STATE_TRANSPORT_DELETED
719	      && (s->flags & SESSION_F_CUSTOM_TX))
720	    return 0;
721	  return 2;
722	}
723    }
724  return 0;
725}
726
727always_inline transport_connection_t *
728session_tx_get_transport (session_tx_context_t * ctx, u8 peek_data)
729{
730  if (peek_data)
731    {
732      return ctx->transport_vft->get_connection (ctx->s->connection_index,
733						 ctx->s->thread_index);
734    }
735  else
736    {
737      if (ctx->s->session_state == SESSION_STATE_LISTENING)
738	return ctx->transport_vft->get_listener (ctx->s->connection_index);
739      else
740	{
741	  return ctx->transport_vft->get_connection (ctx->s->connection_index,
742						     ctx->s->thread_index);
743	}
744    }
745}
746
747always_inline void
748session_tx_set_dequeue_params (vlib_main_t * vm, session_tx_context_t * ctx,
749			       u32 max_segs, u8 peek_data)
750{
751  u32 n_bytes_per_buf, n_bytes_per_seg;
752  ctx->max_dequeue = svm_fifo_max_dequeue_cons (ctx->s->tx_fifo);
753  if (peek_data)
754    {
755      /* Offset in rx fifo from where to peek data */
756      ctx->tx_offset = ctx->transport_vft->tx_fifo_offset (ctx->tc);
757      if (PREDICT_FALSE (ctx->tx_offset >= ctx->max_dequeue))
758	{
759	  ctx->max_len_to_snd = 0;
760	  return;
761	}
762      ctx->max_dequeue -= ctx->tx_offset;
763    }
764  else
765    {
766      if (ctx->transport_vft->transport_options.tx_type == TRANSPORT_TX_DGRAM)
767	{
768	  if (ctx->max_dequeue <= sizeof (ctx->hdr))
769	    {
770	      ctx->max_len_to_snd = 0;
771	      return;
772	    }
773	  svm_fifo_peek (ctx->s->tx_fifo, 0, sizeof (ctx->hdr),
774			 (u8 *) & ctx->hdr);
775	  ASSERT (ctx->hdr.data_length > ctx->hdr.data_offset);
776	  ctx->max_dequeue = ctx->hdr.data_length - ctx->hdr.data_offset;
777	}
778    }
779  ASSERT (ctx->max_dequeue > 0);
780
781  /* Ensure we're not writing more than transport window allows */
782  if (ctx->max_dequeue < ctx->snd_space)
783    {
784      /* Constrained by tx queue. Try to send only fully formed segments */
785      ctx->max_len_to_snd =
786	(ctx->max_dequeue > ctx->snd_mss) ?
787	ctx->max_dequeue - ctx->max_dequeue % ctx->snd_mss : ctx->max_dequeue;
788      /* TODO Nagle ? */
789    }
790  else
791    {
792      /* Expectation is that snd_space0 is already a multiple of snd_mss */
793      ctx->max_len_to_snd = ctx->snd_space;
794    }
795
796  /* Check if we're tx constrained by the node */
797  ctx->n_segs_per_evt = ceil ((f64) ctx->max_len_to_snd / ctx->snd_mss);
798  if (ctx->n_segs_per_evt > max_segs)
799    {
800      ctx->n_segs_per_evt = max_segs;
801      ctx->max_len_to_snd = max_segs * ctx->snd_mss;
802    }
803
804  n_bytes_per_buf = vlib_buffer_get_default_data_size (vm);
805  ASSERT (n_bytes_per_buf > TRANSPORT_MAX_HDRS_LEN);
806  n_bytes_per_seg = TRANSPORT_MAX_HDRS_LEN + ctx->snd_mss;
807  ctx->n_bufs_per_seg = ceil ((f64) n_bytes_per_seg / n_bytes_per_buf);
808  ctx->deq_per_buf = clib_min (ctx->snd_mss, n_bytes_per_buf);
809  ctx->deq_per_first_buf = clib_min (ctx->snd_mss,
810				     n_bytes_per_buf -
811				     TRANSPORT_MAX_HDRS_LEN);
812}
813
814always_inline int
815session_tx_fifo_read_and_snd_i (session_worker_t * wrk,
816				vlib_node_runtime_t * node,
817				session_evt_elt_t * elt,
818				int *n_tx_packets, u8 peek_data)
819{
820  u32 n_trace, n_bufs_needed = 0, n_left, pbi, next_index, max_burst;
821  session_tx_context_t *ctx = &wrk->ctx;
822  session_main_t *smm = &session_main;
823  session_event_t *e = &elt->evt;
824  vlib_main_t *vm = wrk->vm;
825  transport_proto_t tp;
826  vlib_buffer_t *pb;
827  u16 n_bufs, rv;
828
829  if (PREDICT_FALSE ((rv = session_tx_not_ready (ctx->s, peek_data))))
830    {
831      if (rv < 2)
832	session_evt_add_old (wrk, elt);
833      return SESSION_TX_NO_DATA;
834    }
835
836  next_index = smm->session_type_to_next[ctx->s->session_type];
837  max_burst = VLIB_FRAME_SIZE - *n_tx_packets;
838
839  tp = session_get_transport_proto (ctx->s);
840  ctx->transport_vft = transport_protocol_get_vft (tp);
841  ctx->tc = session_tx_get_transport (ctx, peek_data);
842
843  if (PREDICT_FALSE (e->event_type == SESSION_IO_EVT_TX_FLUSH))
844    {
845      if (ctx->transport_vft->flush_data)
846	ctx->transport_vft->flush_data (ctx->tc);
847      e->event_type = SESSION_IO_EVT_TX;
848    }
849
850  if (ctx->s->flags & SESSION_F_CUSTOM_TX)
851    {
852      u32 n_custom_tx;
853      ctx->s->flags &= ~SESSION_F_CUSTOM_TX;
854      n_custom_tx = ctx->transport_vft->custom_tx (ctx->tc, max_burst);
855      *n_tx_packets += n_custom_tx;
856      if (PREDICT_FALSE
857	  (ctx->s->session_state >= SESSION_STATE_TRANSPORT_CLOSED))
858	return SESSION_TX_OK;
859      max_burst -= n_custom_tx;
860      if (!max_burst)
861	{
862	  session_evt_add_old (wrk, elt);
863	  return SESSION_TX_OK;
864	}
865    }
866
867  ctx->snd_mss = ctx->transport_vft->send_mss (ctx->tc);
868  ctx->snd_space = transport_connection_snd_space (ctx->tc,
869						   vm->clib_time.
870						   last_cpu_time,
871						   ctx->snd_mss);
872
873  if (ctx->snd_space == 0 || ctx->snd_mss == 0)
874    {
875      session_evt_add_old (wrk, elt);
876      return SESSION_TX_NO_DATA;
877    }
878
879  /* Allow enqueuing of a new event */
880  svm_fifo_unset_event (ctx->s->tx_fifo);
881
882  /* Check how much we can pull. */
883  session_tx_set_dequeue_params (vm, ctx, max_burst, peek_data);
884
885  if (PREDICT_FALSE (!ctx->max_len_to_snd))
886    {
887      transport_connection_tx_pacer_reset_bucket (ctx->tc,
888						  vm->clib_time.
889						  last_cpu_time);
890      return SESSION_TX_NO_DATA;
891    }
892
893  n_bufs_needed = ctx->n_segs_per_evt * ctx->n_bufs_per_seg;
894  vec_validate_aligned (wrk->tx_buffers, n_bufs_needed - 1,
895			CLIB_CACHE_LINE_BYTES);
896  n_bufs = vlib_buffer_alloc (vm, wrk->tx_buffers, n_bufs_needed);
897  if (PREDICT_FALSE (n_bufs < n_bufs_needed))
898    {
899      if (n_bufs)
900	vlib_buffer_free (vm, wrk->tx_buffers, n_bufs);
901      session_evt_add_old (wrk, elt);
902      vlib_node_increment_counter (wrk->vm, node->node_index,
903				   SESSION_QUEUE_ERROR_NO_BUFFER, 1);
904      return SESSION_TX_NO_BUFFERS;
905    }
906
907  ctx->left_to_snd = ctx->max_len_to_snd;
908  n_left = ctx->n_segs_per_evt;
909
910  while (n_left >= 4)
911    {
912      vlib_buffer_t *b0, *b1;
913      u32 bi0, bi1;
914
915      pbi = wrk->tx_buffers[n_bufs - 3];
916      pb = vlib_get_buffer (vm, pbi);
917      vlib_prefetch_buffer_header (pb, STORE);
918      pbi = wrk->tx_buffers[n_bufs - 4];
919      pb = vlib_get_buffer (vm, pbi);
920      vlib_prefetch_buffer_header (pb, STORE);
921
922      bi0 = wrk->tx_buffers[--n_bufs];
923      bi1 = wrk->tx_buffers[--n_bufs];
924
925      b0 = vlib_get_buffer (vm, bi0);
926      b1 = vlib_get_buffer (vm, bi1);
927
928      session_tx_fill_buffer (vm, ctx, b0, &n_bufs, peek_data);
929      session_tx_fill_buffer (vm, ctx, b1, &n_bufs, peek_data);
930
931      ctx->transport_vft->push_header (ctx->tc, b0);
932      ctx->transport_vft->push_header (ctx->tc, b1);
933
934      n_left -= 2;
935
936      VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b0);
937      VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b1);
938
939      vec_add1 (wrk->pending_tx_buffers, bi0);
940      vec_add1 (wrk->pending_tx_buffers, bi1);
941      vec_add1 (wrk->pending_tx_nexts, next_index);
942      vec_add1 (wrk->pending_tx_nexts, next_index);
943    }
944  while (n_left)
945    {
946      vlib_buffer_t *b0;
947      u32 bi0;
948
949      if (n_left > 1)
950	{
951	  pbi = wrk->tx_buffers[n_bufs - 2];
952	  pb = vlib_get_buffer (vm, pbi);
953	  vlib_prefetch_buffer_header (pb, STORE);
954	}
955
956      bi0 = wrk->tx_buffers[--n_bufs];
957      b0 = vlib_get_buffer (vm, bi0);
958      session_tx_fill_buffer (vm, ctx, b0, &n_bufs, peek_data);
959
960      /* Ask transport to push header after current_length and
961       * total_length_not_including_first_buffer are updated */
962      ctx->transport_vft->push_header (ctx->tc, b0);
963
964      n_left -= 1;
965
966      VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b0);
967
968      vec_add1 (wrk->pending_tx_buffers, bi0);
969      vec_add1 (wrk->pending_tx_nexts, next_index);
970    }
971
972  if (PREDICT_FALSE ((n_trace = vlib_get_trace_count (vm, node)) > 0))
973    session_tx_trace_frame (vm, node, next_index, wrk->pending_tx_buffers,
974			    ctx->n_segs_per_evt, ctx->s, n_trace);
975
976  if (PREDICT_FALSE (n_bufs))
977    vlib_buffer_free (vm, wrk->tx_buffers, n_bufs);
978
979  *n_tx_packets += ctx->n_segs_per_evt;
980  transport_connection_update_tx_bytes (ctx->tc, ctx->max_len_to_snd);
981
982  SESSION_EVT (SESSION_EVT_DEQ, ctx->s, ctx->max_len_to_snd, ctx->max_dequeue,
983	       ctx->s->tx_fifo->has_event, wrk->last_vlib_time);
984
985  /* If we couldn't dequeue all bytes mark as partially read */
986  ASSERT (ctx->left_to_snd == 0);
987  if (ctx->max_len_to_snd < ctx->max_dequeue)
988    if (svm_fifo_set_event (ctx->s->tx_fifo))
989      session_evt_add_old (wrk, elt);
990
991  if (!peek_data
992      && ctx->transport_vft->transport_options.tx_type == TRANSPORT_TX_DGRAM)
993    {
994      /* Fix dgram pre header */
995      if (ctx->max_len_to_snd < ctx->max_dequeue)
996	svm_fifo_overwrite_head (ctx->s->tx_fifo, (u8 *) & ctx->hdr,
997				 sizeof (session_dgram_pre_hdr_t));
998      /* More data needs to be read */
999      else if (svm_fifo_max_dequeue_cons (ctx->s->tx_fifo) > 0)
1000	if (svm_fifo_set_event (ctx->s->tx_fifo))
1001	  session_evt_add_old (wrk, elt);
1002
1003      if (svm_fifo_needs_deq_ntf (ctx->s->tx_fifo, ctx->max_len_to_snd))
1004	session_dequeue_notify (ctx->s);
1005    }
1006  return SESSION_TX_OK;
1007}
1008
1009int
1010session_tx_fifo_peek_and_snd (session_worker_t * wrk,
1011			      vlib_node_runtime_t * node,
1012			      session_evt_elt_t * e, int *n_tx_packets)
1013{
1014  return session_tx_fifo_read_and_snd_i (wrk, node, e, n_tx_packets, 1);
1015}
1016
1017int
1018session_tx_fifo_dequeue_and_snd (session_worker_t * wrk,
1019				 vlib_node_runtime_t * node,
1020				 session_evt_elt_t * e, int *n_tx_packets)
1021{
1022  return session_tx_fifo_read_and_snd_i (wrk, node, e, n_tx_packets, 0);
1023}
1024
1025int
1026session_tx_fifo_dequeue_internal (session_worker_t * wrk,
1027				  vlib_node_runtime_t * node,
1028				  session_evt_elt_t * e, int *n_tx_packets)
1029{
1030  session_t *s = wrk->ctx.s;
1031
1032  if (PREDICT_FALSE (s->session_state >= SESSION_STATE_TRANSPORT_CLOSED))
1033    return 0;
1034  svm_fifo_unset_event (s->tx_fifo);
1035  return transport_custom_tx (session_get_transport_proto (s), s,
1036			      VLIB_FRAME_SIZE - *n_tx_packets);
1037}
1038
1039always_inline session_t *
1040session_event_get_session (session_event_t * e, u8 thread_index)
1041{
1042  return session_get_if_valid (e->session_index, thread_index);
1043}
1044
1045always_inline void
1046session_event_dispatch_ctrl (session_worker_t * wrk, session_evt_elt_t * elt)
1047{
1048  clib_llist_index_t ei;
1049  void (*fp) (void *);
1050  session_event_t *e;
1051  session_t *s;
1052
1053  ei = clib_llist_entry_index (wrk->event_elts, elt);
1054  e = &elt->evt;
1055
1056  switch (e->event_type)
1057    {
1058    case SESSION_CTRL_EVT_RPC:
1059      fp = e->rpc_args.fp;
1060      (*fp) (e->rpc_args.arg);
1061      break;
1062    case SESSION_CTRL_EVT_CLOSE:
1063      s = session_get_from_handle_if_valid (e->session_handle);
1064      if (PREDICT_FALSE (!s))
1065	break;
1066      session_transport_close (s);
1067      break;
1068    case SESSION_CTRL_EVT_RESET:
1069      s = session_get_from_handle_if_valid (e->session_handle);
1070      if (PREDICT_FALSE (!s))
1071	break;
1072      session_transport_reset (s);
1073      break;
1074    case SESSION_CTRL_EVT_LISTEN:
1075      session_mq_listen_handler (session_evt_ctrl_data (wrk, elt));
1076      break;
1077    case SESSION_CTRL_EVT_LISTEN_URI:
1078      session_mq_listen_uri_handler (session_evt_ctrl_data (wrk, elt));
1079      break;
1080    case SESSION_CTRL_EVT_UNLISTEN:
1081      session_mq_unlisten_handler (session_evt_ctrl_data (wrk, elt));
1082      break;
1083    case SESSION_CTRL_EVT_CONNECT:
1084      session_mq_connect_handler (session_evt_ctrl_data (wrk, elt));
1085      break;
1086    case SESSION_CTRL_EVT_CONNECT_URI:
1087      session_mq_connect_uri_handler (session_evt_ctrl_data (wrk, elt));
1088      break;
1089    case SESSION_CTRL_EVT_DISCONNECT:
1090      session_mq_disconnect_handler (session_evt_ctrl_data (wrk, elt));
1091      break;
1092    case SESSION_CTRL_EVT_DISCONNECTED:
1093      session_mq_disconnected_handler (session_evt_ctrl_data (wrk, elt));
1094      break;
1095    case SESSION_CTRL_EVT_ACCEPTED_REPLY:
1096      session_mq_accepted_reply_handler (session_evt_ctrl_data (wrk, elt));
1097      break;
1098    case SESSION_CTRL_EVT_DISCONNECTED_REPLY:
1099      session_mq_disconnected_reply_handler (session_evt_ctrl_data (wrk,
1100								    elt));
1101      break;
1102    case SESSION_CTRL_EVT_RESET_REPLY:
1103      session_mq_reset_reply_handler (session_evt_ctrl_data (wrk, elt));
1104      break;
1105    case SESSION_CTRL_EVT_WORKER_UPDATE:
1106      session_mq_worker_update_handler (session_evt_ctrl_data (wrk, elt));
1107      break;
1108    case SESSION_CTRL_EVT_APP_DETACH:
1109      app_mq_detach_handler (session_evt_ctrl_data (wrk, elt));
1110      break;
1111    default:
1112      clib_warning ("unhandled event type %d", e->event_type);
1113    }
1114
1115  /* Regrab elements in case pool moved */
1116  elt = pool_elt_at_index (wrk->event_elts, ei);
1117  if (!clib_llist_elt_is_linked (elt, evt_list))
1118    {
1119      e = &elt->evt;
1120      if (e->event_type >= SESSION_CTRL_EVT_BOUND)
1121	session_evt_ctrl_data_free (wrk, elt);
1122      session_evt_elt_free (wrk, elt);
1123    }
1124}
1125
1126always_inline void
1127session_event_dispatch_io (session_worker_t * wrk, vlib_node_runtime_t * node,
1128			   session_evt_elt_t * elt, u32 thread_index,
1129			   int *n_tx_packets)
1130{
1131  session_main_t *smm = &session_main;
1132  app_worker_t *app_wrk;
1133  clib_llist_index_t ei;
1134  session_event_t *e;
1135  session_t *s;
1136
1137  ei = clib_llist_entry_index (wrk->event_elts, elt);
1138  e = &elt->evt;
1139
1140  switch (e->event_type)
1141    {
1142    case SESSION_IO_EVT_TX_FLUSH:
1143    case SESSION_IO_EVT_TX:
1144      s = session_event_get_session (e, thread_index);
1145      if (PREDICT_FALSE (!s))
1146	{
1147	  clib_warning ("session %u was freed!", e->session_index);
1148	  break;
1149	}
1150      CLIB_PREFETCH (s->tx_fifo, 2 * CLIB_CACHE_LINE_BYTES, LOAD);
1151      wrk->ctx.s = s;
1152      /* Spray packets in per session type frames, since they go to
1153       * different nodes */
1154      (smm->session_tx_fns[s->session_type]) (wrk, node, elt, n_tx_packets);
1155      break;
1156    case SESSION_IO_EVT_RX:
1157      s = session_event_get_session (e, thread_index);
1158      if (!s)
1159	break;
1160      transport_app_rx_evt (session_get_transport_proto (s),
1161			    s->connection_index, s->thread_index);
1162      break;
1163    case SESSION_IO_EVT_BUILTIN_RX:
1164      s = session_event_get_session (e, thread_index);
1165      if (PREDICT_FALSE (!s || s->session_state >= SESSION_STATE_CLOSING))
1166	break;
1167      svm_fifo_unset_event (s->rx_fifo);
1168      app_wrk = app_worker_get (s->app_wrk_index);
1169      app_worker_builtin_rx (app_wrk, s);
1170      break;
1171    case SESSION_IO_EVT_BUILTIN_TX:
1172      s = session_get_from_handle_if_valid (e->session_handle);
1173      wrk->ctx.s = s;
1174      if (PREDICT_TRUE (s != 0))
1175	session_tx_fifo_dequeue_internal (wrk, node, elt, n_tx_packets);
1176      break;
1177    default:
1178      clib_warning ("unhandled event type %d", e->event_type);
1179    }
1180
1181  /* Regrab elements in case pool moved */
1182  elt = pool_elt_at_index (wrk->event_elts, ei);
1183  if (!clib_llist_elt_is_linked (elt, evt_list))
1184    session_evt_elt_free (wrk, elt);
1185}
1186
1187/* *INDENT-OFF* */
1188static const u32 session_evt_msg_sizes[] = {
1189#define _(symc, sym) 							\
1190  [SESSION_CTRL_EVT_ ## symc] = sizeof (session_ ## sym ##_msg_t),
1191  foreach_session_ctrl_evt
1192#undef _
1193};
1194/* *INDENT-ON* */
1195
1196always_inline void
1197session_evt_add_to_list (session_worker_t * wrk, session_event_t * evt)
1198{
1199  session_evt_elt_t *elt;
1200
1201  if (evt->event_type >= SESSION_CTRL_EVT_RPC)
1202    {
1203      elt = session_evt_alloc_ctrl (wrk);
1204      if (evt->event_type >= SESSION_CTRL_EVT_BOUND)
1205	{
1206	  elt->evt.ctrl_data_index = session_evt_ctrl_data_alloc (wrk);
1207	  elt->evt.event_type = evt->event_type;
1208	  clib_memcpy_fast (session_evt_ctrl_data (wrk, elt), evt->data,
1209			    session_evt_msg_sizes[evt->event_type]);
1210	}
1211      else
1212	{
1213	  /* Internal control events fit into io events footprint */
1214	  clib_memcpy_fast (&elt->evt, evt, sizeof (elt->evt));
1215	}
1216    }
1217  else
1218    {
1219      elt = session_evt_alloc_new (wrk);
1220      clib_memcpy_fast (&elt->evt, evt, sizeof (elt->evt));
1221    }
1222}
1223
1224static void
1225session_flush_pending_tx_buffers (session_worker_t * wrk,
1226				  vlib_node_runtime_t * node)
1227{
1228  vlib_buffer_enqueue_to_next (wrk->vm, node, wrk->pending_tx_buffers,
1229			       wrk->pending_tx_nexts,
1230			       vec_len (wrk->pending_tx_nexts));
1231  vec_reset_length (wrk->pending_tx_buffers);
1232  vec_reset_length (wrk->pending_tx_nexts);
1233}
1234
1235static uword
1236session_queue_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
1237		       vlib_frame_t * frame)
1238{
1239  session_main_t *smm = vnet_get_session_main ();
1240  u32 thread_index = vm->thread_index, n_to_dequeue;
1241  session_worker_t *wrk = &smm->wrk[thread_index];
1242  session_evt_elt_t *elt, *ctrl_he, *new_he, *old_he;
1243  svm_msg_q_msg_t _msg, *msg = &_msg;
1244  clib_llist_index_t old_ti;
1245  int i, n_tx_packets = 0;
1246  session_event_t *evt;
1247  svm_msg_q_t *mq;
1248
1249  SESSION_EVT (SESSION_EVT_DISPATCH_START, wrk);
1250
1251  wrk->last_vlib_time = vlib_time_now (vm);
1252
1253  /*
1254   *  Update transport time
1255   */
1256  transport_update_time (wrk->last_vlib_time, thread_index);
1257
1258  /*
1259   *  Dequeue and handle new events
1260   */
1261
1262  /* Try to dequeue what is available. Don't wait for lock.
1263   * XXX: we may need priorities here */
1264  mq = wrk->vpp_event_queue;
1265  n_to_dequeue = svm_msg_q_size (mq);
1266  if (n_to_dequeue && svm_msg_q_try_lock (mq) == 0)
1267    {
1268      for (i = 0; i < n_to_dequeue; i++)
1269	{
1270	  svm_msg_q_sub_w_lock (mq, msg);
1271	  evt = svm_msg_q_msg_data (mq, msg);
1272	  session_evt_add_to_list (wrk, evt);
1273	  svm_msg_q_free_msg (mq, msg);
1274	}
1275      svm_msg_q_unlock (mq);
1276    }
1277
1278  /*
1279   * Handle control events
1280   */
1281
1282  ctrl_he = pool_elt_at_index (wrk->event_elts, wrk->ctrl_head);
1283
1284  /* *INDENT-OFF* */
1285  clib_llist_foreach_safe (wrk->event_elts, evt_list, ctrl_he, elt, ({
1286    clib_llist_remove (wrk->event_elts, evt_list, elt);
1287    session_event_dispatch_ctrl (wrk, elt);
1288  }));
1289  /* *INDENT-ON* */
1290
1291  /*
1292   * Handle the new io events.
1293   */
1294
1295  new_he = pool_elt_at_index (wrk->event_elts, wrk->new_head);
1296  old_he = pool_elt_at_index (wrk->event_elts, wrk->old_head);
1297  old_ti = clib_llist_prev_index (old_he, evt_list);
1298
1299  /* *INDENT-OFF* */
1300  clib_llist_foreach_safe (wrk->event_elts, evt_list, new_he, elt, ({
1301    session_evt_type_t et;
1302
1303    et = elt->evt.event_type;
1304    clib_llist_remove (wrk->event_elts, evt_list, elt);
1305
1306    /* Postpone tx events if we can't handle them this dispatch cycle */
1307    if (n_tx_packets >= VLIB_FRAME_SIZE
1308	&& (et == SESSION_IO_EVT_TX || et == SESSION_IO_EVT_TX_FLUSH))
1309      {
1310	clib_llist_add (wrk->event_elts, evt_list, elt, new_he);
1311	continue;
1312      }
1313
1314    session_event_dispatch_io (wrk, node, elt, thread_index, &n_tx_packets);
1315  }));
1316  /* *INDENT-ON* */
1317
1318  /*
1319   * Handle the old io events, if we had any prior to processing the new ones
1320   */
1321
1322  if (old_ti != wrk->old_head)
1323    {
1324      old_he = pool_elt_at_index (wrk->event_elts, wrk->old_head);
1325      while (n_tx_packets < VLIB_FRAME_SIZE)
1326	{
1327	  clib_llist_index_t ei;
1328
1329	  clib_llist_pop_first (wrk->event_elts, evt_list, elt, old_he);
1330	  ei = clib_llist_entry_index (wrk->event_elts, elt);
1331	  session_event_dispatch_io (wrk, node, elt, thread_index,
1332				     &n_tx_packets);
1333
1334	  old_he = pool_elt_at_index (wrk->event_elts, wrk->old_head);
1335	  if (ei == old_ti)
1336	    break;
1337	};
1338    }
1339
1340  if (vec_len (wrk->pending_tx_buffers))
1341    session_flush_pending_tx_buffers (wrk, node);
1342
1343  vlib_node_increment_counter (vm, session_queue_node.index,
1344			       SESSION_QUEUE_ERROR_TX, n_tx_packets);
1345
1346  SESSION_EVT (SESSION_EVT_DISPATCH_END, wrk, n_tx_packets);
1347
1348  return n_tx_packets;
1349}
1350
1351/* *INDENT-OFF* */
1352VLIB_REGISTER_NODE (session_queue_node) =
1353{
1354  .function = session_queue_node_fn,
1355  .flags = VLIB_NODE_FLAG_TRACE_SUPPORTED,
1356  .name = "session-queue",
1357  .format_trace = format_session_queue_trace,
1358  .type = VLIB_NODE_TYPE_INPUT,
1359  .n_errors = ARRAY_LEN (session_queue_error_strings),
1360  .error_strings = session_queue_error_strings,
1361  .state = VLIB_NODE_STATE_DISABLED,
1362};
1363/* *INDENT-ON* */
1364
1365void
1366dump_thread_0_event_queue (void)
1367{
1368  session_main_t *smm = vnet_get_session_main ();
1369  vlib_main_t *vm = &vlib_global_main;
1370  u32 my_thread_index = vm->thread_index;
1371  session_event_t _e, *e = &_e;
1372  svm_msg_q_ring_t *ring;
1373  session_t *s0;
1374  svm_msg_q_msg_t *msg;
1375  svm_msg_q_t *mq;
1376  int i, index;
1377
1378  mq = smm->wrk[my_thread_index].vpp_event_queue;
1379  index = mq->q->head;
1380
1381  for (i = 0; i < mq->q->cursize; i++)
1382    {
1383      msg = (svm_msg_q_msg_t *) (&mq->q->data[0] + mq->q->elsize * index);
1384      ring = svm_msg_q_ring (mq, msg->ring_index);
1385      clib_memcpy_fast (e, svm_msg_q_msg_data (mq, msg), ring->elsize);
1386
1387      switch (e->event_type)
1388	{
1389	case SESSION_IO_EVT_TX:
1390	  s0 = session_event_get_session (e, my_thread_index);
1391	  fformat (stdout, "[%04d] TX session %d\n", i, s0->session_index);
1392	  break;
1393
1394	case SESSION_CTRL_EVT_CLOSE:
1395	  s0 = session_get_from_handle (e->session_handle);
1396	  fformat (stdout, "[%04d] disconnect session %d\n", i,
1397		   s0->session_index);
1398	  break;
1399
1400	case SESSION_IO_EVT_BUILTIN_RX:
1401	  s0 = session_event_get_session (e, my_thread_index);
1402	  fformat (stdout, "[%04d] builtin_rx %d\n", i, s0->session_index);
1403	  break;
1404
1405	case SESSION_CTRL_EVT_RPC:
1406	  fformat (stdout, "[%04d] RPC call %llx with %llx\n",
1407		   i, (u64) (uword) (e->rpc_args.fp),
1408		   (u64) (uword) (e->rpc_args.arg));
1409	  break;
1410
1411	default:
1412	  fformat (stdout, "[%04d] unhandled event type %d\n",
1413		   i, e->event_type);
1414	  break;
1415	}
1416
1417      index++;
1418
1419      if (index == mq->q->maxsize)
1420	index = 0;
1421    }
1422}
1423
1424static u8
1425session_node_cmp_event (session_event_t * e, svm_fifo_t * f)
1426{
1427  session_t *s;
1428  switch (e->event_type)
1429    {
1430    case SESSION_IO_EVT_RX:
1431    case SESSION_IO_EVT_TX:
1432    case SESSION_IO_EVT_BUILTIN_RX:
1433    case SESSION_IO_EVT_BUILTIN_TX:
1434    case SESSION_IO_EVT_TX_FLUSH:
1435      if (e->session_index == f->master_session_index)
1436	return 1;
1437      break;
1438    case SESSION_CTRL_EVT_CLOSE:
1439      break;
1440    case SESSION_CTRL_EVT_RPC:
1441      s = session_get_from_handle (e->session_handle);
1442      if (!s)
1443	{
1444	  clib_warning ("session has event but doesn't exist!");
1445	  break;
1446	}
1447      if (s->rx_fifo == f || s->tx_fifo == f)
1448	return 1;
1449      break;
1450    default:
1451      break;
1452    }
1453  return 0;
1454}
1455
1456u8
1457session_node_lookup_fifo_event (svm_fifo_t * f, session_event_t * e)
1458{
1459  session_evt_elt_t *elt;
1460  session_worker_t *wrk;
1461  int i, index, found = 0;
1462  svm_msg_q_msg_t *msg;
1463  svm_msg_q_ring_t *ring;
1464  svm_msg_q_t *mq;
1465  u8 thread_index;
1466
1467  ASSERT (e);
1468  thread_index = f->master_thread_index;
1469  wrk = session_main_get_worker (thread_index);
1470
1471  /*
1472   * Search evt queue
1473   */
1474  mq = wrk->vpp_event_queue;
1475  index = mq->q->head;
1476  for (i = 0; i < mq->q->cursize; i++)
1477    {
1478      msg = (svm_msg_q_msg_t *) (&mq->q->data[0] + mq->q->elsize * index);
1479      ring = svm_msg_q_ring (mq, msg->ring_index);
1480      clib_memcpy_fast (e, svm_msg_q_msg_data (mq, msg), ring->elsize);
1481      found = session_node_cmp_event (e, f);
1482      if (found)
1483	return 1;
1484      index = (index + 1) % mq->q->maxsize;
1485    }
1486  /*
1487   * Search pending events vector
1488   */
1489
1490  /* *INDENT-OFF* */
1491  clib_llist_foreach (wrk->event_elts, evt_list,
1492                      pool_elt_at_index (wrk->event_elts, wrk->new_head),
1493                      elt, ({
1494    found = session_node_cmp_event (&elt->evt, f);
1495    if (found)
1496      {
1497	clib_memcpy_fast (e, &elt->evt, sizeof (*e));
1498	goto done;
1499      }
1500  }));
1501  /* *INDENT-ON* */
1502
1503  /* *INDENT-OFF* */
1504  clib_llist_foreach (wrk->event_elts, evt_list,
1505                      pool_elt_at_index (wrk->event_elts, wrk->old_head),
1506                      elt, ({
1507    found = session_node_cmp_event (&elt->evt, f);
1508    if (found)
1509      {
1510	clib_memcpy_fast (e, &elt->evt, sizeof (*e));
1511	goto done;
1512      }
1513  }));
1514  /* *INDENT-ON* */
1515
1516done:
1517  return found;
1518}
1519
1520static clib_error_t *
1521session_queue_exit (vlib_main_t * vm)
1522{
1523  if (vec_len (vlib_mains) < 2)
1524    return 0;
1525
1526  /*
1527   * Shut off (especially) worker-thread session nodes.
1528   * Otherwise, vpp can crash as the main thread unmaps the
1529   * API segment.
1530   */
1531  vlib_worker_thread_barrier_sync (vm);
1532  session_node_enable_disable (0 /* is_enable */ );
1533  vlib_worker_thread_barrier_release (vm);
1534  return 0;
1535}
1536
1537VLIB_MAIN_LOOP_EXIT_FUNCTION (session_queue_exit);
1538
1539static uword
1540session_queue_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1541		       vlib_frame_t * f)
1542{
1543  f64 now, timeout = 1.0;
1544  uword *event_data = 0;
1545  uword event_type;
1546
1547  while (1)
1548    {
1549      vlib_process_wait_for_event_or_clock (vm, timeout);
1550      now = vlib_time_now (vm);
1551      event_type = vlib_process_get_events (vm, (uword **) & event_data);
1552
1553      switch (event_type)
1554	{
1555	case SESSION_Q_PROCESS_FLUSH_FRAMES:
1556	  /* Flush the frames by updating all transports times */
1557	  transport_update_time (now, 0);
1558	  break;
1559	case SESSION_Q_PROCESS_STOP:
1560	  timeout = 100000.0;
1561	  break;
1562	case ~0:
1563	  /* Timed out. Update time for all transports to trigger all
1564	   * outstanding retransmits. */
1565	  transport_update_time (now, 0);
1566	  break;
1567	}
1568      vec_reset_length (event_data);
1569    }
1570  return 0;
1571}
1572
1573/* *INDENT-OFF* */
1574VLIB_REGISTER_NODE (session_queue_process_node) =
1575{
1576  .function = session_queue_process,
1577  .type = VLIB_NODE_TYPE_PROCESS,
1578  .name = "session-queue-process",
1579  .state = VLIB_NODE_STATE_DISABLED,
1580};
1581/* *INDENT-ON* */
1582
1583static_always_inline uword
1584session_queue_pre_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node,
1585				vlib_frame_t * frame)
1586{
1587  session_main_t *sm = &session_main;
1588  if (!sm->wrk[0].vpp_event_queue)
1589    return 0;
1590  return session_queue_node_fn (vm, node, frame);
1591}
1592
1593/* *INDENT-OFF* */
1594VLIB_REGISTER_NODE (session_queue_pre_input_node) =
1595{
1596  .function = session_queue_pre_input_inline,
1597  .type = VLIB_NODE_TYPE_PRE_INPUT,
1598  .name = "session-queue-main",
1599  .state = VLIB_NODE_STATE_DISABLED,
1600};
1601/* *INDENT-ON* */
1602
1603/*
1604 * fd.io coding-style-patch-verification: ON
1605 *
1606 * Local Variables:
1607 * eval: (c-set-style "gnu")
1608 * End:
1609 */
1610