session: notify app of session and transport cleanup
[vpp.git] / src / vnet / session / session.c
1 /*
2  * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /**
16  * @file
17  * @brief Session and session manager
18  */
19
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>
25
26 session_main_t session_main;
27
28 static inline int
29 session_send_evt_to_thread (void *data, void *args, u32 thread_index,
30                             session_evt_type_t evt_type)
31 {
32   session_event_t *evt;
33   svm_msg_q_msg_t msg;
34   svm_msg_q_t *mq;
35
36   mq = session_main_get_vpp_event_queue (thread_index);
37   if (PREDICT_FALSE (svm_msg_q_lock (mq)))
38     return -1;
39   if (PREDICT_FALSE (svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
40     {
41       svm_msg_q_unlock (mq);
42       return -2;
43     }
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)))
46     {
47       svm_msg_q_unlock (mq);
48       return -2;
49     }
50   evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
51   evt->event_type = evt_type;
52   switch (evt_type)
53     {
54     case SESSION_CTRL_EVT_RPC:
55       evt->rpc_args.fp = data;
56       evt->rpc_args.arg = args;
57       break;
58     case SESSION_IO_EVT_RX:
59     case SESSION_IO_EVT_TX:
60     case SESSION_IO_EVT_TX_FLUSH:
61     case SESSION_IO_EVT_BUILTIN_RX:
62       evt->session_index = *(u32 *) data;
63       break;
64     case SESSION_IO_EVT_BUILTIN_TX:
65     case SESSION_CTRL_EVT_CLOSE:
66       evt->session_handle = session_handle ((session_t *) data);
67       break;
68     default:
69       clib_warning ("evt unhandled!");
70       svm_msg_q_unlock (mq);
71       return -1;
72     }
73
74   svm_msg_q_add_and_unlock (mq, &msg);
75   return 0;
76 }
77
78 int
79 session_send_io_evt_to_thread (svm_fifo_t * f, session_evt_type_t evt_type)
80 {
81   return session_send_evt_to_thread (&f->master_session_index, 0,
82                                      f->master_thread_index, evt_type);
83 }
84
85 int
86 session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
87                                       session_evt_type_t evt_type)
88 {
89   return session_send_evt_to_thread (data, 0, thread_index, evt_type);
90 }
91
92 int
93 session_send_ctrl_evt_to_thread (session_t * s, session_evt_type_t evt_type)
94 {
95   /* only event supported for now is disconnect */
96   ASSERT (evt_type == SESSION_CTRL_EVT_CLOSE);
97   return session_send_evt_to_thread (s, 0, s->thread_index,
98                                      SESSION_CTRL_EVT_CLOSE);
99 }
100
101 void
102 session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
103                                       void *rpc_args)
104 {
105   session_send_evt_to_thread (fp, rpc_args, thread_index,
106                               SESSION_CTRL_EVT_RPC);
107 }
108
109 void
110 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
111 {
112   if (thread_index != vlib_get_thread_index ())
113     session_send_rpc_evt_to_thread_force (thread_index, fp, rpc_args);
114   else
115     {
116       void (*fnp) (void *) = fp;
117       fnp (rpc_args);
118     }
119 }
120
121 static void
122 session_program_transport_close (session_t * s)
123 {
124   u32 thread_index = vlib_get_thread_index ();
125   session_worker_t *wrk;
126   session_event_t *evt;
127
128   /* If we are in the handler thread, or being called with the worker barrier
129    * held, just append a new event to pending disconnects vector. */
130   if (vlib_thread_is_main_w_barrier () || thread_index == s->thread_index)
131     {
132       wrk = session_main_get_worker (s->thread_index);
133       vec_add2 (wrk->pending_disconnects, evt, 1);
134       clib_memset (evt, 0, sizeof (*evt));
135       evt->session_handle = session_handle (s);
136       evt->event_type = SESSION_CTRL_EVT_CLOSE;
137     }
138   else
139     session_send_ctrl_evt_to_thread (s, SESSION_CTRL_EVT_CLOSE);
140 }
141
142 session_t *
143 session_alloc (u32 thread_index)
144 {
145   session_worker_t *wrk = &session_main.wrk[thread_index];
146   session_t *s;
147   u8 will_expand = 0;
148   pool_get_aligned_will_expand (wrk->sessions, will_expand,
149                                 CLIB_CACHE_LINE_BYTES);
150   /* If we have peekers, let them finish */
151   if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
152     {
153       clib_rwlock_writer_lock (&wrk->peekers_rw_locks);
154       pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
155       clib_rwlock_writer_unlock (&wrk->peekers_rw_locks);
156     }
157   else
158     {
159       pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
160     }
161   clib_memset (s, 0, sizeof (*s));
162   s->session_index = s - wrk->sessions;
163   s->thread_index = thread_index;
164   s->app_index = APP_INVALID_INDEX;
165   return s;
166 }
167
168 void
169 session_free (session_t * s)
170 {
171   if (CLIB_DEBUG)
172     {
173       u8 thread_index = s->thread_index;
174       clib_memset (s, 0xFA, sizeof (*s));
175       pool_put (session_main.wrk[thread_index].sessions, s);
176       return;
177     }
178   SESSION_EVT_DBG (SESSION_EVT_FREE, s);
179   pool_put (session_main.wrk[s->thread_index].sessions, s);
180 }
181
182 static void
183 session_cleanup_notify (session_t * s, session_cleanup_ntf_t ntf)
184 {
185   app_worker_t *app_wrk;
186
187   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
188   if (!app_wrk)
189     return;
190   app_worker_cleanup_notify (app_wrk, s, ntf);
191 }
192
193 void
194 session_free_w_fifos (session_t * s)
195 {
196   session_cleanup_notify (s, SESSION_CLEANUP_SESSION);
197   segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
198   session_free (s);
199 }
200
201 /**
202  * Cleans up session and lookup table.
203  *
204  * Transport connection must still be valid.
205  */
206 static void
207 session_delete (session_t * s)
208 {
209   int rv;
210
211   /* Delete from the main lookup table. */
212   if ((rv = session_lookup_del_session (s)))
213     clib_warning ("hash delete error, rv %d", rv);
214
215   session_free_w_fifos (s);
216 }
217
218 static session_t *
219 session_alloc_for_connection (transport_connection_t * tc)
220 {
221   session_t *s;
222   u32 thread_index = tc->thread_index;
223
224   ASSERT (thread_index == vlib_get_thread_index ()
225           || transport_protocol_is_cl (tc->proto));
226
227   s = session_alloc (thread_index);
228   s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
229   s->session_state = SESSION_STATE_CLOSED;
230
231   /* Attach transport to session and vice versa */
232   s->connection_index = tc->c_index;
233   tc->s_index = s->session_index;
234   return s;
235 }
236
237 /**
238  * Discards bytes from buffer chain
239  *
240  * It discards n_bytes_to_drop starting at first buffer after chain_b
241  */
242 always_inline void
243 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
244                                      vlib_buffer_t ** chain_b,
245                                      u32 n_bytes_to_drop)
246 {
247   vlib_buffer_t *next = *chain_b;
248   u32 to_drop = n_bytes_to_drop;
249   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
250   while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
251     {
252       next = vlib_get_buffer (vm, next->next_buffer);
253       if (next->current_length > to_drop)
254         {
255           vlib_buffer_advance (next, to_drop);
256           to_drop = 0;
257         }
258       else
259         {
260           to_drop -= next->current_length;
261           next->current_length = 0;
262         }
263     }
264   *chain_b = next;
265
266   if (to_drop == 0)
267     b->total_length_not_including_first_buffer -= n_bytes_to_drop;
268 }
269
270 /**
271  * Enqueue buffer chain tail
272  */
273 always_inline int
274 session_enqueue_chain_tail (session_t * s, vlib_buffer_t * b,
275                             u32 offset, u8 is_in_order)
276 {
277   vlib_buffer_t *chain_b;
278   u32 chain_bi, len, diff;
279   vlib_main_t *vm = vlib_get_main ();
280   u8 *data;
281   u32 written = 0;
282   int rv = 0;
283
284   if (is_in_order && offset)
285     {
286       diff = offset - b->current_length;
287       if (diff > b->total_length_not_including_first_buffer)
288         return 0;
289       chain_b = b;
290       session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
291       chain_bi = vlib_get_buffer_index (vm, chain_b);
292     }
293   else
294     chain_bi = b->next_buffer;
295
296   do
297     {
298       chain_b = vlib_get_buffer (vm, chain_bi);
299       data = vlib_buffer_get_current (chain_b);
300       len = chain_b->current_length;
301       if (!len)
302         continue;
303       if (is_in_order)
304         {
305           rv = svm_fifo_enqueue (s->rx_fifo, len, data);
306           if (rv == len)
307             {
308               written += rv;
309             }
310           else if (rv < len)
311             {
312               return (rv > 0) ? (written + rv) : written;
313             }
314           else if (rv > len)
315             {
316               written += rv;
317
318               /* written more than what was left in chain */
319               if (written > b->total_length_not_including_first_buffer)
320                 return written;
321
322               /* drop the bytes that have already been delivered */
323               session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
324             }
325         }
326       else
327         {
328           rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset, len, data);
329           if (rv)
330             {
331               clib_warning ("failed to enqueue multi-buffer seg");
332               return -1;
333             }
334           offset += len;
335         }
336     }
337   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
338           ? chain_b->next_buffer : 0));
339
340   if (is_in_order)
341     return written;
342
343   return 0;
344 }
345
346 /*
347  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
348  * event but on request can queue notification events for later delivery by
349  * calling stream_server_flush_enqueue_events().
350  *
351  * @param tc Transport connection which is to be enqueued data
352  * @param b Buffer to be enqueued
353  * @param offset Offset at which to start enqueueing if out-of-order
354  * @param queue_event Flag to indicate if peer is to be notified or if event
355  *                    is to be queued. The former is useful when more data is
356  *                    enqueued and only one event is to be generated.
357  * @param is_in_order Flag to indicate if data is in order
358  * @return Number of bytes enqueued or a negative value if enqueueing failed.
359  */
360 int
361 session_enqueue_stream_connection (transport_connection_t * tc,
362                                    vlib_buffer_t * b, u32 offset,
363                                    u8 queue_event, u8 is_in_order)
364 {
365   session_t *s;
366   int enqueued = 0, rv, in_order_off;
367
368   s = session_get (tc->s_index, tc->thread_index);
369
370   if (is_in_order)
371     {
372       enqueued = svm_fifo_enqueue (s->rx_fifo,
373                                    b->current_length,
374                                    vlib_buffer_get_current (b));
375       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
376                          && enqueued >= 0))
377         {
378           in_order_off = enqueued > b->current_length ? enqueued : 0;
379           rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
380           if (rv > 0)
381             enqueued += rv;
382         }
383     }
384   else
385     {
386       rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset,
387                                          b->current_length,
388                                          vlib_buffer_get_current (b));
389       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
390         session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
391       /* if something was enqueued, report even this as success for ooo
392        * segment handling */
393       return rv;
394     }
395
396   if (queue_event)
397     {
398       /* Queue RX event on this fifo. Eventually these will need to be flushed
399        * by calling stream_server_flush_enqueue_events () */
400       session_worker_t *wrk;
401
402       wrk = session_main_get_worker (s->thread_index);
403       if (!(s->flags & SESSION_F_RX_EVT))
404         {
405           s->flags |= SESSION_F_RX_EVT;
406           vec_add1 (wrk->session_to_enqueue[tc->proto], s->session_index);
407         }
408     }
409
410   return enqueued;
411 }
412
413 int
414 session_enqueue_dgram_connection (session_t * s,
415                                   session_dgram_hdr_t * hdr,
416                                   vlib_buffer_t * b, u8 proto, u8 queue_event)
417 {
418   int enqueued = 0, rv, in_order_off;
419
420   ASSERT (svm_fifo_max_enqueue_prod (s->rx_fifo)
421           >= b->current_length + sizeof (*hdr));
422
423   svm_fifo_enqueue (s->rx_fifo, sizeof (session_dgram_hdr_t), (u8 *) hdr);
424   enqueued = svm_fifo_enqueue (s->rx_fifo, b->current_length,
425                                vlib_buffer_get_current (b));
426   if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued >= 0))
427     {
428       in_order_off = enqueued > b->current_length ? enqueued : 0;
429       rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
430       if (rv > 0)
431         enqueued += rv;
432     }
433   if (queue_event)
434     {
435       /* Queue RX event on this fifo. Eventually these will need to be flushed
436        * by calling stream_server_flush_enqueue_events () */
437       session_worker_t *wrk;
438
439       wrk = session_main_get_worker (s->thread_index);
440       if (!(s->flags & SESSION_F_RX_EVT))
441         {
442           s->flags |= SESSION_F_RX_EVT;
443           vec_add1 (wrk->session_to_enqueue[proto], s->session_index);
444         }
445     }
446   return enqueued;
447 }
448
449 int
450 session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
451                             u32 offset, u32 max_bytes)
452 {
453   session_t *s = session_get (tc->s_index, tc->thread_index);
454   return svm_fifo_peek (s->tx_fifo, offset, max_bytes, buffer);
455 }
456
457 u32
458 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
459 {
460   session_t *s = session_get (tc->s_index, tc->thread_index);
461   u32 rv;
462
463   rv = svm_fifo_dequeue_drop (s->tx_fifo, max_bytes);
464
465   if (svm_fifo_needs_deq_ntf (s->tx_fifo, max_bytes))
466     session_dequeue_notify (s);
467
468   return rv;
469 }
470
471 static inline int
472 session_notify_subscribers (u32 app_index, session_t * s,
473                             svm_fifo_t * f, session_evt_type_t evt_type)
474 {
475   app_worker_t *app_wrk;
476   application_t *app;
477   int i;
478
479   app = application_get (app_index);
480   if (!app)
481     return -1;
482
483   for (i = 0; i < f->n_subscribers; i++)
484     {
485       app_wrk = application_get_worker (app, f->subscribers[i]);
486       if (!app_wrk)
487         continue;
488       if (app_worker_lock_and_send_event (app_wrk, s, evt_type))
489         return -1;
490     }
491
492   return 0;
493 }
494
495 /**
496  * Notify session peer that new data has been enqueued.
497  *
498  * @param s     Stream session for which the event is to be generated.
499  * @param lock  Flag to indicate if call should lock message queue.
500  *
501  * @return 0 on success or negative number if failed to send notification.
502  */
503 static inline int
504 session_enqueue_notify_inline (session_t * s)
505 {
506   app_worker_t *app_wrk;
507   u32 session_index;
508   u8 n_subscribers;
509
510   session_index = s->session_index;
511   n_subscribers = svm_fifo_n_subscribers (s->rx_fifo);
512
513   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
514   if (PREDICT_FALSE (!app_wrk))
515     {
516       SESSION_DBG ("invalid s->app_index = %d", s->app_wrk_index);
517       return 0;
518     }
519
520   /* *INDENT-OFF* */
521   SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
522       ed->data[0] = SESSION_IO_EVT_RX;
523       ed->data[1] = svm_fifo_max_dequeue_prod (s->rx_fifo);
524   }));
525   /* *INDENT-ON* */
526
527   s->flags &= ~SESSION_F_RX_EVT;
528   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
529                                                      SESSION_IO_EVT_RX)))
530     return -1;
531
532   if (PREDICT_FALSE (n_subscribers))
533     {
534       s = session_get (session_index, vlib_get_thread_index ());
535       return session_notify_subscribers (app_wrk->app_index, s,
536                                          s->rx_fifo, SESSION_IO_EVT_RX);
537     }
538
539   return 0;
540 }
541
542 int
543 session_enqueue_notify (session_t * s)
544 {
545   return session_enqueue_notify_inline (s);
546 }
547
548 int
549 session_dequeue_notify (session_t * s)
550 {
551   app_worker_t *app_wrk;
552
553   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
554   if (PREDICT_FALSE (!app_wrk))
555     return -1;
556
557   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
558                                                      SESSION_IO_EVT_TX)))
559     return -1;
560
561   if (PREDICT_FALSE (s->tx_fifo->n_subscribers))
562     return session_notify_subscribers (app_wrk->app_index, s,
563                                        s->tx_fifo, SESSION_IO_EVT_TX);
564
565   svm_fifo_clear_deq_ntf (s->tx_fifo);
566
567   return 0;
568 }
569
570 /**
571  * Flushes queue of sessions that are to be notified of new data
572  * enqueued events.
573  *
574  * @param thread_index Thread index for which the flush is to be performed.
575  * @return 0 on success or a positive number indicating the number of
576  *         failures due to API queue being full.
577  */
578 int
579 session_main_flush_enqueue_events (u8 transport_proto, u32 thread_index)
580 {
581   session_worker_t *wrk = session_main_get_worker (thread_index);
582   session_t *s;
583   int i, errors = 0;
584   u32 *indices;
585
586   indices = wrk->session_to_enqueue[transport_proto];
587
588   for (i = 0; i < vec_len (indices); i++)
589     {
590       s = session_get_if_valid (indices[i], thread_index);
591       if (PREDICT_FALSE (!s))
592         {
593           errors++;
594           continue;
595         }
596
597       if (PREDICT_FALSE (session_enqueue_notify_inline (s)))
598         errors++;
599     }
600
601   vec_reset_length (indices);
602   wrk->session_to_enqueue[transport_proto] = indices;
603
604   return errors;
605 }
606
607 int
608 session_main_flush_all_enqueue_events (u8 transport_proto)
609 {
610   vlib_thread_main_t *vtm = vlib_get_thread_main ();
611   int i, errors = 0;
612   for (i = 0; i < 1 + vtm->n_threads; i++)
613     errors += session_main_flush_enqueue_events (transport_proto, i);
614   return errors;
615 }
616
617 static inline int
618 session_stream_connect_notify_inline (transport_connection_t * tc, u8 is_fail,
619                                       session_state_t opened_state)
620 {
621   u32 opaque = 0, new_ti, new_si;
622   app_worker_t *app_wrk;
623   session_t *s = 0;
624   u64 ho_handle;
625
626   /*
627    * Find connection handle and cleanup half-open table
628    */
629   ho_handle = session_lookup_half_open_handle (tc);
630   if (ho_handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
631     {
632       SESSION_DBG ("half-open was removed!");
633       return -1;
634     }
635   session_lookup_del_half_open (tc);
636
637   /* Get the app's index from the handle we stored when opening connection
638    * and the opaque (api_context for external apps) from transport session
639    * index */
640   app_wrk = app_worker_get_if_valid (ho_handle >> 32);
641   if (!app_wrk)
642     return -1;
643
644   opaque = tc->s_index;
645
646   if (is_fail)
647     return app_worker_connect_notify (app_wrk, s, opaque);
648
649   s = session_alloc_for_connection (tc);
650   s->session_state = SESSION_STATE_CONNECTING;
651   s->app_wrk_index = app_wrk->wrk_index;
652   new_si = s->session_index;
653   new_ti = s->thread_index;
654
655   if (app_worker_init_connected (app_wrk, s))
656     {
657       session_free (s);
658       app_worker_connect_notify (app_wrk, 0, opaque);
659       return -1;
660     }
661
662   s = session_get (new_si, new_ti);
663   s->session_state = opened_state;
664   session_lookup_add_connection (tc, session_handle (s));
665
666   if (app_worker_connect_notify (app_wrk, s, opaque))
667     {
668       s = session_get (new_si, new_ti);
669       session_free_w_fifos (s);
670       return -1;
671     }
672
673   return 0;
674 }
675
676 int
677 session_stream_connect_notify (transport_connection_t * tc, u8 is_fail)
678 {
679   return session_stream_connect_notify_inline (tc, is_fail,
680                                                SESSION_STATE_READY);
681 }
682
683 int
684 session_ho_stream_connect_notify (transport_connection_t * tc, u8 is_fail)
685 {
686   return session_stream_connect_notify_inline (tc, is_fail,
687                                                SESSION_STATE_OPENED);
688 }
689
690 typedef struct _session_switch_pool_args
691 {
692   u32 session_index;
693   u32 thread_index;
694   u32 new_thread_index;
695   u32 new_session_index;
696 } session_switch_pool_args_t;
697
698 static void
699 session_switch_pool (void *cb_args)
700 {
701   session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
702   session_t *s;
703   ASSERT (args->thread_index == vlib_get_thread_index ());
704   s = session_get (args->session_index, args->thread_index);
705   s->tx_fifo->master_session_index = args->new_session_index;
706   s->tx_fifo->master_thread_index = args->new_thread_index;
707   transport_cleanup (session_get_transport_proto (s), s->connection_index,
708                      s->thread_index);
709   session_free (s);
710   clib_mem_free (cb_args);
711 }
712
713 /**
714  * Move dgram session to the right thread
715  */
716 int
717 session_dgram_connect_notify (transport_connection_t * tc,
718                               u32 old_thread_index, session_t ** new_session)
719 {
720   session_t *new_s;
721   session_switch_pool_args_t *rpc_args;
722
723   /*
724    * Clone half-open session to the right thread.
725    */
726   new_s = session_clone_safe (tc->s_index, old_thread_index);
727   new_s->connection_index = tc->c_index;
728   new_s->rx_fifo->master_session_index = new_s->session_index;
729   new_s->rx_fifo->master_thread_index = new_s->thread_index;
730   new_s->session_state = SESSION_STATE_READY;
731   session_lookup_add_connection (tc, session_handle (new_s));
732
733   /*
734    * Ask thread owning the old session to clean it up and make us the tx
735    * fifo owner
736    */
737   rpc_args = clib_mem_alloc (sizeof (*rpc_args));
738   rpc_args->new_session_index = new_s->session_index;
739   rpc_args->new_thread_index = new_s->thread_index;
740   rpc_args->session_index = tc->s_index;
741   rpc_args->thread_index = old_thread_index;
742   session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
743                                   rpc_args);
744
745   tc->s_index = new_s->session_index;
746   new_s->connection_index = tc->c_index;
747   *new_session = new_s;
748   return 0;
749 }
750
751 /**
752  * Notification from transport that connection is being closed.
753  *
754  * A disconnect is sent to application but state is not removed. Once
755  * disconnect is acknowledged by application, session disconnect is called.
756  * Ultimately this leads to close being called on transport (passive close).
757  */
758 void
759 session_transport_closing_notify (transport_connection_t * tc)
760 {
761   app_worker_t *app_wrk;
762   session_t *s;
763
764   s = session_get (tc->s_index, tc->thread_index);
765   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
766     return;
767   s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
768   app_wrk = app_worker_get (s->app_wrk_index);
769   app_worker_close_notify (app_wrk, s);
770 }
771
772 /**
773  * Notification from transport that connection is being deleted
774  *
775  * This removes the session if it is still valid. It should be called only on
776  * previously fully established sessions. For instance failed connects should
777  * call stream_session_connect_notify and indicate that the connect has
778  * failed.
779  */
780 void
781 session_transport_delete_notify (transport_connection_t * tc)
782 {
783   session_t *s;
784
785   /* App might've been removed already */
786   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
787     return;
788
789   switch (s->session_state)
790     {
791     case SESSION_STATE_CREATED:
792       /* Session was created but accept notification was not yet sent to the
793        * app. Cleanup everything. */
794       session_lookup_del_session (s);
795       session_free_w_fifos (s);
796       break;
797     case SESSION_STATE_ACCEPTING:
798     case SESSION_STATE_TRANSPORT_CLOSING:
799       /* If transport finishes or times out before we get a reply
800        * from the app, mark transport as closed and wait for reply
801        * before removing the session. Cleanup session table in advance
802        * because transport will soon be closed and closed sessions
803        * are assumed to have been removed from the lookup table */
804       session_lookup_del_session (s);
805       s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
806       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
807       svm_fifo_dequeue_drop_all (s->tx_fifo);
808       break;
809     case SESSION_STATE_CLOSING:
810     case SESSION_STATE_CLOSED_WAITING:
811       /* Cleanup lookup table as transport needs to still be valid.
812        * Program transport close to ensure that all session events
813        * have been cleaned up. Once transport close is called, the
814        * session is just removed because both transport and app have
815        * confirmed the close*/
816       session_lookup_del_session (s);
817       s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
818       session_program_transport_close (s);
819       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
820       svm_fifo_dequeue_drop_all (s->tx_fifo);
821       break;
822     case SESSION_STATE_TRANSPORT_CLOSED:
823       break;
824     case SESSION_STATE_CLOSED:
825       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
826       session_delete (s);
827       break;
828     default:
829       clib_warning ("session state %u", s->session_state);
830       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
831       session_delete (s);
832       break;
833     }
834 }
835
836 /**
837  * Notification from transport that session can be closed
838  *
839  * Should be called by transport only if it was closed with non-empty
840  * tx fifo and once it decides to begin the closing procedure prior to
841  * issuing a delete notify. This gives the chance to the session layer
842  * to cleanup any outstanding events.
843  */
844 void
845 session_transport_closed_notify (transport_connection_t * tc)
846 {
847   session_t *s;
848
849   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
850     return;
851
852   /* Transport thinks that app requested close but it actually didn't.
853    * Can happen for tcp if fin and rst are received in close succession. */
854   if (s->session_state == SESSION_STATE_READY)
855     {
856       session_transport_closing_notify (tc);
857       svm_fifo_dequeue_drop_all (s->tx_fifo);
858     }
859   /* If app close has not been received or has not yet resulted in
860    * a transport close, only mark the session transport as closed */
861   else if (s->session_state <= SESSION_STATE_CLOSING)
862     {
863       session_lookup_del_session (s);
864       s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
865     }
866   else
867     s->session_state = SESSION_STATE_CLOSED;
868 }
869
870 /**
871  * Notify application that connection has been reset.
872  */
873 void
874 session_transport_reset_notify (transport_connection_t * tc)
875 {
876   app_worker_t *app_wrk;
877   session_t *s;
878
879   s = session_get (tc->s_index, tc->thread_index);
880   svm_fifo_dequeue_drop_all (s->tx_fifo);
881   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
882     return;
883   s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
884   app_wrk = app_worker_get (s->app_wrk_index);
885   app_worker_reset_notify (app_wrk, s);
886 }
887
888 int
889 session_stream_accept_notify (transport_connection_t * tc)
890 {
891   app_worker_t *app_wrk;
892   session_t *s;
893
894   s = session_get (tc->s_index, tc->thread_index);
895   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
896   if (!app_wrk)
897     return -1;
898   s->session_state = SESSION_STATE_ACCEPTING;
899   return app_worker_accept_notify (app_wrk, s);
900 }
901
902 /**
903  * Accept a stream session. Optionally ping the server by callback.
904  */
905 int
906 session_stream_accept (transport_connection_t * tc, u32 listener_index,
907                        u32 thread_index, u8 notify)
908 {
909   session_t *s;
910   int rv;
911
912   s = session_alloc_for_connection (tc);
913   s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
914   s->session_state = SESSION_STATE_CREATED;
915
916   if ((rv = app_worker_init_accepted (s)))
917     return rv;
918
919   session_lookup_add_connection (tc, session_handle (s));
920
921   /* Shoulder-tap the server */
922   if (notify)
923     {
924       app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
925       return app_worker_accept_notify (app_wrk, s);
926     }
927
928   return 0;
929 }
930
931 int
932 session_open_cl (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
933 {
934   transport_connection_t *tc;
935   transport_endpoint_cfg_t *tep;
936   app_worker_t *app_wrk;
937   session_handle_t sh;
938   session_t *s;
939   int rv;
940
941   tep = session_endpoint_to_transport_cfg (rmt);
942   rv = transport_connect (rmt->transport_proto, tep);
943   if (rv < 0)
944     {
945       SESSION_DBG ("Transport failed to open connection.");
946       return VNET_API_ERROR_SESSION_CONNECT;
947     }
948
949   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
950
951   /* For dgram type of service, allocate session and fifos now */
952   app_wrk = app_worker_get (app_wrk_index);
953   s = session_alloc_for_connection (tc);
954   s->app_wrk_index = app_wrk->wrk_index;
955   s->session_state = SESSION_STATE_OPENED;
956   if (app_worker_init_connected (app_wrk, s))
957     {
958       session_free (s);
959       return -1;
960     }
961
962   sh = session_handle (s);
963   session_lookup_add_connection (tc, sh);
964   return app_worker_connect_notify (app_wrk, s, opaque);
965 }
966
967 int
968 session_open_vc (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
969 {
970   transport_connection_t *tc;
971   transport_endpoint_cfg_t *tep;
972   u64 handle;
973   int rv;
974
975   tep = session_endpoint_to_transport_cfg (rmt);
976   rv = transport_connect (rmt->transport_proto, tep);
977   if (rv < 0)
978     {
979       SESSION_DBG ("Transport failed to open connection.");
980       return VNET_API_ERROR_SESSION_CONNECT;
981     }
982
983   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
984
985   /* If transport offers a stream service, only allocate session once the
986    * connection has been established.
987    * Add connection to half-open table and save app and tc index. The
988    * latter is needed to help establish the connection while the former
989    * is needed when the connect notify comes and we have to notify the
990    * external app
991    */
992   handle = (((u64) app_wrk_index) << 32) | (u64) tc->c_index;
993   session_lookup_add_half_open (tc, handle);
994
995   /* Store api_context (opaque) for when the reply comes. Not the nicest
996    * thing but better than allocating a separate half-open pool.
997    */
998   tc->s_index = opaque;
999   if (transport_half_open_has_fifos (rmt->transport_proto))
1000     return session_ho_stream_connect_notify (tc, 0 /* is_fail */ );
1001   return 0;
1002 }
1003
1004 int
1005 session_open_app (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1006 {
1007   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) rmt;
1008   transport_endpoint_cfg_t *tep_cfg = session_endpoint_to_transport_cfg (sep);
1009
1010   sep->app_wrk_index = app_wrk_index;
1011   sep->opaque = opaque;
1012
1013   return transport_connect (rmt->transport_proto, tep_cfg);
1014 }
1015
1016 typedef int (*session_open_service_fn) (u32, session_endpoint_t *, u32);
1017
1018 /* *INDENT-OFF* */
1019 static session_open_service_fn session_open_srv_fns[TRANSPORT_N_SERVICES] = {
1020   session_open_vc,
1021   session_open_cl,
1022   session_open_app,
1023 };
1024 /* *INDENT-ON* */
1025
1026 /**
1027  * Ask transport to open connection to remote transport endpoint.
1028  *
1029  * Stores handle for matching request with reply since the call can be
1030  * asynchronous. For instance, for TCP the 3-way handshake must complete
1031  * before reply comes. Session is only created once connection is established.
1032  *
1033  * @param app_index Index of the application requesting the connect
1034  * @param st Session type requested.
1035  * @param tep Remote transport endpoint
1036  * @param opaque Opaque data (typically, api_context) the application expects
1037  *               on open completion.
1038  */
1039 int
1040 session_open (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1041 {
1042   transport_service_type_t tst;
1043   tst = transport_protocol_service_type (rmt->transport_proto);
1044   return session_open_srv_fns[tst] (app_wrk_index, rmt, opaque);
1045 }
1046
1047 /**
1048  * Ask transport to listen on session endpoint.
1049  *
1050  * @param s Session for which listen will be called. Note that unlike
1051  *          established sessions, listen sessions are not associated to a
1052  *          thread.
1053  * @param sep Local endpoint to be listened on.
1054  */
1055 int
1056 session_listen (session_t * ls, session_endpoint_cfg_t * sep)
1057 {
1058   transport_endpoint_t *tep;
1059   u32 tc_index, s_index;
1060
1061   /* Transport bind/listen */
1062   tep = session_endpoint_to_transport (sep);
1063   s_index = ls->session_index;
1064   tc_index = transport_start_listen (session_get_transport_proto (ls),
1065                                      s_index, tep);
1066
1067   if (tc_index == (u32) ~ 0)
1068     return -1;
1069
1070   /* Attach transport to session. Lookup tables are populated by the app
1071    * worker because local tables (for ct sessions) are not backed by a fib */
1072   ls = listen_session_get (s_index);
1073   ls->connection_index = tc_index;
1074
1075   return 0;
1076 }
1077
1078 /**
1079  * Ask transport to stop listening on local transport endpoint.
1080  *
1081  * @param s Session to stop listening on. It must be in state LISTENING.
1082  */
1083 int
1084 session_stop_listen (session_t * s)
1085 {
1086   transport_proto_t tp = session_get_transport_proto (s);
1087   transport_connection_t *tc;
1088
1089   if (s->session_state != SESSION_STATE_LISTENING)
1090     return -1;
1091
1092   tc = transport_get_listener (tp, s->connection_index);
1093   if (!tc)
1094     return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
1095
1096   if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
1097     session_lookup_del_connection (tc);
1098   transport_stop_listen (tp, s->connection_index);
1099   return 0;
1100 }
1101
1102 /**
1103  * Initialize session closing procedure.
1104  *
1105  * Request is always sent to session node to ensure that all outstanding
1106  * requests are served before transport is notified.
1107  */
1108 void
1109 session_close (session_t * s)
1110 {
1111   if (!s)
1112     return;
1113
1114   if (s->session_state >= SESSION_STATE_CLOSING)
1115     {
1116       /* Session will only be removed once both app and transport
1117        * acknowledge the close */
1118       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1119         session_program_transport_close (s);
1120
1121       /* Session already closed. Clear the tx fifo */
1122       if (s->session_state == SESSION_STATE_CLOSED)
1123         svm_fifo_dequeue_drop_all (s->tx_fifo);
1124       return;
1125     }
1126
1127   s->session_state = SESSION_STATE_CLOSING;
1128   session_program_transport_close (s);
1129 }
1130
1131 /**
1132  * Notify transport the session can be disconnected. This should eventually
1133  * result in a delete notification that allows us to cleanup session state.
1134  * Called for both active/passive disconnects.
1135  *
1136  * Must be called from the session's thread.
1137  */
1138 void
1139 session_transport_close (session_t * s)
1140 {
1141   /* If transport is already closed, just free the session */
1142   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSED)
1143     {
1144       session_free_w_fifos (s);
1145       return;
1146     }
1147
1148   /* If tx queue wasn't drained, change state to closed waiting for transport.
1149    * This way, the transport, if it so wishes, can continue to try sending the
1150    * outstanding data (in closed state it cannot). It MUST however at one
1151    * point, either after sending everything or after a timeout, call delete
1152    * notify. This will finally lead to the complete cleanup of the session.
1153    */
1154   if (svm_fifo_max_dequeue_cons (s->tx_fifo))
1155     s->session_state = SESSION_STATE_CLOSED_WAITING;
1156   else
1157     s->session_state = SESSION_STATE_CLOSED;
1158
1159   transport_close (session_get_transport_proto (s), s->connection_index,
1160                    s->thread_index);
1161 }
1162
1163 /**
1164  * Cleanup transport and session state.
1165  *
1166  * Notify transport of the cleanup and free the session. This should
1167  * be called only if transport reported some error and is already
1168  * closed.
1169  */
1170 void
1171 session_transport_cleanup (session_t * s)
1172 {
1173   s->session_state = SESSION_STATE_CLOSED;
1174
1175   /* Delete from main lookup table before we axe the the transport */
1176   session_lookup_del_session (s);
1177   transport_cleanup (session_get_transport_proto (s), s->connection_index,
1178                      s->thread_index);
1179   /* Since we called cleanup, no delete notification will come. So, make
1180    * sure the session is properly freed. */
1181   session_free_w_fifos (s);
1182 }
1183
1184 /**
1185  * Allocate event queues in the shared-memory segment
1186  *
1187  * That can either be a newly created memfd segment, that will need to be
1188  * mapped by all stack users, or the binary api's svm region. The latter is
1189  * assumed to be already mapped. NOTE that this assumption DOES NOT hold if
1190  * api clients bootstrap shm api over sockets (i.e. use memfd segments) and
1191  * vpp uses api svm region for event queues.
1192  */
1193 void
1194 session_vpp_event_queues_allocate (session_main_t * smm)
1195 {
1196   u32 evt_q_length = 2048, evt_size = sizeof (session_event_t);
1197   ssvm_private_t *eqs = &smm->evt_qs_segment;
1198   api_main_t *am = &api_main;
1199   uword eqs_size = 64 << 20;
1200   pid_t vpp_pid = getpid ();
1201   void *oldheap;
1202   int i;
1203
1204   if (smm->configured_event_queue_length)
1205     evt_q_length = smm->configured_event_queue_length;
1206
1207   if (smm->evt_qs_use_memfd_seg)
1208     {
1209       if (smm->evt_qs_segment_size)
1210         eqs_size = smm->evt_qs_segment_size;
1211
1212       eqs->ssvm_size = eqs_size;
1213       eqs->i_am_master = 1;
1214       eqs->my_pid = vpp_pid;
1215       eqs->name = format (0, "%s%c", "evt-qs-segment", 0);
1216       eqs->requested_va = smm->session_baseva;
1217
1218       if (ssvm_master_init (eqs, SSVM_SEGMENT_MEMFD))
1219         {
1220           clib_warning ("failed to initialize queue segment");
1221           return;
1222         }
1223     }
1224
1225   if (smm->evt_qs_use_memfd_seg)
1226     oldheap = ssvm_push_heap (eqs->sh);
1227   else
1228     oldheap = svm_push_data_heap (am->vlib_rp);
1229
1230   for (i = 0; i < vec_len (smm->wrk); i++)
1231     {
1232       svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1233       svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
1234         {evt_q_length, evt_size, 0}
1235         ,
1236         {evt_q_length >> 1, 256, 0}
1237       };
1238       cfg->consumer_pid = 0;
1239       cfg->n_rings = 2;
1240       cfg->q_nitems = evt_q_length;
1241       cfg->ring_cfgs = rc;
1242       smm->wrk[i].vpp_event_queue = svm_msg_q_alloc (cfg);
1243       if (smm->evt_qs_use_memfd_seg)
1244         {
1245           if (svm_msg_q_alloc_consumer_eventfd (smm->wrk[i].vpp_event_queue))
1246             clib_warning ("eventfd returned");
1247         }
1248     }
1249
1250   if (smm->evt_qs_use_memfd_seg)
1251     ssvm_pop_heap (oldheap);
1252   else
1253     svm_pop_heap (oldheap);
1254 }
1255
1256 ssvm_private_t *
1257 session_main_get_evt_q_segment (void)
1258 {
1259   session_main_t *smm = &session_main;
1260   if (smm->evt_qs_use_memfd_seg)
1261     return &smm->evt_qs_segment;
1262   return 0;
1263 }
1264
1265 u64
1266 session_segment_handle (session_t * s)
1267 {
1268   svm_fifo_t *f;
1269
1270   if (!s->rx_fifo)
1271     return SESSION_INVALID_HANDLE;
1272
1273   f = s->rx_fifo;
1274   return segment_manager_make_segment_handle (f->segment_manager,
1275                                               f->segment_index);
1276 }
1277
1278 /* *INDENT-OFF* */
1279 static session_fifo_rx_fn *session_tx_fns[TRANSPORT_TX_N_FNS] = {
1280     session_tx_fifo_peek_and_snd,
1281     session_tx_fifo_dequeue_and_snd,
1282     session_tx_fifo_dequeue_internal,
1283     session_tx_fifo_dequeue_and_snd
1284 };
1285 /* *INDENT-ON* */
1286
1287 /**
1288  * Initialize session layer for given transport proto and ip version
1289  *
1290  * Allocates per session type (transport proto + ip version) data structures
1291  * and adds arc from session queue node to session type output node.
1292  */
1293 void
1294 session_register_transport (transport_proto_t transport_proto,
1295                             const transport_proto_vft_t * vft, u8 is_ip4,
1296                             u32 output_node)
1297 {
1298   session_main_t *smm = &session_main;
1299   session_type_t session_type;
1300   u32 next_index = ~0;
1301
1302   session_type = session_type_from_proto_and_ip (transport_proto, is_ip4);
1303
1304   vec_validate (smm->session_type_to_next, session_type);
1305   vec_validate (smm->session_tx_fns, session_type);
1306
1307   /* *INDENT-OFF* */
1308   if (output_node != ~0)
1309     {
1310       foreach_vlib_main (({
1311           next_index = vlib_node_add_next (this_vlib_main,
1312                                            session_queue_node.index,
1313                                            output_node);
1314       }));
1315     }
1316   /* *INDENT-ON* */
1317
1318   smm->session_type_to_next[session_type] = next_index;
1319   smm->session_tx_fns[session_type] =
1320     session_tx_fns[vft->transport_options.tx_type];
1321 }
1322
1323 transport_connection_t *
1324 session_get_transport (session_t * s)
1325 {
1326   if (s->session_state != SESSION_STATE_LISTENING)
1327     return transport_get_connection (session_get_transport_proto (s),
1328                                      s->connection_index, s->thread_index);
1329   else
1330     return transport_get_listener (session_get_transport_proto (s),
1331                                    s->connection_index);
1332 }
1333
1334 void
1335 session_get_endpoint (session_t * s, transport_endpoint_t * tep, u8 is_lcl)
1336 {
1337   if (s->session_state != SESSION_STATE_LISTENING)
1338     return transport_get_endpoint (session_get_transport_proto (s),
1339                                    s->connection_index, s->thread_index, tep,
1340                                    is_lcl);
1341   else
1342     return transport_get_listener_endpoint (session_get_transport_proto (s),
1343                                             s->connection_index, tep, is_lcl);
1344 }
1345
1346 transport_connection_t *
1347 listen_session_get_transport (session_t * s)
1348 {
1349   return transport_get_listener (session_get_transport_proto (s),
1350                                  s->connection_index);
1351 }
1352
1353 void
1354 session_flush_frames_main_thread (vlib_main_t * vm)
1355 {
1356   ASSERT (vlib_get_thread_index () == 0);
1357   vlib_process_signal_event_mt (vm, session_queue_process_node.index,
1358                                 SESSION_Q_PROCESS_FLUSH_FRAMES, 0);
1359 }
1360
1361 static clib_error_t *
1362 session_manager_main_enable (vlib_main_t * vm)
1363 {
1364   segment_manager_main_init_args_t _sm_args = { 0 }, *sm_args = &_sm_args;
1365   session_main_t *smm = &session_main;
1366   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1367   u32 num_threads, preallocated_sessions_per_worker;
1368   session_worker_t *wrk;
1369   int i;
1370
1371   num_threads = 1 /* main thread */  + vtm->n_threads;
1372
1373   if (num_threads < 1)
1374     return clib_error_return (0, "n_thread_stacks not set");
1375
1376   /* Allocate cache line aligned worker contexts */
1377   vec_validate_aligned (smm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1378
1379   for (i = 0; i < num_threads; i++)
1380     {
1381       wrk = &smm->wrk[i];
1382       vec_validate (wrk->free_event_vector, 128);
1383       _vec_len (wrk->free_event_vector) = 0;
1384       vec_validate (wrk->pending_event_vector, 128);
1385       _vec_len (wrk->pending_event_vector) = 0;
1386       vec_validate (wrk->pending_disconnects, 128);
1387       _vec_len (wrk->pending_disconnects) = 0;
1388       vec_validate (wrk->postponed_event_vector, 128);
1389       _vec_len (wrk->postponed_event_vector) = 0;
1390
1391       wrk->last_vlib_time = vlib_time_now (vlib_mains[i]);
1392       wrk->dispatch_period = 500e-6;
1393
1394       if (num_threads > 1)
1395         clib_rwlock_init (&smm->wrk[i].peekers_rw_locks);
1396     }
1397
1398 #if SESSION_DEBUG
1399   vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
1400 #endif
1401
1402   /* Allocate vpp event queues segment and queue */
1403   session_vpp_event_queues_allocate (smm);
1404
1405   /* Initialize fifo segment main baseva and timeout */
1406   sm_args->baseva = smm->session_baseva + smm->evt_qs_segment_size;
1407   sm_args->size = smm->session_va_space_size;
1408   segment_manager_main_init (sm_args);
1409
1410   /* Preallocate sessions */
1411   if (smm->preallocated_sessions)
1412     {
1413       if (num_threads == 1)
1414         {
1415           pool_init_fixed (smm->wrk[0].sessions, smm->preallocated_sessions);
1416         }
1417       else
1418         {
1419           int j;
1420           preallocated_sessions_per_worker =
1421             (1.1 * (f64) smm->preallocated_sessions /
1422              (f64) (num_threads - 1));
1423
1424           for (j = 1; j < num_threads; j++)
1425             {
1426               pool_init_fixed (smm->wrk[j].sessions,
1427                                preallocated_sessions_per_worker);
1428             }
1429         }
1430     }
1431
1432   session_lookup_init ();
1433   app_namespaces_init ();
1434   transport_init ();
1435
1436   smm->is_enabled = 1;
1437
1438   /* Enable transports */
1439   transport_enable_disable (vm, 1);
1440   transport_init_tx_pacers_period ();
1441   return 0;
1442 }
1443
1444 void
1445 session_node_enable_disable (u8 is_en)
1446 {
1447   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1448   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1449   u8 have_workers = vtm->n_threads != 0;
1450
1451   /* *INDENT-OFF* */
1452   foreach_vlib_main (({
1453     if (have_workers && ii == 0)
1454       {
1455         vlib_node_set_state (this_vlib_main, session_queue_process_node.index,
1456                              state);
1457         if (is_en)
1458           {
1459             vlib_node_t *n = vlib_get_node (this_vlib_main,
1460                                             session_queue_process_node.index);
1461             vlib_start_process (this_vlib_main, n->runtime_index);
1462           }
1463         else
1464           {
1465             vlib_process_signal_event_mt (this_vlib_main,
1466                                           session_queue_process_node.index,
1467                                           SESSION_Q_PROCESS_STOP, 0);
1468           }
1469
1470         continue;
1471       }
1472     vlib_node_set_state (this_vlib_main, session_queue_node.index,
1473                          state);
1474   }));
1475   /* *INDENT-ON* */
1476 }
1477
1478 clib_error_t *
1479 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1480 {
1481   clib_error_t *error = 0;
1482   if (is_en)
1483     {
1484       if (session_main.is_enabled)
1485         return 0;
1486
1487       session_node_enable_disable (is_en);
1488       error = session_manager_main_enable (vm);
1489     }
1490   else
1491     {
1492       session_main.is_enabled = 0;
1493       session_node_enable_disable (is_en);
1494     }
1495
1496   return error;
1497 }
1498
1499 clib_error_t *
1500 session_manager_main_init (vlib_main_t * vm)
1501 {
1502   session_main_t *smm = &session_main;
1503   smm->session_baseva = HIGH_SEGMENT_BASEVA;
1504 #if (HIGH_SEGMENT_BASEVA > (4ULL << 30))
1505   smm->session_va_space_size = 128ULL << 30;
1506   smm->evt_qs_segment_size = 64 << 20;
1507 #else
1508   smm->session_va_space_size = 128 << 20;
1509   smm->evt_qs_segment_size = 1 << 20;
1510 #endif
1511   smm->is_enabled = 0;
1512   return 0;
1513 }
1514
1515 VLIB_INIT_FUNCTION (session_manager_main_init);
1516
1517 static clib_error_t *
1518 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1519 {
1520   session_main_t *smm = &session_main;
1521   u32 nitems;
1522   uword tmp;
1523
1524   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1525     {
1526       if (unformat (input, "event-queue-length %d", &nitems))
1527         {
1528           if (nitems >= 2048)
1529             smm->configured_event_queue_length = nitems;
1530           else
1531             clib_warning ("event queue length %d too small, ignored", nitems);
1532         }
1533       else if (unformat (input, "preallocated-sessions %d",
1534                          &smm->preallocated_sessions))
1535         ;
1536       else if (unformat (input, "v4-session-table-buckets %d",
1537                          &smm->configured_v4_session_table_buckets))
1538         ;
1539       else if (unformat (input, "v4-halfopen-table-buckets %d",
1540                          &smm->configured_v4_halfopen_table_buckets))
1541         ;
1542       else if (unformat (input, "v6-session-table-buckets %d",
1543                          &smm->configured_v6_session_table_buckets))
1544         ;
1545       else if (unformat (input, "v6-halfopen-table-buckets %d",
1546                          &smm->configured_v6_halfopen_table_buckets))
1547         ;
1548       else if (unformat (input, "v4-session-table-memory %U",
1549                          unformat_memory_size, &tmp))
1550         {
1551           if (tmp >= 0x100000000)
1552             return clib_error_return (0, "memory size %llx (%lld) too large",
1553                                       tmp, tmp);
1554           smm->configured_v4_session_table_memory = tmp;
1555         }
1556       else if (unformat (input, "v4-halfopen-table-memory %U",
1557                          unformat_memory_size, &tmp))
1558         {
1559           if (tmp >= 0x100000000)
1560             return clib_error_return (0, "memory size %llx (%lld) too large",
1561                                       tmp, tmp);
1562           smm->configured_v4_halfopen_table_memory = tmp;
1563         }
1564       else if (unformat (input, "v6-session-table-memory %U",
1565                          unformat_memory_size, &tmp))
1566         {
1567           if (tmp >= 0x100000000)
1568             return clib_error_return (0, "memory size %llx (%lld) too large",
1569                                       tmp, tmp);
1570           smm->configured_v6_session_table_memory = tmp;
1571         }
1572       else if (unformat (input, "v6-halfopen-table-memory %U",
1573                          unformat_memory_size, &tmp))
1574         {
1575           if (tmp >= 0x100000000)
1576             return clib_error_return (0, "memory size %llx (%lld) too large",
1577                                       tmp, tmp);
1578           smm->configured_v6_halfopen_table_memory = tmp;
1579         }
1580       else if (unformat (input, "local-endpoints-table-memory %U",
1581                          unformat_memory_size, &tmp))
1582         {
1583           if (tmp >= 0x100000000)
1584             return clib_error_return (0, "memory size %llx (%lld) too large",
1585                                       tmp, tmp);
1586           smm->local_endpoints_table_memory = tmp;
1587         }
1588       else if (unformat (input, "local-endpoints-table-buckets %d",
1589                          &smm->local_endpoints_table_buckets))
1590         ;
1591       else if (unformat (input, "evt_qs_memfd_seg"))
1592         smm->evt_qs_use_memfd_seg = 1;
1593       else if (unformat (input, "evt_qs_seg_size %U", unformat_memory_size,
1594                          &smm->evt_qs_segment_size))
1595         ;
1596       else
1597         return clib_error_return (0, "unknown input `%U'",
1598                                   format_unformat_error, input);
1599     }
1600   return 0;
1601 }
1602
1603 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1604
1605 /*
1606  * fd.io coding-style-patch-verification: ON
1607  *
1608  * Local Variables:
1609  * eval: (c-set-style "gnu")
1610  * End:
1611  */