71f6d35d43ba6dae30c636abfbb7794d012a9123
[vpp.git] / src / vnet / session / session.h
1 /*
2  * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef __included_session_h__
16 #define __included_session_h__
17
18 #include <vppinfra/llist.h>
19 #include <vnet/session/session_types.h>
20 #include <vnet/session/session_lookup.h>
21 #include <vnet/session/session_debug.h>
22 #include <svm/message_queue.h>
23 #include <svm/fifo_segment.h>
24
25 #define foreach_session_input_error                                     \
26 _(NO_SESSION, "No session drops")                                       \
27 _(NO_LISTENER, "No listener for dst port drops")                        \
28 _(ENQUEUED, "Packets pushed into rx fifo")                              \
29 _(NOT_READY, "Session not ready packets")                               \
30 _(FIFO_FULL, "Packets dropped for lack of rx fifo space")               \
31 _(EVENT_FIFO_FULL, "Events not sent for lack of event fifo space")      \
32 _(API_QUEUE_FULL, "Sessions not created for lack of API queue space")   \
33
34 typedef enum
35 {
36 #define _(sym,str) SESSION_ERROR_##sym,
37   foreach_session_input_error
38 #undef _
39     SESSION_N_ERROR,
40 } session_input_error_t;
41
42 typedef struct session_tx_context_
43 {
44   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
45   session_t *s;
46   transport_proto_vft_t *transport_vft;
47   transport_connection_t *tc;
48   transport_send_params_t sp;
49   u32 max_dequeue;
50   u32 left_to_snd;
51   u32 max_len_to_snd;
52   u16 deq_per_first_buf;
53   u16 deq_per_buf;
54   u16 n_segs_per_evt;
55   u16 n_bufs_needed;
56   u8 n_bufs_per_seg;
57     CLIB_CACHE_LINE_ALIGN_MARK (cacheline1);
58   session_dgram_hdr_t hdr;
59
60   /** Vector of tx buffer free lists */
61   u32 *tx_buffers;
62   vlib_buffer_t **transport_pending_bufs;
63 } session_tx_context_t;
64
65 typedef struct session_evt_elt
66 {
67   clib_llist_anchor_t evt_list;
68   session_event_t evt;
69 } session_evt_elt_t;
70
71 typedef struct session_ctrl_evt_data_
72 {
73   u8 data[SESSION_CTRL_MSG_MAX_SIZE];
74 } session_evt_ctrl_data_t;
75
76 typedef enum session_wrk_state_
77 {
78   SESSION_WRK_POLLING,
79   SESSION_WRK_INTERRUPT,
80   SESSION_WRK_IDLE,
81 } __clib_packed session_wrk_state_t;
82
83 typedef enum session_wrk_flags_
84 {
85   SESSION_WRK_F_ADAPTIVE = 1 << 0,
86 } __clib_packed session_wrk_flag_t;
87
88 typedef struct session_worker_
89 {
90   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
91
92   /** Worker session pool */
93   session_t *sessions;
94
95   /** vpp event message queue for worker */
96   svm_msg_q_t *vpp_event_queue;
97
98   /** vlib_time_now last time around the track */
99   clib_time_type_t last_vlib_time;
100
101   /** vlib_time_now rounded to us precision and as u64 */
102   clib_us_time_t last_vlib_us_time;
103
104   /** Convenience pointer to this worker's vlib_main */
105   vlib_main_t *vm;
106
107   /** Per-proto vector of sessions to enqueue */
108   u32 **session_to_enqueue;
109
110   /** Timerfd used to periodically signal wrk session queue node */
111   int timerfd;
112
113   /** Worker flags */
114   session_wrk_flag_t flags;
115
116   /** Worker state */
117   session_wrk_state_t state;
118
119   /** Context for session tx */
120   session_tx_context_t ctx;
121
122   /** Pool of session event list elements */
123   session_evt_elt_t *event_elts;
124
125   /** Pool of ctrl events data buffers */
126   session_evt_ctrl_data_t *ctrl_evts_data;
127
128   /** Head of control events list */
129   clib_llist_index_t ctrl_head;
130
131   /** Head of list of elements */
132   clib_llist_index_t new_head;
133
134   /** Head of list of pending events */
135   clib_llist_index_t old_head;
136
137   /** Peekers rw lock */
138   clib_rwlock_t peekers_rw_locks;
139
140   /** Vector of buffers to be sent */
141   u32 *pending_tx_buffers;
142
143   /** Vector of nexts for the pending tx buffers */
144   u16 *pending_tx_nexts;
145
146   /** Clib file for timerfd. Used only if adaptive mode is on */
147   uword timerfd_file;
148
149   /** List of pending connects for first worker */
150   clib_llist_index_t pending_connects;
151
152   /** Flag that is set if main thread signaled to handle connects */
153   u32 n_pending_connects;
154
155   /** Main thread loops in poll mode without a connect */
156   u32 no_connect_loops;
157
158   /** List head for first worker evts pending handling on main */
159   clib_llist_index_t evts_pending_main;
160
161 #if SESSION_DEBUG
162   /** last event poll time by thread */
163   clib_time_type_t last_event_poll;
164 #endif
165 } session_worker_t;
166
167 typedef int (session_fifo_rx_fn) (session_worker_t * wrk,
168                                   vlib_node_runtime_t * node,
169                                   session_evt_elt_t * e, int *n_tx_packets);
170
171 extern session_fifo_rx_fn session_tx_fifo_peek_and_snd;
172 extern session_fifo_rx_fn session_tx_fifo_dequeue_and_snd;
173 extern session_fifo_rx_fn session_tx_fifo_dequeue_internal;
174
175 u8 session_node_lookup_fifo_event (svm_fifo_t * f, session_event_t * e);
176
177 typedef void (*session_update_time_fn) (f64 time_now, u8 thread_index);
178
179 typedef struct session_main_
180 {
181   /** Worker contexts */
182   session_worker_t *wrk;
183
184   /** Vector of transport update time functions */
185   session_update_time_fn *update_time_fns;
186
187   /** Event queues memfd segment */
188   fifo_segment_t wrk_mqs_segment;
189
190   /** Unique segment name counter */
191   u32 unique_segment_name_counter;
192
193   /** Per transport rx function that can either dequeue or peek */
194   session_fifo_rx_fn **session_tx_fns;
195
196   /** Per session type output nodes. Could optimize to group nodes by
197    * fib but lookup would then require session type parsing in session node.
198    * Trade memory for speed, for now */
199   u32 *session_type_to_next;
200
201   /** Thread for cl and ho that rely on cl allocs */
202   u32 transport_cl_thread;
203
204   transport_proto_t last_transport_proto_type;
205
206   /** Number of workers at pool realloc barrier */
207   u32 pool_realloc_at_barrier;
208
209   /** Lock to synchronize parallel forced reallocs */
210   clib_spinlock_t pool_realloc_lock;
211
212   /*
213    * Config parameters
214    */
215
216   /** Session manager is enabled */
217   u8 is_enabled;
218
219   /** Session manager initialized (not necessarily enabled) */
220   u8 is_initialized;
221
222   /** Enable session manager at startup */
223   u8 session_enable_asap;
224
225   /** Poll session node in main thread */
226   u8 poll_main;
227
228   /** Allocate private rx mqs for external apps */
229   u8 use_private_rx_mqs;
230
231   /** Do not enable session queue node adaptive mode */
232   u8 no_adaptive;
233
234   /** vpp fifo event queue configured length */
235   u32 configured_wrk_mq_length;
236
237   /** Session ssvm segment configs*/
238   uword wrk_mqs_segment_size;
239
240   /** Session table size parameters */
241   u32 configured_v4_session_table_buckets;
242   u32 configured_v4_session_table_memory;
243   u32 configured_v4_halfopen_table_buckets;
244   u32 configured_v4_halfopen_table_memory;
245   u32 configured_v6_session_table_buckets;
246   u32 configured_v6_session_table_memory;
247   u32 configured_v6_halfopen_table_buckets;
248   u32 configured_v6_halfopen_table_memory;
249
250   /** Transport table (preallocation) size parameters */
251   u32 local_endpoints_table_memory;
252   u32 local_endpoints_table_buckets;
253
254   /** Preallocate session config parameter */
255   u32 preallocated_sessions;
256
257   u16 msg_id_base;
258 } session_main_t;
259
260 extern session_main_t session_main;
261 extern vlib_node_registration_t session_queue_node;
262 extern vlib_node_registration_t session_queue_process_node;
263 extern vlib_node_registration_t session_queue_pre_input_node;
264
265 typedef enum session_q_process_evt_
266 {
267   SESSION_Q_PROCESS_RUN_ON_MAIN = 1,
268   SESSION_Q_PROCESS_STOP
269 } session_q_process_evt_t;
270
271 #define TRANSPORT_PROTO_INVALID (session_main.last_transport_proto_type + 1)
272 #define TRANSPORT_N_PROTOS (session_main.last_transport_proto_type + 1)
273
274 static inline void
275 session_evt_add_old (session_worker_t * wrk, session_evt_elt_t * elt)
276 {
277   clib_llist_add_tail (wrk->event_elts, evt_list, elt,
278                        clib_llist_elt (wrk->event_elts, wrk->old_head));
279 }
280
281 static inline void
282 session_evt_add_head_old (session_worker_t * wrk, session_evt_elt_t * elt)
283 {
284   clib_llist_add (wrk->event_elts, evt_list, elt,
285                   clib_llist_elt (wrk->event_elts, wrk->old_head));
286 }
287
288
289 static inline u32
290 session_evt_ctrl_data_alloc (session_worker_t * wrk)
291 {
292   session_evt_ctrl_data_t *data;
293   pool_get (wrk->ctrl_evts_data, data);
294   return (data - wrk->ctrl_evts_data);
295 }
296
297 static inline session_evt_elt_t *
298 session_evt_alloc_ctrl (session_worker_t * wrk)
299 {
300   session_evt_elt_t *elt;
301   clib_llist_get (wrk->event_elts, elt);
302   clib_llist_add_tail (wrk->event_elts, evt_list, elt,
303                        clib_llist_elt (wrk->event_elts, wrk->ctrl_head));
304   return elt;
305 }
306
307 static inline void *
308 session_evt_ctrl_data (session_worker_t * wrk, session_evt_elt_t * elt)
309 {
310   return (void *) (pool_elt_at_index (wrk->ctrl_evts_data,
311                                       elt->evt.ctrl_data_index));
312 }
313
314 static inline void
315 session_evt_ctrl_data_free (session_worker_t * wrk, session_evt_elt_t * elt)
316 {
317   ASSERT (elt->evt.event_type > SESSION_IO_EVT_BUILTIN_TX);
318   pool_put_index (wrk->ctrl_evts_data, elt->evt.ctrl_data_index);
319 }
320
321 static inline session_evt_elt_t *
322 session_evt_alloc_new (session_worker_t * wrk)
323 {
324   session_evt_elt_t *elt;
325   clib_llist_get (wrk->event_elts, elt);
326   clib_llist_add_tail (wrk->event_elts, evt_list, elt,
327                        clib_llist_elt (wrk->event_elts, wrk->new_head));
328   return elt;
329 }
330
331 static inline session_evt_elt_t *
332 session_evt_alloc_old (session_worker_t * wrk)
333 {
334   session_evt_elt_t *elt;
335   clib_llist_get (wrk->event_elts, elt);
336   clib_llist_add_tail (wrk->event_elts, evt_list, elt,
337                        clib_llist_elt (wrk->event_elts, wrk->old_head));
338   return elt;
339 }
340
341 int session_wrk_handle_mq (session_worker_t *wrk, svm_msg_q_t *mq);
342
343 session_t *session_alloc (u32 thread_index);
344 void session_free (session_t * s);
345 void session_free_w_fifos (session_t * s);
346 void session_cleanup_half_open (session_handle_t ho_handle);
347 u8 session_is_valid (u32 si, u8 thread_index);
348
349 always_inline session_t *
350 session_get (u32 si, u32 thread_index)
351 {
352   ASSERT (session_is_valid (si, thread_index));
353   return pool_elt_at_index (session_main.wrk[thread_index].sessions, si);
354 }
355
356 always_inline session_t *
357 session_get_if_valid (u64 si, u32 thread_index)
358 {
359   if (thread_index >= vec_len (session_main.wrk))
360     return 0;
361
362   if (pool_is_free_index (session_main.wrk[thread_index].sessions, si))
363     return 0;
364
365   ASSERT (session_is_valid (si, thread_index));
366   return pool_elt_at_index (session_main.wrk[thread_index].sessions, si);
367 }
368
369 always_inline session_t *
370 session_get_from_handle (session_handle_t handle)
371 {
372   session_main_t *smm = &session_main;
373   u32 session_index, thread_index;
374   session_parse_handle (handle, &session_index, &thread_index);
375   return pool_elt_at_index (smm->wrk[thread_index].sessions, session_index);
376 }
377
378 always_inline session_t *
379 session_get_from_handle_if_valid (session_handle_t handle)
380 {
381   u32 session_index, thread_index;
382   session_parse_handle (handle, &session_index, &thread_index);
383   return session_get_if_valid (session_index, thread_index);
384 }
385
386 u64 session_segment_handle (session_t * s);
387
388 /**
389  * Acquires a lock that blocks a session pool from expanding.
390  *
391  * This is typically used for safely peeking into other threads'
392  * pools in order to clone elements. Lock should be dropped as soon
393  * as possible by calling @ref session_pool_remove_peeker.
394  *
395  * NOTE: Avoid using pool_elt_at_index while the lock is held because
396  * it may lead to free elt bitmap expansion/contraction!
397  */
398 always_inline void
399 session_pool_add_peeker (u32 thread_index)
400 {
401   session_worker_t *wrk = &session_main.wrk[thread_index];
402   if (thread_index == vlib_get_thread_index ())
403     return;
404   clib_rwlock_reader_lock (&wrk->peekers_rw_locks);
405 }
406
407 always_inline void
408 session_pool_remove_peeker (u32 thread_index)
409 {
410   session_worker_t *wrk = &session_main.wrk[thread_index];
411   if (thread_index == vlib_get_thread_index ())
412     return;
413   clib_rwlock_reader_unlock (&wrk->peekers_rw_locks);
414 }
415
416 /**
417  * Get session from handle and 'lock' pool resize if not in same thread
418  *
419  * Caller should drop the peek 'lock' as soon as possible.
420  */
421 always_inline session_t *
422 session_get_from_handle_safe (u64 handle)
423 {
424   u32 thread_index = session_thread_from_handle (handle);
425   session_worker_t *wrk = &session_main.wrk[thread_index];
426
427   if (thread_index == vlib_get_thread_index ())
428     {
429       return pool_elt_at_index (wrk->sessions,
430                                 session_index_from_handle (handle));
431     }
432   else
433     {
434       session_pool_add_peeker (thread_index);
435       /* Don't use pool_elt_at index. See @ref session_pool_add_peeker */
436       return wrk->sessions + session_index_from_handle (handle);
437     }
438 }
439
440 always_inline u32
441 session_get_index (session_t * s)
442 {
443   return (s - session_main.wrk[s->thread_index].sessions);
444 }
445
446 always_inline session_t *
447 session_clone_safe (u32 session_index, u32 thread_index)
448 {
449   session_t *old_s, *new_s;
450   u32 current_thread_index = vlib_get_thread_index ();
451
452   /* If during the memcpy pool is reallocated AND the memory allocator
453    * decides to give the old chunk of memory to somebody in a hurry to
454    * scribble something on it, we have a problem. So add this thread as
455    * a session pool peeker.
456    */
457   session_pool_add_peeker (thread_index);
458   new_s = session_alloc (current_thread_index);
459   old_s = session_main.wrk[thread_index].sessions + session_index;
460   clib_memcpy_fast (new_s, old_s, sizeof (*new_s));
461   session_pool_remove_peeker (thread_index);
462   new_s->thread_index = current_thread_index;
463   new_s->session_index = session_get_index (new_s);
464   return new_s;
465 }
466
467 int session_open (session_endpoint_cfg_t *sep, session_handle_t *rsh);
468 int session_listen (session_t * s, session_endpoint_cfg_t * sep);
469 int session_stop_listen (session_t * s);
470 void session_half_close (session_t *s);
471 void session_close (session_t * s);
472 void session_reset (session_t * s);
473 void session_transport_half_close (session_t *s);
474 void session_transport_close (session_t * s);
475 void session_transport_reset (session_t * s);
476 void session_transport_cleanup (session_t * s);
477 int session_send_io_evt_to_thread (svm_fifo_t * f,
478                                    session_evt_type_t evt_type);
479 int session_enqueue_notify (session_t * s);
480 int session_dequeue_notify (session_t * s);
481 int session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
482                                           session_evt_type_t evt_type);
483 void session_send_rpc_evt_to_thread (u32 thread_index, void *fp,
484                                      void *rpc_args);
485 void session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
486                                            void *rpc_args);
487 void session_add_self_custom_tx_evt (transport_connection_t * tc,
488                                      u8 has_prio);
489 void sesssion_reschedule_tx (transport_connection_t * tc);
490 transport_connection_t *session_get_transport (session_t * s);
491 void session_get_endpoint (session_t * s, transport_endpoint_t * tep,
492                            u8 is_lcl);
493 int session_transport_attribute (session_t *s, u8 is_get,
494                                  transport_endpt_attr_t *attr);
495
496 u8 *format_session (u8 * s, va_list * args);
497 uword unformat_session (unformat_input_t * input, va_list * args);
498 uword unformat_transport_connection (unformat_input_t * input,
499                                      va_list * args);
500
501 /*
502  * Interface to transport protos
503  */
504
505 int session_enqueue_stream_connection (transport_connection_t * tc,
506                                        vlib_buffer_t * b, u32 offset,
507                                        u8 queue_event, u8 is_in_order);
508 int session_enqueue_dgram_connection (session_t * s,
509                                       session_dgram_hdr_t * hdr,
510                                       vlib_buffer_t * b, u8 proto,
511                                       u8 queue_event);
512 int session_stream_connect_notify (transport_connection_t * tc,
513                                    session_error_t err);
514 int session_dgram_connect_notify (transport_connection_t * tc,
515                                   u32 old_thread_index,
516                                   session_t ** new_session);
517 int session_stream_accept_notify (transport_connection_t * tc);
518 void session_transport_closing_notify (transport_connection_t * tc);
519 void session_transport_delete_notify (transport_connection_t * tc);
520 void session_half_open_delete_notify (transport_connection_t *tc);
521 void session_half_open_migrate_notify (transport_connection_t *tc);
522 int session_half_open_migrated_notify (transport_connection_t *tc);
523 void session_transport_closed_notify (transport_connection_t * tc);
524 void session_transport_reset_notify (transport_connection_t * tc);
525 int session_stream_accept (transport_connection_t * tc, u32 listener_index,
526                            u32 thread_index, u8 notify);
527 int session_dgram_accept (transport_connection_t * tc, u32 listener_index,
528                           u32 thread_index);
529 /**
530  * Initialize session layer for given transport proto and ip version
531  *
532  * Allocates per session type (transport proto + ip version) data structures
533  * and adds arc from session queue node to session type output node.
534  *
535  * @param transport_proto       transport proto to be registered
536  * @param vft                   virtual function table for transport
537  * @param is_ip4                flag that indicates if transports uses ipv4
538  *                              as underlying network layer
539  * @param output_node           output node for transport
540  */
541 void session_register_transport (transport_proto_t transport_proto,
542                                  const transport_proto_vft_t * vft, u8 is_ip4,
543                                  u32 output_node);
544 transport_proto_t session_add_transport_proto (void);
545 void session_register_update_time_fn (session_update_time_fn fn, u8 is_add);
546 int session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
547                                 u32 offset, u32 max_bytes);
548 u32 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes);
549
550 always_inline u32
551 transport_max_rx_enqueue (transport_connection_t * tc)
552 {
553   session_t *s = session_get (tc->s_index, tc->thread_index);
554   return svm_fifo_max_enqueue_prod (s->rx_fifo);
555 }
556
557 always_inline u32
558 transport_max_tx_dequeue (transport_connection_t * tc)
559 {
560   session_t *s = session_get (tc->s_index, tc->thread_index);
561   return svm_fifo_max_dequeue_cons (s->tx_fifo);
562 }
563
564 always_inline u32
565 transport_max_rx_dequeue (transport_connection_t * tc)
566 {
567   session_t *s = session_get (tc->s_index, tc->thread_index);
568   return svm_fifo_max_dequeue (s->rx_fifo);
569 }
570
571 always_inline u32
572 transport_rx_fifo_size (transport_connection_t * tc)
573 {
574   session_t *s = session_get (tc->s_index, tc->thread_index);
575   return svm_fifo_size (s->rx_fifo);
576 }
577
578 always_inline u32
579 transport_tx_fifo_size (transport_connection_t * tc)
580 {
581   session_t *s = session_get (tc->s_index, tc->thread_index);
582   return svm_fifo_size (s->tx_fifo);
583 }
584
585 always_inline u8
586 transport_rx_fifo_has_ooo_data (transport_connection_t * tc)
587 {
588   session_t *s = session_get (tc->c_index, tc->thread_index);
589   return svm_fifo_has_ooo_data (s->rx_fifo);
590 }
591
592 always_inline void
593 transport_rx_fifo_req_deq_ntf (transport_connection_t *tc)
594 {
595   session_t *s = session_get (tc->s_index, tc->thread_index);
596   svm_fifo_add_want_deq_ntf (s->rx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
597 }
598
599 always_inline clib_time_type_t
600 transport_time_now (u32 thread_index)
601 {
602   return session_main.wrk[thread_index].last_vlib_time;
603 }
604
605 always_inline clib_us_time_t
606 transport_us_time_now (u32 thread_index)
607 {
608   return session_main.wrk[thread_index].last_vlib_us_time;
609 }
610
611 always_inline clib_time_type_t
612 transport_seconds_per_loop (u32 thread_index)
613 {
614   return session_main.wrk[thread_index].vm->seconds_per_loop;
615 }
616
617 always_inline void
618 transport_add_tx_event (transport_connection_t * tc)
619 {
620   session_t *s = session_get (tc->s_index, tc->thread_index);
621   if (svm_fifo_has_event (s->tx_fifo))
622     return;
623   session_send_io_evt_to_thread (s->tx_fifo, SESSION_IO_EVT_TX);
624 }
625
626 always_inline u32
627 transport_cl_thread (void)
628 {
629   return session_main.transport_cl_thread;
630 }
631
632 /*
633  * Listen sessions
634  */
635
636 always_inline u64
637 listen_session_get_handle (session_t * s)
638 {
639   ASSERT (s->session_state == SESSION_STATE_LISTENING ||
640           session_get_transport_proto (s) == TRANSPORT_PROTO_QUIC);
641   return session_handle (s);
642 }
643
644 always_inline session_t *
645 listen_session_get_from_handle (session_handle_t handle)
646 {
647   return session_get_from_handle (handle);
648 }
649
650 always_inline void
651 listen_session_parse_handle (session_handle_t handle, u32 * index,
652                              u32 * thread_index)
653 {
654   session_parse_handle (handle, index, thread_index);
655 }
656
657 always_inline session_t *
658 listen_session_alloc (u8 thread_index, session_type_t type)
659 {
660   session_t *s;
661   s = session_alloc (thread_index);
662   s->session_type = type;
663   s->session_state = SESSION_STATE_LISTENING;
664   return s;
665 }
666
667 always_inline session_t *
668 listen_session_get (u32 ls_index)
669 {
670   return session_get (ls_index, 0);
671 }
672
673 always_inline void
674 listen_session_free (session_t * s)
675 {
676   ASSERT (!s->rx_fifo);
677   session_free (s);
678 }
679
680 always_inline session_t *
681 ho_session_alloc (void)
682 {
683   session_t *s;
684   ASSERT (vlib_get_thread_index () == 0);
685   s = session_alloc (0);
686   s->session_state = SESSION_STATE_CONNECTING;
687   s->flags |= SESSION_F_HALF_OPEN;
688   /* Not ideal. Half-opens are only allocated from main with worker barrier
689    * but can be cleaned up, i.e., session_half_open_free, from main without
690    * a barrier. In debug images, the free_bitmap can grow while workers peek
691    * the sessions pool, e.g., session_half_open_migrate_notify, and as a
692    * result crash while validating the session. To avoid this, grow the bitmap
693    * now. */
694   if (CLIB_DEBUG)
695     {
696       session_t *sp = session_main.wrk[0].sessions;
697       clib_bitmap_validate (pool_header (sp)->free_bitmap, s->session_index);
698     }
699   return s;
700 }
701
702 always_inline session_t *
703 ho_session_get (u32 ho_index)
704 {
705   return session_get (ho_index, 0 /* half-open thread */);
706 }
707
708 always_inline void
709 ho_session_free (session_t *s)
710 {
711   ASSERT (!s->rx_fifo && s->thread_index == 0);
712   session_free (s);
713 }
714
715 transport_connection_t *listen_session_get_transport (session_t * s);
716
717 /*
718  * Session layer functions
719  */
720
721 always_inline session_main_t *
722 vnet_get_session_main ()
723 {
724   return &session_main;
725 }
726
727 always_inline session_worker_t *
728 session_main_get_worker (u32 thread_index)
729 {
730   return &session_main.wrk[thread_index];
731 }
732
733 static inline session_worker_t *
734 session_main_get_worker_if_valid (u32 thread_index)
735 {
736   if (thread_index > vec_len (session_main.wrk))
737     return 0;
738   return &session_main.wrk[thread_index];
739 }
740
741 always_inline svm_msg_q_t *
742 session_main_get_vpp_event_queue (u32 thread_index)
743 {
744   return session_main.wrk[thread_index].vpp_event_queue;
745 }
746
747 always_inline u8
748 session_main_is_enabled ()
749 {
750   return session_main.is_enabled == 1;
751 }
752
753 #define session_cli_return_if_not_enabled()                             \
754 do {                                                                    \
755     if (!session_main.is_enabled)                                       \
756       return clib_error_return (0, "session layer is not enabled");     \
757 } while (0)
758
759 int session_main_flush_enqueue_events (u8 proto, u32 thread_index);
760 int session_main_flush_all_enqueue_events (u8 transport_proto);
761 void session_queue_run_on_main_thread (vlib_main_t * vm);
762
763 /**
764  * Add session node pending buffer with custom node
765  *
766  * @param thread_index  worker thread expected to send the buffer
767  * @param bi            buffer index
768  * @param next_node     next node edge index for buffer. Edge to next node
769  *                      must exist
770  */
771 always_inline void
772 session_add_pending_tx_buffer (u32 thread_index, u32 bi, u32 next_node)
773 {
774   session_worker_t *wrk = session_main_get_worker (thread_index);
775   vec_add1 (wrk->pending_tx_buffers, bi);
776   vec_add1 (wrk->pending_tx_nexts, next_node);
777   if (PREDICT_FALSE (wrk->state == SESSION_WRK_INTERRUPT))
778     vlib_node_set_interrupt_pending (wrk->vm, session_queue_node.index);
779 }
780
781 always_inline void
782 session_wrk_update_time (session_worker_t *wrk, f64 now)
783 {
784   wrk->last_vlib_time = now;
785   wrk->last_vlib_us_time = wrk->last_vlib_time * CLIB_US_TIME_FREQ;
786 }
787
788 void session_wrk_enable_adaptive_mode (session_worker_t *wrk);
789 fifo_segment_t *session_main_get_wrk_mqs_segment (void);
790 void session_node_enable_disable (u8 is_en);
791 clib_error_t *vnet_session_enable_disable (vlib_main_t * vm, u8 is_en);
792 void session_wrk_handle_evts_main_rpc ();
793
794 session_t *session_alloc_for_connection (transport_connection_t * tc);
795 session_t *session_alloc_for_half_open (transport_connection_t *tc);
796
797 typedef void (pool_safe_realloc_rpc_fn) (void *rpc_args);
798
799 typedef struct
800 {
801   u8 ph[STRUCT_OFFSET_OF (pool_header_t, max_elts) + 4];
802   u32 flag;
803 } pool_safe_realloc_header_t;
804
805 STATIC_ASSERT_SIZEOF (pool_safe_realloc_header_t, sizeof (pool_header_t));
806
807 #define POOL_REALLOC_SAFE_ELT_THRESH 32
808
809 #define pool_realloc_flag(PH)                                                 \
810   ((pool_safe_realloc_header_t *) pool_header (PH))->flag
811
812 #define pool_realloc_safe_aligned(P, align)                                   \
813   do                                                                          \
814     {                                                                         \
815       vlib_main_t *vm = vlib_get_main ();                                     \
816       u32 free_elts, max_elts, n_alloc;                                       \
817       ASSERT (vlib_get_thread_index () == 0);                                 \
818       vlib_worker_thread_barrier_sync (vm);                                   \
819       free_elts = pool_free_elts (P);                                         \
820       max_elts = pool_max_len (P);                                            \
821       n_alloc = clib_max (2 * max_elts, POOL_REALLOC_SAFE_ELT_THRESH);        \
822       pool_alloc_aligned (P, free_elts + n_alloc, align);                     \
823       clib_bitmap_validate (pool_header (P)->free_bitmap,                     \
824                             max_elts + n_alloc);                              \
825       pool_realloc_flag (P) = 0;                                              \
826       vlib_worker_thread_barrier_release (vm);                                \
827     }                                                                         \
828   while (0)
829
830 always_inline void
831 pool_program_safe_realloc (void *p, u32 thread_index,
832                            pool_safe_realloc_rpc_fn *rpc_fn)
833 {
834   /* Reuse pad as a realloc flag */
835   if (pool_realloc_flag (p))
836     return;
837
838   pool_realloc_flag (p) = 1;
839   session_send_rpc_evt_to_thread (0 /* thread index */, rpc_fn,
840                                   uword_to_pointer (thread_index, void *));
841 }
842
843 always_inline void
844 pool_realloc_maybe_wait_at_barrier (void)
845 {
846   if (!(*vlib_worker_threads->wait_at_barrier))
847     return;
848
849   /* Node refork required. Don't stop at the barrier from within a node */
850   if (*vlib_worker_threads->node_reforks_required)
851     return;
852
853   clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, 1);
854
855   while (*vlib_worker_threads->wait_at_barrier)
856     ;
857
858   clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, -1);
859 }
860
861 #define pool_realloc_all_at_barrier(_not)                                     \
862   (*vlib_worker_threads->workers_at_barrier >= (vlib_num_workers () - _not))
863
864 #define pool_realloc_safe_force(P)                                            \
865   do                                                                          \
866     {                                                                         \
867       ALWAYS_ASSERT (*vlib_worker_threads->node_reforks_required);            \
868       if (pool_realloc_all_at_barrier (1))                                    \
869         {                                                                     \
870           pool_alloc (P, pool_max_len (P));                                   \
871         }                                                                     \
872       else                                                                    \
873         {                                                                     \
874           session_main_t *sm = &session_main;                                 \
875           clib_warning ("forced pool realloc");                               \
876           clib_atomic_fetch_add (&sm->pool_realloc_at_barrier, 1);            \
877           while (!pool_realloc_all_at_barrier (sm->pool_realloc_at_barrier))  \
878             ;                                                                 \
879           clib_spinlock_lock (&sm->pool_realloc_lock);                        \
880           pool_alloc (P, pool_max_len (P));                                   \
881           clib_spinlock_unlock (&sm->pool_realloc_lock);                      \
882           clib_atomic_fetch_add (&sm->pool_realloc_at_barrier, -1);           \
883         }                                                                     \
884     }                                                                         \
885   while (0)
886
887 #define pool_needs_realloc(P)                                                 \
888   ((!P) ||                                                                    \
889    (vec_len (pool_header (P)->free_indices) < POOL_REALLOC_SAFE_ELT_THRESH && \
890     pool_free_elts (P) < POOL_REALLOC_SAFE_ELT_THRESH))
891
892 #define pool_get_aligned_safe(P, E, thread_index, rpc_fn, align)              \
893   do                                                                          \
894     {                                                                         \
895       ASSERT (vlib_get_thread_index () == thread_index ||                     \
896               vlib_thread_is_main_w_barrier ());                              \
897       if (PREDICT_FALSE (pool_needs_realloc (P)))                             \
898         {                                                                     \
899           if (PREDICT_FALSE (!(P)))                                           \
900             {                                                                 \
901               pool_alloc_aligned (P, 2 * POOL_REALLOC_SAFE_ELT_THRESH,        \
902                                   align);                                     \
903             }                                                                 \
904           else if (PREDICT_FALSE (pool_free_elts (P) <                        \
905                                   POOL_REALLOC_SAFE_ELT_THRESH / 2))          \
906             {                                                                 \
907               volatile typeof (P) *PP = &(P);                                 \
908               pool_program_safe_realloc (P, thread_index, rpc_fn);            \
909               if (thread_index)                                               \
910                 {                                                             \
911                   while (pool_realloc_flag (P))                               \
912                     {                                                         \
913                       /* If refork required abort and consume existing elt */ \
914                       if (*vlib_worker_threads->node_reforks_required)        \
915                         {                                                     \
916                           /* All workers at barrier realloc now */            \
917                           if (pool_realloc_all_at_barrier (1))                \
918                             pool_alloc_aligned (P, pool_max_len (P), align);  \
919                           break;                                              \
920                         }                                                     \
921                       pool_realloc_maybe_wait_at_barrier ();                  \
922                     }                                                         \
923                   if (pool_free_elts (P) == 0)                                \
924                     pool_realloc_safe_force (P);                              \
925                   ALWAYS_ASSERT (pool_free_elts (P) > 0);                     \
926                 }                                                             \
927               (P) = *PP;                                                      \
928             }                                                                 \
929           else                                                                \
930             {                                                                 \
931               pool_program_safe_realloc (P, thread_index, rpc_fn);            \
932             }                                                                 \
933         }                                                                     \
934       pool_get_aligned (P, E, align);                                         \
935     }                                                                         \
936   while (0)
937
938 #endif /* __included_session_h__ */
939
940 /*
941  * fd.io coding-style-patch-verification: ON
942  *
943  * Local Variables:
944  * eval: (c-set-style "gnu")
945  * End:
946  */