09bc00e745aa9867871e6ad5b3658fe0fe98adf6
[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 <vlibmemory/api.h>
22 #include <vnet/dpo/load_balance.h>
23 #include <vnet/fib/ip4_fib.h>
24 #include <vnet/session/application.h>
25 #include <vnet/tcp/tcp.h>
26 #include <vnet/session/session_debug.h>
27
28 /**
29  * Per-type vector of transport protocol virtual function tables
30  */
31 static transport_proto_vft_t *tp_vfts;
32
33 session_manager_main_t session_manager_main;
34
35 transport_connection_t *
36 stream_session_lookup_half_open (transport_connection_t * tc)
37 {
38   session_manager_main_t *smm = &session_manager_main;
39   session_kv4_t kv4;
40   int rv;
41   if (tc->is_ip4)
42     {
43       make_v4_ss_kv_from_tc (&kv4, tc);
44       rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
45       if (rv == 0)
46         return tp_vfts[tc->proto].get_half_open (kv4.value & 0xFFFFFFFFULL);
47     }
48   return 0;
49 }
50
51 /*
52  * Session lookup key; (src-ip, dst-ip, src-port, dst-port, session-type)
53  * Value: (owner thread index << 32 | session_index);
54  */
55 void
56 stream_session_table_add_for_tc (transport_connection_t * tc, u64 value)
57 {
58   session_manager_main_t *smm = &session_manager_main;
59   session_kv4_t kv4;
60   session_kv6_t kv6;
61
62   switch (tc->proto)
63     {
64     case SESSION_TYPE_IP4_UDP:
65     case SESSION_TYPE_IP4_TCP:
66       make_v4_ss_kv_from_tc (&kv4, tc);
67       kv4.value = value;
68       clib_bihash_add_del_16_8 (&smm->v4_session_hash, &kv4, 1 /* is_add */ );
69       break;
70     case SESSION_TYPE_IP6_UDP:
71     case SESSION_TYPE_IP6_TCP:
72       make_v6_ss_kv_from_tc (&kv6, tc);
73       kv6.value = value;
74       clib_bihash_add_del_48_8 (&smm->v6_session_hash, &kv6, 1 /* is_add */ );
75       break;
76     default:
77       clib_warning ("Session type not supported");
78       ASSERT (0);
79     }
80 }
81
82 void
83 stream_session_table_add (session_manager_main_t * smm, stream_session_t * s,
84                           u64 value)
85 {
86   transport_connection_t *tc;
87
88   tc = tp_vfts[s->session_type].get_connection (s->connection_index,
89                                                 s->thread_index);
90   stream_session_table_add_for_tc (tc, value);
91 }
92
93 static void
94 stream_session_half_open_table_add (session_type_t sst,
95                                     transport_connection_t * tc, u64 value)
96 {
97   session_manager_main_t *smm = &session_manager_main;
98   session_kv4_t kv4;
99   session_kv6_t kv6;
100
101   switch (sst)
102     {
103     case SESSION_TYPE_IP4_UDP:
104     case SESSION_TYPE_IP4_TCP:
105       make_v4_ss_kv_from_tc (&kv4, tc);
106       kv4.value = value;
107       clib_bihash_add_del_16_8 (&smm->v4_half_open_hash, &kv4,
108                                 1 /* is_add */ );
109       break;
110     case SESSION_TYPE_IP6_UDP:
111     case SESSION_TYPE_IP6_TCP:
112       make_v6_ss_kv_from_tc (&kv6, tc);
113       kv6.value = value;
114       clib_bihash_add_del_48_8 (&smm->v6_half_open_hash, &kv6,
115                                 1 /* is_add */ );
116       break;
117     default:
118       clib_warning ("Session type not supported");
119       ASSERT (0);
120     }
121 }
122
123 int
124 stream_session_table_del_for_tc (transport_connection_t * tc)
125 {
126   session_manager_main_t *smm = &session_manager_main;
127   session_kv4_t kv4;
128   session_kv6_t kv6;
129   switch (tc->proto)
130     {
131     case SESSION_TYPE_IP4_UDP:
132     case SESSION_TYPE_IP4_TCP:
133       make_v4_ss_kv_from_tc (&kv4, tc);
134       return clib_bihash_add_del_16_8 (&smm->v4_session_hash, &kv4,
135                                        0 /* is_add */ );
136       break;
137     case SESSION_TYPE_IP6_UDP:
138     case SESSION_TYPE_IP6_TCP:
139       make_v6_ss_kv_from_tc (&kv6, tc);
140       return clib_bihash_add_del_48_8 (&smm->v6_session_hash, &kv6,
141                                        0 /* is_add */ );
142       break;
143     default:
144       clib_warning ("Session type not supported");
145       ASSERT (0);
146     }
147
148   return 0;
149 }
150
151 static int
152 stream_session_table_del (session_manager_main_t * smm, stream_session_t * s)
153 {
154   transport_connection_t *ts;
155
156   ts = tp_vfts[s->session_type].get_connection (s->connection_index,
157                                                 s->thread_index);
158   return stream_session_table_del_for_tc (ts);
159 }
160
161 static void
162 stream_session_half_open_table_del (session_manager_main_t * smm, u8 sst,
163                                     transport_connection_t * tc)
164 {
165   session_kv4_t kv4;
166   session_kv6_t kv6;
167
168   switch (sst)
169     {
170     case SESSION_TYPE_IP4_UDP:
171     case SESSION_TYPE_IP4_TCP:
172       make_v4_ss_kv_from_tc (&kv4, tc);
173       clib_bihash_add_del_16_8 (&smm->v4_half_open_hash, &kv4,
174                                 0 /* is_add */ );
175       break;
176     case SESSION_TYPE_IP6_UDP:
177     case SESSION_TYPE_IP6_TCP:
178       make_v6_ss_kv_from_tc (&kv6, tc);
179       clib_bihash_add_del_48_8 (&smm->v6_half_open_hash, &kv6,
180                                 0 /* is_add */ );
181       break;
182     default:
183       clib_warning ("Session type not supported");
184       ASSERT (0);
185     }
186 }
187
188 stream_session_t *
189 stream_session_lookup_listener4 (ip4_address_t * lcl, u16 lcl_port, u8 proto)
190 {
191   session_manager_main_t *smm = &session_manager_main;
192   session_kv4_t kv4;
193   int rv;
194
195   make_v4_listener_kv (&kv4, lcl, lcl_port, proto);
196   rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
197   if (rv == 0)
198     return pool_elt_at_index (smm->listen_sessions[proto], (u32) kv4.value);
199
200   /* Zero out the lcl ip */
201   kv4.key[0] = 0;
202   rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
203   if (rv == 0)
204     return pool_elt_at_index (smm->listen_sessions[proto], kv4.value);
205
206   return 0;
207 }
208
209 /** Looks up a session based on the 5-tuple passed as argument.
210  *
211  * First it tries to find an established session, if this fails, it tries
212  * finding a listener session if this fails, it tries a lookup with a
213  * wildcarded local source (listener bound to all interfaces)
214  */
215 stream_session_t *
216 stream_session_lookup4 (ip4_address_t * lcl, ip4_address_t * rmt,
217                         u16 lcl_port, u16 rmt_port, u8 proto)
218 {
219   session_manager_main_t *smm = &session_manager_main;
220   session_kv4_t kv4;
221   stream_session_t *s;
222   int rv;
223
224   /* Lookup session amongst established ones */
225   make_v4_ss_kv (&kv4, lcl, rmt, lcl_port, rmt_port, proto);
226   rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
227   if (rv == 0)
228     return stream_session_get_from_handle (kv4.value);
229
230   /* If nothing is found, check if any listener is available */
231   if ((s = stream_session_lookup_listener4 (lcl, lcl_port, proto)))
232     return s;
233
234   /* Finally, try half-open connections */
235   rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
236   if (rv == 0)
237     return stream_session_get_from_handle (kv4.value);
238   return 0;
239 }
240
241 stream_session_t *
242 stream_session_lookup_listener6 (ip6_address_t * lcl, u16 lcl_port, u8 proto)
243 {
244   session_manager_main_t *smm = &session_manager_main;
245   session_kv6_t kv6;
246   int rv;
247
248   make_v6_listener_kv (&kv6, lcl, lcl_port, proto);
249   rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
250   if (rv == 0)
251     return pool_elt_at_index (smm->listen_sessions[proto], kv6.value);
252
253   /* Zero out the lcl ip */
254   kv6.key[0] = kv6.key[1] = 0;
255   rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
256   if (rv == 0)
257     return pool_elt_at_index (smm->listen_sessions[proto], kv6.value);
258
259   return 0;
260 }
261
262 /* Looks up a session based on the 5-tuple passed as argument.
263  * First it tries to find an established session, if this fails, it tries
264  * finding a listener session if this fails, it tries a lookup with a
265  * wildcarded local source (listener bound to all interfaces) */
266 stream_session_t *
267 stream_session_lookup6 (ip6_address_t * lcl, ip6_address_t * rmt,
268                         u16 lcl_port, u16 rmt_port, u8 proto)
269 {
270   session_manager_main_t *smm = vnet_get_session_manager_main ();
271   session_kv6_t kv6;
272   stream_session_t *s;
273   int rv;
274
275   make_v6_ss_kv (&kv6, lcl, rmt, lcl_port, rmt_port, proto);
276   rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
277   if (rv == 0)
278     return stream_session_get_from_handle (kv6.value);
279
280   /* If nothing is found, check if any listener is available */
281   if ((s = stream_session_lookup_listener6 (lcl, lcl_port, proto)))
282     return s;
283
284   /* Finally, try half-open connections */
285   rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
286   if (rv == 0)
287     return stream_session_get_from_handle (kv6.value);
288   return 0;
289 }
290
291 stream_session_t *
292 stream_session_lookup_listener (ip46_address_t * lcl, u16 lcl_port, u8 proto)
293 {
294   switch (proto)
295     {
296     case SESSION_TYPE_IP4_UDP:
297     case SESSION_TYPE_IP4_TCP:
298       return stream_session_lookup_listener4 (&lcl->ip4, lcl_port, proto);
299       break;
300     case SESSION_TYPE_IP6_UDP:
301     case SESSION_TYPE_IP6_TCP:
302       return stream_session_lookup_listener6 (&lcl->ip6, lcl_port, proto);
303       break;
304     }
305   return 0;
306 }
307
308 static u64
309 stream_session_half_open_lookup (session_manager_main_t * smm,
310                                  ip46_address_t * lcl, ip46_address_t * rmt,
311                                  u16 lcl_port, u16 rmt_port, u8 proto)
312 {
313   session_kv4_t kv4;
314   session_kv6_t kv6;
315   int rv;
316
317   switch (proto)
318     {
319     case SESSION_TYPE_IP4_UDP:
320     case SESSION_TYPE_IP4_TCP:
321       make_v4_ss_kv (&kv4, &lcl->ip4, &rmt->ip4, lcl_port, rmt_port, proto);
322       rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
323
324       if (rv == 0)
325         return kv4.value;
326
327       return (u64) ~ 0;
328       break;
329     case SESSION_TYPE_IP6_UDP:
330     case SESSION_TYPE_IP6_TCP:
331       make_v6_ss_kv (&kv6, &lcl->ip6, &rmt->ip6, lcl_port, rmt_port, proto);
332       rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
333
334       if (rv == 0)
335         return kv6.value;
336
337       return (u64) ~ 0;
338       break;
339     }
340   return 0;
341 }
342
343 transport_connection_t *
344 stream_session_lookup_transport_wt4 (ip4_address_t * lcl, ip4_address_t * rmt,
345                                      u16 lcl_port, u16 rmt_port, u8 proto,
346                                      u32 my_thread_index)
347 {
348   session_manager_main_t *smm = &session_manager_main;
349   session_kv4_t kv4;
350   stream_session_t *s;
351   int rv;
352
353   /* Lookup session amongst established ones */
354   make_v4_ss_kv (&kv4, lcl, rmt, lcl_port, rmt_port, proto);
355   rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
356   if (rv == 0)
357     {
358       s = stream_session_get_tsi (kv4.value, my_thread_index);
359
360       return tp_vfts[s->session_type].get_connection (s->connection_index,
361                                                       my_thread_index);
362     }
363
364   /* If nothing is found, check if any listener is available */
365   s = stream_session_lookup_listener4 (lcl, lcl_port, proto);
366   if (s)
367     return tp_vfts[s->session_type].get_listener (s->connection_index);
368
369   /* Finally, try half-open connections */
370   rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
371   if (rv == 0)
372     return tp_vfts[proto].get_half_open (kv4.value & 0xFFFFFFFF);
373   return 0;
374 }
375
376 transport_connection_t *
377 stream_session_lookup_transport4 (ip4_address_t * lcl, ip4_address_t * rmt,
378                                   u16 lcl_port, u16 rmt_port, u8 proto)
379 {
380   session_manager_main_t *smm = &session_manager_main;
381   session_kv4_t kv4;
382   stream_session_t *s;
383   int rv;
384
385   /* Lookup session amongst established ones */
386   make_v4_ss_kv (&kv4, lcl, rmt, lcl_port, rmt_port, proto);
387   rv = clib_bihash_search_inline_16_8 (&smm->v4_session_hash, &kv4);
388   if (rv == 0)
389     {
390       s = stream_session_get_from_handle (kv4.value);
391       return tp_vfts[s->session_type].get_connection (s->connection_index,
392                                                       s->thread_index);
393     }
394
395   /* If nothing is found, check if any listener is available */
396   s = stream_session_lookup_listener4 (lcl, lcl_port, proto);
397   if (s)
398     return tp_vfts[s->session_type].get_listener (s->connection_index);
399
400   /* Finally, try half-open connections */
401   rv = clib_bihash_search_inline_16_8 (&smm->v4_half_open_hash, &kv4);
402   if (rv == 0)
403     return tp_vfts[proto].get_half_open (kv4.value & 0xFFFFFFFF);
404   return 0;
405 }
406
407 transport_connection_t *
408 stream_session_lookup_transport_wt6 (ip6_address_t * lcl, ip6_address_t * rmt,
409                                      u16 lcl_port, u16 rmt_port, u8 proto,
410                                      u32 my_thread_index)
411 {
412   session_manager_main_t *smm = &session_manager_main;
413   stream_session_t *s;
414   session_kv6_t kv6;
415   int rv;
416
417   make_v6_ss_kv (&kv6, lcl, rmt, lcl_port, rmt_port, proto);
418   rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
419   if (rv == 0)
420     {
421       s = stream_session_get_tsi (kv6.value, my_thread_index);
422
423       return tp_vfts[s->session_type].get_connection (s->connection_index,
424                                                       my_thread_index);
425     }
426
427   /* If nothing is found, check if any listener is available */
428   s = stream_session_lookup_listener6 (lcl, lcl_port, proto);
429   if (s)
430     return tp_vfts[s->session_type].get_listener (s->connection_index);
431
432   /* Finally, try half-open connections */
433   rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
434   if (rv == 0)
435     return tp_vfts[proto].get_half_open (kv6.value & 0xFFFFFFFF);
436
437   return 0;
438 }
439
440 transport_connection_t *
441 stream_session_lookup_transport6 (ip6_address_t * lcl, ip6_address_t * rmt,
442                                   u16 lcl_port, u16 rmt_port, u8 proto)
443 {
444   session_manager_main_t *smm = &session_manager_main;
445   stream_session_t *s;
446   session_kv6_t kv6;
447   int rv;
448
449   make_v6_ss_kv (&kv6, lcl, rmt, lcl_port, rmt_port, proto);
450   rv = clib_bihash_search_inline_48_8 (&smm->v6_session_hash, &kv6);
451   if (rv == 0)
452     {
453       s = stream_session_get_from_handle (kv6.value);
454       return tp_vfts[s->session_type].get_connection (s->connection_index,
455                                                       s->thread_index);
456     }
457
458   /* If nothing is found, check if any listener is available */
459   s = stream_session_lookup_listener6 (lcl, lcl_port, proto);
460   if (s)
461     return tp_vfts[s->session_type].get_listener (s->connection_index);
462
463   /* Finally, try half-open connections */
464   rv = clib_bihash_search_inline_48_8 (&smm->v6_half_open_hash, &kv6);
465   if (rv == 0)
466     return tp_vfts[proto].get_half_open (kv6.value & 0xFFFFFFFF);
467
468   return 0;
469 }
470
471 int
472 stream_session_create_i (segment_manager_t * sm, transport_connection_t * tc,
473                          stream_session_t ** ret_s)
474 {
475   session_manager_main_t *smm = &session_manager_main;
476   svm_fifo_t *server_rx_fifo = 0, *server_tx_fifo = 0;
477   u32 fifo_segment_index;
478   u32 pool_index;
479   stream_session_t *s;
480   u64 value;
481   u32 thread_index = tc->thread_index;
482   int rv;
483
484   ASSERT (thread_index == vlib_get_thread_index ());
485
486   if ((rv = segment_manager_alloc_session_fifos (sm, &server_rx_fifo,
487                                                  &server_tx_fifo,
488                                                  &fifo_segment_index)))
489     return rv;
490
491   /* Create the session */
492   pool_get_aligned (smm->sessions[thread_index], s, CLIB_CACHE_LINE_BYTES);
493   memset (s, 0, sizeof (*s));
494
495   /* Initialize backpointers */
496   pool_index = s - smm->sessions[thread_index];
497   server_rx_fifo->master_session_index = pool_index;
498   server_rx_fifo->master_thread_index = thread_index;
499
500   server_tx_fifo->master_session_index = pool_index;
501   server_tx_fifo->master_thread_index = thread_index;
502
503   s->server_rx_fifo = server_rx_fifo;
504   s->server_tx_fifo = server_tx_fifo;
505
506   /* Initialize state machine, such as it is... */
507   s->session_type = tc->proto;
508   s->session_state = SESSION_STATE_CONNECTING;
509   s->svm_segment_index = fifo_segment_index;
510   s->thread_index = thread_index;
511   s->session_index = pool_index;
512
513   /* Attach transport to session */
514   s->connection_index = tc->c_index;
515
516   /* Attach session to transport */
517   tc->s_index = s->session_index;
518
519   /* Add to the main lookup table */
520   value = stream_session_handle (s);
521   stream_session_table_add_for_tc (tc, value);
522
523   *ret_s = s;
524
525   return 0;
526 }
527
528 /** Enqueue buffer chain tail */
529 always_inline int
530 session_enqueue_chain_tail (stream_session_t * s, vlib_buffer_t * b,
531                             u32 offset, u8 is_in_order)
532 {
533   vlib_buffer_t *chain_b;
534   u32 chain_bi = b->next_buffer;
535   vlib_main_t *vm = vlib_get_main ();
536   u8 *data, len;
537   u16 written = 0;
538   int rv = 0;
539
540   do
541     {
542       chain_b = vlib_get_buffer (vm, chain_bi);
543       data = vlib_buffer_get_current (chain_b);
544       len = chain_b->current_length;
545       if (is_in_order)
546         {
547           rv = svm_fifo_enqueue_nowait (s->server_rx_fifo, len, data);
548           if (rv < len)
549             {
550               return (rv > 0) ? (written + rv) : written;
551             }
552           written += rv;
553         }
554       else
555         {
556           rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset, len,
557                                              data);
558           if (rv)
559             return -1;
560           offset += len;
561         }
562     }
563   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
564           ? chain_b->next_buffer : 0));
565
566   if (is_in_order)
567     return written;
568
569   return 0;
570 }
571
572 /*
573  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
574  * event but on request can queue notification events for later delivery by
575  * calling stream_server_flush_enqueue_events().
576  *
577  * @param tc Transport connection which is to be enqueued data
578  * @param b Buffer to be enqueued
579  * @param offset Offset at which to start enqueueing if out-of-order
580  * @param queue_event Flag to indicate if peer is to be notified or if event
581  *                    is to be queued. The former is useful when more data is
582  *                    enqueued and only one event is to be generated.
583  * @param is_in_order Flag to indicate if data is in order
584  * @return Number of bytes enqueued or a negative value if enqueueing failed.
585  */
586 int
587 stream_session_enqueue_data (transport_connection_t * tc, vlib_buffer_t * b,
588                              u32 offset, u8 queue_event, u8 is_in_order)
589 {
590   stream_session_t *s;
591   int enqueued = 0, rv;
592
593   s = stream_session_get (tc->s_index, tc->thread_index);
594
595   if (is_in_order)
596     {
597       enqueued =
598         svm_fifo_enqueue_nowait (s->server_rx_fifo, b->current_length,
599                                  vlib_buffer_get_current (b));
600       if (PREDICT_FALSE
601           ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued > 0))
602         {
603           rv = session_enqueue_chain_tail (s, b, 0, 1);
604           if (rv <= 0)
605             return enqueued;
606           enqueued += rv;
607         }
608     }
609   else
610     {
611       rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset,
612                                          b->current_length,
613                                          vlib_buffer_get_current (b));
614       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
615         rv = session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
616       if (rv)
617         return -1;
618     }
619
620   if (queue_event)
621     {
622       /* Queue RX event on this fifo. Eventually these will need to be flushed
623        * by calling stream_server_flush_enqueue_events () */
624       session_manager_main_t *smm = vnet_get_session_manager_main ();
625       u32 thread_index = s->thread_index;
626       u32 my_enqueue_epoch = smm->current_enqueue_epoch[thread_index];
627
628       if (s->enqueue_epoch != my_enqueue_epoch)
629         {
630           s->enqueue_epoch = my_enqueue_epoch;
631           vec_add1 (smm->session_indices_to_enqueue_by_thread[thread_index],
632                     s - smm->sessions[thread_index]);
633         }
634     }
635
636   if (is_in_order)
637     return enqueued;
638
639   return 0;
640 }
641
642 /** Check if we have space in rx fifo to push more bytes */
643 u8
644 stream_session_no_space (transport_connection_t * tc, u32 thread_index,
645                          u16 data_len)
646 {
647   stream_session_t *s = stream_session_get (tc->s_index, thread_index);
648
649   if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY))
650     return 1;
651
652   if (data_len > svm_fifo_max_enqueue (s->server_rx_fifo))
653     return 1;
654
655   return 0;
656 }
657
658 u32
659 stream_session_tx_fifo_max_dequeue (transport_connection_t * tc)
660 {
661   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
662   if (s->session_state != SESSION_STATE_READY)
663     return 0;
664   return svm_fifo_max_dequeue (s->server_tx_fifo);
665 }
666
667 int
668 stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
669                            u32 offset, u32 max_bytes)
670 {
671   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
672   return svm_fifo_peek (s->server_tx_fifo, offset, max_bytes, buffer);
673 }
674
675 u32
676 stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
677 {
678   stream_session_t *s = stream_session_get (tc->s_index, tc->thread_index);
679   return svm_fifo_dequeue_drop (s->server_tx_fifo, max_bytes);
680 }
681
682 /**
683  * Notify session peer that new data has been enqueued.
684  *
685  * @param s Stream session for which the event is to be generated.
686  * @param block Flag to indicate if call should block if event queue is full.
687  *
688  * @return 0 on succes or negative number if failed to send notification.
689  */
690 static int
691 stream_session_enqueue_notify (stream_session_t * s, u8 block)
692 {
693   application_t *app;
694   session_fifo_event_t evt;
695   unix_shared_memory_queue_t *q;
696   static u32 serial_number;
697
698   if (PREDICT_FALSE (s->session_state == SESSION_STATE_CLOSED))
699     return 0;
700
701   /* Get session's server */
702   app = application_get (s->app_index);
703
704   /* Built-in server? Hand event to the callback... */
705   if (app->cb_fns.builtin_server_rx_callback)
706     return app->cb_fns.builtin_server_rx_callback (s);
707
708   /* If no event, send one */
709   if (svm_fifo_set_event (s->server_rx_fifo))
710     {
711       /* Fabricate event */
712       evt.fifo = s->server_rx_fifo;
713       evt.event_type = FIFO_EVENT_APP_RX;
714       evt.event_id = serial_number++;
715
716       /* Add event to server's event queue */
717       q = app->event_queue;
718
719       /* Based on request block (or not) for lack of space */
720       if (block || PREDICT_TRUE (q->cursize < q->maxsize))
721         unix_shared_memory_queue_add (app->event_queue, (u8 *) & evt,
722                                       0 /* do wait for mutex */ );
723       else
724         {
725           clib_warning ("fifo full");
726           return -1;
727         }
728     }
729
730   /* *INDENT-OFF* */
731   SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
732       ed->data[0] = evt.event_id;
733       ed->data[1] = svm_fifo_max_dequeue (s->server_rx_fifo);
734   }));
735   /* *INDENT-ON* */
736
737   return 0;
738 }
739
740 /**
741  * Flushes queue of sessions that are to be notified of new data
742  * enqueued events.
743  *
744  * @param thread_index Thread index for which the flush is to be performed.
745  * @return 0 on success or a positive number indicating the number of
746  *         failures due to API queue being full.
747  */
748 int
749 session_manager_flush_enqueue_events (u32 thread_index)
750 {
751   session_manager_main_t *smm = &session_manager_main;
752   u32 *session_indices_to_enqueue;
753   int i, errors = 0;
754
755   session_indices_to_enqueue =
756     smm->session_indices_to_enqueue_by_thread[thread_index];
757
758   for (i = 0; i < vec_len (session_indices_to_enqueue); i++)
759     {
760       stream_session_t *s0;
761
762       /* Get session */
763       s0 = stream_session_get (session_indices_to_enqueue[i], thread_index);
764       if (stream_session_enqueue_notify (s0, 0 /* don't block */ ))
765         {
766           errors++;
767         }
768     }
769
770   vec_reset_length (session_indices_to_enqueue);
771
772   smm->session_indices_to_enqueue_by_thread[thread_index] =
773     session_indices_to_enqueue;
774
775   /* Increment enqueue epoch for next round */
776   smm->current_enqueue_epoch[thread_index]++;
777
778   return errors;
779 }
780
781 /**
782  * Init fifo tail and head pointers
783  *
784  * Useful if transport uses absolute offsets for tracking ooo segments.
785  */
786 void
787 stream_session_init_fifos_pointers (transport_connection_t * tc,
788                                     u32 rx_pointer, u32 tx_pointer)
789 {
790   stream_session_t *s;
791   s = stream_session_get (tc->s_index, tc->thread_index);
792   svm_fifo_init_pointers (s->server_rx_fifo, rx_pointer);
793   svm_fifo_init_pointers (s->server_tx_fifo, tx_pointer);
794 }
795
796 int
797 stream_session_connect_notify (transport_connection_t * tc, u8 sst,
798                                u8 is_fail)
799 {
800   session_manager_main_t *smm = &session_manager_main;
801   application_t *app;
802   stream_session_t *new_s = 0;
803   u64 handle;
804   u32 api_context = 0;
805   int error = 0;
806
807   handle = stream_session_half_open_lookup (smm, &tc->lcl_ip, &tc->rmt_ip,
808                                             tc->lcl_port, tc->rmt_port,
809                                             tc->proto);
810   if (handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
811     {
812       clib_warning ("This can't be good!");
813       return -1;
814     }
815
816   /* Get the app's index from the handle we stored when opening connection */
817   app = application_get (handle >> 32);
818   api_context = tc->s_index;
819
820   if (!is_fail)
821     {
822       segment_manager_t *sm;
823       sm = application_get_connect_segment_manager (app);
824
825       /* Create new session (svm segments are allocated if needed) */
826       if (stream_session_create_i (sm, tc, &new_s))
827         {
828           is_fail = 1;
829           error = -1;
830         }
831       else
832         new_s->app_index = app->index;
833     }
834
835   /* Notify client */
836   if (app->cb_fns.session_connected_callback (app->index, api_context, new_s,
837                                               is_fail))
838     {
839       clib_warning ("failed to notify app");
840       if (!is_fail)
841         stream_session_disconnect (new_s);
842     }
843   else
844     {
845       if (!is_fail)
846         new_s->session_state = SESSION_STATE_READY;
847     }
848
849   /* Cleanup session lookup */
850   stream_session_half_open_table_del (smm, sst, tc);
851
852   return error;
853 }
854
855 void
856 stream_session_accept_notify (transport_connection_t * tc)
857 {
858   application_t *server;
859   stream_session_t *s;
860
861   s = stream_session_get (tc->s_index, tc->thread_index);
862   server = application_get (s->app_index);
863   server->cb_fns.session_accept_callback (s);
864 }
865
866 /**
867  * Notification from transport that connection is being closed.
868  *
869  * A disconnect is sent to application but state is not removed. Once
870  * disconnect is acknowledged by application, session disconnect is called.
871  * Ultimately this leads to close being called on transport (passive close).
872  */
873 void
874 stream_session_disconnect_notify (transport_connection_t * tc)
875 {
876   application_t *server;
877   stream_session_t *s;
878
879   s = stream_session_get (tc->s_index, tc->thread_index);
880   server = application_get (s->app_index);
881   server->cb_fns.session_disconnect_callback (s);
882 }
883
884 /**
885  * Cleans up session and associated app if needed.
886  */
887 void
888 stream_session_delete (stream_session_t * s)
889 {
890   session_manager_main_t *smm = vnet_get_session_manager_main ();
891   int rv;
892
893   /* Delete from the main lookup table. */
894   if ((rv = stream_session_table_del (smm, s)))
895     clib_warning ("hash delete error, rv %d", rv);
896
897   /* Cleanup fifo segments */
898   segment_manager_dealloc_fifos (s->svm_segment_index, s->server_rx_fifo,
899                                  s->server_tx_fifo);
900
901   pool_put (smm->sessions[s->thread_index], s);
902   if (CLIB_DEBUG)
903     memset (s, 0xFA, sizeof (*s));
904 }
905
906 /**
907  * Notification from transport that connection is being deleted
908  *
909  * This should be called only on previously fully established sessions. For
910  * instance failed connects should call stream_session_connect_notify and
911  * indicate that the connect has failed.
912  */
913 void
914 stream_session_delete_notify (transport_connection_t * tc)
915 {
916   stream_session_t *s;
917
918   /* App might've been removed already */
919   s = stream_session_get_if_valid (tc->s_index, tc->thread_index);
920   if (!s)
921     {
922       return;
923     }
924   stream_session_delete (s);
925 }
926
927 /**
928  * Notify application that connection has been reset.
929  */
930 void
931 stream_session_reset_notify (transport_connection_t * tc)
932 {
933   stream_session_t *s;
934   application_t *app;
935   s = stream_session_get (tc->s_index, tc->thread_index);
936
937   app = application_get (s->app_index);
938   app->cb_fns.session_reset_callback (s);
939 }
940
941 /**
942  * Accept a stream session. Optionally ping the server by callback.
943  */
944 int
945 stream_session_accept (transport_connection_t * tc, u32 listener_index,
946                        u8 sst, u8 notify)
947 {
948   application_t *server;
949   stream_session_t *s, *listener;
950   segment_manager_t *sm;
951
952   int rv;
953
954   /* Find the server */
955   listener = listen_session_get (sst, listener_index);
956   server = application_get (listener->app_index);
957
958   sm = application_get_listen_segment_manager (server, listener);
959   if ((rv = stream_session_create_i (sm, tc, &s)))
960     return rv;
961
962   s->app_index = server->index;
963   s->listener_index = listener_index;
964   s->session_state = SESSION_STATE_ACCEPTING;
965
966   /* Shoulder-tap the server */
967   if (notify)
968     {
969       server->cb_fns.session_accept_callback (s);
970     }
971
972   return 0;
973 }
974
975 /**
976  * Ask transport to open connection to remote transport endpoint.
977  *
978  * Stores handle for matching request with reply since the call can be
979  * asynchronous. For instance, for TCP the 3-way handshake must complete
980  * before reply comes. Session is only created once connection is established.
981  *
982  * @param app_index Index of the application requesting the connect
983  * @param st Session type requested.
984  * @param tep Remote transport endpoint
985  * @param res Resulting transport connection .
986  */
987 int
988 stream_session_open (u32 app_index, session_type_t st,
989                      transport_endpoint_t * tep,
990                      transport_connection_t ** res)
991 {
992   transport_connection_t *tc;
993   int rv;
994   u64 handle;
995
996   rv = tp_vfts[st].open (&tep->ip, tep->port);
997   if (rv < 0)
998     {
999       clib_warning ("Transport failed to open connection.");
1000       return VNET_API_ERROR_SESSION_CONNECT_FAIL;
1001     }
1002
1003   tc = tp_vfts[st].get_half_open ((u32) rv);
1004
1005   /* Save app and tc index. The latter is needed to help establish the
1006    * connection while the former is needed when the connect notify comes
1007    * and we have to notify the external app */
1008   handle = (((u64) app_index) << 32) | (u64) tc->c_index;
1009
1010   /* Add to the half-open lookup table */
1011   stream_session_half_open_table_add (st, tc, handle);
1012
1013   *res = tc;
1014
1015   return 0;
1016 }
1017
1018 /**
1019  * Ask transport to listen on local transport endpoint.
1020  *
1021  * @param s Session for which listen will be called. Note that unlike
1022  *          established sessions, listen sessions are not associated to a
1023  *          thread.
1024  * @param tep Local endpoint to be listened on.
1025  */
1026 int
1027 stream_session_listen (stream_session_t * s, transport_endpoint_t * tep)
1028 {
1029   transport_connection_t *tc;
1030   u32 tci;
1031
1032   /* Transport bind/listen  */
1033   tci = tp_vfts[s->session_type].bind (s->session_index, &tep->ip, tep->port);
1034
1035   if (tci == (u32) ~ 0)
1036     return -1;
1037
1038   /* Attach transport to session */
1039   s->connection_index = tci;
1040   tc = tp_vfts[s->session_type].get_listener (tci);
1041
1042   /* Weird but handle it ... */
1043   if (tc == 0)
1044     return -1;
1045
1046   /* Add to the main lookup table */
1047   stream_session_table_add_for_tc (tc, s->session_index);
1048
1049   return 0;
1050 }
1051
1052 /**
1053  * Ask transport to stop listening on local transport endpoint.
1054  *
1055  * @param s Session to stop listening on. It must be in state LISTENING.
1056  */
1057 int
1058 stream_session_stop_listen (stream_session_t * s)
1059 {
1060   transport_connection_t *tc;
1061
1062   if (s->session_state != SESSION_STATE_LISTENING)
1063     {
1064       clib_warning ("not a listening session");
1065       return -1;
1066     }
1067
1068   tc = tp_vfts[s->session_type].get_listener (s->connection_index);
1069   if (!tc)
1070     {
1071       clib_warning ("no transport");
1072       return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
1073     }
1074
1075   stream_session_table_del_for_tc (tc);
1076   tp_vfts[s->session_type].unbind (s->connection_index);
1077   return 0;
1078 }
1079
1080 void
1081 session_send_session_evt_to_thread (u64 session_handle,
1082                                     fifo_event_type_t evt_type,
1083                                     u32 thread_index)
1084 {
1085   static u16 serial_number = 0;
1086   session_fifo_event_t evt;
1087   unix_shared_memory_queue_t *q;
1088
1089   /* Fabricate event */
1090   evt.session_handle = session_handle;
1091   evt.event_type = evt_type;
1092   evt.event_id = serial_number++;
1093
1094   q = session_manager_get_vpp_event_queue (thread_index);
1095
1096   /* Based on request block (or not) for lack of space */
1097   if (PREDICT_TRUE (q->cursize < q->maxsize))
1098     {
1099       if (unix_shared_memory_queue_add (q, (u8 *) & evt,
1100                                         1 /* do wait for mutex */ ))
1101         {
1102           clib_warning ("failed to enqueue evt");
1103         }
1104     }
1105   else
1106     {
1107       clib_warning ("queue full");
1108       return;
1109     }
1110 }
1111
1112 /**
1113  * Disconnect session and propagate to transport. This should eventually
1114  * result in a delete notification that allows us to cleanup session state.
1115  * Called for both active/passive disconnects.
1116  *
1117  * Should be called from the session's thread.
1118  */
1119 void
1120 stream_session_disconnect (stream_session_t * s)
1121 {
1122   s->session_state = SESSION_STATE_CLOSED;
1123   tp_vfts[s->session_type].close (s->connection_index, s->thread_index);
1124 }
1125
1126 /**
1127  * Cleanup transport and session state.
1128  *
1129  * Notify transport of the cleanup, wait for a delete notify to actually
1130  * remove the session state.
1131  */
1132 void
1133 stream_session_cleanup (stream_session_t * s)
1134 {
1135   session_manager_main_t *smm = &session_manager_main;
1136   int rv;
1137
1138   s->session_state = SESSION_STATE_CLOSED;
1139
1140   /* Delete from the main lookup table to avoid more enqueues */
1141   rv = stream_session_table_del (smm, s);
1142   if (rv)
1143     clib_warning ("hash delete error, rv %d", rv);
1144
1145   tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
1146 }
1147
1148 void
1149 session_register_transport (u8 type, const transport_proto_vft_t * vft)
1150 {
1151   session_manager_main_t *smm = vnet_get_session_manager_main ();
1152
1153   vec_validate (tp_vfts, type);
1154   tp_vfts[type] = *vft;
1155
1156   /* If an offset function is provided, then peek instead of dequeue */
1157   smm->session_tx_fns[type] =
1158     (vft->tx_fifo_offset) ? session_tx_fifo_peek_and_snd :
1159     session_tx_fifo_dequeue_and_snd;
1160 }
1161
1162 transport_proto_vft_t *
1163 session_get_transport_vft (u8 type)
1164 {
1165   if (type >= vec_len (tp_vfts))
1166     return 0;
1167   return &tp_vfts[type];
1168 }
1169
1170 /**
1171  * Allocate vpp event queue (once) per worker thread
1172  */
1173 void
1174 session_vpp_event_queue_allocate (session_manager_main_t * smm,
1175                                   u32 thread_index)
1176 {
1177   api_main_t *am = &api_main;
1178   void *oldheap;
1179   u32 event_queue_length = 2048;
1180
1181   if (smm->vpp_event_queues[thread_index] == 0)
1182     {
1183       /* Allocate event fifo in the /vpe-api shared-memory segment */
1184       oldheap = svm_push_data_heap (am->vlib_rp);
1185
1186       if (smm->configured_event_queue_length)
1187         event_queue_length = smm->configured_event_queue_length;
1188
1189       smm->vpp_event_queues[thread_index] =
1190         unix_shared_memory_queue_init
1191         (event_queue_length,
1192          sizeof (session_fifo_event_t), 0 /* consumer pid */ ,
1193          0 /* (do not) send signal when queue non-empty */ );
1194
1195       svm_pop_heap (oldheap);
1196     }
1197 }
1198
1199 session_type_t
1200 session_type_from_proto_and_ip (transport_proto_t proto, u8 is_ip4)
1201 {
1202   if (proto == TRANSPORT_PROTO_TCP)
1203     {
1204       if (is_ip4)
1205         return SESSION_TYPE_IP4_TCP;
1206       else
1207         return SESSION_TYPE_IP6_TCP;
1208     }
1209   else
1210     {
1211       if (is_ip4)
1212         return SESSION_TYPE_IP4_UDP;
1213       else
1214         return SESSION_TYPE_IP6_UDP;
1215     }
1216
1217   return SESSION_N_TYPES;
1218 }
1219
1220 static clib_error_t *
1221 session_manager_main_enable (vlib_main_t * vm)
1222 {
1223   session_manager_main_t *smm = &session_manager_main;
1224   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1225   u32 num_threads;
1226   int i;
1227
1228   num_threads = 1 /* main thread */  + vtm->n_threads;
1229
1230   if (num_threads < 1)
1231     return clib_error_return (0, "n_thread_stacks not set");
1232
1233   /* $$$ config parameters */
1234   svm_fifo_segment_init (0x200000000ULL /* first segment base VA */ ,
1235                          20 /* timeout in seconds */ );
1236
1237   /* configure per-thread ** vectors */
1238   vec_validate (smm->sessions, num_threads - 1);
1239   vec_validate (smm->session_indices_to_enqueue_by_thread, num_threads - 1);
1240   vec_validate (smm->tx_buffers, num_threads - 1);
1241   vec_validate (smm->pending_event_vector, num_threads - 1);
1242   vec_validate (smm->free_event_vector, num_threads - 1);
1243   vec_validate (smm->current_enqueue_epoch, num_threads - 1);
1244   vec_validate (smm->vpp_event_queues, num_threads - 1);
1245
1246   for (i = 0; i < num_threads; i++)
1247     {
1248       vec_validate (smm->free_event_vector[i], 0);
1249       _vec_len (smm->free_event_vector[i]) = 0;
1250       vec_validate (smm->pending_event_vector[i], 0);
1251       _vec_len (smm->pending_event_vector[i]) = 0;
1252     }
1253
1254 #if SESSION_DBG
1255   vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
1256 #endif
1257
1258   /* Allocate vpp event queues */
1259   for (i = 0; i < vec_len (smm->vpp_event_queues); i++)
1260     session_vpp_event_queue_allocate (smm, i);
1261
1262   /* $$$$ preallocate hack config parameter */
1263   for (i = 0; i < smm->preallocated_sessions; i++)
1264     {
1265       stream_session_t *ss __attribute__ ((unused));
1266       pool_get_aligned (smm->sessions[0], ss, CLIB_CACHE_LINE_BYTES);
1267     }
1268
1269   for (i = 0; i < smm->preallocated_sessions; i++)
1270     pool_put_index (smm->sessions[0], i);
1271
1272   clib_bihash_init_16_8 (&smm->v4_session_hash, "v4 session table",
1273                          200000 /* $$$$ config parameter nbuckets */ ,
1274                          (64 << 20) /*$$$ config parameter table size */ );
1275   clib_bihash_init_48_8 (&smm->v6_session_hash, "v6 session table",
1276                          200000 /* $$$$ config parameter nbuckets */ ,
1277                          (64 << 20) /*$$$ config parameter table size */ );
1278
1279   clib_bihash_init_16_8 (&smm->v4_half_open_hash, "v4 half-open table",
1280                          200000 /* $$$$ config parameter nbuckets */ ,
1281                          (64 << 20) /*$$$ config parameter table size */ );
1282   clib_bihash_init_48_8 (&smm->v6_half_open_hash, "v6 half-open table",
1283                          200000 /* $$$$ config parameter nbuckets */ ,
1284                          (64 << 20) /*$$$ config parameter table size */ );
1285
1286   smm->is_enabled = 1;
1287
1288   /* Enable TCP transport */
1289   vnet_tcp_enable_disable (vm, 1);
1290
1291   return 0;
1292 }
1293
1294 void
1295 session_node_enable_disable (u8 is_en)
1296 {
1297   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1298   /* *INDENT-OFF* */
1299   foreach_vlib_main (({
1300     vlib_node_set_state (this_vlib_main, session_queue_node.index,
1301                          state);
1302   }));
1303   /* *INDENT-ON* */
1304 }
1305
1306 clib_error_t *
1307 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1308 {
1309   if (is_en)
1310     {
1311       if (session_manager_main.is_enabled)
1312         return 0;
1313
1314       session_node_enable_disable (is_en);
1315
1316       return session_manager_main_enable (vm);
1317     }
1318   else
1319     {
1320       session_manager_main.is_enabled = 0;
1321       session_node_enable_disable (is_en);
1322     }
1323
1324   return 0;
1325 }
1326
1327 clib_error_t *
1328 session_manager_main_init (vlib_main_t * vm)
1329 {
1330   session_manager_main_t *smm = &session_manager_main;
1331
1332   smm->vlib_main = vm;
1333   smm->vnet_main = vnet_get_main ();
1334   smm->is_enabled = 0;
1335
1336   return 0;
1337 }
1338
1339 VLIB_INIT_FUNCTION (session_manager_main_init);
1340
1341 static clib_error_t *
1342 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1343 {
1344   session_manager_main_t *smm = &session_manager_main;
1345   u32 nitems;
1346
1347   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1348     {
1349       if (unformat (input, "event-queue-length %d", &nitems))
1350         {
1351           if (nitems >= 2048)
1352             smm->configured_event_queue_length = nitems;
1353           else
1354             clib_warning ("event queue length %d too small, ignored", nitems);
1355         }
1356       if (unformat (input, "preallocated-sessions %d",
1357                     &smm->preallocated_sessions))
1358         ;
1359       else
1360         return clib_error_return (0, "unknown input `%U'",
1361                                   format_unformat_error, input);
1362     }
1363   return 0;
1364 }
1365
1366 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1367
1368 /*
1369  * fd.io coding-style-patch-verification: ON
1370  *
1371  * Local Variables:
1372  * eval: (c-set-style "gnu")
1373  * End:
1374  */