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