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)
36 mq = session_main_get_vpp_event_queue (thread_index);
37 if (PREDICT_FALSE (svm_msg_q_lock (mq)))
39 if (PREDICT_FALSE (svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
41 svm_msg_q_unlock (mq);
44 msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
45 if (PREDICT_FALSE (svm_msg_q_msg_is_invalid (&msg)))
47 svm_msg_q_unlock (mq);
50 evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
51 evt->event_type = evt_type;
54 case SESSION_CTRL_EVT_RPC:
55 evt->rpc_args.fp = data;
56 evt->rpc_args.arg = args;
58 case SESSION_IO_EVT_TX:
59 case SESSION_IO_EVT_TX_FLUSH:
60 case SESSION_IO_EVT_BUILTIN_RX:
61 evt->session_index = *(u32 *) data;
63 case SESSION_IO_EVT_BUILTIN_TX:
64 case SESSION_CTRL_EVT_CLOSE:
65 evt->session_handle = session_handle ((session_t *) data);
68 clib_warning ("evt unhandled!");
69 svm_msg_q_unlock (mq);
73 svm_msg_q_add_and_unlock (mq, &msg);
78 session_send_io_evt_to_thread (svm_fifo_t * f, session_evt_type_t evt_type)
80 return session_send_evt_to_thread (&f->master_session_index, 0,
81 f->master_thread_index, evt_type);
85 session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
86 session_evt_type_t evt_type)
88 return session_send_evt_to_thread (data, 0, thread_index, evt_type);
92 session_send_ctrl_evt_to_thread (session_t * s, session_evt_type_t evt_type)
94 /* only event supported for now is disconnect */
95 ASSERT (evt_type == SESSION_CTRL_EVT_CLOSE);
96 return session_send_evt_to_thread (s, 0, s->thread_index,
97 SESSION_CTRL_EVT_CLOSE);
101 session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
104 session_send_evt_to_thread (fp, rpc_args, thread_index,
105 SESSION_CTRL_EVT_RPC);
109 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
111 if (thread_index != vlib_get_thread_index ())
112 session_send_rpc_evt_to_thread_force (thread_index, fp, rpc_args);
115 void (*fnp) (void *) = fp;
121 session_program_transport_close (session_t * s)
123 u32 thread_index = vlib_get_thread_index ();
124 session_worker_t *wrk;
125 session_event_t *evt;
127 /* If we are in the handler thread, or being called with the worker barrier
128 * held, just append a new event to pending disconnects vector. */
129 if (vlib_thread_is_main_w_barrier () || thread_index == s->thread_index)
131 wrk = session_main_get_worker (s->thread_index);
132 vec_add2 (wrk->pending_disconnects, evt, 1);
133 clib_memset (evt, 0, sizeof (*evt));
134 evt->session_handle = session_handle (s);
135 evt->event_type = SESSION_CTRL_EVT_CLOSE;
138 session_send_ctrl_evt_to_thread (s, SESSION_CTRL_EVT_CLOSE);
142 session_alloc (u32 thread_index)
144 session_worker_t *wrk = &session_main.wrk[thread_index];
147 pool_get_aligned_will_expand (wrk->sessions, will_expand,
148 CLIB_CACHE_LINE_BYTES);
149 /* If we have peekers, let them finish */
150 if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
152 clib_rwlock_writer_lock (&wrk->peekers_rw_locks);
153 pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
154 clib_rwlock_writer_unlock (&wrk->peekers_rw_locks);
158 pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
160 clib_memset (s, 0, sizeof (*s));
161 s->session_index = s - wrk->sessions;
162 s->thread_index = thread_index;
163 s->app_index = APP_INVALID_INDEX;
168 session_free (session_t * s)
172 u8 thread_index = s->thread_index;
173 clib_memset (s, 0xFA, sizeof (*s));
174 pool_put (session_main.wrk[thread_index].sessions, s);
177 SESSION_EVT_DBG (SESSION_EVT_FREE, s);
178 pool_put (session_main.wrk[s->thread_index].sessions, s);
182 session_free_w_fifos (session_t * s)
184 segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
189 * Cleans up session and lookup table.
191 * Transport connection must still be valid.
194 session_delete (session_t * s)
198 /* Delete from the main lookup table. */
199 if ((rv = session_lookup_del_session (s)))
200 clib_warning ("hash delete error, rv %d", rv);
202 session_free_w_fifos (s);
206 session_alloc_for_connection (transport_connection_t * tc)
209 u32 thread_index = tc->thread_index;
211 ASSERT (thread_index == vlib_get_thread_index ()
212 || transport_protocol_is_cl (tc->proto));
214 s = session_alloc (thread_index);
215 s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
216 s->session_state = SESSION_STATE_CLOSED;
218 /* Attach transport to session and vice versa */
219 s->connection_index = tc->c_index;
220 tc->s_index = s->session_index;
225 * Discards bytes from buffer chain
227 * It discards n_bytes_to_drop starting at first buffer after chain_b
230 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
231 vlib_buffer_t ** chain_b,
234 vlib_buffer_t *next = *chain_b;
235 u32 to_drop = n_bytes_to_drop;
236 ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
237 while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
239 next = vlib_get_buffer (vm, next->next_buffer);
240 if (next->current_length > to_drop)
242 vlib_buffer_advance (next, to_drop);
247 to_drop -= next->current_length;
248 next->current_length = 0;
254 b->total_length_not_including_first_buffer -= n_bytes_to_drop;
258 * Enqueue buffer chain tail
261 session_enqueue_chain_tail (session_t * s, vlib_buffer_t * b,
262 u32 offset, u8 is_in_order)
264 vlib_buffer_t *chain_b;
265 u32 chain_bi, len, diff;
266 vlib_main_t *vm = vlib_get_main ();
271 if (is_in_order && offset)
273 diff = offset - b->current_length;
274 if (diff > b->total_length_not_including_first_buffer)
277 session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
278 chain_bi = vlib_get_buffer_index (vm, chain_b);
281 chain_bi = b->next_buffer;
285 chain_b = vlib_get_buffer (vm, chain_bi);
286 data = vlib_buffer_get_current (chain_b);
287 len = chain_b->current_length;
292 rv = svm_fifo_enqueue (s->rx_fifo, len, data);
299 return (rv > 0) ? (written + rv) : written;
305 /* written more than what was left in chain */
306 if (written > b->total_length_not_including_first_buffer)
309 /* drop the bytes that have already been delivered */
310 session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
315 rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset, len, data);
318 clib_warning ("failed to enqueue multi-buffer seg");
324 while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
325 ? chain_b->next_buffer : 0));
334 * Enqueue data for delivery to session peer. Does not notify peer of enqueue
335 * event but on request can queue notification events for later delivery by
336 * calling stream_server_flush_enqueue_events().
338 * @param tc Transport connection which is to be enqueued data
339 * @param b Buffer to be enqueued
340 * @param offset Offset at which to start enqueueing if out-of-order
341 * @param queue_event Flag to indicate if peer is to be notified or if event
342 * is to be queued. The former is useful when more data is
343 * enqueued and only one event is to be generated.
344 * @param is_in_order Flag to indicate if data is in order
345 * @return Number of bytes enqueued or a negative value if enqueueing failed.
348 session_enqueue_stream_connection (transport_connection_t * tc,
349 vlib_buffer_t * b, u32 offset,
350 u8 queue_event, u8 is_in_order)
353 int enqueued = 0, rv, in_order_off;
355 s = session_get (tc->s_index, tc->thread_index);
359 enqueued = svm_fifo_enqueue (s->rx_fifo,
361 vlib_buffer_get_current (b));
362 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
365 in_order_off = enqueued > b->current_length ? enqueued : 0;
366 rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
373 rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset,
375 vlib_buffer_get_current (b));
376 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
377 session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
378 /* if something was enqueued, report even this as success for ooo
379 * segment handling */
385 /* Queue RX event on this fifo. Eventually these will need to be flushed
386 * by calling stream_server_flush_enqueue_events () */
387 session_worker_t *wrk;
389 wrk = session_main_get_worker (s->thread_index);
390 if (!(s->flags & SESSION_F_RX_EVT))
392 s->flags |= SESSION_F_RX_EVT;
393 vec_add1 (wrk->session_to_enqueue[tc->proto], s->session_index);
401 session_enqueue_dgram_connection (session_t * s,
402 session_dgram_hdr_t * hdr,
403 vlib_buffer_t * b, u8 proto, u8 queue_event)
405 int enqueued = 0, rv, in_order_off;
407 ASSERT (svm_fifo_max_enqueue_prod (s->rx_fifo)
408 >= b->current_length + sizeof (*hdr));
410 svm_fifo_enqueue (s->rx_fifo, sizeof (session_dgram_hdr_t), (u8 *) hdr);
411 enqueued = svm_fifo_enqueue (s->rx_fifo, b->current_length,
412 vlib_buffer_get_current (b));
413 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued >= 0))
415 in_order_off = enqueued > b->current_length ? enqueued : 0;
416 rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
422 /* Queue RX event on this fifo. Eventually these will need to be flushed
423 * by calling stream_server_flush_enqueue_events () */
424 session_worker_t *wrk;
426 wrk = session_main_get_worker (s->thread_index);
427 if (!(s->flags & SESSION_F_RX_EVT))
429 s->flags |= SESSION_F_RX_EVT;
430 vec_add1 (wrk->session_to_enqueue[proto], s->session_index);
437 session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
438 u32 offset, u32 max_bytes)
440 session_t *s = session_get (tc->s_index, tc->thread_index);
441 return svm_fifo_peek (s->tx_fifo, offset, max_bytes, buffer);
445 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
447 session_t *s = session_get (tc->s_index, tc->thread_index);
450 rv = svm_fifo_dequeue_drop (s->tx_fifo, max_bytes);
452 if (svm_fifo_needs_tx_ntf (s->tx_fifo, max_bytes))
453 session_dequeue_notify (s);
459 session_notify_subscribers (u32 app_index, session_t * s,
460 svm_fifo_t * f, session_evt_type_t evt_type)
462 app_worker_t *app_wrk;
466 app = application_get (app_index);
470 for (i = 0; i < f->n_subscribers; i++)
472 app_wrk = application_get_worker (app, f->subscribers[i]);
475 if (app_worker_lock_and_send_event (app_wrk, s, evt_type))
483 * Notify session peer that new data has been enqueued.
485 * @param s Stream session for which the event is to be generated.
486 * @param lock Flag to indicate if call should lock message queue.
488 * @return 0 on success or negative number if failed to send notification.
491 session_enqueue_notify_inline (session_t * s)
493 app_worker_t *app_wrk;
497 session_index = s->session_index;
498 n_subscribers = svm_fifo_n_subscribers (s->rx_fifo);
500 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
501 if (PREDICT_FALSE (!app_wrk))
503 SESSION_DBG ("invalid s->app_index = %d", s->app_wrk_index);
508 SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
509 ed->data[0] = SESSION_IO_EVT_RX;
510 ed->data[1] = svm_fifo_max_dequeue_prod (s->rx_fifo);
514 s->flags &= ~SESSION_F_RX_EVT;
515 if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
519 if (PREDICT_FALSE (n_subscribers))
521 s = session_get (session_index, vlib_get_thread_index ());
522 return session_notify_subscribers (app_wrk->app_index, s,
523 s->rx_fifo, SESSION_IO_EVT_RX);
530 session_enqueue_notify (session_t * s)
532 return session_enqueue_notify_inline (s);
536 session_dequeue_notify (session_t * s)
538 app_worker_t *app_wrk;
540 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
541 if (PREDICT_FALSE (!app_wrk))
544 if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
548 if (PREDICT_FALSE (s->tx_fifo->n_subscribers))
549 return session_notify_subscribers (app_wrk->app_index, s,
550 s->tx_fifo, SESSION_IO_EVT_TX);
552 svm_fifo_clear_tx_ntf (s->tx_fifo);
558 * Flushes queue of sessions that are to be notified of new data
561 * @param thread_index Thread index for which the flush is to be performed.
562 * @return 0 on success or a positive number indicating the number of
563 * failures due to API queue being full.
566 session_main_flush_enqueue_events (u8 transport_proto, u32 thread_index)
568 session_worker_t *wrk = session_main_get_worker (thread_index);
573 indices = wrk->session_to_enqueue[transport_proto];
575 for (i = 0; i < vec_len (indices); i++)
577 s = session_get_if_valid (indices[i], thread_index);
578 if (PREDICT_FALSE (!s))
584 if (PREDICT_FALSE (session_enqueue_notify_inline (s)))
588 vec_reset_length (indices);
589 wrk->session_to_enqueue[transport_proto] = indices;
595 session_main_flush_all_enqueue_events (u8 transport_proto)
597 vlib_thread_main_t *vtm = vlib_get_thread_main ();
599 for (i = 0; i < 1 + vtm->n_threads; i++)
600 errors += session_main_flush_enqueue_events (transport_proto, i);
605 session_stream_connect_notify (transport_connection_t * tc, u8 is_fail)
607 u32 opaque = 0, new_ti, new_si;
608 app_worker_t *app_wrk;
613 * Find connection handle and cleanup half-open table
615 ho_handle = session_lookup_half_open_handle (tc);
616 if (ho_handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
618 SESSION_DBG ("half-open was removed!");
621 session_lookup_del_half_open (tc);
623 /* Get the app's index from the handle we stored when opening connection
624 * and the opaque (api_context for external apps) from transport session
626 app_wrk = app_worker_get_if_valid (ho_handle >> 32);
630 opaque = tc->s_index;
633 return app_worker_connect_notify (app_wrk, s, opaque);
635 s = session_alloc_for_connection (tc);
636 s->session_state = SESSION_STATE_CONNECTING;
637 s->app_wrk_index = app_wrk->wrk_index;
638 new_si = s->session_index;
639 new_ti = s->thread_index;
641 if (app_worker_init_connected (app_wrk, s))
644 app_worker_connect_notify (app_wrk, 0, opaque);
648 if (app_worker_connect_notify (app_wrk, s, opaque))
650 s = session_get (new_si, new_ti);
651 session_free_w_fifos (s);
655 s = session_get (new_si, new_ti);
656 s->session_state = SESSION_STATE_READY;
657 session_lookup_add_connection (tc, session_handle (s));
662 typedef struct _session_switch_pool_args
666 u32 new_thread_index;
667 u32 new_session_index;
668 } session_switch_pool_args_t;
671 session_switch_pool (void *cb_args)
673 session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
675 ASSERT (args->thread_index == vlib_get_thread_index ());
676 s = session_get (args->session_index, args->thread_index);
677 s->tx_fifo->master_session_index = args->new_session_index;
678 s->tx_fifo->master_thread_index = args->new_thread_index;
679 transport_cleanup (session_get_transport_proto (s), s->connection_index,
682 clib_mem_free (cb_args);
686 * Move dgram session to the right thread
689 session_dgram_connect_notify (transport_connection_t * tc,
690 u32 old_thread_index, session_t ** new_session)
693 session_switch_pool_args_t *rpc_args;
696 * Clone half-open session to the right thread.
698 new_s = session_clone_safe (tc->s_index, old_thread_index);
699 new_s->connection_index = tc->c_index;
700 new_s->rx_fifo->master_session_index = new_s->session_index;
701 new_s->rx_fifo->master_thread_index = new_s->thread_index;
702 new_s->session_state = SESSION_STATE_READY;
703 session_lookup_add_connection (tc, session_handle (new_s));
706 * Ask thread owning the old session to clean it up and make us the tx
709 rpc_args = clib_mem_alloc (sizeof (*rpc_args));
710 rpc_args->new_session_index = new_s->session_index;
711 rpc_args->new_thread_index = new_s->thread_index;
712 rpc_args->session_index = tc->s_index;
713 rpc_args->thread_index = old_thread_index;
714 session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
717 tc->s_index = new_s->session_index;
718 new_s->connection_index = tc->c_index;
719 *new_session = new_s;
724 * Notification from transport that connection is being closed.
726 * A disconnect is sent to application but state is not removed. Once
727 * disconnect is acknowledged by application, session disconnect is called.
728 * Ultimately this leads to close being called on transport (passive close).
731 session_transport_closing_notify (transport_connection_t * tc)
733 app_worker_t *app_wrk;
736 s = session_get (tc->s_index, tc->thread_index);
737 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
739 s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
740 app_wrk = app_worker_get (s->app_wrk_index);
741 app_worker_close_notify (app_wrk, s);
745 * Notification from transport that connection is being deleted
747 * This removes the session if it is still valid. It should be called only on
748 * previously fully established sessions. For instance failed connects should
749 * call stream_session_connect_notify and indicate that the connect has
753 session_transport_delete_notify (transport_connection_t * tc)
757 /* App might've been removed already */
758 if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
761 /* Make sure we don't try to send anything more */
762 svm_fifo_dequeue_drop_all (s->tx_fifo);
764 switch (s->session_state)
766 case SESSION_STATE_CREATED:
767 /* Session was created but accept notification was not yet sent to the
768 * app. Cleanup everything. */
769 session_lookup_del_session (s);
770 session_free_w_fifos (s);
772 case SESSION_STATE_ACCEPTING:
773 case SESSION_STATE_TRANSPORT_CLOSING:
774 /* If transport finishes or times out before we get a reply
775 * from the app, mark transport as closed and wait for reply
776 * before removing the session. Cleanup session table in advance
777 * because transport will soon be closed and closed sessions
778 * are assumed to have been removed from the lookup table */
779 session_lookup_del_session (s);
780 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
782 case SESSION_STATE_CLOSING:
783 case SESSION_STATE_CLOSED_WAITING:
784 /* Cleanup lookup table as transport needs to still be valid.
785 * Program transport close to ensure that all session events
786 * have been cleaned up. Once transport close is called, the
787 * session is just removed because both transport and app have
788 * confirmed the close*/
789 session_lookup_del_session (s);
790 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
791 session_program_transport_close (s);
793 case SESSION_STATE_TRANSPORT_CLOSED:
795 case SESSION_STATE_CLOSED:
799 clib_warning ("session state %u", s->session_state);
806 * Notification from transport that session can be closed
808 * Should be called by transport only if it was closed with non-empty
809 * tx fifo and once it decides to begin the closing procedure prior to
810 * issuing a delete notify. This gives the chance to the session layer
811 * to cleanup any outstanding events.
814 session_transport_closed_notify (transport_connection_t * tc)
818 if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
821 /* Transport thinks that app requested close but it actually didn't.
822 * Can happen for tcp if fin and rst are received in close succession. */
823 if (s->session_state == SESSION_STATE_READY)
825 session_transport_closing_notify (tc);
826 svm_fifo_dequeue_drop_all (s->tx_fifo);
828 /* If app close has not been received or has not yet resulted in
829 * a transport close, only mark the session transport as closed */
830 else if (s->session_state <= SESSION_STATE_CLOSING)
832 session_lookup_del_session (s);
833 s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
836 s->session_state = SESSION_STATE_CLOSED;
840 * Notify application that connection has been reset.
843 session_transport_reset_notify (transport_connection_t * tc)
845 app_worker_t *app_wrk;
848 s = session_get (tc->s_index, tc->thread_index);
849 svm_fifo_dequeue_drop_all (s->tx_fifo);
850 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
852 s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
853 app_wrk = app_worker_get (s->app_wrk_index);
854 app_worker_reset_notify (app_wrk, s);
858 session_stream_accept_notify (transport_connection_t * tc)
860 app_worker_t *app_wrk;
863 s = session_get (tc->s_index, tc->thread_index);
864 app_wrk = app_worker_get_if_valid (s->app_wrk_index);
867 s->session_state = SESSION_STATE_ACCEPTING;
868 return app_worker_accept_notify (app_wrk, s);
872 * Accept a stream session. Optionally ping the server by callback.
875 session_stream_accept (transport_connection_t * tc, u32 listener_index,
876 u32 thread_index, u8 notify)
881 s = session_alloc_for_connection (tc);
882 s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
883 s->session_state = SESSION_STATE_CREATED;
885 if ((rv = app_worker_init_accepted (s)))
888 session_lookup_add_connection (tc, session_handle (s));
890 /* Shoulder-tap the server */
893 app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
894 return app_worker_accept_notify (app_wrk, s);
901 session_open_cl (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
903 transport_connection_t *tc;
904 transport_endpoint_cfg_t *tep;
905 app_worker_t *app_wrk;
910 tep = session_endpoint_to_transport_cfg (rmt);
911 rv = transport_connect (rmt->transport_proto, tep);
914 SESSION_DBG ("Transport failed to open connection.");
915 return VNET_API_ERROR_SESSION_CONNECT;
918 tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
920 /* For dgram type of service, allocate session and fifos now */
921 app_wrk = app_worker_get (app_wrk_index);
922 s = session_alloc_for_connection (tc);
923 s->app_wrk_index = app_wrk->wrk_index;
924 s->session_state = SESSION_STATE_OPENED;
925 if (app_worker_init_connected (app_wrk, s))
931 sh = session_handle (s);
932 session_lookup_add_connection (tc, sh);
934 return app_worker_connect_notify (app_wrk, s, opaque);
938 session_open_vc (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
940 transport_connection_t *tc;
941 transport_endpoint_cfg_t *tep;
945 tep = session_endpoint_to_transport_cfg (rmt);
946 rv = transport_connect (rmt->transport_proto, tep);
949 SESSION_DBG ("Transport failed to open connection.");
950 return VNET_API_ERROR_SESSION_CONNECT;
953 tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
955 /* If transport offers a stream service, only allocate session once the
956 * connection has been established.
957 * Add connection to half-open table and save app and tc index. The
958 * latter is needed to help establish the connection while the former
959 * is needed when the connect notify comes and we have to notify the
962 handle = (((u64) app_wrk_index) << 32) | (u64) tc->c_index;
963 session_lookup_add_half_open (tc, handle);
965 /* Store api_context (opaque) for when the reply comes. Not the nicest
966 * thing but better than allocating a separate half-open pool.
968 tc->s_index = opaque;
973 session_open_app (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
975 session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) rmt;
976 transport_endpoint_cfg_t *tep_cfg = session_endpoint_to_transport_cfg (sep);
978 sep->app_wrk_index = app_wrk_index;
979 sep->opaque = opaque;
981 return transport_connect (rmt->transport_proto, tep_cfg);
984 typedef int (*session_open_service_fn) (u32, session_endpoint_t *, u32);
987 static session_open_service_fn session_open_srv_fns[TRANSPORT_N_SERVICES] = {
995 * Ask transport to open connection to remote transport endpoint.
997 * Stores handle for matching request with reply since the call can be
998 * asynchronous. For instance, for TCP the 3-way handshake must complete
999 * before reply comes. Session is only created once connection is established.
1001 * @param app_index Index of the application requesting the connect
1002 * @param st Session type requested.
1003 * @param tep Remote transport endpoint
1004 * @param opaque Opaque data (typically, api_context) the application expects
1005 * on open completion.
1008 session_open (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1010 transport_service_type_t tst;
1011 tst = transport_protocol_service_type (rmt->transport_proto);
1012 return session_open_srv_fns[tst] (app_wrk_index, rmt, opaque);
1016 * Ask transport to listen on session endpoint.
1018 * @param s Session for which listen will be called. Note that unlike
1019 * established sessions, listen sessions are not associated to a
1021 * @param sep Local endpoint to be listened on.
1024 session_listen (session_t * ls, session_endpoint_cfg_t * sep)
1026 transport_endpoint_t *tep;
1027 u32 tc_index, s_index;
1029 /* Transport bind/listen */
1030 tep = session_endpoint_to_transport (sep);
1031 s_index = ls->session_index;
1032 tc_index = transport_start_listen (session_get_transport_proto (ls),
1035 if (tc_index == (u32) ~ 0)
1038 /* Attach transport to session. Lookup tables are populated by the app
1039 * worker because local tables (for ct sessions) are not backed by a fib */
1040 ls = listen_session_get (s_index);
1041 ls->connection_index = tc_index;
1047 * Ask transport to stop listening on local transport endpoint.
1049 * @param s Session to stop listening on. It must be in state LISTENING.
1052 session_stop_listen (session_t * s)
1054 transport_proto_t tp = session_get_transport_proto (s);
1055 transport_connection_t *tc;
1057 if (s->session_state != SESSION_STATE_LISTENING)
1060 tc = transport_get_listener (tp, s->connection_index);
1062 return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
1064 session_lookup_del_connection (tc);
1065 transport_stop_listen (tp, s->connection_index);
1070 * Initialize session closing procedure.
1072 * Request is always sent to session node to ensure that all outstanding
1073 * requests are served before transport is notified.
1076 session_close (session_t * s)
1081 if (s->session_state >= SESSION_STATE_CLOSING)
1083 /* Session will only be removed once both app and transport
1084 * acknowledge the close */
1085 if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1086 session_program_transport_close (s);
1088 /* Session already closed. Clear the tx fifo */
1089 if (s->session_state == SESSION_STATE_CLOSED)
1090 svm_fifo_dequeue_drop_all (s->tx_fifo);
1094 s->session_state = SESSION_STATE_CLOSING;
1095 session_program_transport_close (s);
1099 * Notify transport the session can be disconnected. This should eventually
1100 * result in a delete notification that allows us to cleanup session state.
1101 * Called for both active/passive disconnects.
1103 * Must be called from the session's thread.
1106 session_transport_close (session_t * s)
1108 /* If transport is already closed, just free the session */
1109 if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSED)
1111 session_free_w_fifos (s);
1115 /* If tx queue wasn't drained, change state to closed waiting for transport.
1116 * This way, the transport, if it so wishes, can continue to try sending the
1117 * outstanding data (in closed state it cannot). It MUST however at one
1118 * point, either after sending everything or after a timeout, call delete
1119 * notify. This will finally lead to the complete cleanup of the session.
1121 if (svm_fifo_max_dequeue_cons (s->tx_fifo))
1122 s->session_state = SESSION_STATE_CLOSED_WAITING;
1124 s->session_state = SESSION_STATE_CLOSED;
1126 transport_close (session_get_transport_proto (s), s->connection_index,
1131 * Cleanup transport and session state.
1133 * Notify transport of the cleanup and free the session. This should
1134 * be called only if transport reported some error and is already
1138 session_transport_cleanup (session_t * s)
1140 s->session_state = SESSION_STATE_CLOSED;
1142 /* Delete from main lookup table before we axe the the transport */
1143 session_lookup_del_session (s);
1144 transport_cleanup (session_get_transport_proto (s), s->connection_index,
1146 /* Since we called cleanup, no delete notification will come. So, make
1147 * sure the session is properly freed. */
1148 session_free_w_fifos (s);
1152 * Allocate event queues in the shared-memory segment
1154 * That can either be a newly created memfd segment, that will need to be
1155 * mapped by all stack users, or the binary api's svm region. The latter is
1156 * assumed to be already mapped. NOTE that this assumption DOES NOT hold if
1157 * api clients bootstrap shm api over sockets (i.e. use memfd segments) and
1158 * vpp uses api svm region for event queues.
1161 session_vpp_event_queues_allocate (session_main_t * smm)
1163 u32 evt_q_length = 2048, evt_size = sizeof (session_event_t);
1164 ssvm_private_t *eqs = &smm->evt_qs_segment;
1165 api_main_t *am = &api_main;
1166 uword eqs_size = 64 << 20;
1167 pid_t vpp_pid = getpid ();
1171 if (smm->configured_event_queue_length)
1172 evt_q_length = smm->configured_event_queue_length;
1174 if (smm->evt_qs_use_memfd_seg)
1176 if (smm->evt_qs_segment_size)
1177 eqs_size = smm->evt_qs_segment_size;
1179 eqs->ssvm_size = eqs_size;
1180 eqs->i_am_master = 1;
1181 eqs->my_pid = vpp_pid;
1182 eqs->name = format (0, "%s%c", "evt-qs-segment", 0);
1183 eqs->requested_va = smm->session_baseva;
1185 if (ssvm_master_init (eqs, SSVM_SEGMENT_MEMFD))
1187 clib_warning ("failed to initialize queue segment");
1192 if (smm->evt_qs_use_memfd_seg)
1193 oldheap = ssvm_push_heap (eqs->sh);
1195 oldheap = svm_push_data_heap (am->vlib_rp);
1197 for (i = 0; i < vec_len (smm->wrk); i++)
1199 svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1200 svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
1201 {evt_q_length, evt_size, 0}
1203 {evt_q_length >> 1, 256, 0}
1205 cfg->consumer_pid = 0;
1207 cfg->q_nitems = evt_q_length;
1208 cfg->ring_cfgs = rc;
1209 smm->wrk[i].vpp_event_queue = svm_msg_q_alloc (cfg);
1210 if (smm->evt_qs_use_memfd_seg)
1212 if (svm_msg_q_alloc_consumer_eventfd (smm->wrk[i].vpp_event_queue))
1213 clib_warning ("eventfd returned");
1217 if (smm->evt_qs_use_memfd_seg)
1218 ssvm_pop_heap (oldheap);
1220 svm_pop_heap (oldheap);
1224 session_main_get_evt_q_segment (void)
1226 session_main_t *smm = &session_main;
1227 if (smm->evt_qs_use_memfd_seg)
1228 return &smm->evt_qs_segment;
1233 session_segment_handle (session_t * s)
1238 return SESSION_INVALID_HANDLE;
1241 return segment_manager_make_segment_handle (f->segment_manager,
1246 static session_fifo_rx_fn *session_tx_fns[TRANSPORT_TX_N_FNS] = {
1247 session_tx_fifo_peek_and_snd,
1248 session_tx_fifo_dequeue_and_snd,
1249 session_tx_fifo_dequeue_internal,
1250 session_tx_fifo_dequeue_and_snd
1255 * Initialize session layer for given transport proto and ip version
1257 * Allocates per session type (transport proto + ip version) data structures
1258 * and adds arc from session queue node to session type output node.
1261 session_register_transport (transport_proto_t transport_proto,
1262 const transport_proto_vft_t * vft, u8 is_ip4,
1265 session_main_t *smm = &session_main;
1266 session_type_t session_type;
1267 u32 next_index = ~0;
1269 session_type = session_type_from_proto_and_ip (transport_proto, is_ip4);
1271 vec_validate (smm->session_type_to_next, session_type);
1272 vec_validate (smm->session_tx_fns, session_type);
1275 if (output_node != ~0)
1277 foreach_vlib_main (({
1278 next_index = vlib_node_add_next (this_vlib_main,
1279 session_queue_node.index,
1285 smm->session_type_to_next[session_type] = next_index;
1286 smm->session_tx_fns[session_type] =
1287 session_tx_fns[vft->transport_options.tx_type];
1290 transport_connection_t *
1291 session_get_transport (session_t * s)
1293 if (s->session_state != SESSION_STATE_LISTENING)
1294 return transport_get_connection (session_get_transport_proto (s),
1295 s->connection_index, s->thread_index);
1297 return transport_get_listener (session_get_transport_proto (s),
1298 s->connection_index);
1302 session_get_endpoint (session_t * s, transport_endpoint_t * tep, u8 is_lcl)
1304 if (s->session_state != SESSION_STATE_LISTENING)
1305 return transport_get_endpoint (session_get_transport_proto (s),
1306 s->connection_index, s->thread_index, tep,
1309 return transport_get_listener_endpoint (session_get_transport_proto (s),
1310 s->connection_index, tep, is_lcl);
1313 transport_connection_t *
1314 listen_session_get_transport (session_t * s)
1316 return transport_get_listener (session_get_transport_proto (s),
1317 s->connection_index);
1321 session_flush_frames_main_thread (vlib_main_t * vm)
1323 ASSERT (vlib_get_thread_index () == 0);
1324 vlib_process_signal_event_mt (vm, session_queue_process_node.index,
1325 SESSION_Q_PROCESS_FLUSH_FRAMES, 0);
1328 static clib_error_t *
1329 session_manager_main_enable (vlib_main_t * vm)
1331 segment_manager_main_init_args_t _sm_args = { 0 }, *sm_args = &_sm_args;
1332 session_main_t *smm = &session_main;
1333 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1334 u32 num_threads, preallocated_sessions_per_worker;
1335 session_worker_t *wrk;
1338 num_threads = 1 /* main thread */ + vtm->n_threads;
1340 if (num_threads < 1)
1341 return clib_error_return (0, "n_thread_stacks not set");
1343 /* Allocate cache line aligned worker contexts */
1344 vec_validate_aligned (smm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1346 for (i = 0; i < num_threads; i++)
1349 vec_validate (wrk->free_event_vector, 128);
1350 _vec_len (wrk->free_event_vector) = 0;
1351 vec_validate (wrk->pending_event_vector, 128);
1352 _vec_len (wrk->pending_event_vector) = 0;
1353 vec_validate (wrk->pending_disconnects, 128);
1354 _vec_len (wrk->pending_disconnects) = 0;
1355 vec_validate (wrk->postponed_event_vector, 128);
1356 _vec_len (wrk->postponed_event_vector) = 0;
1358 wrk->last_vlib_time = vlib_time_now (vlib_mains[i]);
1359 wrk->dispatch_period = 500e-6;
1361 if (num_threads > 1)
1362 clib_rwlock_init (&smm->wrk[i].peekers_rw_locks);
1366 vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
1369 /* Allocate vpp event queues segment and queue */
1370 session_vpp_event_queues_allocate (smm);
1372 /* Initialize fifo segment main baseva and timeout */
1373 sm_args->baseva = smm->session_baseva + smm->evt_qs_segment_size;
1374 sm_args->size = smm->session_va_space_size;
1375 segment_manager_main_init (sm_args);
1377 /* Preallocate sessions */
1378 if (smm->preallocated_sessions)
1380 if (num_threads == 1)
1382 pool_init_fixed (smm->wrk[0].sessions, smm->preallocated_sessions);
1387 preallocated_sessions_per_worker =
1388 (1.1 * (f64) smm->preallocated_sessions /
1389 (f64) (num_threads - 1));
1391 for (j = 1; j < num_threads; j++)
1393 pool_init_fixed (smm->wrk[j].sessions,
1394 preallocated_sessions_per_worker);
1399 session_lookup_init ();
1400 app_namespaces_init ();
1403 smm->is_enabled = 1;
1405 /* Enable transports */
1406 transport_enable_disable (vm, 1);
1407 transport_init_tx_pacers_period ();
1412 session_node_enable_disable (u8 is_en)
1414 u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1415 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1416 u8 have_workers = vtm->n_threads != 0;
1419 foreach_vlib_main (({
1420 if (have_workers && ii == 0)
1422 vlib_node_set_state (this_vlib_main, session_queue_process_node.index,
1426 vlib_node_t *n = vlib_get_node (this_vlib_main,
1427 session_queue_process_node.index);
1428 vlib_start_process (this_vlib_main, n->runtime_index);
1432 vlib_process_signal_event_mt (this_vlib_main,
1433 session_queue_process_node.index,
1434 SESSION_Q_PROCESS_STOP, 0);
1439 vlib_node_set_state (this_vlib_main, session_queue_node.index,
1446 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1448 clib_error_t *error = 0;
1451 if (session_main.is_enabled)
1454 session_node_enable_disable (is_en);
1455 error = session_manager_main_enable (vm);
1459 session_main.is_enabled = 0;
1460 session_node_enable_disable (is_en);
1467 session_manager_main_init (vlib_main_t * vm)
1469 session_main_t *smm = &session_main;
1470 smm->session_baseva = HIGH_SEGMENT_BASEVA;
1471 #if (HIGH_SEGMENT_BASEVA > (4ULL << 30))
1472 smm->session_va_space_size = 128ULL << 30;
1473 smm->evt_qs_segment_size = 64 << 20;
1475 smm->session_va_space_size = 128 << 20;
1476 smm->evt_qs_segment_size = 1 << 20;
1478 smm->is_enabled = 0;
1482 VLIB_INIT_FUNCTION (session_manager_main_init);
1484 static clib_error_t *
1485 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1487 session_main_t *smm = &session_main;
1491 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1493 if (unformat (input, "event-queue-length %d", &nitems))
1496 smm->configured_event_queue_length = nitems;
1498 clib_warning ("event queue length %d too small, ignored", nitems);
1500 else if (unformat (input, "preallocated-sessions %d",
1501 &smm->preallocated_sessions))
1503 else if (unformat (input, "v4-session-table-buckets %d",
1504 &smm->configured_v4_session_table_buckets))
1506 else if (unformat (input, "v4-halfopen-table-buckets %d",
1507 &smm->configured_v4_halfopen_table_buckets))
1509 else if (unformat (input, "v6-session-table-buckets %d",
1510 &smm->configured_v6_session_table_buckets))
1512 else if (unformat (input, "v6-halfopen-table-buckets %d",
1513 &smm->configured_v6_halfopen_table_buckets))
1515 else if (unformat (input, "v4-session-table-memory %U",
1516 unformat_memory_size, &tmp))
1518 if (tmp >= 0x100000000)
1519 return clib_error_return (0, "memory size %llx (%lld) too large",
1521 smm->configured_v4_session_table_memory = tmp;
1523 else if (unformat (input, "v4-halfopen-table-memory %U",
1524 unformat_memory_size, &tmp))
1526 if (tmp >= 0x100000000)
1527 return clib_error_return (0, "memory size %llx (%lld) too large",
1529 smm->configured_v4_halfopen_table_memory = tmp;
1531 else if (unformat (input, "v6-session-table-memory %U",
1532 unformat_memory_size, &tmp))
1534 if (tmp >= 0x100000000)
1535 return clib_error_return (0, "memory size %llx (%lld) too large",
1537 smm->configured_v6_session_table_memory = tmp;
1539 else if (unformat (input, "v6-halfopen-table-memory %U",
1540 unformat_memory_size, &tmp))
1542 if (tmp >= 0x100000000)
1543 return clib_error_return (0, "memory size %llx (%lld) too large",
1545 smm->configured_v6_halfopen_table_memory = tmp;
1547 else if (unformat (input, "local-endpoints-table-memory %U",
1548 unformat_memory_size, &tmp))
1550 if (tmp >= 0x100000000)
1551 return clib_error_return (0, "memory size %llx (%lld) too large",
1553 smm->local_endpoints_table_memory = tmp;
1555 else if (unformat (input, "local-endpoints-table-buckets %d",
1556 &smm->local_endpoints_table_buckets))
1558 else if (unformat (input, "evt_qs_memfd_seg"))
1559 smm->evt_qs_use_memfd_seg = 1;
1560 else if (unformat (input, "evt_qs_seg_size %U", unformat_memory_size,
1561 &smm->evt_qs_segment_size))
1564 return clib_error_return (0, "unknown input `%U'",
1565 format_unformat_error, input);
1570 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1573 * fd.io coding-style-patch-verification: ON
1576 * eval: (c-set-style "gnu")