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:
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @brief Session and session manager
20 #include <vnet/session/session.h>
21 #include <vnet/session/session_debug.h>
22 #include <vnet/session/application.h>
23 #include <vnet/dpo/load_balance.h>
24 #include <vnet/fib/ip4_fib.h>
26 session_main_t session_main;
29 session_send_evt_to_thread (void *data, void *args, u32 thread_index,
30 session_evt_type_t evt_type)
35 u32 tries = 0, max_tries;
37 mq = session_main_get_vpp_event_queue (thread_index);
38 while (svm_msg_q_try_lock (mq))
40 max_tries = vlib_get_current_process (vlib_get_main ())? 1e6 : 3;
41 if (tries++ == max_tries)
43 SESSION_DBG ("failed to enqueue evt");
47 if (PREDICT_FALSE (svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
49 svm_msg_q_unlock (mq);
52 msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
53 if (PREDICT_FALSE (svm_msg_q_msg_is_invalid (&msg)))
55 svm_msg_q_unlock (mq);
58 evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
59 evt->event_type = evt_type;
62 case SESSION_CTRL_EVT_RPC:
63 evt->rpc_args.fp = data;
64 evt->rpc_args.arg = args;
66 case SESSION_IO_EVT_TX:
67 case SESSION_IO_EVT_TX_FLUSH:
68 case SESSION_IO_EVT_BUILTIN_RX:
69 evt->session_index = *(u32 *) data;
71 case SESSION_IO_EVT_BUILTIN_TX:
72 case SESSION_CTRL_EVT_CLOSE:
73 evt->session_handle = session_handle ((session_t *) data);
76 clib_warning ("evt unhandled!");
77 svm_msg_q_unlock (mq);
81 svm_msg_q_add_and_unlock (mq, &msg);
86 session_send_io_evt_to_thread (svm_fifo_t * f, session_evt_type_t evt_type)
88 return session_send_evt_to_thread (&f->master_session_index, 0,
89 f->master_thread_index, evt_type);
93 session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
94 session_evt_type_t evt_type)
96 return session_send_evt_to_thread (data, 0, thread_index, evt_type);
100 session_send_ctrl_evt_to_thread (session_t * s, session_evt_type_t evt_type)
102 /* only event supported for now is disconnect */
103 ASSERT (evt_type == SESSION_CTRL_EVT_CLOSE);
104 return session_send_evt_to_thread (s, 0, s->thread_index,
105 SESSION_CTRL_EVT_CLOSE);
109 session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
112 session_send_evt_to_thread (fp, rpc_args, thread_index,
113 SESSION_CTRL_EVT_RPC);
117 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
119 if (thread_index != vlib_get_thread_index ())
120 session_send_rpc_evt_to_thread_force (thread_index, fp, rpc_args);
123 void (*fnp) (void *) = fp;
129 session_program_transport_close (session_t * s)
131 u32 thread_index = vlib_get_thread_index ();
132 session_worker_t *wrk;
133 session_event_t *evt;
135 /* If we are in the handler thread, or being called with the worker barrier
136 * held, just append a new event to pending disconnects vector. */
137 if (vlib_thread_is_main_w_barrier () || thread_index == s->thread_index)
139 wrk = session_main_get_worker (s->thread_index);
140 vec_add2 (wrk->pending_disconnects, evt, 1);
141 clib_memset (evt, 0, sizeof (*evt));
142 evt->session_handle = session_handle (s);
143 evt->event_type = SESSION_CTRL_EVT_CLOSE;
146 session_send_ctrl_evt_to_thread (s, SESSION_CTRL_EVT_CLOSE);
150 session_alloc (u32 thread_index)
152 session_worker_t *wrk = &session_main.wrk[thread_index];
155 pool_get_aligned_will_expand (wrk->sessions, will_expand,
156 CLIB_CACHE_LINE_BYTES);
157 /* If we have peekers, let them finish */
158 if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
160 clib_rwlock_writer_lock (&wrk->peekers_rw_locks);
161 pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
162 clib_rwlock_writer_unlock (&wrk->peekers_rw_locks);
166 pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
168 clib_memset (s, 0, sizeof (*s));
169 s->session_index = s - wrk->sessions;
170 s->thread_index = thread_index;
171 s->app_index = APP_INVALID_INDEX;
176 session_free (session_t * s)
180 u8 thread_index = s->thread_index;
181 clib_memset (s, 0xFA, sizeof (*s));
182 pool_put (session_main.wrk[thread_index].sessions, s);
185 SESSION_EVT_DBG (SESSION_EVT_FREE, s);
186 pool_put (session_main.wrk[s->thread_index].sessions, s);
190 session_free_w_fifos (session_t * s)
192 segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
197 * Cleans up session and lookup table.
199 * Transport connection must still be valid.
202 session_delete (session_t * s)
206 /* Delete from the main lookup table. */
207 if ((rv = session_lookup_del_session (s)))
208 clib_warning ("hash delete error, rv %d", rv);
210 session_free_w_fifos (s);
214 session_alloc_for_connection (transport_connection_t * tc)
217 u32 thread_index = tc->thread_index;
219 ASSERT (thread_index == vlib_get_thread_index ()
220 || transport_protocol_is_cl (tc->proto));
222 s = session_alloc (thread_index);
223 s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
224 s->session_state = SESSION_STATE_CLOSED;
226 /* Attach transport to session and vice versa */
227 s->connection_index = tc->c_index;
228 tc->s_index = s->session_index;
233 * Discards bytes from buffer chain
235 * It discards n_bytes_to_drop starting at first buffer after chain_b
238 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
239 vlib_buffer_t ** chain_b,
242 vlib_buffer_t *next = *chain_b;
243 u32 to_drop = n_bytes_to_drop;
244 ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
245 while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
247 next = vlib_get_buffer (vm, next->next_buffer);
248 if (next->current_length > to_drop)
250 vlib_buffer_advance (next, to_drop);
255 to_drop -= next->current_length;
256 next->current_length = 0;
262 b->total_length_not_including_first_buffer -= n_bytes_to_drop;
266 * Enqueue buffer chain tail
269 session_enqueue_chain_tail (session_t * s, vlib_buffer_t * b,
270 u32 offset, u8 is_in_order)
272 vlib_buffer_t *chain_b;
273 u32 chain_bi, len, diff;
274 vlib_main_t *vm = vlib_get_main ();
279 if (is_in_order && offset)
281 diff = offset - b->current_length;
282 if (diff > b->total_length_not_including_first_buffer)
285 session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
286 chain_bi = vlib_get_buffer_index (vm, chain_b);
289 chain_bi = b->next_buffer;
293 chain_b = vlib_get_buffer (vm, chain_bi);
294 data = vlib_buffer_get_current (chain_b);
295 len = chain_b->current_length;
300 rv = svm_fifo_enqueue (s->rx_fifo, len, data);
307 return (rv > 0) ? (written + rv) : written;
313 /* written more than what was left in chain */
314 if (written > b->total_length_not_including_first_buffer)
317 /* drop the bytes that have already been delivered */
318 session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
323 rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset, len, data);
326 clib_warning ("failed to enqueue multi-buffer seg");
332 while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
333 ? chain_b->next_buffer : 0));
342 * Enqueue data for delivery to session peer. Does not notify peer of enqueue
343 * event but on request can queue notification events for later delivery by
344 * calling stream_server_flush_enqueue_events().
346 * @param tc Transport connection which is to be enqueued data
347 * @param b Buffer to be enqueued
348 * @param offset Offset at which to start enqueueing if out-of-order
349 * @param queue_event Flag to indicate if peer is to be notified or if event
350 * is to be queued. The former is useful when more data is
351 * enqueued and only one event is to be generated.
352 * @param is_in_order Flag to indicate if data is in order
353 * @return Number of bytes enqueued or a negative value if enqueueing failed.
356 session_enqueue_stream_connection (transport_connection_t * tc,
357 vlib_buffer_t * b, u32 offset,
358 u8 queue_event, u8 is_in_order)
361 int enqueued = 0, rv, in_order_off;
363 s = session_get (tc->s_index, tc->thread_index);
367 enqueued = svm_fifo_enqueue (s->rx_fifo,
369 vlib_buffer_get_current (b));
370 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
373 in_order_off = enqueued > b->current_length ? enqueued : 0;
374 rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
381 rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset,
383 vlib_buffer_get_current (b));
384 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
385 session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
386 /* if something was enqueued, report even this as success for ooo
387 * segment handling */
393 /* Queue RX event on this fifo. Eventually these will need to be flushed
394 * by calling stream_server_flush_enqueue_events () */
395 session_worker_t *wrk;
397 wrk = session_main_get_worker (s->thread_index);
398 if (!(s->flags & SESSION_F_RX_EVT))
400 s->flags |= SESSION_F_RX_EVT;
401 vec_add1 (wrk->session_to_enqueue[tc->proto], s->session_index);
409 session_enqueue_dgram_connection (session_t * s,
410 session_dgram_hdr_t * hdr,
411 vlib_buffer_t * b, u8 proto, u8 queue_event)
413 int enqueued = 0, rv, in_order_off;
415 ASSERT (svm_fifo_max_enqueue_prod (s->rx_fifo)
416 >= b->current_length + sizeof (*hdr));
418 svm_fifo_enqueue (s->rx_fifo, sizeof (session_dgram_hdr_t), (u8 *) hdr);
419 enqueued = svm_fifo_enqueue (s->rx_fifo, b->current_length,
420 vlib_buffer_get_current (b));
421 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued >= 0))
423 in_order_off = enqueued > b->current_length ? enqueued : 0;
424 rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
430 /* Queue RX event on this fifo. Eventually these will need to be flushed
431 * by calling stream_server_flush_enqueue_events () */
432 session_worker_t *wrk;
434 wrk = session_main_get_worker (s->thread_index);
435 if (!(s->flags & SESSION_F_RX_EVT))
437 s->flags |= SESSION_F_RX_EVT;
438 vec_add1 (wrk->session_to_enqueue[proto], s->session_index);
445 session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
446 u32 offset, u32 max_bytes)
448 session_t *s = session_get (tc->s_index, tc->thread_index);
449 return svm_fifo_peek (s->tx_fifo, offset, max_bytes, buffer);
453 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
455 session_t *s = session_get (tc->s_index, tc->thread_index);
457 if (svm_fifo_needs_tx_ntf (s->tx_fifo, max_bytes))
458 session_dequeue_notify (s);
460 return svm_fifo_dequeue_drop (s->tx_fifo, max_bytes);
464 session_notify_subscribers (u32 app_index, session_t * s,
465 svm_fifo_t * f, session_evt_type_t evt_type)
467 app_worker_t *app_wrk;
471 app = application_get (app_index);
475 for (i = 0; i < f->n_subscribers; i++)
477 app_wrk = application_get_worker (app, f->subscribers[i]);
480 if (app_worker_lock_and_send_event (app_wrk, s, evt_type))
488 * Notify session peer that new data has been enqueued.
490 * @param s Stream session for which the event is to be generated.
491 * @param lock Flag to indicate if call should lock message queue.
493 * @return 0 on success or negative number if failed to send notification.
496 session_enqueue_notify_inline (session_t * s)
498 app_worker_t *app_wrk;
502 session_index = s->session_index;
503 n_subscribers = svm_fifo_n_subscribers (s->rx_fifo);
505 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
506 if (PREDICT_FALSE (!app_wrk))
508 SESSION_DBG ("invalid s->app_index = %d", s->app_wrk_index);
513 SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
514 ed->data[0] = SESSION_IO_EVT_RX;
515 ed->data[1] = svm_fifo_max_dequeue_prod (s->rx_fifo);
519 s->flags &= ~SESSION_F_RX_EVT;
520 if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
524 if (PREDICT_FALSE (n_subscribers))
526 s = session_get (session_index, vlib_get_thread_index ());
527 return session_notify_subscribers (app_wrk->app_index, s,
528 s->rx_fifo, SESSION_IO_EVT_RX);
535 session_enqueue_notify (session_t * s)
537 return session_enqueue_notify_inline (s);
541 session_dequeue_notify (session_t * s)
543 app_worker_t *app_wrk;
545 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
546 if (PREDICT_FALSE (!app_wrk))
549 if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
553 if (PREDICT_FALSE (s->tx_fifo->n_subscribers))
554 return session_notify_subscribers (app_wrk->app_index, s,
555 s->tx_fifo, SESSION_IO_EVT_TX);
557 svm_fifo_clear_tx_ntf (s->tx_fifo);
563 * Flushes queue of sessions that are to be notified of new data
566 * @param thread_index Thread index for which the flush is to be performed.
567 * @return 0 on success or a positive number indicating the number of
568 * failures due to API queue being full.
571 session_main_flush_enqueue_events (u8 transport_proto, u32 thread_index)
573 session_worker_t *wrk = session_main_get_worker (thread_index);
578 indices = wrk->session_to_enqueue[transport_proto];
580 for (i = 0; i < vec_len (indices); i++)
582 s = session_get_if_valid (indices[i], thread_index);
583 if (PREDICT_FALSE (!s))
589 if (PREDICT_FALSE (session_enqueue_notify_inline (s)))
593 vec_reset_length (indices);
594 wrk->session_to_enqueue[transport_proto] = indices;
600 session_main_flush_all_enqueue_events (u8 transport_proto)
602 vlib_thread_main_t *vtm = vlib_get_thread_main ();
604 for (i = 0; i < 1 + vtm->n_threads; i++)
605 errors += session_main_flush_enqueue_events (transport_proto, i);
610 session_stream_connect_notify (transport_connection_t * tc, u8 is_fail)
612 u32 opaque = 0, new_ti, new_si;
613 app_worker_t *app_wrk;
618 * Find connection handle and cleanup half-open table
620 ho_handle = session_lookup_half_open_handle (tc);
621 if (ho_handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
623 SESSION_DBG ("half-open was removed!");
626 session_lookup_del_half_open (tc);
628 /* Get the app's index from the handle we stored when opening connection
629 * and the opaque (api_context for external apps) from transport session
631 app_wrk = app_worker_get_if_valid (ho_handle >> 32);
635 opaque = tc->s_index;
638 return app_worker_connect_notify (app_wrk, s, opaque);
640 s = session_alloc_for_connection (tc);
641 s->session_state = SESSION_STATE_CONNECTING;
642 s->app_wrk_index = app_wrk->wrk_index;
643 new_si = s->session_index;
644 new_ti = s->thread_index;
646 if (app_worker_init_connected (app_wrk, s))
649 app_worker_connect_notify (app_wrk, 0, opaque);
653 if (app_worker_connect_notify (app_wrk, s, opaque))
655 s = session_get (new_si, new_ti);
656 session_free_w_fifos (s);
660 s = session_get (new_si, new_ti);
661 s->session_state = SESSION_STATE_READY;
662 session_lookup_add_connection (tc, session_handle (s));
667 typedef struct _session_switch_pool_args
671 u32 new_thread_index;
672 u32 new_session_index;
673 } session_switch_pool_args_t;
676 session_switch_pool (void *cb_args)
678 session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
680 ASSERT (args->thread_index == vlib_get_thread_index ());
681 s = session_get (args->session_index, args->thread_index);
682 s->tx_fifo->master_session_index = args->new_session_index;
683 s->tx_fifo->master_thread_index = args->new_thread_index;
684 transport_cleanup (session_get_transport_proto (s), s->connection_index,
687 clib_mem_free (cb_args);
691 * Move dgram session to the right thread
694 session_dgram_connect_notify (transport_connection_t * tc,
695 u32 old_thread_index, session_t ** new_session)
698 session_switch_pool_args_t *rpc_args;
701 * Clone half-open session to the right thread.
703 new_s = session_clone_safe (tc->s_index, old_thread_index);
704 new_s->connection_index = tc->c_index;
705 new_s->rx_fifo->master_session_index = new_s->session_index;
706 new_s->rx_fifo->master_thread_index = new_s->thread_index;
707 new_s->session_state = SESSION_STATE_READY;
708 session_lookup_add_connection (tc, session_handle (new_s));
711 * Ask thread owning the old session to clean it up and make us the tx
714 rpc_args = clib_mem_alloc (sizeof (*rpc_args));
715 rpc_args->new_session_index = new_s->session_index;
716 rpc_args->new_thread_index = new_s->thread_index;
717 rpc_args->session_index = tc->s_index;
718 rpc_args->thread_index = old_thread_index;
719 session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
722 tc->s_index = new_s->session_index;
723 new_s->connection_index = tc->c_index;
724 *new_session = new_s;
729 * Notification from transport that connection is being closed.
731 * A disconnect is sent to application but state is not removed. Once
732 * disconnect is acknowledged by application, session disconnect is called.
733 * Ultimately this leads to close being called on transport (passive close).
736 session_transport_closing_notify (transport_connection_t * tc)
738 app_worker_t *app_wrk;
741 s = session_get (tc->s_index, tc->thread_index);
742 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
744 s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
745 app_wrk = app_worker_get (s->app_wrk_index);
746 app_worker_close_notify (app_wrk, s);
750 * Notification from transport that connection is being deleted
752 * This removes the session if it is still valid. It should be called only on
753 * previously fully established sessions. For instance failed connects should
754 * call stream_session_connect_notify and indicate that the connect has
758 session_transport_delete_notify (transport_connection_t * tc)
762 /* App might've been removed already */
763 if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
766 /* Make sure we don't try to send anything more */
767 svm_fifo_dequeue_drop_all (s->tx_fifo);
769 switch (s->session_state)
771 case SESSION_STATE_CREATED:
772 /* Session was created but accept notification was not yet sent to the
773 * app. Cleanup everything. */
774 session_lookup_del_session (s);
775 session_free_w_fifos (s);
777 case SESSION_STATE_ACCEPTING:
778 case SESSION_STATE_TRANSPORT_CLOSING:
779 /* If transport finishes or times out before we get a reply
780 * from the app, mark transport as closed and wait for reply
781 * before removing the session. Cleanup session table in advance
782 * because transport will soon be closed and closed sessions
783 * are assumed to have been removed from the lookup table */
784 session_lookup_del_session (s);
785 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
787 case SESSION_STATE_CLOSING:
788 case SESSION_STATE_CLOSED_WAITING:
789 /* Cleanup lookup table as transport needs to still be valid.
790 * Program transport close to ensure that all session events
791 * have been cleaned up. Once transport close is called, the
792 * session is just removed because both transport and app have
793 * confirmed the close*/
794 session_lookup_del_session (s);
795 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
796 session_program_transport_close (s);
798 case SESSION_STATE_TRANSPORT_CLOSED:
800 case SESSION_STATE_CLOSED:
804 clib_warning ("session state %u", s->session_state);
811 * Notification from transport that session can be closed
813 * Should be called by transport only if it was closed with non-empty
814 * tx fifo and once it decides to begin the closing procedure prior to
815 * issuing a delete notify. This gives the chance to the session layer
816 * to cleanup any outstanding events.
819 session_transport_closed_notify (transport_connection_t * tc)
823 if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
826 /* Transport thinks that app requested close but it actually didn't.
827 * Can happen for tcp if fin and rst are received in close succession. */
828 if (s->session_state == SESSION_STATE_READY)
830 session_transport_closing_notify (tc);
831 svm_fifo_dequeue_drop_all (s->tx_fifo);
833 /* If app close has not been received or has not yet resulted in
834 * a transport close, only mark the session transport as closed */
835 else if (s->session_state <= SESSION_STATE_CLOSING)
837 session_lookup_del_session (s);
838 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
841 s->session_state = SESSION_STATE_CLOSED;
845 * Notify application that connection has been reset.
848 session_transport_reset_notify (transport_connection_t * tc)
850 app_worker_t *app_wrk;
853 s = session_get (tc->s_index, tc->thread_index);
854 svm_fifo_dequeue_drop_all (s->tx_fifo);
855 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
857 s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
858 app_wrk = app_worker_get (s->app_wrk_index);
859 app_worker_reset_notify (app_wrk, s);
863 session_stream_accept_notify (transport_connection_t * tc)
865 app_worker_t *app_wrk;
868 s = session_get (tc->s_index, tc->thread_index);
869 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
872 s->session_state = SESSION_STATE_ACCEPTING;
873 return app_worker_accept_notify (app_wrk, s);
877 * Accept a stream session. Optionally ping the server by callback.
880 session_stream_accept (transport_connection_t * tc, u32 listener_index,
881 u32 thread_index, u8 notify)
886 s = session_alloc_for_connection (tc);
887 s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
888 s->session_state = SESSION_STATE_CREATED;
890 if ((rv = app_worker_init_accepted (s)))
893 session_lookup_add_connection (tc, session_handle (s));
895 /* Shoulder-tap the server */
898 app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
899 return app_worker_accept_notify (app_wrk, s);
906 session_open_cl (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
908 transport_connection_t *tc;
909 transport_endpoint_cfg_t *tep;
910 app_worker_t *app_wrk;
915 tep = session_endpoint_to_transport_cfg (rmt);
916 rv = transport_connect (rmt->transport_proto, tep);
919 SESSION_DBG ("Transport failed to open connection.");
920 return VNET_API_ERROR_SESSION_CONNECT;
923 tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
925 /* For dgram type of service, allocate session and fifos now */
926 app_wrk = app_worker_get (app_wrk_index);
927 s = session_alloc_for_connection (tc);
928 s->app_wrk_index = app_wrk->wrk_index;
929 s->session_state = SESSION_STATE_OPENED;
930 if (app_worker_init_connected (app_wrk, s))
936 sh = session_handle (s);
937 session_lookup_add_connection (tc, sh);
939 return app_worker_connect_notify (app_wrk, s, opaque);
943 session_open_vc (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
945 transport_connection_t *tc;
946 transport_endpoint_cfg_t *tep;
950 tep = session_endpoint_to_transport_cfg (rmt);
951 rv = transport_connect (rmt->transport_proto, tep);
954 SESSION_DBG ("Transport failed to open connection.");
955 return VNET_API_ERROR_SESSION_CONNECT;
958 tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
960 /* If transport offers a stream service, only allocate session once the
961 * connection has been established.
962 * Add connection to half-open table and save app and tc index. The
963 * latter is needed to help establish the connection while the former
964 * is needed when the connect notify comes and we have to notify the
967 handle = (((u64) app_wrk_index) << 32) | (u64) tc->c_index;
968 session_lookup_add_half_open (tc, handle);
970 /* Store api_context (opaque) for when the reply comes. Not the nicest
971 * thing but better than allocating a separate half-open pool.
973 tc->s_index = opaque;
978 session_open_app (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
980 session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) rmt;
981 transport_endpoint_cfg_t *tep_cfg = session_endpoint_to_transport_cfg (sep);
983 sep->app_wrk_index = app_wrk_index;
984 sep->opaque = opaque;
986 return transport_connect (rmt->transport_proto, tep_cfg);
989 typedef int (*session_open_service_fn) (u32, session_endpoint_t *, u32);
992 static session_open_service_fn session_open_srv_fns[TRANSPORT_N_SERVICES] = {
1000 * Ask transport to open connection to remote transport endpoint.
1002 * Stores handle for matching request with reply since the call can be
1003 * asynchronous. For instance, for TCP the 3-way handshake must complete
1004 * before reply comes. Session is only created once connection is established.
1006 * @param app_index Index of the application requesting the connect
1007 * @param st Session type requested.
1008 * @param tep Remote transport endpoint
1009 * @param opaque Opaque data (typically, api_context) the application expects
1010 * on open completion.
1013 session_open (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1015 transport_service_type_t tst;
1016 tst = transport_protocol_service_type (rmt->transport_proto);
1017 return session_open_srv_fns[tst] (app_wrk_index, rmt, opaque);
1021 * Ask transport to listen on session endpoint.
1023 * @param s Session for which listen will be called. Note that unlike
1024 * established sessions, listen sessions are not associated to a
1026 * @param sep Local endpoint to be listened on.
1029 session_listen (session_t * ls, session_endpoint_cfg_t * sep)
1031 transport_endpoint_t *tep;
1032 u32 tc_index, s_index;
1034 /* Transport bind/listen */
1035 tep = session_endpoint_to_transport (sep);
1036 s_index = ls->session_index;
1037 tc_index = transport_start_listen (session_get_transport_proto (ls),
1040 if (tc_index == (u32) ~ 0)
1043 /* Attach transport to session. Lookup tables are populated by the app
1044 * worker because local tables (for ct sessions) are not backed by a fib */
1045 ls = listen_session_get (s_index);
1046 ls->connection_index = tc_index;
1052 * Ask transport to stop listening on local transport endpoint.
1054 * @param s Session to stop listening on. It must be in state LISTENING.
1057 session_stop_listen (session_t * s)
1059 transport_proto_t tp = session_get_transport_proto (s);
1060 transport_connection_t *tc;
1062 if (s->session_state != SESSION_STATE_LISTENING)
1065 tc = transport_get_listener (tp, s->connection_index);
1067 return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
1069 session_lookup_del_connection (tc);
1070 transport_stop_listen (tp, s->connection_index);
1075 * Initialize session closing procedure.
1077 * Request is always sent to session node to ensure that all outstanding
1078 * requests are served before transport is notified.
1081 session_close (session_t * s)
1086 if (s->session_state >= SESSION_STATE_CLOSING)
1088 /* Session will only be removed once both app and transport
1089 * acknowledge the close */
1090 if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1091 session_program_transport_close (s);
1093 /* Session already closed. Clear the tx fifo */
1094 if (s->session_state == SESSION_STATE_CLOSED)
1095 svm_fifo_dequeue_drop_all (s->tx_fifo);
1099 s->session_state = SESSION_STATE_CLOSING;
1100 session_program_transport_close (s);
1104 * Notify transport the session can be disconnected. This should eventually
1105 * result in a delete notification that allows us to cleanup session state.
1106 * Called for both active/passive disconnects.
1108 * Must be called from the session's thread.
1111 session_transport_close (session_t * s)
1113 /* If transport is already closed, just free the session */
1114 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSED)
1116 session_free_w_fifos (s);
1120 /* If tx queue wasn't drained, change state to closed waiting for transport.
1121 * This way, the transport, if it so wishes, can continue to try sending the
1122 * outstanding data (in closed state it cannot). It MUST however at one
1123 * point, either after sending everything or after a timeout, call delete
1124 * notify. This will finally lead to the complete cleanup of the session.
1126 if (svm_fifo_max_dequeue_cons (s->tx_fifo))
1127 s->session_state = SESSION_STATE_CLOSED_WAITING;
1129 s->session_state = SESSION_STATE_CLOSED;
1131 transport_close (session_get_transport_proto (s), s->connection_index,
1136 * Cleanup transport and session state.
1138 * Notify transport of the cleanup and free the session. This should
1139 * be called only if transport reported some error and is already
1143 session_transport_cleanup (session_t * s)
1145 s->session_state = SESSION_STATE_CLOSED;
1147 /* Delete from main lookup table before we axe the the transport */
1148 session_lookup_del_session (s);
1149 transport_cleanup (session_get_transport_proto (s), s->connection_index,
1151 /* Since we called cleanup, no delete notification will come. So, make
1152 * sure the session is properly freed. */
1153 session_free_w_fifos (s);
1157 * Allocate event queues in the shared-memory segment
1159 * That can either be a newly created memfd segment, that will need to be
1160 * mapped by all stack users, or the binary api's svm region. The latter is
1161 * assumed to be already mapped. NOTE that this assumption DOES NOT hold if
1162 * api clients bootstrap shm api over sockets (i.e. use memfd segments) and
1163 * vpp uses api svm region for event queues.
1166 session_vpp_event_queues_allocate (session_main_t * smm)
1168 u32 evt_q_length = 2048, evt_size = sizeof (session_event_t);
1169 ssvm_private_t *eqs = &smm->evt_qs_segment;
1170 api_main_t *am = &api_main;
1171 uword eqs_size = 64 << 20;
1172 pid_t vpp_pid = getpid ();
1176 if (smm->configured_event_queue_length)
1177 evt_q_length = smm->configured_event_queue_length;
1179 if (smm->evt_qs_use_memfd_seg)
1181 if (smm->evt_qs_segment_size)
1182 eqs_size = smm->evt_qs_segment_size;
1184 eqs->ssvm_size = eqs_size;
1185 eqs->i_am_master = 1;
1186 eqs->my_pid = vpp_pid;
1187 eqs->name = format (0, "%s%c", "evt-qs-segment", 0);
1188 eqs->requested_va = smm->session_baseva;
1190 if (ssvm_master_init (eqs, SSVM_SEGMENT_MEMFD))
1192 clib_warning ("failed to initialize queue segment");
1197 if (smm->evt_qs_use_memfd_seg)
1198 oldheap = ssvm_push_heap (eqs->sh);
1200 oldheap = svm_push_data_heap (am->vlib_rp);
1202 for (i = 0; i < vec_len (smm->wrk); i++)
1204 svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1205 svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
1206 {evt_q_length, evt_size, 0}
1208 {evt_q_length >> 1, 256, 0}
1210 cfg->consumer_pid = 0;
1212 cfg->q_nitems = evt_q_length;
1213 cfg->ring_cfgs = rc;
1214 smm->wrk[i].vpp_event_queue = svm_msg_q_alloc (cfg);
1215 if (smm->evt_qs_use_memfd_seg)
1217 if (svm_msg_q_alloc_consumer_eventfd (smm->wrk[i].vpp_event_queue))
1218 clib_warning ("eventfd returned");
1222 if (smm->evt_qs_use_memfd_seg)
1223 ssvm_pop_heap (oldheap);
1225 svm_pop_heap (oldheap);
1229 session_main_get_evt_q_segment (void)
1231 session_main_t *smm = &session_main;
1232 if (smm->evt_qs_use_memfd_seg)
1233 return &smm->evt_qs_segment;
1238 session_segment_handle (session_t * s)
1243 return SESSION_INVALID_HANDLE;
1246 return segment_manager_make_segment_handle (f->segment_manager,
1251 static session_fifo_rx_fn *session_tx_fns[TRANSPORT_TX_N_FNS] = {
1252 session_tx_fifo_peek_and_snd,
1253 session_tx_fifo_dequeue_and_snd,
1254 session_tx_fifo_dequeue_internal,
1255 session_tx_fifo_dequeue_and_snd
1260 * Initialize session layer for given transport proto and ip version
1262 * Allocates per session type (transport proto + ip version) data structures
1263 * and adds arc from session queue node to session type output node.
1266 session_register_transport (transport_proto_t transport_proto,
1267 const transport_proto_vft_t * vft, u8 is_ip4,
1270 session_main_t *smm = &session_main;
1271 session_type_t session_type;
1272 u32 next_index = ~0;
1274 session_type = session_type_from_proto_and_ip (transport_proto, is_ip4);
1276 vec_validate (smm->session_type_to_next, session_type);
1277 vec_validate (smm->session_tx_fns, session_type);
1280 if (output_node != ~0)
1282 foreach_vlib_main (({
1283 next_index = vlib_node_add_next (this_vlib_main,
1284 session_queue_node.index,
1290 smm->session_type_to_next[session_type] = next_index;
1291 smm->session_tx_fns[session_type] = session_tx_fns[vft->tx_type];
1294 transport_connection_t *
1295 session_get_transport (session_t * s)
1297 if (s->session_state != SESSION_STATE_LISTENING)
1298 return transport_get_connection (session_get_transport_proto (s),
1299 s->connection_index, s->thread_index);
1301 return transport_get_listener (session_get_transport_proto (s),
1302 s->connection_index);
1306 session_get_endpoint (session_t * s, transport_endpoint_t * tep, u8 is_lcl)
1308 if (s->session_state != SESSION_STATE_LISTENING)
1309 return transport_get_endpoint (session_get_transport_proto (s),
1310 s->connection_index, s->thread_index, tep,
1313 return transport_get_listener_endpoint (session_get_transport_proto (s),
1314 s->connection_index, tep, is_lcl);
1317 transport_connection_t *
1318 listen_session_get_transport (session_t * s)
1320 return transport_get_listener (session_get_transport_proto (s),
1321 s->connection_index);
1325 session_flush_frames_main_thread (vlib_main_t * vm)
1327 ASSERT (vlib_get_thread_index () == 0);
1328 vlib_process_signal_event_mt (vm, session_queue_process_node.index,
1329 SESSION_Q_PROCESS_FLUSH_FRAMES, 0);
1332 static clib_error_t *
1333 session_manager_main_enable (vlib_main_t * vm)
1335 segment_manager_main_init_args_t _sm_args = { 0 }, *sm_args = &_sm_args;
1336 session_main_t *smm = &session_main;
1337 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1338 u32 num_threads, preallocated_sessions_per_worker;
1339 session_worker_t *wrk;
1342 num_threads = 1 /* main thread */ + vtm->n_threads;
1344 if (num_threads < 1)
1345 return clib_error_return (0, "n_thread_stacks not set");
1347 /* Allocate cache line aligned worker contexts */
1348 vec_validate_aligned (smm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1350 for (i = 0; i < num_threads; i++)
1353 vec_validate (wrk->free_event_vector, 128);
1354 _vec_len (wrk->free_event_vector) = 0;
1355 vec_validate (wrk->pending_event_vector, 128);
1356 _vec_len (wrk->pending_event_vector) = 0;
1357 vec_validate (wrk->pending_disconnects, 128);
1358 _vec_len (wrk->pending_disconnects) = 0;
1359 vec_validate (wrk->postponed_event_vector, 128);
1360 _vec_len (wrk->postponed_event_vector) = 0;
1362 wrk->last_vlib_time = vlib_time_now (vlib_mains[i]);
1363 wrk->dispatch_period = 500e-6;
1365 if (num_threads > 1)
1366 clib_rwlock_init (&smm->wrk[i].peekers_rw_locks);
1370 vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
1373 /* Allocate vpp event queues segment and queue */
1374 session_vpp_event_queues_allocate (smm);
1376 /* Initialize fifo segment main baseva and timeout */
1377 sm_args->baseva = smm->session_baseva + smm->evt_qs_segment_size;
1378 sm_args->size = smm->session_va_space_size;
1379 segment_manager_main_init (sm_args);
1381 /* Preallocate sessions */
1382 if (smm->preallocated_sessions)
1384 if (num_threads == 1)
1386 pool_init_fixed (smm->wrk[0].sessions, smm->preallocated_sessions);
1391 preallocated_sessions_per_worker =
1392 (1.1 * (f64) smm->preallocated_sessions /
1393 (f64) (num_threads - 1));
1395 for (j = 1; j < num_threads; j++)
1397 pool_init_fixed (smm->wrk[j].sessions,
1398 preallocated_sessions_per_worker);
1403 session_lookup_init ();
1404 app_namespaces_init ();
1407 smm->is_enabled = 1;
1409 /* Enable transports */
1410 transport_enable_disable (vm, 1);
1411 transport_init_tx_pacers_period ();
1416 session_node_enable_disable (u8 is_en)
1418 u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1419 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1420 u8 have_workers = vtm->n_threads != 0;
1423 foreach_vlib_main (({
1424 if (have_workers && ii == 0)
1426 vlib_node_set_state (this_vlib_main, session_queue_process_node.index,
1430 vlib_node_t *n = vlib_get_node (this_vlib_main,
1431 session_queue_process_node.index);
1432 vlib_start_process (this_vlib_main, n->runtime_index);
1436 vlib_process_signal_event_mt (this_vlib_main,
1437 session_queue_process_node.index,
1438 SESSION_Q_PROCESS_STOP, 0);
1443 vlib_node_set_state (this_vlib_main, session_queue_node.index,
1450 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1452 clib_error_t *error = 0;
1455 if (session_main.is_enabled)
1458 session_node_enable_disable (is_en);
1459 error = session_manager_main_enable (vm);
1463 session_main.is_enabled = 0;
1464 session_node_enable_disable (is_en);
1471 session_manager_main_init (vlib_main_t * vm)
1473 session_main_t *smm = &session_main;
1474 smm->session_baseva = HIGH_SEGMENT_BASEVA;
1475 #if (HIGH_SEGMENT_BASEVA > (4ULL << 30))
1476 smm->session_va_space_size = 128ULL << 30;
1477 smm->evt_qs_segment_size = 64 << 20;
1479 smm->session_va_space_size = 128 << 20;
1480 smm->evt_qs_segment_size = 1 << 20;
1482 smm->is_enabled = 0;
1486 VLIB_INIT_FUNCTION (session_manager_main_init);
1488 static clib_error_t *
1489 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1491 session_main_t *smm = &session_main;
1495 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1497 if (unformat (input, "event-queue-length %d", &nitems))
1500 smm->configured_event_queue_length = nitems;
1502 clib_warning ("event queue length %d too small, ignored", nitems);
1504 else if (unformat (input, "preallocated-sessions %d",
1505 &smm->preallocated_sessions))
1507 else if (unformat (input, "v4-session-table-buckets %d",
1508 &smm->configured_v4_session_table_buckets))
1510 else if (unformat (input, "v4-halfopen-table-buckets %d",
1511 &smm->configured_v4_halfopen_table_buckets))
1513 else if (unformat (input, "v6-session-table-buckets %d",
1514 &smm->configured_v6_session_table_buckets))
1516 else if (unformat (input, "v6-halfopen-table-buckets %d",
1517 &smm->configured_v6_halfopen_table_buckets))
1519 else if (unformat (input, "v4-session-table-memory %U",
1520 unformat_memory_size, &tmp))
1522 if (tmp >= 0x100000000)
1523 return clib_error_return (0, "memory size %llx (%lld) too large",
1525 smm->configured_v4_session_table_memory = tmp;
1527 else if (unformat (input, "v4-halfopen-table-memory %U",
1528 unformat_memory_size, &tmp))
1530 if (tmp >= 0x100000000)
1531 return clib_error_return (0, "memory size %llx (%lld) too large",
1533 smm->configured_v4_halfopen_table_memory = tmp;
1535 else if (unformat (input, "v6-session-table-memory %U",
1536 unformat_memory_size, &tmp))
1538 if (tmp >= 0x100000000)
1539 return clib_error_return (0, "memory size %llx (%lld) too large",
1541 smm->configured_v6_session_table_memory = tmp;
1543 else if (unformat (input, "v6-halfopen-table-memory %U",
1544 unformat_memory_size, &tmp))
1546 if (tmp >= 0x100000000)
1547 return clib_error_return (0, "memory size %llx (%lld) too large",
1549 smm->configured_v6_halfopen_table_memory = tmp;
1551 else if (unformat (input, "local-endpoints-table-memory %U",
1552 unformat_memory_size, &tmp))
1554 if (tmp >= 0x100000000)
1555 return clib_error_return (0, "memory size %llx (%lld) too large",
1557 smm->local_endpoints_table_memory = tmp;
1559 else if (unformat (input, "local-endpoints-table-buckets %d",
1560 &smm->local_endpoints_table_buckets))
1562 else if (unformat (input, "evt_qs_memfd_seg"))
1563 smm->evt_qs_use_memfd_seg = 1;
1564 else if (unformat (input, "evt_qs_seg_size %U", unformat_memory_size,
1565 &smm->evt_qs_segment_size))
1568 return clib_error_return (0, "unknown input `%U'",
1569 format_unformat_error, input);
1574 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1577 * fd.io coding-style-patch-verification: ON
1580 * eval: (c-set-style "gnu")