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