caa362e1f1d091f74a543d88be8e9468626dd4c8
[vpp.git] / src / vnet / session / session.c
1 /*
2  * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /**
16  * @file
17  * @brief Session and session manager
18  */
19
20 #include <vnet/session/session.h>
21 #include <vnet/session/session_debug.h>
22 #include <vnet/session/application.h>
23 #include <vnet/dpo/load_balance.h>
24 #include <vnet/fib/ip4_fib.h>
25
26 session_main_t session_main;
27
28 #if SESSION_DEBUG
29 session_dbg_main_t session_dbg_main;
30 #endif
31
32 static inline int
33 session_send_evt_to_thread (void *data, void *args, u32 thread_index,
34                             session_evt_type_t evt_type)
35 {
36   session_event_t *evt;
37   svm_msg_q_msg_t msg;
38   svm_msg_q_t *mq;
39
40   mq = session_main_get_vpp_event_queue (thread_index);
41   if (PREDICT_FALSE (svm_msg_q_lock (mq)))
42     return -1;
43   if (PREDICT_FALSE (svm_msg_q_is_full (mq)
44                      || svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
45     {
46       svm_msg_q_unlock (mq);
47       return -2;
48     }
49   switch (evt_type)
50     {
51     case SESSION_CTRL_EVT_RPC:
52       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
53       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
54       evt->rpc_args.fp = data;
55       evt->rpc_args.arg = args;
56       break;
57     case SESSION_IO_EVT_RX:
58     case SESSION_IO_EVT_TX:
59     case SESSION_IO_EVT_TX_FLUSH:
60     case SESSION_IO_EVT_BUILTIN_RX:
61       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
62       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
63       evt->session_index = *(u32 *) data;
64       break;
65     case SESSION_IO_EVT_BUILTIN_TX:
66     case SESSION_CTRL_EVT_CLOSE:
67     case SESSION_CTRL_EVT_RESET:
68       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
69       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
70       evt->session_handle = session_handle ((session_t *) data);
71       break;
72     default:
73       clib_warning ("evt unhandled!");
74       svm_msg_q_unlock (mq);
75       return -1;
76     }
77   evt->event_type = evt_type;
78
79   svm_msg_q_add_and_unlock (mq, &msg);
80   return 0;
81 }
82
83 int
84 session_send_io_evt_to_thread (svm_fifo_t * f, session_evt_type_t evt_type)
85 {
86   return session_send_evt_to_thread (&f->master_session_index, 0,
87                                      f->master_thread_index, evt_type);
88 }
89
90 int
91 session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
92                                       session_evt_type_t evt_type)
93 {
94   return session_send_evt_to_thread (data, 0, thread_index, evt_type);
95 }
96
97 int
98 session_send_ctrl_evt_to_thread (session_t * s, session_evt_type_t evt_type)
99 {
100   /* only events supported are disconnect and reset */
101   ASSERT (evt_type == SESSION_CTRL_EVT_CLOSE
102           || evt_type == SESSION_CTRL_EVT_RESET);
103   return session_send_evt_to_thread (s, 0, s->thread_index, evt_type);
104 }
105
106 void
107 session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
108                                       void *rpc_args)
109 {
110   session_send_evt_to_thread (fp, rpc_args, thread_index,
111                               SESSION_CTRL_EVT_RPC);
112 }
113
114 void
115 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
116 {
117   if (thread_index != vlib_get_thread_index ())
118     session_send_rpc_evt_to_thread_force (thread_index, fp, rpc_args);
119   else
120     {
121       void (*fnp) (void *) = fp;
122       fnp (rpc_args);
123     }
124 }
125
126 void
127 session_add_self_custom_tx_evt (transport_connection_t * tc, u8 has_prio)
128 {
129   session_t *s;
130
131   s = session_get (tc->s_index, tc->thread_index);
132   ASSERT (s->thread_index == vlib_get_thread_index ());
133   ASSERT (s->session_state != SESSION_STATE_TRANSPORT_DELETED);
134   if (!(s->flags & SESSION_F_CUSTOM_TX))
135     {
136       s->flags |= SESSION_F_CUSTOM_TX;
137       if (svm_fifo_set_event (s->tx_fifo)
138           || transport_connection_is_descheduled (tc))
139         {
140           session_worker_t *wrk;
141           session_evt_elt_t *elt;
142           wrk = session_main_get_worker (tc->thread_index);
143           if (has_prio)
144             elt = session_evt_alloc_new (wrk);
145           else
146             elt = session_evt_alloc_old (wrk);
147           elt->evt.session_index = tc->s_index;
148           elt->evt.event_type = SESSION_IO_EVT_TX;
149           tc->flags &= ~TRANSPORT_CONNECTION_F_DESCHED;
150         }
151     }
152 }
153
154 void
155 sesssion_reschedule_tx (transport_connection_t * tc)
156 {
157   session_worker_t *wrk = session_main_get_worker (tc->thread_index);
158   session_evt_elt_t *elt;
159
160   ASSERT (tc->thread_index == vlib_get_thread_index ());
161
162   elt = session_evt_alloc_new (wrk);
163   elt->evt.session_index = tc->s_index;
164   elt->evt.event_type = SESSION_IO_EVT_TX;
165 }
166
167 static void
168 session_program_transport_ctrl_evt (session_t * s, session_evt_type_t evt)
169 {
170   u32 thread_index = vlib_get_thread_index ();
171   session_evt_elt_t *elt;
172   session_worker_t *wrk;
173
174   /* If we are in the handler thread, or being called with the worker barrier
175    * held, just append a new event to pending disconnects vector. */
176   if (vlib_thread_is_main_w_barrier () || thread_index == s->thread_index)
177     {
178       wrk = session_main_get_worker (s->thread_index);
179       elt = session_evt_alloc_ctrl (wrk);
180       clib_memset (&elt->evt, 0, sizeof (session_event_t));
181       elt->evt.session_handle = session_handle (s);
182       elt->evt.event_type = evt;
183     }
184   else
185     session_send_ctrl_evt_to_thread (s, evt);
186 }
187
188 session_t *
189 session_alloc (u32 thread_index)
190 {
191   session_worker_t *wrk = &session_main.wrk[thread_index];
192   session_t *s;
193   u8 will_expand = 0;
194   pool_get_aligned_will_expand (wrk->sessions, will_expand,
195                                 CLIB_CACHE_LINE_BYTES);
196   /* If we have peekers, let them finish */
197   if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
198     {
199       clib_rwlock_writer_lock (&wrk->peekers_rw_locks);
200       pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
201       clib_rwlock_writer_unlock (&wrk->peekers_rw_locks);
202     }
203   else
204     {
205       pool_get_aligned (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
206     }
207   clib_memset (s, 0, sizeof (*s));
208   s->session_index = s - wrk->sessions;
209   s->thread_index = thread_index;
210   s->app_index = APP_INVALID_INDEX;
211   return s;
212 }
213
214 void
215 session_free (session_t * s)
216 {
217   if (CLIB_DEBUG)
218     {
219       u8 thread_index = s->thread_index;
220       clib_memset (s, 0xFA, sizeof (*s));
221       pool_put (session_main.wrk[thread_index].sessions, s);
222       return;
223     }
224   SESSION_EVT (SESSION_EVT_FREE, s);
225   pool_put (session_main.wrk[s->thread_index].sessions, s);
226 }
227
228 u8
229 session_is_valid (u32 si, u8 thread_index)
230 {
231   session_t *s;
232   transport_connection_t *tc;
233
234   s = pool_elt_at_index (session_main.wrk[thread_index].sessions, si);
235
236   if (!s)
237     return 1;
238
239   if (s->thread_index != thread_index || s->session_index != si)
240     return 0;
241
242   if (s->session_state == SESSION_STATE_TRANSPORT_DELETED
243       || s->session_state <= SESSION_STATE_LISTENING)
244     return 1;
245
246   tc = session_get_transport (s);
247   if (s->connection_index != tc->c_index
248       || s->thread_index != tc->thread_index || tc->s_index != si)
249     return 0;
250
251   return 1;
252 }
253
254 static void
255 session_cleanup_notify (session_t * s, session_cleanup_ntf_t ntf)
256 {
257   app_worker_t *app_wrk;
258
259   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
260   if (!app_wrk)
261     return;
262   app_worker_cleanup_notify (app_wrk, s, ntf);
263 }
264
265 void
266 session_free_w_fifos (session_t * s)
267 {
268   session_cleanup_notify (s, SESSION_CLEANUP_SESSION);
269   segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
270   session_free (s);
271 }
272
273 /**
274  * Cleans up session and lookup table.
275  *
276  * Transport connection must still be valid.
277  */
278 static void
279 session_delete (session_t * s)
280 {
281   int rv;
282
283   /* Delete from the main lookup table. */
284   if ((rv = session_lookup_del_session (s)))
285     clib_warning ("session %u hash delete rv %d", s->session_index, rv);
286
287   session_free_w_fifos (s);
288 }
289
290 session_t *
291 session_alloc_for_connection (transport_connection_t * tc)
292 {
293   session_t *s;
294   u32 thread_index = tc->thread_index;
295
296   ASSERT (thread_index == vlib_get_thread_index ()
297           || transport_protocol_is_cl (tc->proto));
298
299   s = session_alloc (thread_index);
300   s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
301   s->session_state = SESSION_STATE_CLOSED;
302
303   /* Attach transport to session and vice versa */
304   s->connection_index = tc->c_index;
305   tc->s_index = s->session_index;
306   return s;
307 }
308
309 /**
310  * Discards bytes from buffer chain
311  *
312  * It discards n_bytes_to_drop starting at first buffer after chain_b
313  */
314 always_inline void
315 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
316                                      vlib_buffer_t ** chain_b,
317                                      u32 n_bytes_to_drop)
318 {
319   vlib_buffer_t *next = *chain_b;
320   u32 to_drop = n_bytes_to_drop;
321   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
322   while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
323     {
324       next = vlib_get_buffer (vm, next->next_buffer);
325       if (next->current_length > to_drop)
326         {
327           vlib_buffer_advance (next, to_drop);
328           to_drop = 0;
329         }
330       else
331         {
332           to_drop -= next->current_length;
333           next->current_length = 0;
334         }
335     }
336   *chain_b = next;
337
338   if (to_drop == 0)
339     b->total_length_not_including_first_buffer -= n_bytes_to_drop;
340 }
341
342 /**
343  * Enqueue buffer chain tail
344  */
345 always_inline int
346 session_enqueue_chain_tail (session_t * s, vlib_buffer_t * b,
347                             u32 offset, u8 is_in_order)
348 {
349   vlib_buffer_t *chain_b;
350   u32 chain_bi, len, diff;
351   vlib_main_t *vm = vlib_get_main ();
352   u8 *data;
353   u32 written = 0;
354   int rv = 0;
355
356   if (is_in_order && offset)
357     {
358       diff = offset - b->current_length;
359       if (diff > b->total_length_not_including_first_buffer)
360         return 0;
361       chain_b = b;
362       session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
363       chain_bi = vlib_get_buffer_index (vm, chain_b);
364     }
365   else
366     chain_bi = b->next_buffer;
367
368   do
369     {
370       chain_b = vlib_get_buffer (vm, chain_bi);
371       data = vlib_buffer_get_current (chain_b);
372       len = chain_b->current_length;
373       if (!len)
374         continue;
375       if (is_in_order)
376         {
377           rv = svm_fifo_enqueue (s->rx_fifo, len, data);
378           if (rv == len)
379             {
380               written += rv;
381             }
382           else if (rv < len)
383             {
384               return (rv > 0) ? (written + rv) : written;
385             }
386           else if (rv > len)
387             {
388               written += rv;
389
390               /* written more than what was left in chain */
391               if (written > b->total_length_not_including_first_buffer)
392                 return written;
393
394               /* drop the bytes that have already been delivered */
395               session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
396             }
397         }
398       else
399         {
400           rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset, len, data);
401           if (rv)
402             {
403               clib_warning ("failed to enqueue multi-buffer seg");
404               return -1;
405             }
406           offset += len;
407         }
408     }
409   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
410           ? chain_b->next_buffer : 0));
411
412   if (is_in_order)
413     return written;
414
415   return 0;
416 }
417
418 void
419 session_fifo_tuning (session_t * s, svm_fifo_t * f,
420                      session_ft_action_t act, u32 len)
421 {
422   if (s->flags & SESSION_F_CUSTOM_FIFO_TUNING)
423     {
424       app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
425       app_worker_session_fifo_tuning (app_wrk, s, f, act, len);
426       if (CLIB_ASSERT_ENABLE)
427         {
428           segment_manager_t *sm;
429           sm = segment_manager_get (f->segment_manager);
430           ASSERT (f->size >= 4096);
431           ASSERT (f->size <= sm->max_fifo_size);
432         }
433     }
434 }
435
436 /*
437  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
438  * event but on request can queue notification events for later delivery by
439  * calling stream_server_flush_enqueue_events().
440  *
441  * @param tc Transport connection which is to be enqueued data
442  * @param b Buffer to be enqueued
443  * @param offset Offset at which to start enqueueing if out-of-order
444  * @param queue_event Flag to indicate if peer is to be notified or if event
445  *                    is to be queued. The former is useful when more data is
446  *                    enqueued and only one event is to be generated.
447  * @param is_in_order Flag to indicate if data is in order
448  * @return Number of bytes enqueued or a negative value if enqueueing failed.
449  */
450 int
451 session_enqueue_stream_connection (transport_connection_t * tc,
452                                    vlib_buffer_t * b, u32 offset,
453                                    u8 queue_event, u8 is_in_order)
454 {
455   session_t *s;
456   int enqueued = 0, rv, in_order_off;
457
458   s = session_get (tc->s_index, tc->thread_index);
459
460   if (is_in_order)
461     {
462       enqueued = svm_fifo_enqueue (s->rx_fifo,
463                                    b->current_length,
464                                    vlib_buffer_get_current (b));
465       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
466                          && enqueued >= 0))
467         {
468           in_order_off = enqueued > b->current_length ? enqueued : 0;
469           rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
470           if (rv > 0)
471             enqueued += rv;
472         }
473     }
474   else
475     {
476       rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset,
477                                          b->current_length,
478                                          vlib_buffer_get_current (b));
479       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
480         session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
481       /* if something was enqueued, report even this as success for ooo
482        * segment handling */
483       return rv;
484     }
485
486   if (queue_event)
487     {
488       /* Queue RX event on this fifo. Eventually these will need to be flushed
489        * by calling stream_server_flush_enqueue_events () */
490       session_worker_t *wrk;
491
492       wrk = session_main_get_worker (s->thread_index);
493       if (!(s->flags & SESSION_F_RX_EVT))
494         {
495           s->flags |= SESSION_F_RX_EVT;
496           vec_add1 (wrk->session_to_enqueue[tc->proto], s->session_index);
497         }
498
499       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED, 0);
500     }
501
502   return enqueued;
503 }
504
505 int
506 session_enqueue_dgram_connection (session_t * s,
507                                   session_dgram_hdr_t * hdr,
508                                   vlib_buffer_t * b, u8 proto, u8 queue_event)
509 {
510   int enqueued = 0, rv, in_order_off;
511
512   ASSERT (svm_fifo_max_enqueue_prod (s->rx_fifo)
513           >= b->current_length + sizeof (*hdr));
514
515   svm_fifo_enqueue (s->rx_fifo, sizeof (session_dgram_hdr_t), (u8 *) hdr);
516   enqueued = svm_fifo_enqueue (s->rx_fifo, b->current_length,
517                                vlib_buffer_get_current (b));
518   if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && enqueued >= 0))
519     {
520       in_order_off = enqueued > b->current_length ? enqueued : 0;
521       rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
522       if (rv > 0)
523         enqueued += rv;
524     }
525   if (queue_event)
526     {
527       /* Queue RX event on this fifo. Eventually these will need to be flushed
528        * by calling stream_server_flush_enqueue_events () */
529       session_worker_t *wrk;
530
531       wrk = session_main_get_worker (s->thread_index);
532       if (!(s->flags & SESSION_F_RX_EVT))
533         {
534           s->flags |= SESSION_F_RX_EVT;
535           vec_add1 (wrk->session_to_enqueue[proto], s->session_index);
536         }
537
538       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED, 0);
539     }
540   return enqueued;
541 }
542
543 int
544 session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
545                             u32 offset, u32 max_bytes)
546 {
547   session_t *s = session_get (tc->s_index, tc->thread_index);
548   return svm_fifo_peek (s->tx_fifo, offset, max_bytes, buffer);
549 }
550
551 u32
552 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
553 {
554   session_t *s = session_get (tc->s_index, tc->thread_index);
555   u32 rv;
556
557   rv = svm_fifo_dequeue_drop (s->tx_fifo, max_bytes);
558   session_fifo_tuning (s, s->tx_fifo, SESSION_FT_ACTION_DEQUEUED, rv);
559
560   if (svm_fifo_needs_deq_ntf (s->tx_fifo, max_bytes))
561     session_dequeue_notify (s);
562
563   return rv;
564 }
565
566 static inline int
567 session_notify_subscribers (u32 app_index, session_t * s,
568                             svm_fifo_t * f, session_evt_type_t evt_type)
569 {
570   app_worker_t *app_wrk;
571   application_t *app;
572   int i;
573
574   app = application_get (app_index);
575   if (!app)
576     return -1;
577
578   for (i = 0; i < f->n_subscribers; i++)
579     {
580       app_wrk = application_get_worker (app, f->subscribers[i]);
581       if (!app_wrk)
582         continue;
583       if (app_worker_lock_and_send_event (app_wrk, s, evt_type))
584         return -1;
585     }
586
587   return 0;
588 }
589
590 /**
591  * Notify session peer that new data has been enqueued.
592  *
593  * @param s     Stream session for which the event is to be generated.
594  * @param lock  Flag to indicate if call should lock message queue.
595  *
596  * @return 0 on success or negative number if failed to send notification.
597  */
598 static inline int
599 session_enqueue_notify_inline (session_t * s)
600 {
601   app_worker_t *app_wrk;
602   u32 session_index;
603   u8 n_subscribers;
604
605   session_index = s->session_index;
606   n_subscribers = svm_fifo_n_subscribers (s->rx_fifo);
607
608   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
609   if (PREDICT_FALSE (!app_wrk))
610     {
611       SESSION_DBG ("invalid s->app_index = %d", s->app_wrk_index);
612       return 0;
613     }
614
615   SESSION_EVT (SESSION_EVT_ENQ, s, svm_fifo_max_dequeue_prod (s->rx_fifo));
616
617   s->flags &= ~SESSION_F_RX_EVT;
618   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
619                                                      SESSION_IO_EVT_RX)))
620     return -1;
621
622   if (PREDICT_FALSE (n_subscribers))
623     {
624       s = session_get (session_index, vlib_get_thread_index ());
625       return session_notify_subscribers (app_wrk->app_index, s,
626                                          s->rx_fifo, SESSION_IO_EVT_RX);
627     }
628
629   return 0;
630 }
631
632 int
633 session_enqueue_notify (session_t * s)
634 {
635   return session_enqueue_notify_inline (s);
636 }
637
638 static void
639 session_enqueue_notify_rpc (void *arg)
640 {
641   u32 session_index = pointer_to_uword (arg);
642   session_t *s;
643
644   s = session_get_if_valid (session_index, vlib_get_thread_index ());
645   if (!s)
646     return;
647
648   session_enqueue_notify (s);
649 }
650
651 /**
652  * Like session_enqueue_notify, but can be called from a thread that does not
653  * own the session.
654  */
655 void
656 session_enqueue_notify_thread (session_handle_t sh)
657 {
658   u32 thread_index = session_thread_from_handle (sh);
659   u32 session_index = session_index_from_handle (sh);
660
661   /*
662    * Pass session index (u32) as opposed to handle (u64) in case pointers
663    * are not 64-bit.
664    */
665   session_send_rpc_evt_to_thread (thread_index,
666                                   session_enqueue_notify_rpc,
667                                   uword_to_pointer (session_index, void *));
668 }
669
670 int
671 session_dequeue_notify (session_t * s)
672 {
673   app_worker_t *app_wrk;
674
675   svm_fifo_clear_deq_ntf (s->tx_fifo);
676
677   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
678   if (PREDICT_FALSE (!app_wrk))
679     return -1;
680
681   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
682                                                      SESSION_IO_EVT_TX)))
683     return -1;
684
685   if (PREDICT_FALSE (s->tx_fifo->n_subscribers))
686     return session_notify_subscribers (app_wrk->app_index, s,
687                                        s->tx_fifo, SESSION_IO_EVT_TX);
688
689   return 0;
690 }
691
692 /**
693  * Flushes queue of sessions that are to be notified of new data
694  * enqueued events.
695  *
696  * @param thread_index Thread index for which the flush is to be performed.
697  * @return 0 on success or a positive number indicating the number of
698  *         failures due to API queue being full.
699  */
700 int
701 session_main_flush_enqueue_events (u8 transport_proto, u32 thread_index)
702 {
703   session_worker_t *wrk = session_main_get_worker (thread_index);
704   session_t *s;
705   int i, errors = 0;
706   u32 *indices;
707
708   indices = wrk->session_to_enqueue[transport_proto];
709
710   for (i = 0; i < vec_len (indices); i++)
711     {
712       s = session_get_if_valid (indices[i], thread_index);
713       if (PREDICT_FALSE (!s))
714         {
715           errors++;
716           continue;
717         }
718
719       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED,
720                            0 /* TODO/not needed */ );
721
722       if (PREDICT_FALSE (session_enqueue_notify_inline (s)))
723         errors++;
724     }
725
726   vec_reset_length (indices);
727   wrk->session_to_enqueue[transport_proto] = indices;
728
729   return errors;
730 }
731
732 int
733 session_main_flush_all_enqueue_events (u8 transport_proto)
734 {
735   vlib_thread_main_t *vtm = vlib_get_thread_main ();
736   int i, errors = 0;
737   for (i = 0; i < 1 + vtm->n_threads; i++)
738     errors += session_main_flush_enqueue_events (transport_proto, i);
739   return errors;
740 }
741
742 static inline int
743 session_stream_connect_notify_inline (transport_connection_t * tc,
744                                       session_error_t err,
745                                       session_state_t opened_state)
746 {
747   u32 opaque = 0, new_ti, new_si;
748   app_worker_t *app_wrk;
749   session_t *s = 0;
750   u64 ho_handle;
751
752   /*
753    * Find connection handle and cleanup half-open table
754    */
755   ho_handle = session_lookup_half_open_handle (tc);
756   if (ho_handle == HALF_OPEN_LOOKUP_INVALID_VALUE)
757     {
758       SESSION_DBG ("half-open was removed!");
759       return -1;
760     }
761   session_lookup_del_half_open (tc);
762
763   /* Get the app's index from the handle we stored when opening connection
764    * and the opaque (api_context for external apps) from transport session
765    * index */
766   app_wrk = app_worker_get_if_valid (ho_handle >> 32);
767   if (!app_wrk)
768     return -1;
769
770   opaque = tc->s_index;
771
772   if (err)
773     return app_worker_connect_notify (app_wrk, s, err, opaque);
774
775   s = session_alloc_for_connection (tc);
776   s->session_state = SESSION_STATE_CONNECTING;
777   s->app_wrk_index = app_wrk->wrk_index;
778   new_si = s->session_index;
779   new_ti = s->thread_index;
780
781   if ((err = app_worker_init_connected (app_wrk, s)))
782     {
783       session_free (s);
784       app_worker_connect_notify (app_wrk, 0, err, opaque);
785       return -1;
786     }
787
788   s = session_get (new_si, new_ti);
789   s->session_state = opened_state;
790   session_lookup_add_connection (tc, session_handle (s));
791
792   if (app_worker_connect_notify (app_wrk, s, SESSION_E_NONE, opaque))
793     {
794       s = session_get (new_si, new_ti);
795       session_free_w_fifos (s);
796       return -1;
797     }
798
799   return 0;
800 }
801
802 int
803 session_stream_connect_notify (transport_connection_t * tc,
804                                session_error_t err)
805 {
806   return session_stream_connect_notify_inline (tc, err, SESSION_STATE_READY);
807 }
808
809 int
810 session_ho_stream_connect_notify (transport_connection_t * tc,
811                                   session_error_t err)
812 {
813   return session_stream_connect_notify_inline (tc, err, SESSION_STATE_OPENED);
814 }
815
816 static void
817 session_switch_pool_reply (void *arg)
818 {
819   u32 session_index = pointer_to_uword (arg);
820   segment_manager_t *sm;
821   app_worker_t *app_wrk;
822   session_t *s;
823
824   s = session_get_if_valid (session_index, vlib_get_thread_index ());
825   if (!s)
826     return;
827
828   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
829   if (!app_wrk)
830     return;
831
832   /* Attach fifos to the right session and segment slice */
833   sm = app_worker_get_connect_segment_manager (app_wrk);
834   segment_manager_attach_fifo (sm, s->rx_fifo, s);
835   segment_manager_attach_fifo (sm, s->tx_fifo, s);
836
837   /* Notify app that it has data on the new session */
838   session_enqueue_notify (s);
839 }
840
841 typedef struct _session_switch_pool_args
842 {
843   u32 session_index;
844   u32 thread_index;
845   u32 new_thread_index;
846   u32 new_session_index;
847 } session_switch_pool_args_t;
848
849 /**
850  * Notify old thread of the session pool switch
851  */
852 static void
853 session_switch_pool (void *cb_args)
854 {
855   session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
856   session_handle_t new_sh;
857   segment_manager_t *sm;
858   app_worker_t *app_wrk;
859   session_t *s;
860   void *rargs;
861
862   ASSERT (args->thread_index == vlib_get_thread_index ());
863   s = session_get (args->session_index, args->thread_index);
864
865   transport_cleanup (session_get_transport_proto (s), s->connection_index,
866                      s->thread_index);
867
868   new_sh = session_make_handle (args->new_session_index,
869                                 args->new_thread_index);
870
871   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
872   if (app_wrk)
873     {
874       /* Cleanup fifo segment slice state for fifos */
875       sm = app_worker_get_connect_segment_manager (app_wrk);
876       segment_manager_detach_fifo (sm, s->rx_fifo);
877       segment_manager_detach_fifo (sm, s->tx_fifo);
878
879       /* Notify app, using old session, about the migration event */
880       app_worker_migrate_notify (app_wrk, s, new_sh);
881     }
882
883   /* Trigger app read and fifo updates on the new thread */
884   rargs = uword_to_pointer (args->new_session_index, void *);
885   session_send_rpc_evt_to_thread (args->new_thread_index,
886                                   session_switch_pool_reply, rargs);
887
888   session_free (s);
889   clib_mem_free (cb_args);
890 }
891
892 /**
893  * Move dgram session to the right thread
894  */
895 int
896 session_dgram_connect_notify (transport_connection_t * tc,
897                               u32 old_thread_index, session_t ** new_session)
898 {
899   session_t *new_s;
900   session_switch_pool_args_t *rpc_args;
901
902   /*
903    * Clone half-open session to the right thread.
904    */
905   new_s = session_clone_safe (tc->s_index, old_thread_index);
906   new_s->connection_index = tc->c_index;
907   new_s->session_state = SESSION_STATE_READY;
908   new_s->flags |= SESSION_F_IS_MIGRATING;
909
910   session_lookup_add_connection (tc, session_handle (new_s));
911
912   /*
913    * Ask thread owning the old session to clean it up and make us the tx
914    * fifo owner
915    */
916   rpc_args = clib_mem_alloc (sizeof (*rpc_args));
917   rpc_args->new_session_index = new_s->session_index;
918   rpc_args->new_thread_index = new_s->thread_index;
919   rpc_args->session_index = tc->s_index;
920   rpc_args->thread_index = old_thread_index;
921   session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
922                                   rpc_args);
923
924   tc->s_index = new_s->session_index;
925   new_s->connection_index = tc->c_index;
926   *new_session = new_s;
927   return 0;
928 }
929
930 /**
931  * Notification from transport that connection is being closed.
932  *
933  * A disconnect is sent to application but state is not removed. Once
934  * disconnect is acknowledged by application, session disconnect is called.
935  * Ultimately this leads to close being called on transport (passive close).
936  */
937 void
938 session_transport_closing_notify (transport_connection_t * tc)
939 {
940   app_worker_t *app_wrk;
941   session_t *s;
942
943   s = session_get (tc->s_index, tc->thread_index);
944   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
945     return;
946   s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
947   app_wrk = app_worker_get (s->app_wrk_index);
948   app_worker_close_notify (app_wrk, s);
949 }
950
951 /**
952  * Notification from transport that connection is being deleted
953  *
954  * This removes the session if it is still valid. It should be called only on
955  * previously fully established sessions. For instance failed connects should
956  * call stream_session_connect_notify and indicate that the connect has
957  * failed.
958  */
959 void
960 session_transport_delete_notify (transport_connection_t * tc)
961 {
962   session_t *s;
963
964   /* App might've been removed already */
965   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
966     return;
967
968   switch (s->session_state)
969     {
970     case SESSION_STATE_CREATED:
971       /* Session was created but accept notification was not yet sent to the
972        * app. Cleanup everything. */
973       session_lookup_del_session (s);
974       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
975       session_free (s);
976       break;
977     case SESSION_STATE_ACCEPTING:
978     case SESSION_STATE_TRANSPORT_CLOSING:
979     case SESSION_STATE_CLOSING:
980     case SESSION_STATE_TRANSPORT_CLOSED:
981       /* If transport finishes or times out before we get a reply
982        * from the app, mark transport as closed and wait for reply
983        * before removing the session. Cleanup session table in advance
984        * because transport will soon be closed and closed sessions
985        * are assumed to have been removed from the lookup table */
986       session_lookup_del_session (s);
987       s->session_state = SESSION_STATE_TRANSPORT_DELETED;
988       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
989       svm_fifo_dequeue_drop_all (s->tx_fifo);
990       break;
991     case SESSION_STATE_APP_CLOSED:
992       /* Cleanup lookup table as transport needs to still be valid.
993        * Program transport close to ensure that all session events
994        * have been cleaned up. Once transport close is called, the
995        * session is just removed because both transport and app have
996        * confirmed the close*/
997       session_lookup_del_session (s);
998       s->session_state = SESSION_STATE_TRANSPORT_DELETED;
999       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1000       svm_fifo_dequeue_drop_all (s->tx_fifo);
1001       session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1002       break;
1003     case SESSION_STATE_TRANSPORT_DELETED:
1004       break;
1005     case SESSION_STATE_CLOSED:
1006       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1007       session_delete (s);
1008       break;
1009     default:
1010       clib_warning ("session state %u", s->session_state);
1011       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1012       session_delete (s);
1013       break;
1014     }
1015 }
1016
1017 /**
1018  * Notification from transport that it is closed
1019  *
1020  * Should be called by transport, prior to calling delete notify, once it
1021  * knows that no more data will be exchanged. This could serve as an
1022  * early acknowledgment of an active close especially if transport delete
1023  * can be delayed a long time, e.g., tcp time-wait.
1024  */
1025 void
1026 session_transport_closed_notify (transport_connection_t * tc)
1027 {
1028   app_worker_t *app_wrk;
1029   session_t *s;
1030
1031   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
1032     return;
1033
1034   /* Transport thinks that app requested close but it actually didn't.
1035    * Can happen for tcp if fin and rst are received in close succession. */
1036   if (s->session_state == SESSION_STATE_READY)
1037     {
1038       session_transport_closing_notify (tc);
1039       svm_fifo_dequeue_drop_all (s->tx_fifo);
1040       s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
1041     }
1042   /* If app close has not been received or has not yet resulted in
1043    * a transport close, only mark the session transport as closed */
1044   else if (s->session_state <= SESSION_STATE_CLOSING)
1045     {
1046       s->session_state = SESSION_STATE_TRANSPORT_CLOSED;
1047     }
1048   /* If app also closed, switch to closed */
1049   else if (s->session_state == SESSION_STATE_APP_CLOSED)
1050     s->session_state = SESSION_STATE_CLOSED;
1051
1052   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
1053   if (app_wrk)
1054     app_worker_transport_closed_notify (app_wrk, s);
1055 }
1056
1057 /**
1058  * Notify application that connection has been reset.
1059  */
1060 void
1061 session_transport_reset_notify (transport_connection_t * tc)
1062 {
1063   app_worker_t *app_wrk;
1064   session_t *s;
1065
1066   s = session_get (tc->s_index, tc->thread_index);
1067   svm_fifo_dequeue_drop_all (s->tx_fifo);
1068   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
1069     return;
1070   s->session_state = SESSION_STATE_TRANSPORT_CLOSING;
1071   app_wrk = app_worker_get (s->app_wrk_index);
1072   app_worker_reset_notify (app_wrk, s);
1073 }
1074
1075 int
1076 session_stream_accept_notify (transport_connection_t * tc)
1077 {
1078   app_worker_t *app_wrk;
1079   session_t *s;
1080
1081   s = session_get (tc->s_index, tc->thread_index);
1082   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
1083   if (!app_wrk)
1084     return -1;
1085   s->session_state = SESSION_STATE_ACCEPTING;
1086   if (app_worker_accept_notify (app_wrk, s))
1087     {
1088       /* On transport delete, no notifications should be sent. Unless, the
1089        * accept is retried and successful. */
1090       s->session_state = SESSION_STATE_CREATED;
1091       return -1;
1092     }
1093   return 0;
1094 }
1095
1096 /**
1097  * Accept a stream session. Optionally ping the server by callback.
1098  */
1099 int
1100 session_stream_accept (transport_connection_t * tc, u32 listener_index,
1101                        u32 thread_index, u8 notify)
1102 {
1103   session_t *s;
1104   int rv;
1105
1106   s = session_alloc_for_connection (tc);
1107   s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
1108   s->session_state = SESSION_STATE_CREATED;
1109
1110   if ((rv = app_worker_init_accepted (s)))
1111     {
1112       session_free (s);
1113       return rv;
1114     }
1115
1116   session_lookup_add_connection (tc, session_handle (s));
1117
1118   /* Shoulder-tap the server */
1119   if (notify)
1120     {
1121       app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
1122       if ((rv = app_worker_accept_notify (app_wrk, s)))
1123         {
1124           session_lookup_del_session (s);
1125           segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1126           session_free (s);
1127           return rv;
1128         }
1129     }
1130
1131   return 0;
1132 }
1133
1134 int
1135 session_dgram_accept (transport_connection_t * tc, u32 listener_index,
1136                       u32 thread_index)
1137 {
1138   app_worker_t *app_wrk;
1139   session_t *s;
1140   int rv;
1141
1142   s = session_alloc_for_connection (tc);
1143   s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
1144
1145   if ((rv = app_worker_init_accepted (s)))
1146     {
1147       session_free (s);
1148       return rv;
1149     }
1150
1151   app_wrk = app_worker_get (s->app_wrk_index);
1152   if ((rv = app_worker_accept_notify (app_wrk, s)))
1153     {
1154       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1155       session_free (s);
1156       return rv;
1157     }
1158
1159   s->session_state = SESSION_STATE_READY;
1160   session_lookup_add_connection (tc, session_handle (s));
1161
1162   return 0;
1163 }
1164
1165 int
1166 session_open_cl (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1167 {
1168   transport_connection_t *tc;
1169   transport_endpoint_cfg_t *tep;
1170   app_worker_t *app_wrk;
1171   session_handle_t sh;
1172   session_t *s;
1173   int rv;
1174
1175   tep = session_endpoint_to_transport_cfg (rmt);
1176   rv = transport_connect (rmt->transport_proto, tep);
1177   if (rv < 0)
1178     {
1179       SESSION_DBG ("Transport failed to open connection.");
1180       return rv;
1181     }
1182
1183   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
1184
1185   /* For dgram type of service, allocate session and fifos now */
1186   app_wrk = app_worker_get (app_wrk_index);
1187   s = session_alloc_for_connection (tc);
1188   s->app_wrk_index = app_wrk->wrk_index;
1189   s->session_state = SESSION_STATE_OPENED;
1190   if (app_worker_init_connected (app_wrk, s))
1191     {
1192       session_free (s);
1193       return -1;
1194     }
1195
1196   sh = session_handle (s);
1197   session_lookup_add_connection (tc, sh);
1198   return app_worker_connect_notify (app_wrk, s, SESSION_E_NONE, opaque);
1199 }
1200
1201 int
1202 session_open_vc (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1203 {
1204   transport_connection_t *tc;
1205   transport_endpoint_cfg_t *tep;
1206   u64 handle;
1207   int rv;
1208
1209   tep = session_endpoint_to_transport_cfg (rmt);
1210   rv = transport_connect (rmt->transport_proto, tep);
1211   if (rv < 0)
1212     {
1213       SESSION_DBG ("Transport failed to open connection.");
1214       return rv;
1215     }
1216
1217   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
1218
1219   /* If transport offers a stream service, only allocate session once the
1220    * connection has been established.
1221    * Add connection to half-open table and save app and tc index. The
1222    * latter is needed to help establish the connection while the former
1223    * is needed when the connect notify comes and we have to notify the
1224    * external app
1225    */
1226   handle = (((u64) app_wrk_index) << 32) | (u64) tc->c_index;
1227   session_lookup_add_half_open (tc, handle);
1228
1229   /* Store api_context (opaque) for when the reply comes. Not the nicest
1230    * thing but better than allocating a separate half-open pool.
1231    */
1232   tc->s_index = opaque;
1233   if (transport_half_open_has_fifos (rmt->transport_proto))
1234     return session_ho_stream_connect_notify (tc, 0 /* is_fail */ );
1235   return 0;
1236 }
1237
1238 int
1239 session_open_app (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1240 {
1241   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) rmt;
1242   transport_endpoint_cfg_t *tep_cfg = session_endpoint_to_transport_cfg (sep);
1243
1244   sep->app_wrk_index = app_wrk_index;
1245   sep->opaque = opaque;
1246
1247   return transport_connect (rmt->transport_proto, tep_cfg);
1248 }
1249
1250 typedef int (*session_open_service_fn) (u32, session_endpoint_t *, u32);
1251
1252 /* *INDENT-OFF* */
1253 static session_open_service_fn session_open_srv_fns[TRANSPORT_N_SERVICES] = {
1254   session_open_vc,
1255   session_open_cl,
1256   session_open_app,
1257 };
1258 /* *INDENT-ON* */
1259
1260 /**
1261  * Ask transport to open connection to remote transport endpoint.
1262  *
1263  * Stores handle for matching request with reply since the call can be
1264  * asynchronous. For instance, for TCP the 3-way handshake must complete
1265  * before reply comes. Session is only created once connection is established.
1266  *
1267  * @param app_index Index of the application requesting the connect
1268  * @param st Session type requested.
1269  * @param tep Remote transport endpoint
1270  * @param opaque Opaque data (typically, api_context) the application expects
1271  *               on open completion.
1272  */
1273 int
1274 session_open (u32 app_wrk_index, session_endpoint_t * rmt, u32 opaque)
1275 {
1276   transport_service_type_t tst;
1277   tst = transport_protocol_service_type (rmt->transport_proto);
1278   return session_open_srv_fns[tst] (app_wrk_index, rmt, opaque);
1279 }
1280
1281 /**
1282  * Ask transport to listen on session endpoint.
1283  *
1284  * @param s Session for which listen will be called. Note that unlike
1285  *          established sessions, listen sessions are not associated to a
1286  *          thread.
1287  * @param sep Local endpoint to be listened on.
1288  */
1289 int
1290 session_listen (session_t * ls, session_endpoint_cfg_t * sep)
1291 {
1292   transport_endpoint_t *tep;
1293   int tc_index;
1294   u32 s_index;
1295
1296   /* Transport bind/listen */
1297   tep = session_endpoint_to_transport (sep);
1298   s_index = ls->session_index;
1299   tc_index = transport_start_listen (session_get_transport_proto (ls),
1300                                      s_index, tep);
1301
1302   if (tc_index < 0)
1303     return tc_index;
1304
1305   /* Attach transport to session. Lookup tables are populated by the app
1306    * worker because local tables (for ct sessions) are not backed by a fib */
1307   ls = listen_session_get (s_index);
1308   ls->connection_index = tc_index;
1309
1310   return 0;
1311 }
1312
1313 /**
1314  * Ask transport to stop listening on local transport endpoint.
1315  *
1316  * @param s Session to stop listening on. It must be in state LISTENING.
1317  */
1318 int
1319 session_stop_listen (session_t * s)
1320 {
1321   transport_proto_t tp = session_get_transport_proto (s);
1322   transport_connection_t *tc;
1323
1324   if (s->session_state != SESSION_STATE_LISTENING)
1325     return SESSION_E_NOLISTEN;
1326
1327   tc = transport_get_listener (tp, s->connection_index);
1328
1329   /* If no transport, assume everything was cleaned up already */
1330   if (!tc)
1331     return SESSION_E_NONE;
1332
1333   if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
1334     session_lookup_del_connection (tc);
1335
1336   transport_stop_listen (tp, s->connection_index);
1337   return 0;
1338 }
1339
1340 /**
1341  * Initialize session closing procedure.
1342  *
1343  * Request is always sent to session node to ensure that all outstanding
1344  * requests are served before transport is notified.
1345  */
1346 void
1347 session_close (session_t * s)
1348 {
1349   if (!s)
1350     return;
1351
1352   if (s->session_state >= SESSION_STATE_CLOSING)
1353     {
1354       /* Session will only be removed once both app and transport
1355        * acknowledge the close */
1356       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED
1357           || s->session_state == SESSION_STATE_TRANSPORT_DELETED)
1358         session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1359       return;
1360     }
1361
1362   s->session_state = SESSION_STATE_CLOSING;
1363   session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1364 }
1365
1366 /**
1367  * Force a close without waiting for data to be flushed
1368  */
1369 void
1370 session_reset (session_t * s)
1371 {
1372   if (s->session_state >= SESSION_STATE_CLOSING)
1373     return;
1374   /* Drop all outstanding tx data */
1375   svm_fifo_dequeue_drop_all (s->tx_fifo);
1376   s->session_state = SESSION_STATE_CLOSING;
1377   session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_RESET);
1378 }
1379
1380 /**
1381  * Notify transport the session can be disconnected. This should eventually
1382  * result in a delete notification that allows us to cleanup session state.
1383  * Called for both active/passive disconnects.
1384  *
1385  * Must be called from the session's thread.
1386  */
1387 void
1388 session_transport_close (session_t * s)
1389 {
1390   if (s->session_state >= SESSION_STATE_APP_CLOSED)
1391     {
1392       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1393         s->session_state = SESSION_STATE_CLOSED;
1394       /* If transport is already deleted, just free the session */
1395       else if (s->session_state >= SESSION_STATE_TRANSPORT_DELETED)
1396         session_free_w_fifos (s);
1397       return;
1398     }
1399
1400   /* If the tx queue wasn't drained, the transport can continue to try
1401    * sending the outstanding data (in closed state it cannot). It MUST however
1402    * at one point, either after sending everything or after a timeout, call
1403    * delete notify. This will finally lead to the complete cleanup of the
1404    * session.
1405    */
1406   s->session_state = SESSION_STATE_APP_CLOSED;
1407
1408   transport_close (session_get_transport_proto (s), s->connection_index,
1409                    s->thread_index);
1410 }
1411
1412 /**
1413  * Force transport close
1414  */
1415 void
1416 session_transport_reset (session_t * s)
1417 {
1418   if (s->session_state >= SESSION_STATE_APP_CLOSED)
1419     {
1420       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1421         s->session_state = SESSION_STATE_CLOSED;
1422       else if (s->session_state >= SESSION_STATE_TRANSPORT_DELETED)
1423         session_free_w_fifos (s);
1424       return;
1425     }
1426
1427   s->session_state = SESSION_STATE_APP_CLOSED;
1428   transport_reset (session_get_transport_proto (s), s->connection_index,
1429                    s->thread_index);
1430 }
1431
1432 /**
1433  * Cleanup transport and session state.
1434  *
1435  * Notify transport of the cleanup and free the session. This should
1436  * be called only if transport reported some error and is already
1437  * closed.
1438  */
1439 void
1440 session_transport_cleanup (session_t * s)
1441 {
1442   /* Delete from main lookup table before we axe the the transport */
1443   session_lookup_del_session (s);
1444   if (s->session_state != SESSION_STATE_TRANSPORT_DELETED)
1445     transport_cleanup (session_get_transport_proto (s), s->connection_index,
1446                        s->thread_index);
1447   /* Since we called cleanup, no delete notification will come. So, make
1448    * sure the session is properly freed. */
1449   segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1450   session_free (s);
1451 }
1452
1453 /**
1454  * Allocate event queues in the shared-memory segment
1455  *
1456  * That can either be a newly created memfd segment, that will need to be
1457  * mapped by all stack users, or the binary api's svm region. The latter is
1458  * assumed to be already mapped. NOTE that this assumption DOES NOT hold if
1459  * api clients bootstrap shm api over sockets (i.e. use memfd segments) and
1460  * vpp uses api svm region for event queues.
1461  */
1462 void
1463 session_vpp_event_queues_allocate (session_main_t * smm)
1464 {
1465   u32 evt_q_length = 2048, evt_size = sizeof (session_event_t);
1466   ssvm_private_t *eqs = &smm->evt_qs_segment;
1467   uword eqs_size = 64 << 20;
1468   pid_t vpp_pid = getpid ();
1469   void *oldheap;
1470   int i;
1471
1472   if (smm->configured_event_queue_length)
1473     evt_q_length = smm->configured_event_queue_length;
1474
1475   if (smm->evt_qs_use_memfd_seg)
1476     {
1477       if (smm->evt_qs_segment_size)
1478         eqs_size = smm->evt_qs_segment_size;
1479
1480       eqs->ssvm_size = eqs_size;
1481       eqs->i_am_master = 1;
1482       eqs->my_pid = vpp_pid;
1483       eqs->name = format (0, "%s%c", "evt-qs-segment", 0);
1484       eqs->requested_va = smm->session_baseva;
1485
1486       if (ssvm_master_init (eqs, SSVM_SEGMENT_MEMFD))
1487         {
1488           clib_warning ("failed to initialize queue segment");
1489           return;
1490         }
1491     }
1492
1493   if (smm->evt_qs_use_memfd_seg)
1494     oldheap = ssvm_push_heap (eqs->sh);
1495   else
1496     oldheap = vl_msg_push_heap ();
1497
1498   for (i = 0; i < vec_len (smm->wrk); i++)
1499     {
1500       svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1501       svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
1502         {evt_q_length, evt_size, 0}
1503         ,
1504         {evt_q_length >> 1, 256, 0}
1505       };
1506       cfg->consumer_pid = 0;
1507       cfg->n_rings = 2;
1508       cfg->q_nitems = evt_q_length;
1509       cfg->ring_cfgs = rc;
1510       smm->wrk[i].vpp_event_queue = svm_msg_q_alloc (cfg);
1511       if (smm->evt_qs_use_memfd_seg)
1512         {
1513           if (svm_msg_q_alloc_consumer_eventfd (smm->wrk[i].vpp_event_queue))
1514             clib_warning ("eventfd returned");
1515         }
1516     }
1517
1518   if (smm->evt_qs_use_memfd_seg)
1519     ssvm_pop_heap (oldheap);
1520   else
1521     vl_msg_pop_heap (oldheap);
1522 }
1523
1524 ssvm_private_t *
1525 session_main_get_evt_q_segment (void)
1526 {
1527   session_main_t *smm = &session_main;
1528   if (smm->evt_qs_use_memfd_seg)
1529     return &smm->evt_qs_segment;
1530   return 0;
1531 }
1532
1533 u64
1534 session_segment_handle (session_t * s)
1535 {
1536   svm_fifo_t *f;
1537
1538   if (!s->rx_fifo)
1539     return SESSION_INVALID_HANDLE;
1540
1541   f = s->rx_fifo;
1542   return segment_manager_make_segment_handle (f->segment_manager,
1543                                               f->segment_index);
1544 }
1545
1546 /* *INDENT-OFF* */
1547 static session_fifo_rx_fn *session_tx_fns[TRANSPORT_TX_N_FNS] = {
1548     session_tx_fifo_peek_and_snd,
1549     session_tx_fifo_dequeue_and_snd,
1550     session_tx_fifo_dequeue_internal,
1551     session_tx_fifo_dequeue_and_snd
1552 };
1553 /* *INDENT-ON* */
1554
1555 void
1556 session_register_transport (transport_proto_t transport_proto,
1557                             const transport_proto_vft_t * vft, u8 is_ip4,
1558                             u32 output_node)
1559 {
1560   session_main_t *smm = &session_main;
1561   session_type_t session_type;
1562   u32 next_index = ~0;
1563
1564   session_type = session_type_from_proto_and_ip (transport_proto, is_ip4);
1565
1566   vec_validate (smm->session_type_to_next, session_type);
1567   vec_validate (smm->session_tx_fns, session_type);
1568
1569   /* *INDENT-OFF* */
1570   if (output_node != ~0)
1571     {
1572       foreach_vlib_main (({
1573           next_index = vlib_node_add_next (this_vlib_main,
1574                                            session_queue_node.index,
1575                                            output_node);
1576       }));
1577     }
1578   /* *INDENT-ON* */
1579
1580   smm->session_type_to_next[session_type] = next_index;
1581   smm->session_tx_fns[session_type] =
1582     session_tx_fns[vft->transport_options.tx_type];
1583 }
1584
1585 transport_proto_t
1586 session_add_transport_proto (void)
1587 {
1588   session_main_t *smm = &session_main;
1589   session_worker_t *wrk;
1590   u32 thread;
1591
1592   smm->last_transport_proto_type += 1;
1593
1594   for (thread = 0; thread < vec_len (smm->wrk); thread++)
1595     {
1596       wrk = session_main_get_worker (thread);
1597       vec_validate (wrk->session_to_enqueue, smm->last_transport_proto_type);
1598     }
1599
1600   return smm->last_transport_proto_type;
1601 }
1602
1603 transport_connection_t *
1604 session_get_transport (session_t * s)
1605 {
1606   if (s->session_state != SESSION_STATE_LISTENING)
1607     return transport_get_connection (session_get_transport_proto (s),
1608                                      s->connection_index, s->thread_index);
1609   else
1610     return transport_get_listener (session_get_transport_proto (s),
1611                                    s->connection_index);
1612 }
1613
1614 void
1615 session_get_endpoint (session_t * s, transport_endpoint_t * tep, u8 is_lcl)
1616 {
1617   if (s->session_state != SESSION_STATE_LISTENING)
1618     return transport_get_endpoint (session_get_transport_proto (s),
1619                                    s->connection_index, s->thread_index, tep,
1620                                    is_lcl);
1621   else
1622     return transport_get_listener_endpoint (session_get_transport_proto (s),
1623                                             s->connection_index, tep, is_lcl);
1624 }
1625
1626 transport_connection_t *
1627 listen_session_get_transport (session_t * s)
1628 {
1629   return transport_get_listener (session_get_transport_proto (s),
1630                                  s->connection_index);
1631 }
1632
1633 void
1634 session_queue_run_on_main_thread (vlib_main_t * vm)
1635 {
1636   ASSERT (vlib_get_thread_index () == 0);
1637   vlib_process_signal_event_mt (vm, session_queue_process_node.index,
1638                                 SESSION_Q_PROCESS_RUN_ON_MAIN, 0);
1639 }
1640
1641 static clib_error_t *
1642 session_manager_main_enable (vlib_main_t * vm)
1643 {
1644   segment_manager_main_init_args_t _sm_args = { 0 }, *sm_args = &_sm_args;
1645   session_main_t *smm = &session_main;
1646   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1647   u32 num_threads, preallocated_sessions_per_worker;
1648   session_worker_t *wrk;
1649   int i;
1650
1651   num_threads = 1 /* main thread */  + vtm->n_threads;
1652
1653   if (num_threads < 1)
1654     return clib_error_return (0, "n_thread_stacks not set");
1655
1656   /* Allocate cache line aligned worker contexts */
1657   vec_validate_aligned (smm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1658
1659   for (i = 0; i < num_threads; i++)
1660     {
1661       wrk = &smm->wrk[i];
1662       wrk->ctrl_head = clib_llist_make_head (wrk->event_elts, evt_list);
1663       wrk->new_head = clib_llist_make_head (wrk->event_elts, evt_list);
1664       wrk->old_head = clib_llist_make_head (wrk->event_elts, evt_list);
1665       wrk->vm = vlib_mains[i];
1666       wrk->last_vlib_time = vlib_time_now (vlib_mains[i]);
1667       wrk->last_vlib_us_time = wrk->last_vlib_time * CLIB_US_TIME_FREQ;
1668       vec_validate (wrk->session_to_enqueue, smm->last_transport_proto_type);
1669
1670       if (num_threads > 1)
1671         clib_rwlock_init (&smm->wrk[i].peekers_rw_locks);
1672     }
1673
1674   /* Allocate vpp event queues segment and queue */
1675   session_vpp_event_queues_allocate (smm);
1676
1677   /* Initialize fifo segment main baseva and timeout */
1678   sm_args->baseva = smm->session_baseva + smm->evt_qs_segment_size;
1679   sm_args->size = smm->session_va_space_size;
1680   segment_manager_main_init (sm_args);
1681
1682   /* Preallocate sessions */
1683   if (smm->preallocated_sessions)
1684     {
1685       if (num_threads == 1)
1686         {
1687           pool_init_fixed (smm->wrk[0].sessions, smm->preallocated_sessions);
1688         }
1689       else
1690         {
1691           int j;
1692           preallocated_sessions_per_worker =
1693             (1.1 * (f64) smm->preallocated_sessions /
1694              (f64) (num_threads - 1));
1695
1696           for (j = 1; j < num_threads; j++)
1697             {
1698               pool_init_fixed (smm->wrk[j].sessions,
1699                                preallocated_sessions_per_worker);
1700             }
1701         }
1702     }
1703
1704   session_lookup_init ();
1705   app_namespaces_init ();
1706   transport_init ();
1707
1708   smm->is_enabled = 1;
1709
1710   /* Enable transports */
1711   transport_enable_disable (vm, 1);
1712
1713 #if SESSION_DEBUG
1714   session_dbg_main_t *sdm = &session_dbg_main;
1715   vec_validate_aligned (sdm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1716   int thread;
1717   for (thread = 0; thread < num_threads; thread++)
1718     {
1719       clib_memset (&sdm->wrk[thread], 0, sizeof (session_dbg_evts_t));
1720     }
1721 #endif /* SESSION_DEBUG */
1722
1723   return 0;
1724 }
1725
1726 void
1727 session_node_enable_disable (u8 is_en)
1728 {
1729   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
1730   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1731   u8 have_workers = vtm->n_threads != 0;
1732
1733   /* *INDENT-OFF* */
1734   foreach_vlib_main (({
1735     if (have_workers && ii == 0)
1736       {
1737         vlib_node_set_state (this_vlib_main, session_queue_process_node.index,
1738                              state);
1739         if (is_en)
1740           {
1741             vlib_node_t *n = vlib_get_node (this_vlib_main,
1742                                             session_queue_process_node.index);
1743             vlib_start_process (this_vlib_main, n->runtime_index);
1744           }
1745         else
1746           {
1747             vlib_process_signal_event_mt (this_vlib_main,
1748                                           session_queue_process_node.index,
1749                                           SESSION_Q_PROCESS_STOP, 0);
1750           }
1751
1752         continue;
1753       }
1754     vlib_node_set_state (this_vlib_main, session_queue_node.index,
1755                          state);
1756   }));
1757   /* *INDENT-ON* */
1758 }
1759
1760 clib_error_t *
1761 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
1762 {
1763   clib_error_t *error = 0;
1764   if (is_en)
1765     {
1766       if (session_main.is_enabled)
1767         return 0;
1768
1769       error = session_manager_main_enable (vm);
1770       session_node_enable_disable (is_en);
1771     }
1772   else
1773     {
1774       session_main.is_enabled = 0;
1775       session_node_enable_disable (is_en);
1776     }
1777
1778   return error;
1779 }
1780
1781 clib_error_t *
1782 session_main_init (vlib_main_t * vm)
1783 {
1784   session_main_t *smm = &session_main;
1785
1786   smm->is_enabled = 0;
1787   smm->session_enable_asap = 0;
1788   smm->session_baseva = HIGH_SEGMENT_BASEVA;
1789
1790 #if (HIGH_SEGMENT_BASEVA > (4ULL << 30))
1791   smm->session_va_space_size = 128ULL << 30;
1792   smm->evt_qs_segment_size = 64 << 20;
1793 #else
1794   smm->session_va_space_size = 128 << 20;
1795   smm->evt_qs_segment_size = 1 << 20;
1796 #endif
1797
1798   smm->last_transport_proto_type = TRANSPORT_PROTO_QUIC;
1799
1800   return 0;
1801 }
1802
1803 static clib_error_t *
1804 session_main_loop_init (vlib_main_t * vm)
1805 {
1806   session_main_t *smm = &session_main;
1807   if (smm->session_enable_asap)
1808     {
1809       vlib_worker_thread_barrier_sync (vm);
1810       vnet_session_enable_disable (vm, 1 /* is_en */ );
1811       vlib_worker_thread_barrier_release (vm);
1812     }
1813   return 0;
1814 }
1815
1816 VLIB_INIT_FUNCTION (session_main_init);
1817 VLIB_MAIN_LOOP_ENTER_FUNCTION (session_main_loop_init);
1818
1819 static clib_error_t *
1820 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
1821 {
1822   session_main_t *smm = &session_main;
1823   u32 nitems;
1824   uword tmp;
1825
1826   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1827     {
1828       if (unformat (input, "event-queue-length %d", &nitems))
1829         {
1830           if (nitems >= 2048)
1831             smm->configured_event_queue_length = nitems;
1832           else
1833             clib_warning ("event queue length %d too small, ignored", nitems);
1834         }
1835       else if (unformat (input, "preallocated-sessions %d",
1836                          &smm->preallocated_sessions))
1837         ;
1838       else if (unformat (input, "v4-session-table-buckets %d",
1839                          &smm->configured_v4_session_table_buckets))
1840         ;
1841       else if (unformat (input, "v4-halfopen-table-buckets %d",
1842                          &smm->configured_v4_halfopen_table_buckets))
1843         ;
1844       else if (unformat (input, "v6-session-table-buckets %d",
1845                          &smm->configured_v6_session_table_buckets))
1846         ;
1847       else if (unformat (input, "v6-halfopen-table-buckets %d",
1848                          &smm->configured_v6_halfopen_table_buckets))
1849         ;
1850       else if (unformat (input, "v4-session-table-memory %U",
1851                          unformat_memory_size, &tmp))
1852         {
1853           if (tmp >= 0x100000000)
1854             return clib_error_return (0, "memory size %llx (%lld) too large",
1855                                       tmp, tmp);
1856           smm->configured_v4_session_table_memory = tmp;
1857         }
1858       else if (unformat (input, "v4-halfopen-table-memory %U",
1859                          unformat_memory_size, &tmp))
1860         {
1861           if (tmp >= 0x100000000)
1862             return clib_error_return (0, "memory size %llx (%lld) too large",
1863                                       tmp, tmp);
1864           smm->configured_v4_halfopen_table_memory = tmp;
1865         }
1866       else if (unformat (input, "v6-session-table-memory %U",
1867                          unformat_memory_size, &tmp))
1868         {
1869           if (tmp >= 0x100000000)
1870             return clib_error_return (0, "memory size %llx (%lld) too large",
1871                                       tmp, tmp);
1872           smm->configured_v6_session_table_memory = tmp;
1873         }
1874       else if (unformat (input, "v6-halfopen-table-memory %U",
1875                          unformat_memory_size, &tmp))
1876         {
1877           if (tmp >= 0x100000000)
1878             return clib_error_return (0, "memory size %llx (%lld) too large",
1879                                       tmp, tmp);
1880           smm->configured_v6_halfopen_table_memory = tmp;
1881         }
1882       else if (unformat (input, "local-endpoints-table-memory %U",
1883                          unformat_memory_size, &tmp))
1884         {
1885           if (tmp >= 0x100000000)
1886             return clib_error_return (0, "memory size %llx (%lld) too large",
1887                                       tmp, tmp);
1888           smm->local_endpoints_table_memory = tmp;
1889         }
1890       else if (unformat (input, "local-endpoints-table-buckets %d",
1891                          &smm->local_endpoints_table_buckets))
1892         ;
1893       else if (unformat (input, "evt_qs_memfd_seg"))
1894         smm->evt_qs_use_memfd_seg = 1;
1895       else if (unformat (input, "evt_qs_seg_size %U", unformat_memory_size,
1896                          &smm->evt_qs_segment_size))
1897         ;
1898       else if (unformat (input, "enable"))
1899         smm->session_enable_asap = 1;
1900       else
1901         return clib_error_return (0, "unknown input `%U'",
1902                                   format_unformat_error, input);
1903     }
1904   return 0;
1905 }
1906
1907 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
1908
1909 /*
1910  * fd.io coding-style-patch-verification: ON
1911  *
1912  * Local Variables:
1913  * eval: (c-set-style "gnu")
1914  * End:
1915  */