session: add support for proxying apps
[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 static void
32 session_send_evt_to_thread (u64 session_handle, fifo_event_type_t evt_type,
33                             u32 thread_index, void *fp, void *rpc_args)
34 {
35   u32 tries = 0;
36   session_fifo_event_t evt = { {0}, };
37   unix_shared_memory_queue_t *q;
38
39   evt.event_type = evt_type;
40   if (evt_type == FIFO_EVENT_RPC)
41     {
42       evt.rpc_args.fp = fp;
43       evt.rpc_args.arg = rpc_args;
44     }
45   else
46     evt.session_handle = session_handle;
47
48   q = session_manager_get_vpp_event_queue (thread_index);
49   while (unix_shared_memory_queue_add (q, (u8 *) & evt, 1))
50     {
51       if (tries++ == 3)
52         {
53           SESSION_DBG ("failed to enqueue evt");
54           break;
55         }
56     }
57 }
58
59 void
60 session_send_session_evt_to_thread (u64 session_handle,
61                                     fifo_event_type_t evt_type,
62                                     u32 thread_index)
63 {
64   session_send_evt_to_thread (session_handle, evt_type, thread_index, 0, 0);
65 }
66
67 void
68 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
69 {
70   if (thread_index != vlib_get_thread_index ())
71     session_send_evt_to_thread (0, FIFO_EVENT_RPC, thread_index, fp,
72                                 rpc_args);
73   else
74     {
75       void (*fnp) (void *) = fp;
76       fnp (rpc_args);
77     }
78 }
79
80 stream_session_t *
81 session_alloc (u32 thread_index)
82 {
83   session_manager_main_t *smm = &session_manager_main;
84   stream_session_t *s;
85   u8 will_expand = 0;
86   pool_get_aligned_will_expand (smm->sessions[thread_index], will_expand,
87                                 CLIB_CACHE_LINE_BYTES);
88   /* If we have peekers, let them finish */
89   if (PREDICT_FALSE (will_expand))
90     {
91       clib_spinlock_lock_if_init (&smm->peekers_write_locks[thread_index]);
92       pool_get_aligned (session_manager_main.sessions[thread_index], s,
93                         CLIB_CACHE_LINE_BYTES);
94       clib_spinlock_unlock_if_init (&smm->peekers_write_locks[thread_index]);
95     }
96   else
97     {
98       pool_get_aligned (session_manager_main.sessions[thread_index], s,
99                         CLIB_CACHE_LINE_BYTES);
100     }
101   memset (s, 0, sizeof (*s));
102   s->session_index = s - session_manager_main.sessions[thread_index];
103   s->thread_index = thread_index;
104   return s;
105 }
106
107 static void
108 session_free (stream_session_t * s)
109 {
110   pool_put (session_manager_main.sessions[s->thread_index], s);
111   if (CLIB_DEBUG)
112     memset (s, 0xFA, sizeof (*s));
113 }
114
115 static int
116 session_alloc_fifos (segment_manager_t * sm, stream_session_t * s)
117 {
118   svm_fifo_t *server_rx_fifo = 0, *server_tx_fifo = 0;
119   u32 fifo_segment_index;
120   int rv;
121
122   if ((rv = segment_manager_alloc_session_fifos (sm, &server_rx_fifo,
123                                                  &server_tx_fifo,
124                                                  &fifo_segment_index)))
125     return rv;
126   /* Initialize backpointers */
127   server_rx_fifo->master_session_index = s->session_index;
128   server_rx_fifo->master_thread_index = s->thread_index;
129
130   server_tx_fifo->master_session_index = s->session_index;
131   server_tx_fifo->master_thread_index = s->thread_index;
132
133   s->server_rx_fifo = server_rx_fifo;
134   s->server_tx_fifo = server_tx_fifo;
135   s->svm_segment_index = fifo_segment_index;
136   return 0;
137 }
138
139 static stream_session_t *
140 session_alloc_for_connection (transport_connection_t * tc)
141 {
142   stream_session_t *s;
143   u32 thread_index = tc->thread_index;
144
145   ASSERT (thread_index == vlib_get_thread_index ());
146
147   s = session_alloc (thread_index);
148   s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
149   s->session_state = SESSION_STATE_CONNECTING;
150   s->thread_index = thread_index;
151
152   /* Attach transport to session and vice versa */
153   s->connection_index = tc->c_index;
154   tc->s_index = s->session_index;
155   return s;
156 }
157
158 static int
159 session_alloc_and_init (segment_manager_t * sm, transport_connection_t * tc,
160                         u8 alloc_fifos, stream_session_t ** ret_s)
161 {
162   stream_session_t *s;
163   int rv;
164
165   s = session_alloc_for_connection (tc);
166   if (alloc_fifos && (rv = session_alloc_fifos (sm, s)))
167     {
168       session_free (s);
169       return rv;
170     }
171
172   /* Add to the main lookup table */
173   session_lookup_add_connection (tc, session_handle (s));
174
175   *ret_s = s;
176   return 0;
177 }
178
179 /**
180  * Discards bytes from buffer chain
181  *
182  * It discards n_bytes_to_drop starting at first buffer after chain_b
183  */
184 always_inline void
185 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
186                                      vlib_buffer_t ** chain_b,
187                                      u32 n_bytes_to_drop)
188 {
189   vlib_buffer_t *next = *chain_b;
190   u32 to_drop = n_bytes_to_drop;
191   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
192   while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
193     {
194       next = vlib_get_buffer (vm, next->next_buffer);
195       if (next->current_length > to_drop)
196         {
197           vlib_buffer_advance (next, to_drop);
198           to_drop = 0;
199         }
200       else
201         {
202           to_drop -= next->current_length;
203           next->current_length = 0;
204         }
205     }
206   *chain_b = next;
207
208   if (to_drop == 0)
209     b->total_length_not_including_first_buffer -= n_bytes_to_drop;
210 }
211
212 /**
213  * Enqueue buffer chain tail
214  */
215 always_inline int
216 session_enqueue_chain_tail (stream_session_t * s, vlib_buffer_t * b,
217                             u32 offset, u8 is_in_order)
218 {
219   vlib_buffer_t *chain_b;
220   u32 chain_bi, len, diff;
221   vlib_main_t *vm = vlib_get_main ();
222   u8 *data;
223   u32 written = 0;
224   int rv = 0;
225
226   if (is_in_order && offset)
227     {
228       diff = offset - b->current_length;
229       if (diff > b->total_length_not_including_first_buffer)
230         return 0;
231       chain_b = b;
232       session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
233       chain_bi = vlib_get_buffer_index (vm, chain_b);
234     }
235   else
236     chain_bi = b->next_buffer;
237
238   do
239     {
240       chain_b = vlib_get_buffer (vm, chain_bi);
241       data = vlib_buffer_get_current (chain_b);
242       len = chain_b->current_length;
243       if (!len)
244         continue;
245       if (is_in_order)
246         {
247           rv = svm_fifo_enqueue_nowait (s->server_rx_fifo, len, data);
248           if (rv == len)
249             {
250               written += rv;
251             }
252           else if (rv < len)
253             {
254               return (rv > 0) ? (written + rv) : written;
255             }
256           else if (rv > len)
257             {
258               written += rv;
259
260               /* written more than what was left in chain */
261               if (written > b->total_length_not_including_first_buffer)
262                 return written;
263
264               /* drop the bytes that have already been delivered */
265               session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
266             }
267         }
268       else
269         {
270           rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset, len,
271                                              data);
272           if (rv)
273             {
274               clib_warning ("failed to enqueue multi-buffer seg");
275               return -1;
276             }
277           offset += len;
278         }
279     }
280   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
281           ? chain_b->next_buffer : 0));
282
283   if (is_in_order)
284     return written;
285
286   return 0;
287 }
288
289 /*
290  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
291  * event but on request can queue notification events for later delivery by
292  * calling stream_server_flush_enqueue_events().
293  *
294  * @param tc Transport connection which is to be enqueued data
295  * @param b Buffer to be enqueued
296  * @param offset Offset at which to start enqueueing if out-of-order
297  * @param queue_event Flag to indicate if peer is to be notified or if event
298  *                    is to be queued. The former is useful when more data is
299  *                    enqueued and only one event is to be generated.
300  * @param is_in_order Flag to indicate if data is in order
301  * @return Number of bytes enqueued or a negative value if enqueueing failed.
302  */
303 int
304 session_enqueue_stream_connection (transport_connection_t * tc,
305                                    vlib_buffer_t * b, u32 offset,
306                                    u8 queue_event, u8 is_in_order)
307 {
308   stream_session_t *s;
309   int enqueued = 0, rv, in_order_off;
310
311   s = session_get (tc->s_index, tc->thread_index);
312
313   if (is_in_order)
314     {
315       enqueued = svm_fifo_enqueue_nowait (s->server_rx_fifo,
316                                           b->current_length,
317                                           vlib_buffer_get_current (b));
318       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
319                          && enqueued >= 0))
320         {
321           in_order_off = enqueued > b->current_length ? enqueued : 0;
322           rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
323           if (rv > 0)
324             enqueued += rv;
325         }
326     }
327   else
328     {
329       rv = svm_fifo_enqueue_with_offset (s->server_rx_fifo, offset,
330                                          b->current_length,
331                                          vlib_buffer_get_current (b));
332       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
333         session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
334       /* if something was enqueued, report even this as success for ooo
335        * segment handling */
336       return rv;
337     }
338
339   if (queue_event)
340     {
341       /* Queue RX event on this fifo. Eventually these will need to be flushed
342        * by calling stream_server_flush_enqueue_events () */
343       session_manager_main_t *smm = vnet_get_session_manager_main ();
344       u32 thread_index = s->thread_index;
345       u32 enqueue_epoch = smm->current_enqueue_epoch[tc->proto][thread_index];
346
347       if (s->enqueue_epoch != enqueue_epoch)
348         {
349           s->enqueue_epoch = enqueue_epoch;
350           vec_add1 (smm->session_to_enqueue[tc->proto][thread_index],
351                     s - smm->sessions[thread_index]);
352         }
353     }
354
355   return enqueued;
356 }
357
358 int
359 session_enqueue_dgram_connection (stream_session_t * s, vlib_buffer_t * b,
360                                   u8 proto, u8 queue_event)
361 {
362   int enqueued = 0, rv, in_order_off;
363
364   if (svm_fifo_max_enqueue (s->server_rx_fifo) < b->current_length)
365     return -1;
366   enqueued = svm_fifo_enqueue_nowait (s->server_rx_fifo, b->current_length,
367                                       vlib_buffer_get_current (b));
368   if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued >= 0))
369     {
370       in_order_off = enqueued > b->current_length ? enqueued : 0;
371       rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
372       if (rv > 0)
373         enqueued += rv;
374     }
375   if (queue_event)
376     {
377       /* Queue RX event on this fifo. Eventually these will need to be flushed
378        * by calling stream_server_flush_enqueue_events () */
379       session_manager_main_t *smm = vnet_get_session_manager_main ();
380       u32 thread_index = s->thread_index;
381       u32 enqueue_epoch = smm->current_enqueue_epoch[proto][thread_index];
382
383       if (s->enqueue_epoch != enqueue_epoch)
384         {
385           s->enqueue_epoch = enqueue_epoch;
386           vec_add1 (smm->session_to_enqueue[proto][thread_index],
387                     s - smm->sessions[thread_index]);
388         }
389     }
390   return enqueued;
391 }
392
393 /** Check if we have space in rx fifo to push more bytes */
394 u8
395 stream_session_no_space (transport_connection_t * tc, u32 thread_index,
396                          u16 data_len)
397 {
398   stream_session_t *s = session_get (tc->s_index, thread_index);
399
400   if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY))
401     return 1;
402
403   if (data_len > svm_fifo_max_enqueue (s->server_rx_fifo))
404     return 1;
405
406   return 0;
407 }
408
409 u32
410 stream_session_tx_fifo_max_dequeue (transport_connection_t * tc)
411 {
412   stream_session_t *s = session_get (tc->s_index, tc->thread_index);
413   if (!s->server_tx_fifo)
414     return 0;
415   return svm_fifo_max_dequeue (s->server_tx_fifo);
416 }
417
418 int
419 stream_session_peek_bytes (transport_connection_t * tc, u8 * buffer,
420                            u32 offset, u32 max_bytes)
421 {
422   stream_session_t *s = session_get (tc->s_index, tc->thread_index);
423   return svm_fifo_peek (s->server_tx_fifo, offset, max_bytes, buffer);
424 }
425
426 u32
427 stream_session_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
428 {
429   stream_session_t *s = session_get (tc->s_index, tc->thread_index);
430   return svm_fifo_dequeue_drop (s->server_tx_fifo, max_bytes);
431 }
432
433 /**
434  * Notify session peer that new data has been enqueued.
435  *
436  * @param s Stream session for which the event is to be generated.
437  * @param block Flag to indicate if call should block if event queue is full.
438  *
439  * @return 0 on succes or negative number if failed to send notification.
440  */
441 static int
442 session_enqueue_notify (stream_session_t * s, u8 block)
443 {
444   application_t *app;
445   session_fifo_event_t evt;
446   unix_shared_memory_queue_t *q;
447
448   if (PREDICT_FALSE (s->session_state == SESSION_STATE_CLOSED))
449     {
450       /* Session is closed so app will never clean up. Flush rx fifo */
451       u32 to_dequeue = svm_fifo_max_dequeue (s->server_rx_fifo);
452       if (to_dequeue)
453         svm_fifo_dequeue_drop (s->server_rx_fifo, to_dequeue);
454       return 0;
455     }
456
457   /* Get session's server */
458   app = application_get_if_valid (s->app_index);
459
460   if (PREDICT_FALSE (app == 0))
461     {
462       clib_warning ("invalid s->app_index = %d", s->app_index);
463       return 0;
464     }
465
466   /* Built-in server? Hand event to the callback... */
467   if (app->cb_fns.builtin_server_rx_callback)
468     return app->cb_fns.builtin_server_rx_callback (s);
469
470   /* If no event, send one */
471   if (svm_fifo_set_event (s->server_rx_fifo))
472     {
473       /* Fabricate event */
474       evt.fifo = s->server_rx_fifo;
475       evt.event_type = FIFO_EVENT_APP_RX;
476
477       /* Add event to server's event queue */
478       q = app->event_queue;
479
480       /* Based on request block (or not) for lack of space */
481       if (block || PREDICT_TRUE (q->cursize < q->maxsize))
482         unix_shared_memory_queue_add (app->event_queue, (u8 *) & evt,
483                                       0 /* do wait for mutex */ );
484       else
485         {
486           clib_warning ("fifo full");
487           return -1;
488         }
489     }
490
491   /* *INDENT-OFF* */
492   SESSION_EVT_DBG(SESSION_EVT_ENQ, s, ({
493       ed->data[0] = evt.event_type;
494       ed->data[1] = svm_fifo_max_dequeue (s->server_rx_fifo);
495   }));
496   /* *INDENT-ON* */
497
498   return 0;
499 }
500
501 /**
502  * Flushes queue of sessions that are to be notified of new data
503  * enqueued events.
504  *
505  * @param thread_index Thread index for which the flush is to be performed.
506  * @return 0 on success or a positive number indicating the number of
507  *         failures due to API queue being full.
508  */
509 int
510 session_manager_flush_enqueue_events (u8 transport_proto, u32 thread_index)
511 {
512   session_manager_main_t *smm = &session_manager_main;
513   u32 *indices;
514   stream_session_t *s;
515   int i, errors = 0;
516
517   indices = smm->session_to_enqueue[transport_proto][thread_index];
518
519   for (i = 0; i < vec_len (indices); i++)
520     {
521       s = session_get_if_valid (indices[i], thread_index);
522       if (s == 0 || session_enqueue_notify (s, 0 /* don't block */ ))
523         errors++;
524     }
525
526   vec_reset_length (indices);
527   smm->session_to_enqueue[transport_proto][thread_index] = indices;
528   smm->current_enqueue_epoch[transport_proto][thread_index]++;
529
530   return errors;
531 }
532
533 /**
534  * Init fifo tail and head pointers
535  *
536  * Useful if transport uses absolute offsets for tracking ooo segments.
537  */
538 void
539 stream_session_init_fifos_pointers (transport_connection_t * tc,
540                                     u32 rx_pointer, u32 tx_pointer)
541 {
542   stream_session_t *s;
543   s = session_get (tc->s_index, tc->thread_index);
544   svm_fifo_init_pointers (s->server_rx_fifo, rx_pointer);
545   svm_fifo_init_pointers (s->server_tx_fifo, tx_pointer);
546 }
547
548 int
549 session_stream_connect_notify (transport_connection_t * tc, u8 is_fail)
550 {
551   application_t *app;
552   stream_session_t *new_s = 0;
553   u64 handle;
554   u32 opaque = 0;
555   int error = 0;
556   segment_manager_t *sm;
557   u8 alloc_fifos;
558
559   /*
560    * Find connection handle and cleanup half-open table
561    */
562   handle = session_lookup_half_open_handle (tc);
563   if (handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
564     {
565       SESSION_DBG ("half-open was removed!");
566       return -1;
567     }
568   session_lookup_del_half_open (tc);
569
570   /* Get the app's index from the handle we stored when opening connection
571    * and the opaque (api_context for external apps) from transport session
572    * index */
573   app = application_get_if_valid (handle >> 32);
574   if (!app)
575     return -1;
576   opaque = tc->s_index;
577
578   /*
579    * Allocate new session with fifos (svm segments are allocated if needed)
580    */
581   if (!is_fail)
582     {
583       sm = application_get_connect_segment_manager (app);
584       alloc_fifos = !application_is_builtin_proxy (app);
585       if (session_alloc_and_init (sm, tc, alloc_fifos, &new_s))
586         {
587           is_fail = 1;
588           error = -1;
589         }
590       else
591         new_s->app_index = app->index;
592     }
593
594   /*
595    * Notify client application
596    */
597   if (app->cb_fns.session_connected_callback (app->index, opaque, new_s,
598                                               is_fail))
599     {
600       SESSION_DBG ("failed to notify app");
601       if (!is_fail)
602         stream_session_disconnect (new_s);
603     }
604   else
605     {
606       if (!is_fail)
607         new_s->session_state = SESSION_STATE_READY;
608     }
609
610   return error;
611 }
612
613 typedef struct _session_switch_pool_args
614 {
615   u32 session_index;
616   u32 thread_index;
617   u32 new_thread_index;
618   u32 new_session_index;
619 } session_switch_pool_args_t;
620
621 static void
622 session_switch_pool (void *cb_args)
623 {
624   session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
625   stream_session_t *s;
626   ASSERT (args->thread_index == vlib_get_thread_index ());
627   s = session_get (args->session_index, args->thread_index);
628   s->server_tx_fifo->master_session_index = args->new_session_index;
629   s->server_tx_fifo->master_thread_index = args->new_thread_index;
630   tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
631   session_free (s);
632   clib_mem_free (cb_args);
633 }
634
635 /**
636  * Move dgram session to the right thread
637  */
638 int
639 session_dgram_connect_notify (transport_connection_t * tc,
640                               u32 old_thread_index,
641                               stream_session_t ** new_session)
642 {
643   stream_session_t *new_s;
644   session_switch_pool_args_t *rpc_args;
645
646   /*
647    * Clone half-open session to the right thread.
648    */
649   new_s = session_clone_safe (tc->s_index, old_thread_index);
650   new_s->connection_index = tc->c_index;
651   new_s->server_rx_fifo->master_session_index = new_s->session_index;
652   new_s->server_rx_fifo->master_thread_index = new_s->thread_index;
653   new_s->session_state = SESSION_STATE_READY;
654   session_lookup_add_connection (tc, session_handle (new_s));
655
656   /*
657    * Ask thread owning the old session to clean it up and make us the tx
658    * fifo owner
659    */
660   rpc_args = clib_mem_alloc (sizeof (*rpc_args));
661   rpc_args->new_session_index = new_s->session_index;
662   rpc_args->new_thread_index = new_s->thread_index;
663   rpc_args->session_index = tc->s_index;
664   rpc_args->thread_index = old_thread_index;
665   session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
666                                   rpc_args);
667
668   tc->s_index = new_s->session_index;
669   new_s->connection_index = tc->c_index;
670   *new_session = new_s;
671   return 0;
672 }
673
674 void
675 stream_session_accept_notify (transport_connection_t * tc)
676 {
677   application_t *server;
678   stream_session_t *s;
679
680   s = session_get (tc->s_index, tc->thread_index);
681   server = application_get (s->app_index);
682   server->cb_fns.session_accept_callback (s);
683 }
684
685 /**
686  * Notification from transport that connection is being closed.
687  *
688  * A disconnect is sent to application but state is not removed. Once
689  * disconnect is acknowledged by application, session disconnect is called.
690  * Ultimately this leads to close being called on transport (passive close).
691  */
692 void
693 stream_session_disconnect_notify (transport_connection_t * tc)
694 {
695   application_t *server;
696   stream_session_t *s;
697
698   s = session_get (tc->s_index, tc->thread_index);
699   server = application_get (s->app_index);
700   server->cb_fns.session_disconnect_callback (s);
701 }
702
703 /**
704  * Cleans up session and lookup table.
705  */
706 void
707 stream_session_delete (stream_session_t * s)
708 {
709   int rv;
710
711   /* Delete from the main lookup table. */
712   if ((rv = session_lookup_del_session (s)))
713     clib_warning ("hash delete error, rv %d", rv);
714
715   /* Cleanup fifo segments */
716   segment_manager_dealloc_fifos (s->svm_segment_index, s->server_rx_fifo,
717                                  s->server_tx_fifo);
718   session_free (s);
719 }
720
721 /**
722  * Notification from transport that connection is being deleted
723  *
724  * This removes the session if it is still valid. It should be called only on
725  * previously fully established sessions. For instance failed connects should
726  * call stream_session_connect_notify and indicate that the connect has
727  * failed.
728  */
729 void
730 stream_session_delete_notify (transport_connection_t * tc)
731 {
732   stream_session_t *s;
733
734   /* App might've been removed already */
735   s = session_get_if_valid (tc->s_index, tc->thread_index);
736   if (!s)
737     return;
738   stream_session_delete (s);
739 }
740
741 /**
742  * Notify application that connection has been reset.
743  */
744 void
745 stream_session_reset_notify (transport_connection_t * tc)
746 {
747   stream_session_t *s;
748   application_t *app;
749   s = session_get (tc->s_index, tc->thread_index);
750
751   app = application_get (s->app_index);
752   app->cb_fns.session_reset_callback (s);
753 }
754
755 /**
756  * Accept a stream session. Optionally ping the server by callback.
757  */
758 int
759 stream_session_accept (transport_connection_t * tc, u32 listener_index,
760                        u8 notify)
761 {
762   application_t *server;
763   stream_session_t *s, *listener;
764   segment_manager_t *sm;
765   session_type_t sst;
766   int rv;
767
768   sst = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
769
770   /* Find the server */
771   listener = listen_session_get (sst, listener_index);
772   server = application_get (listener->app_index);
773
774   sm = application_get_listen_segment_manager (server, listener);
775   if ((rv = session_alloc_and_init (sm, tc, 1, &s)))
776     return rv;
777
778   s->app_index = server->index;
779   s->listener_index = listener_index;
780   s->session_state = SESSION_STATE_ACCEPTING;
781
782   /* Shoulder-tap the server */
783   if (notify)
784     {
785       server->cb_fns.session_accept_callback (s);
786     }
787
788   return 0;
789 }
790
791 /**
792  * Ask transport to open connection to remote transport endpoint.
793  *
794  * Stores handle for matching request with reply since the call can be
795  * asynchronous. For instance, for TCP the 3-way handshake must complete
796  * before reply comes. Session is only created once connection is established.
797  *
798  * @param app_index Index of the application requesting the connect
799  * @param st Session type requested.
800  * @param tep Remote transport endpoint
801  * @param opaque Opaque data (typically, api_context) the application expects
802  *               on open completion.
803  */
804 int
805 session_open (u32 app_index, session_endpoint_t * rmt, u32 opaque)
806 {
807   transport_connection_t *tc;
808   session_type_t sst;
809   segment_manager_t *sm;
810   stream_session_t *s;
811   application_t *app;
812   int rv;
813   u64 handle;
814
815   sst = session_type_from_proto_and_ip (rmt->transport_proto, rmt->is_ip4);
816   rv = tp_vfts[sst].open (session_endpoint_to_transport (rmt));
817   if (rv < 0)
818     {
819       SESSION_DBG ("Transport failed to open connection.");
820       return VNET_API_ERROR_SESSION_CONNECT;
821     }
822
823   tc = tp_vfts[sst].get_half_open ((u32) rv);
824
825   /* If transport offers a stream service, only allocate session once the
826    * connection has been established.
827    */
828   if (transport_is_stream (rmt->transport_proto))
829     {
830       /* Add connection to half-open table and save app and tc index. The
831        * latter is needed to help establish the connection while the former
832        * is needed when the connect notify comes and we have to notify the
833        * external app
834        */
835       handle = (((u64) app_index) << 32) | (u64) tc->c_index;
836       session_lookup_add_half_open (tc, handle);
837
838       /* Store api_context (opaque) for when the reply comes. Not the nicest
839        * thing but better than allocating a separate half-open pool.
840        */
841       tc->s_index = opaque;
842     }
843   /* For dgram type of service, allocate session and fifos now.
844    */
845   else
846     {
847       app = application_get (app_index);
848       sm = application_get_connect_segment_manager (app);
849
850       if (session_alloc_and_init (sm, tc, 1, &s))
851         return -1;
852       s->app_index = app->index;
853       s->session_state = SESSION_STATE_CONNECTING_READY;
854
855       /* Tell the app about the new event fifo for this session */
856       app->cb_fns.session_connected_callback (app->index, opaque, s, 0);
857     }
858   return 0;
859 }
860
861 /**
862  * Ask transport to listen on local transport endpoint.
863  *
864  * @param s Session for which listen will be called. Note that unlike
865  *          established sessions, listen sessions are not associated to a
866  *          thread.
867  * @param tep Local endpoint to be listened on.
868  */
869 int
870 stream_session_listen (stream_session_t * s, session_endpoint_t * sep)
871 {
872   transport_connection_t *tc;
873   u32 tci;
874
875   /* Transport bind/listen  */
876   tci = tp_vfts[s->session_type].bind (s->session_index,
877                                        session_endpoint_to_transport (sep));
878
879   if (tci == (u32) ~ 0)
880     return -1;
881
882   /* Attach transport to session */
883   s->connection_index = tci;
884   tc = tp_vfts[s->session_type].get_listener (tci);
885
886   /* Weird but handle it ... */
887   if (tc == 0)
888     return -1;
889
890   /* Add to the main lookup table */
891   session_lookup_add_connection (tc, s->session_index);
892   return 0;
893 }
894
895 /**
896  * Ask transport to stop listening on local transport endpoint.
897  *
898  * @param s Session to stop listening on. It must be in state LISTENING.
899  */
900 int
901 stream_session_stop_listen (stream_session_t * s)
902 {
903   transport_connection_t *tc;
904
905   if (s->session_state != SESSION_STATE_LISTENING)
906     {
907       clib_warning ("not a listening session");
908       return -1;
909     }
910
911   tc = tp_vfts[s->session_type].get_listener (s->connection_index);
912   if (!tc)
913     {
914       clib_warning ("no transport");
915       return VNET_API_ERROR_ADDRESS_NOT_IN_USE;
916     }
917
918   session_lookup_del_connection (tc);
919   tp_vfts[s->session_type].unbind (s->connection_index);
920   return 0;
921 }
922
923 /**
924  * Disconnect session and propagate to transport. This should eventually
925  * result in a delete notification that allows us to cleanup session state.
926  * Called for both active/passive disconnects.
927  *
928  * Should be called from the session's thread.
929  */
930 void
931 stream_session_disconnect (stream_session_t * s)
932 {
933   s->session_state = SESSION_STATE_CLOSED;
934   tp_vfts[s->session_type].close (s->connection_index, s->thread_index);
935 }
936
937 /**
938  * Cleanup transport and session state.
939  *
940  * Notify transport of the cleanup, wait for a delete notify to actually
941  * remove the session state.
942  */
943 void
944 stream_session_cleanup (stream_session_t * s)
945 {
946   int rv;
947
948   s->session_state = SESSION_STATE_CLOSED;
949
950   /* Delete from the main lookup table to avoid more enqueues */
951   rv = session_lookup_del_session (s);
952   if (rv)
953     clib_warning ("hash delete error, rv %d", rv);
954
955   tp_vfts[s->session_type].cleanup (s->connection_index, s->thread_index);
956 }
957
958 /**
959  * Allocate vpp event queue (once) per worker thread
960  */
961 void
962 session_vpp_event_queue_allocate (session_manager_main_t * smm,
963                                   u32 thread_index)
964 {
965   api_main_t *am = &api_main;
966   void *oldheap;
967   u32 event_queue_length = 2048;
968
969   if (smm->vpp_event_queues[thread_index] == 0)
970     {
971       /* Allocate event fifo in the /vpe-api shared-memory segment */
972       oldheap = svm_push_data_heap (am->vlib_rp);
973
974       if (smm->configured_event_queue_length)
975         event_queue_length = smm->configured_event_queue_length;
976
977       smm->vpp_event_queues[thread_index] =
978         unix_shared_memory_queue_init
979         (event_queue_length,
980          sizeof (session_fifo_event_t), 0 /* consumer pid */ ,
981          0 /* (do not) send signal when queue non-empty */ );
982
983       svm_pop_heap (oldheap);
984     }
985 }
986
987 session_type_t
988 session_type_from_proto_and_ip (transport_proto_t proto, u8 is_ip4)
989 {
990   if (proto == TRANSPORT_PROTO_TCP)
991     {
992       if (is_ip4)
993         return SESSION_TYPE_IP4_TCP;
994       else
995         return SESSION_TYPE_IP6_TCP;
996     }
997   else
998     {
999       if (is_ip4)
1000         return SESSION_TYPE_IP4_UDP;
1001       else
1002         return SESSION_TYPE_IP6_UDP;
1003     }
1004
1005   return SESSION_N_TYPES;
1006 }
1007
1008 transport_connection_t *
1009 session_get_transport (stream_session_t * s)
1010 {
1011   if (s->session_state != SESSION_STATE_LISTENING)
1012     return tp_vfts[s->session_type].get_connection (s->connection_index,
1013                                                     s->thread_index);
1014   return 0;
1015 }
1016
1017 transport_connection_t *
1018 listen_session_get_transport (stream_session_t * s)
1019 {
1020   return tp_vfts[s->session_type].get_listener (s->connection_index);
1021 }
1022
1023 int
1024 listen_session_get_local_session_endpoint (stream_session_t * listener,
1025                                            session_endpoint_t * sep)
1026 {
1027   transport_connection_t *tc;
1028   tc =
1029     tp_vfts[listener->session_type].get_listener (listener->connection_index);
1030   if (!tc)
1031     {
1032       clib_warning ("no transport");
1033       return -1;
1034     }
1035
1036   /* N.B. The ip should not be copied because this is the local endpoint */
1037   sep->port = tc->lcl_port;
1038   sep->transport_proto = tc->proto;
1039   sep->is_ip4 = tc->is_ip4;
1040   return 0;
1041 }
1042
1043 static clib_error_t *
1044 session_manager_main_enable (vlib_main_t * vm)
1045 {
1046   session_manager_main_t *smm = &session_manager_main;
1047   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1048   u32 num_threads;
1049   u32 preallocated_sessions_per_worker;
1050   int i, j;
1051
1052   num_threads = 1 /* main thread */  + vtm->n_threads;
1053
1054   if (num_threads < 1)
1055     return clib_error_return (0, "n_thread_stacks not set");
1056
1057   /* $$$ config parameters */
1058   svm_fifo_segment_init (0x200000000ULL /* first segment base VA */ ,
1059                          20 /* timeout in seconds */ );
1060
1061   /* configure per-thread ** vectors */
1062   vec_validate (smm->sessions, num_threads - 1);
1063   vec_validate (smm->tx_buffers, num_threads - 1);
1064   vec_validate (smm->pending_event_vector, num_threads - 1);
1065   vec_validate (smm->pending_disconnects, num_threads - 1);
1066   vec_validate (smm->free_event_vector, num_threads - 1);
1067   vec_validate (smm->vpp_event_queues, num_threads - 1);
1068   vec_validate (smm->session_peekers, num_threads - 1);
1069   vec_validate (smm->peekers_readers_locks, num_threads - 1);
1070   vec_validate (smm->peekers_write_locks, num_threads - 1);
1071
1072   for (i = 0; i < TRANSPORT_N_PROTO; i++)
1073     for (j = 0; j < num_threads; j++)
1074       {
1075         vec_validate (smm->session_to_enqueue[i], num_threads - 1);
1076         vec_validate (smm->current_enqueue_epoch[i], num_threads - 1);
1077       }
1078
1079   for (i = 0; i < num_threads; i++)
1080     {
1081       vec_validate (smm->free_event_vector[i], 0);
1082       _vec_len (smm->free_event_vector[i]) = 0;
1083       vec_validate (smm->pending_event_vector[i], 0);
1084       _vec_len (smm->pending_event_vector[i]) = 0;
1085       vec_validate (smm->pending_disconnects[i], 0);
1086       _vec_len (smm->pending_disconnects[i]) = 0;
1087     }
1088
1089 #if SESSION_DBG
1090   vec_validate (smm->last_event_poll_by_thread, num_threads - 1);
1091 #endif
1092
1093   /* Allocate vpp event queues */
1094   for (i = 0; i < vec_len (smm->vpp_event_queues); i++)
1095     session_vpp_event_queue_allocate (smm, i);
1096
1097   /* Preallocate sessions */
1098   if (smm->preallocated_sessions)
1099     {
1100       if (num_threads == 1)
1101         {
1102           pool_init_fixed (smm->sessions[0], smm->preallocated_sessions);
1103         }
1104       else
1105         {
1106           int j;
1107           preallocated_sessions_per_worker =
1108             (1.1 * (f64) smm->preallocated_sessions /
1109              (f64) (num_threads - 1));
1110
1111           for (j = 1; j < num_threads; j++)
1112             {
1113               pool_init_fixed (smm->sessions[j],
1114                                preallocated_sessions_per_worker);
1115             }
1116         }
1117     }
1118
1119   session_lookup_init ();
1120   app_namespaces_init ();
1121   transport_init ();
1122
1123   smm->is_enabled = 1;
1124
1125   /* Enable TCP transport */
1126   vnet_tcp_enable_disable (vm, 1);
1127
1128   return 0;
1129 }
1130
1131 void
1132 session_node_enable_disable (u8 is_en)
1133 {
1134   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1135   /* *INDENT-OFF* */
1136   foreach_vlib_main (({
1137     vlib_node_set_state (this_vlib_main, session_queue_node.index,
1138                          state);
1139   }));
1140   /* *INDENT-ON* */
1141 }
1142
1143 clib_error_t *
1144 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1145 {
1146   clib_error_t *error = 0;
1147   if (is_en)
1148     {
1149       if (session_manager_main.is_enabled)
1150         return 0;
1151
1152       session_node_enable_disable (is_en);
1153       error = session_manager_main_enable (vm);
1154     }
1155   else
1156     {
1157       session_manager_main.is_enabled = 0;
1158       session_node_enable_disable (is_en);
1159     }
1160
1161   return error;
1162 }
1163
1164 clib_error_t *
1165 session_manager_main_init (vlib_main_t * vm)
1166 {
1167   session_manager_main_t *smm = &session_manager_main;
1168   smm->is_enabled = 0;
1169   return 0;
1170 }
1171
1172 VLIB_INIT_FUNCTION (session_manager_main_init);
1173
1174 static clib_error_t *
1175 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1176 {
1177   session_manager_main_t *smm = &session_manager_main;
1178   u32 nitems;
1179   uword tmp;
1180
1181   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1182     {
1183       if (unformat (input, "event-queue-length %d", &nitems))
1184         {
1185           if (nitems >= 2048)
1186             smm->configured_event_queue_length = nitems;
1187           else
1188             clib_warning ("event queue length %d too small, ignored", nitems);
1189         }
1190       else if (unformat (input, "preallocated-sessions %d",
1191                          &smm->preallocated_sessions))
1192         ;
1193       else if (unformat (input, "v4-session-table-buckets %d",
1194                          &smm->configured_v4_session_table_buckets))
1195         ;
1196       else if (unformat (input, "v4-halfopen-table-buckets %d",
1197                          &smm->configured_v4_halfopen_table_buckets))
1198         ;
1199       else if (unformat (input, "v6-session-table-buckets %d",
1200                          &smm->configured_v6_session_table_buckets))
1201         ;
1202       else if (unformat (input, "v6-halfopen-table-buckets %d",
1203                          &smm->configured_v6_halfopen_table_buckets))
1204         ;
1205       else if (unformat (input, "v4-session-table-memory %U",
1206                          unformat_memory_size, &tmp))
1207         {
1208           if (tmp >= 0x100000000)
1209             return clib_error_return (0, "memory size %llx (%lld) too large",
1210                                       tmp, tmp);
1211           smm->configured_v4_session_table_memory = tmp;
1212         }
1213       else if (unformat (input, "v4-halfopen-table-memory %U",
1214                          unformat_memory_size, &tmp))
1215         {
1216           if (tmp >= 0x100000000)
1217             return clib_error_return (0, "memory size %llx (%lld) too large",
1218                                       tmp, tmp);
1219           smm->configured_v4_halfopen_table_memory = tmp;
1220         }
1221       else if (unformat (input, "v6-session-table-memory %U",
1222                          unformat_memory_size, &tmp))
1223         {
1224           if (tmp >= 0x100000000)
1225             return clib_error_return (0, "memory size %llx (%lld) too large",
1226                                       tmp, tmp);
1227           smm->configured_v6_session_table_memory = tmp;
1228         }
1229       else if (unformat (input, "v6-halfopen-table-memory %U",
1230                          unformat_memory_size, &tmp))
1231         {
1232           if (tmp >= 0x100000000)
1233             return clib_error_return (0, "memory size %llx (%lld) too large",
1234                                       tmp, tmp);
1235           smm->configured_v6_halfopen_table_memory = tmp;
1236         }
1237       else
1238         return clib_error_return (0, "unknown input `%U'",
1239                                   format_unformat_error, input);
1240     }
1241   return 0;
1242 }
1243
1244 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1245
1246 /*
1247  * fd.io coding-style-patch-verification: ON
1248  *
1249  * Local Variables:
1250  * eval: (c-set-style "gnu")
1251  * End:
1252  */