3a3e4dfe58813004f84bbd3101a8885fb129f269
[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 #include <vnet/tcp/tcp.h>
27
28 session_manager_main_t session_manager_main;
29 extern transport_proto_vft_t *tp_vfts;
30
31 int
32 stream_session_create_i (segment_manager_t * sm, transport_connection_t * tc,
33                          u8 alloc_fifos, stream_session_t ** ret_s)
34 {
35   session_manager_main_t *smm = &session_manager_main;
36   svm_fifo_t *server_rx_fifo = 0, *server_tx_fifo = 0;
37   u32 fifo_segment_index;
38   u32 pool_index;
39   stream_session_t *s;
40   u64 value;
41   u32 thread_index = tc->thread_index;
42   int rv;
43
44   ASSERT (thread_index == vlib_get_thread_index ());
45
46   /* Create the session */
47   pool_get_aligned (smm->sessions[thread_index], s, CLIB_CACHE_LINE_BYTES);
48   memset (s, 0, sizeof (*s));
49   pool_index = s - smm->sessions[thread_index];
50
51   /* Allocate fifos */
52   if (alloc_fifos)
53     {
54       if ((rv = segment_manager_alloc_session_fifos (sm, &server_rx_fifo,
55                                                      &server_tx_fifo,
56                                                      &fifo_segment_index)))
57         {
58           pool_put (smm->sessions[thread_index], s);
59           return rv;
60         }
61       /* Initialize backpointers */
62       server_rx_fifo->master_session_index = pool_index;
63       server_rx_fifo->master_thread_index = thread_index;
64
65       server_tx_fifo->master_session_index = pool_index;
66       server_tx_fifo->master_thread_index = thread_index;
67
68       s->server_rx_fifo = server_rx_fifo;
69       s->server_tx_fifo = server_tx_fifo;
70       s->svm_segment_index = fifo_segment_index;
71     }
72
73   /* Initialize state machine, such as it is... */
74   s->session_type = session_type_from_proto_and_ip (tc->transport_proto,
75                                                     tc->is_ip4);
76   s->session_state = SESSION_STATE_CONNECTING;
77   s->thread_index = thread_index;
78   s->session_index = pool_index;
79
80   /* Attach transport to session */
81   s->connection_index = tc->c_index;
82
83   /* Attach session to transport */
84   tc->s_index = s->session_index;
85
86   /* Add to the main lookup table */
87   value = stream_session_handle (s);
88   stream_session_table_add_for_tc (tc, value);
89
90   *ret_s = s;
91
92   return 0;
93 }
94
95 /** Enqueue buffer chain tail */
96 always_inline int
97 session_enqueue_chain_tail (stream_session_t * s, vlib_buffer_t * b,
98                             u32 offset, u8 is_in_order)
99 {
100   vlib_buffer_t *chain_b;
101   u32 chain_bi = b->next_buffer, len;
102   vlib_main_t *vm = vlib_get_main ();
103   u8 *data;
104   u16 written = 0;
105   int rv = 0;
106
107   do
108     {
109       chain_b = vlib_get_buffer (vm, chain_bi);
110       data = vlib_buffer_get_current (chain_b);
111       len = chain_b->current_length;
112       if (is_in_order)
113         {
114           rv = svm_fifo_enqueue_nowait (s->server_rx_fifo, len, data);
115           if (rv < len)
116             {
117               return (rv > 0) ? (written + rv) : written;
118             }
119           written += rv;
120         }
121       else
122         {
123           rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset, len,
124                                              data);
125           if (rv)
126             return -1;
127           offset += len;
128         }
129     }
130   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
131           ? chain_b->next_buffer : 0));
132
133   if (is_in_order)
134     return written;
135
136   return 0;
137 }
138
139 /*
140  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
141  * event but on request can queue notification events for later delivery by
142  * calling stream_server_flush_enqueue_events().
143  *
144  * @param tc Transport connection which is to be enqueued data
145  * @param b Buffer to be enqueued
146  * @param offset Offset at which to start enqueueing if out-of-order
147  * @param queue_event Flag to indicate if peer is to be notified or if event
148  *                    is to be queued. The former is useful when more data is
149  *                    enqueued and only one event is to be generated.
150  * @param is_in_order Flag to indicate if data is in order
151  * @return Number of bytes enqueued or a negative value if enqueueing failed.
152  */
153 int
154 stream_session_enqueue_data (transport_connection_t * tc, vlib_buffer_t * b,
155                              u32 offset, u8 queue_event, u8 is_in_order)
156 {
157   stream_session_t *s;
158   int enqueued = 0, rv;
159
160   s = stream_session_get (tc->s_index, tc->thread_index);
161
162   if (is_in_order)
163     {
164       enqueued =
165         svm_fifo_enqueue_nowait (s->server_rx_fifo, b->current_length,
166                                  vlib_buffer_get_current (b));
167       if (PREDICT_FALSE
168           ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued > 0))
169         {
170           rv = session_enqueue_chain_tail (s, b, 0, 1);
171           if (rv <= 0)
172             return enqueued;
173           enqueued += rv;
174         }
175     }
176   else
177     {
178       rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset,
179                                          b->current_length,
180                                          vlib_buffer_get_current (b));
181       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
182         rv = session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
183       if (rv)
184         return -1;
185     }
186
187   if (queue_event)
188     {
189       /* Queue RX event on this fifo. Eventually these will need to be flushed
190        * by calling stream_server_flush_enqueue_events () */
191       session_manager_main_t *smm = vnet_get_session_manager_main ();
192       u32 thread_index = s->thread_index;
193       u32 my_enqueue_epoch = smm->current_enqueue_epoch[thread_index];
194
195       if (s->enqueue_epoch != my_enqueue_epoch)
196         {
197           s->enqueue_epoch = my_enqueue_epoch;
198           vec_add1 (smm->session_indices_to_enqueue_by_thread[thread_index],
199                     s - smm->sessions[thread_index]);
200         }
201     }
202
203   if (is_in_order)
204     return enqueued;
205
206   return 0;
207 }
208
209 /** Check if we have space in rx fifo to push more bytes */
210 u8
211 stream_session_no_space (transport_connection_t * tc, u32 thread_index,
212                          u16 data_len)
213 {
214   stream_session_t *s = stream_session_get (tc->s_index, thread_index);
215
216   if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY))
217     return 1;
218
219   if (data_len > svm_fifo_max_enqueue (s->server_rx_fifo))
220     return 1;
221
222   return 0;
223 }
224
225 u32
226 stream_session_tx_fifo_max_dequeue (transport_connection_t * tc)
227 {
228   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
229   if (!s->server_tx_fifo)
230     return 0;
231   return svm_fifo_max_dequeue (s->server_tx_fifo);
232 }
233
234 int
235 stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
236                            u32 offset, u32 max_bytes)
237 {
238   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
239   return svm_fifo_peek (s->server_tx_fifo, offset, max_bytes, buffer);
240 }
241
242 u32
243 stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
244 {
245   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
246   return svm_fifo_dequeue_drop (s->server_tx_fifo, max_bytes);
247 }
248
249 /**
250  * Notify session peer that new data has been enqueued.
251  *
252  * @param s Stream session for which the event is to be generated.
253  * @param block Flag to indicate if call should block if event queue is full.
254  *
255  * @return 0 on succes or negative number if failed to send notification.
256  */
257 static int
258 stream_session_enqueue_notify (stream_session_t * s, u8 block)
259 {
260   application_t *app;
261   session_fifo_event_t evt;
262   unix_shared_memory_queue_t *q;
263   static u32 serial_number;
264
265   if (PREDICT_FALSE (s->session_state == SESSION_STATE_CLOSED))
266     return 0;
267
268   /* Get session's server */
269   app = application_get_if_valid (s->app_index);
270
271   if (PREDICT_FALSE (app == 0))
272     {
273       clib_warning ("invalid s->app_index = %d", s->app_index);
274       return 0;
275     }
276
277   /* Built-in server? Hand event to the callback... */
278   if (app->cb_fns.builtin_server_rx_callback)
279     return app->cb_fns.builtin_server_rx_callback (s);
280
281   /* If no event, send one */
282   if (svm_fifo_set_event (s->server_rx_fifo))
283     {
284       /* Fabricate event */
285       evt.fifo = s->server_rx_fifo;
286       evt.event_type = FIFO_EVENT_APP_RX;
287       evt.event_id = serial_number++;
288
289       /* Add event to server's event queue */
290       q = app->event_queue;
291
292       /* Based on request block (or not) for lack of space */
293       if (block || PREDICT_TRUE (q->cursize < q->maxsize))
294         unix_shared_memory_queue_add (app->event_queue, (u8 *) & evt,
295                                       0 /* do wait for mutex */ );
296       else
297         {
298           clib_warning ("fifo full");
299           return -1;
300         }
301     }
302
303   /* *INDENT-OFF* */
304   SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
305       ed->data[0] = evt.event_id;
306       ed->data[1] = svm_fifo_max_dequeue (s->server_rx_fifo);
307   }));
308   /* *INDENT-ON* */
309
310   return 0;
311 }
312
313 /**
314  * Flushes queue of sessions that are to be notified of new data
315  * enqueued events.
316  *
317  * @param thread_index Thread index for which the flush is to be performed.
318  * @return 0 on success or a positive number indicating the number of
319  *         failures due to API queue being full.
320  */
321 int
322 session_manager_flush_enqueue_events (u32 thread_index)
323 {
324   session_manager_main_t *smm = &session_manager_main;
325   u32 *session_indices_to_enqueue;
326   int i, errors = 0;
327
328   session_indices_to_enqueue =
329     smm->session_indices_to_enqueue_by_thread[thread_index];
330
331   for (i = 0; i < vec_len (session_indices_to_enqueue); i++)
332     {
333       stream_session_t *s0;
334
335       /* Get session */
336       s0 = stream_session_get_if_valid (session_indices_to_enqueue[i],
337                                         thread_index);
338       if (s0 == 0 || stream_session_enqueue_notify (s0, 0 /* don't block */ ))
339         {
340           errors++;
341         }
342     }
343
344   vec_reset_length (session_indices_to_enqueue);
345
346   smm->session_indices_to_enqueue_by_thread[thread_index] =
347     session_indices_to_enqueue;
348
349   /* Increment enqueue epoch for next round */
350   smm->current_enqueue_epoch[thread_index]++;
351
352   return errors;
353 }
354
355 /**
356  * Init fifo tail and head pointers
357  *
358  * Useful if transport uses absolute offsets for tracking ooo segments.
359  */
360 void
361 stream_session_init_fifos_pointers (transport_connection_t * tc,
362                                     u32 rx_pointer, u32 tx_pointer)
363 {
364   stream_session_t *s;
365   s = stream_session_get (tc->s_index, tc->thread_index);
366   svm_fifo_init_pointers (s->server_rx_fifo, rx_pointer);
367   svm_fifo_init_pointers (s->server_tx_fifo, tx_pointer);
368 }
369
370 int
371 stream_session_connect_notify (transport_connection_t * tc, u8 is_fail)
372 {
373   application_t *app;
374   stream_session_t *new_s = 0;
375   u64 handle;
376   u32 api_context = 0;
377   int error = 0;
378
379   handle = stream_session_half_open_lookup_handle (&tc->lcl_ip, &tc->rmt_ip,
380                                                    tc->lcl_port, tc->rmt_port,
381                                                    tc->transport_proto);
382   if (handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
383     {
384       clib_warning ("This can't be good!");
385       return -1;
386     }
387
388   /* Get the app's index from the handle we stored when opening connection */
389   app = application_get (handle >> 32);
390   api_context = tc->s_index;
391
392   if (!is_fail)
393     {
394       segment_manager_t *sm;
395       u8 alloc_fifos;
396       sm = application_get_connect_segment_manager (app);
397       alloc_fifos = application_is_proxy (app);
398       /* Create new session (svm segments are allocated if needed) */
399       if (stream_session_create_i (sm, tc, alloc_fifos, &new_s))
400         {
401           is_fail = 1;
402           error = -1;
403         }
404       else
405         new_s->app_index = app->index;
406     }
407
408   /* Notify client application */
409   if (app->cb_fns.session_connected_callback (app->index, api_context, new_s,
410                                               is_fail))
411     {
412       clib_warning ("failed to notify app");
413       if (!is_fail)
414         stream_session_disconnect (new_s);
415     }
416   else
417     {
418       if (!is_fail)
419         new_s->session_state = SESSION_STATE_READY;
420     }
421
422   /* Cleanup session lookup */
423   stream_session_half_open_table_del (tc);
424
425   return error;
426 }
427
428 void
429 stream_session_accept_notify (transport_connection_t * tc)
430 {
431   application_t *server;
432   stream_session_t *s;
433
434   s = stream_session_get (tc->s_index, tc->thread_index);
435   server = application_get (s->app_index);
436   server->cb_fns.session_accept_callback (s);
437 }
438
439 /**
440  * Notification from transport that connection is being closed.
441  *
442  * A disconnect is sent to application but state is not removed. Once
443  * disconnect is acknowledged by application, session disconnect is called.
444  * Ultimately this leads to close being called on transport (passive close).
445  */
446 void
447 stream_session_disconnect_notify (transport_connection_t * tc)
448 {
449   application_t *server;
450   stream_session_t *s;
451
452   s = stream_session_get (tc->s_index, tc->thread_index);
453   server = application_get (s->app_index);
454   server->cb_fns.session_disconnect_callback (s);
455 }
456
457 /**
458  * Cleans up session and associated app if needed.
459  */
460 void
461 stream_session_delete (stream_session_t * s)
462 {
463   session_manager_main_t *smm = vnet_get_session_manager_main ();
464   int rv;
465
466   /* Delete from the main lookup table. */
467   if ((rv = stream_session_table_del (s)))
468     clib_warning ("hash delete error, rv %d", rv);
469
470   /* Cleanup fifo segments */
471   segment_manager_dealloc_fifos (s->svm_segment_index, s->server_rx_fifo,
472                                  s->server_tx_fifo);
473
474   pool_put (smm->sessions[s->thread_index], s);
475   if (CLIB_DEBUG)
476     memset (s, 0xFA, sizeof (*s));
477 }
478
479 /**
480  * Notification from transport that connection is being deleted
481  *
482  * This should be called only on previously fully established sessions. For
483  * instance failed connects should call stream_session_connect_notify and
484  * indicate that the connect has failed.
485  */
486 void
487 stream_session_delete_notify (transport_connection_t * tc)
488 {
489   stream_session_t *s;
490
491   /* App might've been removed already */
492   s = stream_session_get_if_valid (tc->s_index, tc->thread_index);
493   if (!s)
494     {
495       return;
496     }
497   stream_session_delete (s);
498 }
499
500 /**
501  * Notify application that connection has been reset.
502  */
503 void
504 stream_session_reset_notify (transport_connection_t * tc)
505 {
506   stream_session_t *s;
507   application_t *app;
508   s = stream_session_get (tc->s_index, tc->thread_index);
509
510   app = application_get (s->app_index);
511   app->cb_fns.session_reset_callback (s);
512 }
513
514 /**
515  * Accept a stream session. Optionally ping the server by callback.
516  */
517 int
518 stream_session_accept (transport_connection_t * tc, u32 listener_index,
519                        u8 sst, u8 notify)
520 {
521   application_t *server;
522   stream_session_t *s, *listener;
523   segment_manager_t *sm;
524
525   int rv;
526
527   /* Find the server */
528   listener = listen_session_get (sst, listener_index);
529   server = application_get (listener->app_index);
530
531   sm = application_get_listen_segment_manager (server, listener);
532   if ((rv = stream_session_create_i (sm, tc, 1, &s)))
533     return rv;
534
535   s->app_index = server->index;
536   s->listener_index = listener_index;
537   s->session_state = SESSION_STATE_ACCEPTING;
538
539   /* Shoulder-tap the server */
540   if (notify)
541     {
542       server->cb_fns.session_accept_callback (s);
543     }
544
545   return 0;
546 }
547
548 /**
549  * Ask transport to open connection to remote transport endpoint.
550  *
551  * Stores handle for matching request with reply since the call can be
552  * asynchronous. For instance, for TCP the 3-way handshake must complete
553  * before reply comes. Session is only created once connection is established.
554  *
555  * @param app_index Index of the application requesting the connect
556  * @param st Session type requested.
557  * @param tep Remote transport endpoint
558  * @param res Resulting transport connection .
559  */
560 int
561 stream_session_open (u32 app_index, session_type_t st,
562                      transport_endpoint_t * rmt,
563                      transport_connection_t ** res)
564 {
565   transport_connection_t *tc;
566   int rv;
567   u64 handle;
568
569   rv = tp_vfts[st].open (rmt);
570   if (rv < 0)
571     {
572       clib_warning ("Transport failed to open connection.");
573       return VNET_API_ERROR_SESSION_CONNECT_FAIL;
574     }
575
576   tc = tp_vfts[st].get_half_open ((u32) rv);
577
578   /* Save app and tc index. The latter is needed to help establish the
579    * connection while the former is needed when the connect notify comes
580    * and we have to notify the external app */
581   handle = (((u64) app_index) << 32) | (u64) tc->c_index;
582
583   /* Add to the half-open lookup table */
584   stream_session_half_open_table_add (tc, handle);
585
586   *res = tc;
587
588   return 0;
589 }
590
591 /**
592  * Ask transport to listen on local transport endpoint.
593  *
594  * @param s Session for which listen will be called. Note that unlike
595  *          established sessions, listen sessions are not associated to a
596  *          thread.
597  * @param tep Local endpoint to be listened on.
598  */
599 int
600 stream_session_listen (stream_session_t * s, transport_endpoint_t * tep)
601 {
602   transport_connection_t *tc;
603   u32 tci;
604
605   /* Transport bind/listen  */
606   tci = tp_vfts[s->session_type].bind (s->session_index, tep);
607
608   if (tci == (u32) ~ 0)
609     return -1;
610
611   /* Attach transport to session */
612   s->connection_index = tci;
613   tc = tp_vfts[s->session_type].get_listener (tci);
614
615   /* Weird but handle it ... */
616   if (tc == 0)
617     return -1;
618
619   /* Add to the main lookup table */
620   stream_session_table_add_for_tc (tc, s->session_index);
621
622   return 0;
623 }
624
625 /**
626  * Ask transport to stop listening on local transport endpoint.
627  *
628  * @param s Session to stop listening on. It must be in state LISTENING.
629  */
630 int
631 stream_session_stop_listen (stream_session_t * s)
632 {
633   transport_connection_t *tc;
634
635   if (s->session_state != SESSION_STATE_LISTENING)
636     {
637       clib_warning ("not a listening session");
638       return -1;
639     }
640
641   tc = tp_vfts[s->session_type].get_listener (s->connection_index);
642   if (!tc)
643     {
644       clib_warning ("no transport");
645       return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
646     }
647
648   stream_session_table_del_for_tc (tc);
649   tp_vfts[s->session_type].unbind (s->connection_index);
650   return 0;
651 }
652
653 void
654 session_send_session_evt_to_thread (u64 session_handle,
655                                     fifo_event_type_t evt_type,
656                                     u32 thread_index)
657 {
658   static u16 serial_number = 0;
659   session_fifo_event_t evt;
660   unix_shared_memory_queue_t *q;
661
662   /* Fabricate event */
663   evt.session_handle = session_handle;
664   evt.event_type = evt_type;
665   evt.event_id = serial_number++;
666
667   q = session_manager_get_vpp_event_queue (thread_index);
668
669   /* Based on request block (or not) for lack of space */
670   if (PREDICT_TRUE (q->cursize < q->maxsize))
671     {
672       if (unix_shared_memory_queue_add (q, (u8 *) & evt,
673                                         1 /* do wait for mutex */ ))
674         {
675           clib_warning ("failed to enqueue evt");
676         }
677     }
678   else
679     {
680       clib_warning ("queue full");
681       return;
682     }
683 }
684
685 /**
686  * Disconnect session and propagate to transport. This should eventually
687  * result in a delete notification that allows us to cleanup session state.
688  * Called for both active/passive disconnects.
689  *
690  * Should be called from the session's thread.
691  */
692 void
693 stream_session_disconnect (stream_session_t * s)
694 {
695   s->session_state = SESSION_STATE_CLOSED;
696   tp_vfts[s->session_type].close (s->connection_index, s->thread_index);
697 }
698
699 /**
700  * Cleanup transport and session state.
701  *
702  * Notify transport of the cleanup, wait for a delete notify to actually
703  * remove the session state.
704  */
705 void
706 stream_session_cleanup (stream_session_t * s)
707 {
708   int rv;
709
710   s->session_state = SESSION_STATE_CLOSED;
711
712   /* Delete from the main lookup table to avoid more enqueues */
713   rv = stream_session_table_del (s);
714   if (rv)
715     clib_warning ("hash delete error, rv %d", rv);
716
717   tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
718 }
719
720 /**
721  * Allocate vpp event queue (once) per worker thread
722  */
723 void
724 session_vpp_event_queue_allocate (session_manager_main_t * smm,
725                                   u32 thread_index)
726 {
727   api_main_t *am = &api_main;
728   void *oldheap;
729   u32 event_queue_length = 2048;
730
731   if (smm->vpp_event_queues[thread_index] == 0)
732     {
733       /* Allocate event fifo in the /vpe-api shared-memory segment */
734       oldheap = svm_push_data_heap (am->vlib_rp);
735
736       if (smm->configured_event_queue_length)
737         event_queue_length = smm->configured_event_queue_length;
738
739       smm->vpp_event_queues[thread_index] =
740         unix_shared_memory_queue_init
741         (event_queue_length,
742          sizeof (session_fifo_event_t), 0 /* consumer pid */ ,
743          0 /* (do not) send signal when queue non-empty */ );
744
745       svm_pop_heap (oldheap);
746     }
747 }
748
749 session_type_t
750 session_type_from_proto_and_ip (transport_proto_t proto, u8 is_ip4)
751 {
752   if (proto == TRANSPORT_PROTO_TCP)
753     {
754       if (is_ip4)
755         return SESSION_TYPE_IP4_TCP;
756       else
757         return SESSION_TYPE_IP6_TCP;
758     }
759   else
760     {
761       if (is_ip4)
762         return SESSION_TYPE_IP4_UDP;
763       else
764         return SESSION_TYPE_IP6_UDP;
765     }
766
767   return SESSION_N_TYPES;
768 }
769
770 static clib_error_t *
771 session_manager_main_enable (vlib_main_t * vm)
772 {
773   session_manager_main_t *smm = &session_manager_main;
774   vlib_thread_main_t *vtm = vlib_get_thread_main ();
775   u32 num_threads;
776   u32 preallocated_sessions_per_worker;
777   int i;
778
779   num_threads = 1 /* main thread */  + vtm->n_threads;
780
781   if (num_threads < 1)
782     return clib_error_return (0, "n_thread_stacks not set");
783
784   /* $$$ config parameters */
785   svm_fifo_segment_init (0x200000000ULL /* first segment base VA */ ,
786                          20 /* timeout in seconds */ );
787
788   /* configure per-thread ** vectors */
789   vec_validate (smm->sessions, num_threads - 1);
790   vec_validate (smm->session_indices_to_enqueue_by_thread, num_threads - 1);
791   vec_validate (smm->tx_buffers, num_threads - 1);
792   vec_validate (smm->pending_event_vector, num_threads - 1);
793   vec_validate (smm->free_event_vector, num_threads - 1);
794   vec_validate (smm->current_enqueue_epoch, num_threads - 1);
795   vec_validate (smm->vpp_event_queues, num_threads - 1);
796
797   for (i = 0; i < num_threads; i++)
798     {
799       vec_validate (smm->free_event_vector[i], 0);
800       _vec_len (smm->free_event_vector[i]) = 0;
801       vec_validate (smm->pending_event_vector[i], 0);
802       _vec_len (smm->pending_event_vector[i]) = 0;
803     }
804
805 #if SESSION_DBG
806   vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
807 #endif
808
809   /* Allocate vpp event queues */
810   for (i = 0; i < vec_len (smm->vpp_event_queues); i++)
811     session_vpp_event_queue_allocate (smm, i);
812
813   /* Preallocate sessions */
814   if (num_threads == 1)
815     {
816       for (i = 0; i < smm->preallocated_sessions; i++)
817         {
818           stream_session_t *ss __attribute__ ((unused));
819           pool_get_aligned (smm->sessions[0], ss, CLIB_CACHE_LINE_BYTES);
820         }
821
822       for (i = 0; i < smm->preallocated_sessions; i++)
823         pool_put_index (smm->sessions[0], i);
824     }
825   else
826     {
827       int j;
828       preallocated_sessions_per_worker = smm->preallocated_sessions /
829         (num_threads - 1);
830
831       for (j = 1; j < num_threads; j++)
832         {
833           for (i = 0; i < preallocated_sessions_per_worker; i++)
834             {
835               stream_session_t *ss __attribute__ ((unused));
836               pool_get_aligned (smm->sessions[j], ss, CLIB_CACHE_LINE_BYTES);
837             }
838           for (i = 0; i < preallocated_sessions_per_worker; i++)
839             pool_put_index (smm->sessions[j], i);
840         }
841     }
842
843   session_lookup_init ();
844
845   smm->is_enabled = 1;
846
847   /* Enable TCP transport */
848   vnet_tcp_enable_disable (vm, 1);
849
850   return 0;
851 }
852
853 void
854 session_node_enable_disable (u8 is_en)
855 {
856   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
857   /* *INDENT-OFF* */
858   foreach_vlib_main (({
859     vlib_node_set_state (this_vlib_main, session_queue_node.index,
860                          state);
861   }));
862   /* *INDENT-ON* */
863 }
864
865 clib_error_t *
866 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
867 {
868   if (is_en)
869     {
870       if (session_manager_main.is_enabled)
871         return 0;
872
873       session_node_enable_disable (is_en);
874
875       return session_manager_main_enable (vm);
876     }
877   else
878     {
879       session_manager_main.is_enabled = 0;
880       session_node_enable_disable (is_en);
881     }
882
883   return 0;
884 }
885
886 clib_error_t *
887 session_manager_main_init (vlib_main_t * vm)
888 {
889   session_manager_main_t *smm = &session_manager_main;
890   smm->is_enabled = 0;
891   return 0;
892 }
893
894 VLIB_INIT_FUNCTION (session_manager_main_init);
895
896 static clib_error_t *
897 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
898 {
899   session_manager_main_t *smm = &session_manager_main;
900   u32 nitems;
901   uword tmp;
902
903   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
904     {
905       if (unformat (input, "event-queue-length %d", &nitems))
906         {
907           if (nitems >= 2048)
908             smm->configured_event_queue_length = nitems;
909           else
910             clib_warning ("event queue length %d too small, ignored", nitems);
911         }
912       else if (unformat (input, "preallocated-sessions %d",
913                          &smm->preallocated_sessions))
914         ;
915       else if (unformat (input, "v4-session-table-buckets %d",
916                          &smm->configured_v4_session_table_buckets))
917         ;
918       else if (unformat (input, "v4-halfopen-table-buckets %d",
919                          &smm->configured_v4_halfopen_table_buckets))
920         ;
921       else if (unformat (input, "v6-session-table-buckets %d",
922                          &smm->configured_v6_session_table_buckets))
923         ;
924       else if (unformat (input, "v6-halfopen-table-buckets %d",
925                          &smm->configured_v6_halfopen_table_buckets))
926         ;
927       else if (unformat (input, "v4-session-table-memory %U",
928                          unformat_memory_size, &tmp))
929         {
930           if (tmp >= 0x100000000)
931             return clib_error_return (0, "memory size %llx (%lld) too large",
932                                       tmp, tmp);
933           smm->configured_v4_session_table_memory = tmp;
934         }
935       else if (unformat (input, "v4-halfopen-table-memory %U",
936                          unformat_memory_size, &tmp))
937         {
938           if (tmp >= 0x100000000)
939             return clib_error_return (0, "memory size %llx (%lld) too large",
940                                       tmp, tmp);
941           smm->configured_v4_halfopen_table_memory = tmp;
942         }
943       else if (unformat (input, "v6-session-table-memory %U",
944                          unformat_memory_size, &tmp))
945         {
946           if (tmp >= 0x100000000)
947             return clib_error_return (0, "memory size %llx (%lld) too large",
948                                       tmp, tmp);
949           smm->configured_v6_session_table_memory = tmp;
950         }
951       else if (unformat (input, "v6-halfopen-table-memory %U",
952                          unformat_memory_size, &tmp))
953         {
954           if (tmp >= 0x100000000)
955             return clib_error_return (0, "memory size %llx (%lld) too large",
956                                       tmp, tmp);
957           smm->configured_v6_halfopen_table_memory = tmp;
958         }
959       else
960         return clib_error_return (0, "unknown input `%U'",
961                                   format_unformat_error, input);
962     }
963   return 0;
964 }
965
966 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
967
968 /*
969  * fd.io coding-style-patch-verification: ON
970  *
971  * Local Variables:
972  * eval: (c-set-style "gnu")
973  * End:
974  */