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