2 * Copyright (c) 2017 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this 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 <vlibmemory/api.h>
24 #include <vnet/dpo/load_balance.h>
25 #include <vnet/fib/ip4_fib.h>
26 #include <vnet/tcp/tcp.h>
28 session_manager_main_t session_manager_main;
29 extern transport_proto_vft_t *tp_vfts;
32 stream_session_create_i (segment_manager_t * sm, transport_connection_t * tc,
33 stream_session_t ** ret_s)
35 session_manager_main_t *smm = &session_manager_main;
36 svm_fifo_t *server_rx_fifo = 0, *server_tx_fifo = 0;
37 u32 fifo_segment_index;
41 u32 thread_index = tc->thread_index;
44 ASSERT (thread_index == vlib_get_thread_index ());
46 if ((rv = segment_manager_alloc_session_fifos (sm, &server_rx_fifo,
48 &fifo_segment_index)))
51 /* Create the session */
52 pool_get_aligned (smm->sessions[thread_index], s, CLIB_CACHE_LINE_BYTES);
53 memset (s, 0, sizeof (*s));
55 /* Initialize backpointers */
56 pool_index = s - smm->sessions[thread_index];
57 server_rx_fifo->master_session_index = pool_index;
58 server_rx_fifo->master_thread_index = thread_index;
60 server_tx_fifo->master_session_index = pool_index;
61 server_tx_fifo->master_thread_index = thread_index;
63 s->server_rx_fifo = server_rx_fifo;
64 s->server_tx_fifo = server_tx_fifo;
66 /* Initialize state machine, such as it is... */
67 s->session_type = tc->proto;
68 s->session_state = SESSION_STATE_CONNECTING;
69 s->svm_segment_index = fifo_segment_index;
70 s->thread_index = thread_index;
71 s->session_index = pool_index;
73 /* Attach transport to session */
74 s->connection_index = tc->c_index;
76 /* Attach session to transport */
77 tc->s_index = s->session_index;
79 /* Add to the main lookup table */
80 value = stream_session_handle (s);
81 stream_session_table_add_for_tc (tc, value);
88 /** Enqueue buffer chain tail */
90 session_enqueue_chain_tail (stream_session_t * s, vlib_buffer_t * b,
91 u32 offset, u8 is_in_order)
93 vlib_buffer_t *chain_b;
94 u32 chain_bi = b->next_buffer;
95 vlib_main_t *vm = vlib_get_main ();
102 chain_b = vlib_get_buffer (vm, chain_bi);
103 data = vlib_buffer_get_current (chain_b);
104 len = chain_b->current_length;
107 rv = svm_fifo_enqueue_nowait (s->server_rx_fifo, len, data);
110 return (rv > 0) ? (written + rv) : written;
116 rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset, len,
123 while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
124 ? chain_b->next_buffer : 0));
133 * Enqueue data for delivery to session peer. Does not notify peer of enqueue
134 * event but on request can queue notification events for later delivery by
135 * calling stream_server_flush_enqueue_events().
137 * @param tc Transport connection which is to be enqueued data
138 * @param b Buffer to be enqueued
139 * @param offset Offset at which to start enqueueing if out-of-order
140 * @param queue_event Flag to indicate if peer is to be notified or if event
141 * is to be queued. The former is useful when more data is
142 * enqueued and only one event is to be generated.
143 * @param is_in_order Flag to indicate if data is in order
144 * @return Number of bytes enqueued or a negative value if enqueueing failed.
147 stream_session_enqueue_data (transport_connection_t * tc, vlib_buffer_t * b,
148 u32 offset, u8 queue_event, u8 is_in_order)
151 int enqueued = 0, rv;
153 s = stream_session_get (tc->s_index, tc->thread_index);
158 svm_fifo_enqueue_nowait (s->server_rx_fifo, b->current_length,
159 vlib_buffer_get_current (b));
161 ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued > 0))
163 rv = session_enqueue_chain_tail (s, b, 0, 1);
171 rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset,
173 vlib_buffer_get_current (b));
174 if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
175 rv = session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
182 /* Queue RX event on this fifo. Eventually these will need to be flushed
183 * by calling stream_server_flush_enqueue_events () */
184 session_manager_main_t *smm = vnet_get_session_manager_main ();
185 u32 thread_index = s->thread_index;
186 u32 my_enqueue_epoch = smm->current_enqueue_epoch[thread_index];
188 if (s->enqueue_epoch != my_enqueue_epoch)
190 s->enqueue_epoch = my_enqueue_epoch;
191 vec_add1 (smm->session_indices_to_enqueue_by_thread[thread_index],
192 s - smm->sessions[thread_index]);
202 /** Check if we have space in rx fifo to push more bytes */
204 stream_session_no_space (transport_connection_t * tc, u32 thread_index,
207 stream_session_t *s = stream_session_get (tc->s_index, thread_index);
209 if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY))
212 if (data_len > svm_fifo_max_enqueue (s->server_rx_fifo))
219 stream_session_tx_fifo_max_dequeue (transport_connection_t * tc)
221 stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
222 if (s->session_state != SESSION_STATE_READY)
224 return svm_fifo_max_dequeue (s->server_tx_fifo);
228 stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
229 u32 offset, u32 max_bytes)
231 stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
232 return svm_fifo_peek (s->server_tx_fifo, offset, max_bytes, buffer);
236 stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
238 stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
239 return svm_fifo_dequeue_drop (s->server_tx_fifo, max_bytes);
243 * Notify session peer that new data has been enqueued.
245 * @param s Stream session for which the event is to be generated.
246 * @param block Flag to indicate if call should block if event queue is full.
248 * @return 0 on succes or negative number if failed to send notification.
251 stream_session_enqueue_notify (stream_session_t * s, u8 block)
254 session_fifo_event_t evt;
255 unix_shared_memory_queue_t *q;
256 static u32 serial_number;
258 if (PREDICT_FALSE (s->session_state == SESSION_STATE_CLOSED))
261 /* Get session's server */
262 app = application_get (s->app_index);
264 /* Built-in server? Hand event to the callback... */
265 if (app->cb_fns.builtin_server_rx_callback)
266 return app->cb_fns.builtin_server_rx_callback (s);
268 /* If no event, send one */
269 if (svm_fifo_set_event (s->server_rx_fifo))
271 /* Fabricate event */
272 evt.fifo = s->server_rx_fifo;
273 evt.event_type = FIFO_EVENT_APP_RX;
274 evt.event_id = serial_number++;
276 /* Add event to server's event queue */
277 q = app->event_queue;
279 /* Based on request block (or not) for lack of space */
280 if (block || PREDICT_TRUE (q->cursize < q->maxsize))
281 unix_shared_memory_queue_add (app->event_queue, (u8 *) & evt,
282 0 /* do wait for mutex */ );
285 clib_warning ("fifo full");
291 SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
292 ed->data[0] = evt.event_id;
293 ed->data[1] = svm_fifo_max_dequeue (s->server_rx_fifo);
301 * Flushes queue of sessions that are to be notified of new data
304 * @param thread_index Thread index for which the flush is to be performed.
305 * @return 0 on success or a positive number indicating the number of
306 * failures due to API queue being full.
309 session_manager_flush_enqueue_events (u32 thread_index)
311 session_manager_main_t *smm = &session_manager_main;
312 u32 *session_indices_to_enqueue;
315 session_indices_to_enqueue =
316 smm->session_indices_to_enqueue_by_thread[thread_index];
318 for (i = 0; i < vec_len (session_indices_to_enqueue); i++)
320 stream_session_t *s0;
323 s0 = stream_session_get (session_indices_to_enqueue[i], thread_index);
324 if (stream_session_enqueue_notify (s0, 0 /* don't block */ ))
330 vec_reset_length (session_indices_to_enqueue);
332 smm->session_indices_to_enqueue_by_thread[thread_index] =
333 session_indices_to_enqueue;
335 /* Increment enqueue epoch for next round */
336 smm->current_enqueue_epoch[thread_index]++;
342 * Init fifo tail and head pointers
344 * Useful if transport uses absolute offsets for tracking ooo segments.
347 stream_session_init_fifos_pointers (transport_connection_t * tc,
348 u32 rx_pointer, u32 tx_pointer)
351 s = stream_session_get (tc->s_index, tc->thread_index);
352 svm_fifo_init_pointers (s->server_rx_fifo, rx_pointer);
353 svm_fifo_init_pointers (s->server_tx_fifo, tx_pointer);
357 stream_session_connect_notify (transport_connection_t * tc, u8 sst,
361 stream_session_t *new_s = 0;
366 handle = stream_session_half_open_lookup_handle (&tc->lcl_ip, &tc->rmt_ip,
367 tc->lcl_port, tc->rmt_port,
369 if (handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
371 clib_warning ("This can't be good!");
375 /* Get the app's index from the handle we stored when opening connection */
376 app = application_get (handle >> 32);
377 api_context = tc->s_index;
381 segment_manager_t *sm;
382 sm = application_get_connect_segment_manager (app);
384 /* Create new session (svm segments are allocated if needed) */
385 if (stream_session_create_i (sm, tc, &new_s))
391 new_s->app_index = app->index;
395 if (app->cb_fns.session_connected_callback (app->index, api_context, new_s,
398 clib_warning ("failed to notify app");
400 stream_session_disconnect (new_s);
405 new_s->session_state = SESSION_STATE_READY;
408 /* Cleanup session lookup */
409 stream_session_half_open_table_del (sst, tc);
415 stream_session_accept_notify (transport_connection_t * tc)
417 application_t *server;
420 s = stream_session_get (tc->s_index, tc->thread_index);
421 server = application_get (s->app_index);
422 server->cb_fns.session_accept_callback (s);
426 * Notification from transport that connection is being closed.
428 * A disconnect is sent to application but state is not removed. Once
429 * disconnect is acknowledged by application, session disconnect is called.
430 * Ultimately this leads to close being called on transport (passive close).
433 stream_session_disconnect_notify (transport_connection_t * tc)
435 application_t *server;
438 s = stream_session_get (tc->s_index, tc->thread_index);
439 server = application_get (s->app_index);
440 server->cb_fns.session_disconnect_callback (s);
444 * Cleans up session and associated app if needed.
447 stream_session_delete (stream_session_t * s)
449 session_manager_main_t *smm = vnet_get_session_manager_main ();
452 /* Delete from the main lookup table. */
453 if ((rv = stream_session_table_del (s)))
454 clib_warning ("hash delete error, rv %d", rv);
456 /* Cleanup fifo segments */
457 segment_manager_dealloc_fifos (s->svm_segment_index, s->server_rx_fifo,
460 pool_put (smm->sessions[s->thread_index], s);
462 memset (s, 0xFA, sizeof (*s));
466 * Notification from transport that connection is being deleted
468 * This should be called only on previously fully established sessions. For
469 * instance failed connects should call stream_session_connect_notify and
470 * indicate that the connect has failed.
473 stream_session_delete_notify (transport_connection_t * tc)
477 /* App might've been removed already */
478 s = stream_session_get_if_valid (tc->s_index, tc->thread_index);
483 stream_session_delete (s);
487 * Notify application that connection has been reset.
490 stream_session_reset_notify (transport_connection_t * tc)
494 s = stream_session_get (tc->s_index, tc->thread_index);
496 app = application_get (s->app_index);
497 app->cb_fns.session_reset_callback (s);
501 * Accept a stream session. Optionally ping the server by callback.
504 stream_session_accept (transport_connection_t * tc, u32 listener_index,
507 application_t *server;
508 stream_session_t *s, *listener;
509 segment_manager_t *sm;
513 /* Find the server */
514 listener = listen_session_get (sst, listener_index);
515 server = application_get (listener->app_index);
517 sm = application_get_listen_segment_manager (server, listener);
518 if ((rv = stream_session_create_i (sm, tc, &s)))
521 s->app_index = server->index;
522 s->listener_index = listener_index;
523 s->session_state = SESSION_STATE_ACCEPTING;
525 /* Shoulder-tap the server */
528 server->cb_fns.session_accept_callback (s);
535 * Ask transport to open connection to remote transport endpoint.
537 * Stores handle for matching request with reply since the call can be
538 * asynchronous. For instance, for TCP the 3-way handshake must complete
539 * before reply comes. Session is only created once connection is established.
541 * @param app_index Index of the application requesting the connect
542 * @param st Session type requested.
543 * @param tep Remote transport endpoint
544 * @param res Resulting transport connection .
547 stream_session_open (u32 app_index, session_type_t st,
548 transport_endpoint_t * rmt,
549 transport_connection_t ** res)
551 transport_connection_t *tc;
555 rv = tp_vfts[st].open (rmt);
558 clib_warning ("Transport failed to open connection.");
559 return VNET_API_ERROR_SESSION_CONNECT_FAIL;
562 tc = tp_vfts[st].get_half_open ((u32) rv);
564 /* Save app and tc index. The latter is needed to help establish the
565 * connection while the former is needed when the connect notify comes
566 * and we have to notify the external app */
567 handle = (((u64) app_index) << 32) | (u64) tc->c_index;
569 /* Add to the half-open lookup table */
570 stream_session_half_open_table_add (st, tc, handle);
578 * Ask transport to listen on local transport endpoint.
580 * @param s Session for which listen will be called. Note that unlike
581 * established sessions, listen sessions are not associated to a
583 * @param tep Local endpoint to be listened on.
586 stream_session_listen (stream_session_t * s, transport_endpoint_t * tep)
588 transport_connection_t *tc;
591 /* Transport bind/listen */
592 tci = tp_vfts[s->session_type].bind (s->session_index, tep);
594 if (tci == (u32) ~ 0)
597 /* Attach transport to session */
598 s->connection_index = tci;
599 tc = tp_vfts[s->session_type].get_listener (tci);
601 /* Weird but handle it ... */
605 /* Add to the main lookup table */
606 stream_session_table_add_for_tc (tc, s->session_index);
612 * Ask transport to stop listening on local transport endpoint.
614 * @param s Session to stop listening on. It must be in state LISTENING.
617 stream_session_stop_listen (stream_session_t * s)
619 transport_connection_t *tc;
621 if (s->session_state != SESSION_STATE_LISTENING)
623 clib_warning ("not a listening session");
627 tc = tp_vfts[s->session_type].get_listener (s->connection_index);
630 clib_warning ("no transport");
631 return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
634 stream_session_table_del_for_tc (tc);
635 tp_vfts[s->session_type].unbind (s->connection_index);
640 session_send_session_evt_to_thread (u64 session_handle,
641 fifo_event_type_t evt_type,
644 static u16 serial_number = 0;
645 session_fifo_event_t evt;
646 unix_shared_memory_queue_t *q;
648 /* Fabricate event */
649 evt.session_handle = session_handle;
650 evt.event_type = evt_type;
651 evt.event_id = serial_number++;
653 q = session_manager_get_vpp_event_queue (thread_index);
655 /* Based on request block (or not) for lack of space */
656 if (PREDICT_TRUE (q->cursize < q->maxsize))
658 if (unix_shared_memory_queue_add (q, (u8 *) & evt,
659 1 /* do wait for mutex */ ))
661 clib_warning ("failed to enqueue evt");
666 clib_warning ("queue full");
672 * Disconnect session and propagate to transport. This should eventually
673 * result in a delete notification that allows us to cleanup session state.
674 * Called for both active/passive disconnects.
676 * Should be called from the session's thread.
679 stream_session_disconnect (stream_session_t * s)
681 s->session_state = SESSION_STATE_CLOSED;
682 tp_vfts[s->session_type].close (s->connection_index, s->thread_index);
686 * Cleanup transport and session state.
688 * Notify transport of the cleanup, wait for a delete notify to actually
689 * remove the session state.
692 stream_session_cleanup (stream_session_t * s)
696 s->session_state = SESSION_STATE_CLOSED;
698 /* Delete from the main lookup table to avoid more enqueues */
699 rv = stream_session_table_del (s);
701 clib_warning ("hash delete error, rv %d", rv);
703 tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
707 * Allocate vpp event queue (once) per worker thread
710 session_vpp_event_queue_allocate (session_manager_main_t * smm,
713 api_main_t *am = &api_main;
715 u32 event_queue_length = 2048;
717 if (smm->vpp_event_queues[thread_index] == 0)
719 /* Allocate event fifo in the /vpe-api shared-memory segment */
720 oldheap = svm_push_data_heap (am->vlib_rp);
722 if (smm->configured_event_queue_length)
723 event_queue_length = smm->configured_event_queue_length;
725 smm->vpp_event_queues[thread_index] =
726 unix_shared_memory_queue_init
728 sizeof (session_fifo_event_t), 0 /* consumer pid */ ,
729 0 /* (do not) send signal when queue non-empty */ );
731 svm_pop_heap (oldheap);
736 session_type_from_proto_and_ip (transport_proto_t proto, u8 is_ip4)
738 if (proto == TRANSPORT_PROTO_TCP)
741 return SESSION_TYPE_IP4_TCP;
743 return SESSION_TYPE_IP6_TCP;
748 return SESSION_TYPE_IP4_UDP;
750 return SESSION_TYPE_IP6_UDP;
753 return SESSION_N_TYPES;
756 static clib_error_t *
757 session_manager_main_enable (vlib_main_t * vm)
759 session_manager_main_t *smm = &session_manager_main;
760 vlib_thread_main_t *vtm = vlib_get_thread_main ();
764 num_threads = 1 /* main thread */ + vtm->n_threads;
767 return clib_error_return (0, "n_thread_stacks not set");
769 /* $$$ config parameters */
770 svm_fifo_segment_init (0x200000000ULL /* first segment base VA */ ,
771 20 /* timeout in seconds */ );
773 /* configure per-thread ** vectors */
774 vec_validate (smm->sessions, num_threads - 1);
775 vec_validate (smm->session_indices_to_enqueue_by_thread, num_threads - 1);
776 vec_validate (smm->tx_buffers, num_threads - 1);
777 vec_validate (smm->pending_event_vector, num_threads - 1);
778 vec_validate (smm->free_event_vector, num_threads - 1);
779 vec_validate (smm->current_enqueue_epoch, num_threads - 1);
780 vec_validate (smm->vpp_event_queues, num_threads - 1);
782 for (i = 0; i < num_threads; i++)
784 vec_validate (smm->free_event_vector[i], 0);
785 _vec_len (smm->free_event_vector[i]) = 0;
786 vec_validate (smm->pending_event_vector[i], 0);
787 _vec_len (smm->pending_event_vector[i]) = 0;
791 vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
794 /* Allocate vpp event queues */
795 for (i = 0; i < vec_len (smm->vpp_event_queues); i++)
796 session_vpp_event_queue_allocate (smm, i);
798 /* $$$$ preallocate hack config parameter */
799 for (i = 0; i < smm->preallocated_sessions; i++)
801 stream_session_t *ss __attribute__ ((unused));
802 pool_get_aligned (smm->sessions[0], ss, CLIB_CACHE_LINE_BYTES);
805 for (i = 0; i < smm->preallocated_sessions; i++)
806 pool_put_index (smm->sessions[0], i);
808 session_lookup_init ();
812 /* Enable TCP transport */
813 vnet_tcp_enable_disable (vm, 1);
819 session_node_enable_disable (u8 is_en)
821 u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
823 foreach_vlib_main (({
824 vlib_node_set_state (this_vlib_main, session_queue_node.index,
831 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
835 if (session_manager_main.is_enabled)
838 session_node_enable_disable (is_en);
840 return session_manager_main_enable (vm);
844 session_manager_main.is_enabled = 0;
845 session_node_enable_disable (is_en);
852 session_manager_main_init (vlib_main_t * vm)
854 session_manager_main_t *smm = &session_manager_main;
859 VLIB_INIT_FUNCTION (session_manager_main_init);
861 static clib_error_t *
862 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
864 session_manager_main_t *smm = &session_manager_main;
867 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
869 if (unformat (input, "event-queue-length %d", &nitems))
872 smm->configured_event_queue_length = nitems;
874 clib_warning ("event queue length %d too small, ignored", nitems);
876 if (unformat (input, "preallocated-sessions %d",
877 &smm->preallocated_sessions))
880 return clib_error_return (0, "unknown input `%U'",
881 format_unformat_error, input);
886 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
889 * fd.io coding-style-patch-verification: ON
892 * eval: (c-set-style "gnu")