vcl: ldp support SO_ORIGINAL_DST
[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/plugin/plugin.h>
21 #include <vnet/session/session.h>
22 #include <vnet/session/application.h>
23 #include <vnet/dpo/load_balance.h>
24 #include <vnet/fib/ip4_fib.h>
25 #include <vlib/stats/stats.h>
26 #include <vlib/dma/dma.h>
27
28 session_main_t session_main;
29
30 static inline int
31 session_send_evt_to_thread (void *data, void *args, u32 thread_index,
32                             session_evt_type_t evt_type)
33 {
34   session_worker_t *wrk = session_main_get_worker (thread_index);
35   session_event_t *evt;
36   svm_msg_q_msg_t msg;
37   svm_msg_q_t *mq;
38
39   mq = wrk->vpp_event_queue;
40   if (PREDICT_FALSE (svm_msg_q_lock (mq)))
41     return -1;
42   if (PREDICT_FALSE (svm_msg_q_or_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
43     {
44       svm_msg_q_unlock (mq);
45       return -2;
46     }
47   switch (evt_type)
48     {
49     case SESSION_CTRL_EVT_RPC:
50       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
51       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
52       evt->rpc_args.fp = data;
53       evt->rpc_args.arg = args;
54       break;
55     case SESSION_IO_EVT_RX:
56     case SESSION_IO_EVT_TX:
57     case SESSION_IO_EVT_TX_FLUSH:
58     case SESSION_IO_EVT_BUILTIN_RX:
59       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
60       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
61       evt->session_index = *(u32 *) data;
62       break;
63     case SESSION_IO_EVT_TX_MAIN:
64     case SESSION_CTRL_EVT_CLOSE:
65     case SESSION_CTRL_EVT_RESET:
66       msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
67       evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
68       evt->session_handle = session_handle ((session_t *) data);
69       break;
70     default:
71       clib_warning ("evt unhandled!");
72       svm_msg_q_unlock (mq);
73       return -1;
74     }
75   evt->event_type = evt_type;
76
77   svm_msg_q_add_and_unlock (mq, &msg);
78
79   if (PREDICT_FALSE (wrk->state == SESSION_WRK_INTERRUPT))
80     vlib_node_set_interrupt_pending (wrk->vm, session_queue_node.index);
81
82   return 0;
83 }
84
85 int
86 session_send_io_evt_to_thread (svm_fifo_t * f, session_evt_type_t evt_type)
87 {
88   return session_send_evt_to_thread (&f->shr->master_session_index, 0,
89                                      f->master_thread_index, evt_type);
90 }
91
92 int
93 session_send_io_evt_to_thread_custom (void *data, u32 thread_index,
94                                       session_evt_type_t evt_type)
95 {
96   return session_send_evt_to_thread (data, 0, thread_index, evt_type);
97 }
98
99 int
100 session_send_ctrl_evt_to_thread (session_t * s, session_evt_type_t evt_type)
101 {
102   /* only events supported are disconnect, shutdown and reset */
103   ASSERT (evt_type == SESSION_CTRL_EVT_CLOSE ||
104           evt_type == SESSION_CTRL_EVT_HALF_CLOSE ||
105           evt_type == SESSION_CTRL_EVT_RESET);
106   return session_send_evt_to_thread (s, 0, s->thread_index, evt_type);
107 }
108
109 void
110 session_send_rpc_evt_to_thread_force (u32 thread_index, void *fp,
111                                       void *rpc_args)
112 {
113   session_send_evt_to_thread (fp, rpc_args, thread_index,
114                               SESSION_CTRL_EVT_RPC);
115 }
116
117 void
118 session_send_rpc_evt_to_thread (u32 thread_index, void *fp, void *rpc_args)
119 {
120   if (thread_index != vlib_get_thread_index ())
121     session_send_rpc_evt_to_thread_force (thread_index, fp, rpc_args);
122   else
123     {
124       void (*fnp) (void *) = fp;
125       fnp (rpc_args);
126     }
127 }
128
129 void
130 session_add_self_custom_tx_evt (transport_connection_t * tc, u8 has_prio)
131 {
132   session_t *s = session_get (tc->s_index, tc->thread_index);
133
134   ASSERT (s->thread_index == vlib_get_thread_index ());
135   ASSERT (s->session_state != SESSION_STATE_TRANSPORT_DELETED);
136
137   if (!(s->flags & SESSION_F_CUSTOM_TX))
138     {
139       s->flags |= SESSION_F_CUSTOM_TX;
140       if (svm_fifo_set_event (s->tx_fifo)
141           || transport_connection_is_descheduled (tc))
142         {
143           session_evt_elt_t *elt;
144           session_worker_t *wrk;
145
146           wrk = session_main_get_worker (tc->thread_index);
147           if (has_prio)
148             elt = session_evt_alloc_new (wrk);
149           else
150             elt = session_evt_alloc_old (wrk);
151           elt->evt.session_index = tc->s_index;
152           elt->evt.event_type = SESSION_IO_EVT_TX;
153           tc->flags &= ~TRANSPORT_CONNECTION_F_DESCHED;
154
155           if (PREDICT_FALSE (wrk->state == SESSION_WRK_INTERRUPT))
156             vlib_node_set_interrupt_pending (wrk->vm,
157                                              session_queue_node.index);
158         }
159     }
160 }
161
162 void
163 sesssion_reschedule_tx (transport_connection_t * tc)
164 {
165   session_worker_t *wrk = session_main_get_worker (tc->thread_index);
166   session_evt_elt_t *elt;
167
168   ASSERT (tc->thread_index == vlib_get_thread_index ());
169
170   elt = session_evt_alloc_new (wrk);
171   elt->evt.session_index = tc->s_index;
172   elt->evt.event_type = SESSION_IO_EVT_TX;
173
174   if (PREDICT_FALSE (wrk->state == SESSION_WRK_INTERRUPT))
175     vlib_node_set_interrupt_pending (wrk->vm, session_queue_node.index);
176 }
177
178 static void
179 session_program_transport_ctrl_evt (session_t * s, session_evt_type_t evt)
180 {
181   u32 thread_index = vlib_get_thread_index ();
182   session_evt_elt_t *elt;
183   session_worker_t *wrk;
184
185   /* If we are in the handler thread, or being called with the worker barrier
186    * held, just append a new event to pending disconnects vector. */
187   if (vlib_thread_is_main_w_barrier () || thread_index == s->thread_index)
188     {
189       wrk = session_main_get_worker (s->thread_index);
190       elt = session_evt_alloc_ctrl (wrk);
191       clib_memset (&elt->evt, 0, sizeof (session_event_t));
192       elt->evt.session_handle = session_handle (s);
193       elt->evt.event_type = evt;
194
195       if (PREDICT_FALSE (wrk->state == SESSION_WRK_INTERRUPT))
196         vlib_node_set_interrupt_pending (wrk->vm, session_queue_node.index);
197     }
198   else
199     session_send_ctrl_evt_to_thread (s, evt);
200 }
201
202 session_t *
203 session_alloc (u32 thread_index)
204 {
205   session_worker_t *wrk = &session_main.wrk[thread_index];
206   session_t *s;
207
208   pool_get_aligned_safe (wrk->sessions, s, CLIB_CACHE_LINE_BYTES);
209   clib_memset (s, 0, sizeof (*s));
210   s->session_index = s - wrk->sessions;
211   s->thread_index = thread_index;
212   s->app_index = APP_INVALID_INDEX;
213
214   return s;
215 }
216
217 void
218 session_free (session_t * s)
219 {
220   session_worker_t *wrk = &session_main.wrk[s->thread_index];
221
222   SESSION_EVT (SESSION_EVT_FREE, s);
223   if (CLIB_DEBUG)
224     clib_memset (s, 0xFA, sizeof (*s));
225   pool_put (wrk->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->thread_index != thread_index || s->session_index != si)
237     return 0;
238
239   if (s->session_state == SESSION_STATE_TRANSPORT_DELETED
240       || s->session_state <= SESSION_STATE_LISTENING)
241     return 1;
242
243   if (s->session_state == SESSION_STATE_CONNECTING &&
244       (s->flags & SESSION_F_HALF_OPEN))
245     return 1;
246
247   tc = session_get_transport (s);
248   if (s->connection_index != tc->c_index
249       || s->thread_index != tc->thread_index || tc->s_index != si)
250     return 0;
251
252   return 1;
253 }
254
255 static void
256 session_cleanup_notify (session_t * s, session_cleanup_ntf_t ntf)
257 {
258   app_worker_t *app_wrk;
259
260   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
261   if (!app_wrk)
262     return;
263   app_worker_cleanup_notify (app_wrk, s, ntf);
264 }
265
266 void
267 session_free_w_fifos (session_t * s)
268 {
269   session_cleanup_notify (s, SESSION_CLEANUP_SESSION);
270   segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
271   session_free (s);
272 }
273
274 /**
275  * Cleans up session and lookup table.
276  *
277  * Transport connection must still be valid.
278  */
279 static void
280 session_delete (session_t * s)
281 {
282   int rv;
283
284   /* Delete from the main lookup table. */
285   if ((rv = session_lookup_del_session (s)))
286     clib_warning ("session %u hash delete rv %d", s->session_index, rv);
287
288   session_free_w_fifos (s);
289 }
290
291 void
292 session_cleanup_half_open (session_handle_t ho_handle)
293 {
294   session_t *ho = session_get_from_handle (ho_handle);
295
296   /* App transports can migrate their half-opens */
297   if (ho->flags & SESSION_F_IS_MIGRATING)
298     {
299       /* Session still migrating, move to closed state to signal that the
300        * session should be removed. */
301       if (ho->connection_index == ~0)
302         {
303           session_set_state (ho, SESSION_STATE_CLOSED);
304           return;
305         }
306       /* Migrated transports are no longer half-opens */
307       transport_cleanup (session_get_transport_proto (ho),
308                          ho->connection_index, ho->app_index /* overloaded */);
309     }
310   else
311     {
312       /* Cleanup half-open session lookup table if need be */
313       if (ho->session_state != SESSION_STATE_TRANSPORT_CLOSED)
314         {
315           transport_connection_t *tc;
316           tc = transport_get_half_open (session_get_transport_proto (ho),
317                                         ho->connection_index);
318           if (tc && !(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
319             session_lookup_del_half_open (tc);
320         }
321       transport_cleanup_half_open (session_get_transport_proto (ho),
322                                    ho->connection_index);
323     }
324   session_free (ho);
325 }
326
327 static void
328 session_half_open_free (session_t *ho)
329 {
330   app_worker_t *app_wrk;
331
332   ASSERT (vlib_get_thread_index () <= transport_cl_thread ());
333   app_wrk = app_worker_get_if_valid (ho->app_wrk_index);
334   if (app_wrk)
335     app_worker_del_half_open (app_wrk, ho);
336   session_free (ho);
337 }
338
339 static void
340 session_half_open_free_rpc (void *args)
341 {
342   session_t *ho = ho_session_get (pointer_to_uword (args));
343   session_half_open_free (ho);
344 }
345
346 void
347 session_half_open_delete_notify (transport_connection_t *tc)
348 {
349   session_t *ho = ho_session_get (tc->s_index);
350
351   /* Cleanup half-open lookup table if need be */
352   if (ho->session_state != SESSION_STATE_TRANSPORT_CLOSED)
353     {
354       if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
355         session_lookup_del_half_open (tc);
356     }
357
358   /* Notification from ctrl thread accepted without rpc */
359   if (tc->thread_index == transport_cl_thread ())
360     {
361       session_half_open_free (ho);
362     }
363   else
364     {
365       void *args = uword_to_pointer ((uword) tc->s_index, void *);
366       session_send_rpc_evt_to_thread_force (transport_cl_thread (),
367                                             session_half_open_free_rpc, args);
368     }
369 }
370
371 void
372 session_half_open_migrate_notify (transport_connection_t *tc)
373 {
374   session_t *ho;
375
376   /* Support half-open migrations only for transports with no lookup */
377   ASSERT (tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP);
378
379   ho = ho_session_get (tc->s_index);
380   ho->flags |= SESSION_F_IS_MIGRATING;
381   ho->connection_index = ~0;
382 }
383
384 int
385 session_half_open_migrated_notify (transport_connection_t *tc)
386 {
387   session_t *ho;
388
389   ho = ho_session_get (tc->s_index);
390
391   /* App probably detached so the half-open must be cleaned up */
392   if (ho->session_state == SESSION_STATE_CLOSED)
393     {
394       session_half_open_delete_notify (tc);
395       return -1;
396     }
397   ho->connection_index = tc->c_index;
398   /* Overload app index for half-open with new thread */
399   ho->app_index = tc->thread_index;
400   return 0;
401 }
402
403 session_t *
404 session_alloc_for_connection (transport_connection_t * tc)
405 {
406   session_t *s;
407   u32 thread_index = tc->thread_index;
408
409   ASSERT (thread_index == vlib_get_thread_index ()
410           || transport_protocol_is_cl (tc->proto));
411
412   s = session_alloc (thread_index);
413   s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
414   session_set_state (s, SESSION_STATE_CLOSED);
415
416   /* Attach transport to session and vice versa */
417   s->connection_index = tc->c_index;
418   tc->s_index = s->session_index;
419   return s;
420 }
421
422 session_t *
423 session_alloc_for_half_open (transport_connection_t *tc)
424 {
425   session_t *s;
426
427   s = ho_session_alloc ();
428   s->session_type = session_type_from_proto_and_ip (tc->proto, tc->is_ip4);
429   s->connection_index = tc->c_index;
430   tc->s_index = s->session_index;
431   return s;
432 }
433
434 /**
435  * Discards bytes from buffer chain
436  *
437  * It discards n_bytes_to_drop starting at first buffer after chain_b
438  */
439 always_inline void
440 session_enqueue_discard_chain_bytes (vlib_main_t * vm, vlib_buffer_t * b,
441                                      vlib_buffer_t ** chain_b,
442                                      u32 n_bytes_to_drop)
443 {
444   vlib_buffer_t *next = *chain_b;
445   u32 to_drop = n_bytes_to_drop;
446   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
447   while (to_drop && (next->flags & VLIB_BUFFER_NEXT_PRESENT))
448     {
449       next = vlib_get_buffer (vm, next->next_buffer);
450       if (next->current_length > to_drop)
451         {
452           vlib_buffer_advance (next, to_drop);
453           to_drop = 0;
454         }
455       else
456         {
457           to_drop -= next->current_length;
458           next->current_length = 0;
459         }
460     }
461   *chain_b = next;
462
463   if (to_drop == 0)
464     b->total_length_not_including_first_buffer -= n_bytes_to_drop;
465 }
466
467 /**
468  * Enqueue buffer chain tail
469  */
470 always_inline int
471 session_enqueue_chain_tail (session_t * s, vlib_buffer_t * b,
472                             u32 offset, u8 is_in_order)
473 {
474   vlib_buffer_t *chain_b;
475   u32 chain_bi, len, diff;
476   vlib_main_t *vm = vlib_get_main ();
477   u8 *data;
478   u32 written = 0;
479   int rv = 0;
480
481   if (is_in_order && offset)
482     {
483       diff = offset - b->current_length;
484       if (diff > b->total_length_not_including_first_buffer)
485         return 0;
486       chain_b = b;
487       session_enqueue_discard_chain_bytes (vm, b, &chain_b, diff);
488       chain_bi = vlib_get_buffer_index (vm, chain_b);
489     }
490   else
491     chain_bi = b->next_buffer;
492
493   do
494     {
495       chain_b = vlib_get_buffer (vm, chain_bi);
496       data = vlib_buffer_get_current (chain_b);
497       len = chain_b->current_length;
498       if (!len)
499         continue;
500       if (is_in_order)
501         {
502           rv = svm_fifo_enqueue (s->rx_fifo, len, data);
503           if (rv == len)
504             {
505               written += rv;
506             }
507           else if (rv < len)
508             {
509               return (rv > 0) ? (written + rv) : written;
510             }
511           else if (rv > len)
512             {
513               written += rv;
514
515               /* written more than what was left in chain */
516               if (written > b->total_length_not_including_first_buffer)
517                 return written;
518
519               /* drop the bytes that have already been delivered */
520               session_enqueue_discard_chain_bytes (vm, b, &chain_b, rv - len);
521             }
522         }
523       else
524         {
525           rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset, len, data);
526           if (rv)
527             {
528               clib_warning ("failed to enqueue multi-buffer seg");
529               return -1;
530             }
531           offset += len;
532         }
533     }
534   while ((chain_bi = (chain_b->flags & VLIB_BUFFER_NEXT_PRESENT)
535           ? chain_b->next_buffer : 0));
536
537   if (is_in_order)
538     return written;
539
540   return 0;
541 }
542
543 void
544 session_fifo_tuning (session_t * s, svm_fifo_t * f,
545                      session_ft_action_t act, u32 len)
546 {
547   if (s->flags & SESSION_F_CUSTOM_FIFO_TUNING)
548     {
549       app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
550       app_worker_session_fifo_tuning (app_wrk, s, f, act, len);
551       if (CLIB_ASSERT_ENABLE)
552         {
553           segment_manager_t *sm;
554           sm = segment_manager_get (f->segment_manager);
555           ASSERT (f->shr->size >= 4096);
556           ASSERT (f->shr->size <= sm->max_fifo_size);
557         }
558     }
559 }
560
561 /*
562  * Enqueue data for delivery to session peer. Does not notify peer of enqueue
563  * event but on request can queue notification events for later delivery by
564  * calling stream_server_flush_enqueue_events().
565  *
566  * @param tc Transport connection which is to be enqueued data
567  * @param b Buffer to be enqueued
568  * @param offset Offset at which to start enqueueing if out-of-order
569  * @param queue_event Flag to indicate if peer is to be notified or if event
570  *                    is to be queued. The former is useful when more data is
571  *                    enqueued and only one event is to be generated.
572  * @param is_in_order Flag to indicate if data is in order
573  * @return Number of bytes enqueued or a negative value if enqueueing failed.
574  */
575 int
576 session_enqueue_stream_connection (transport_connection_t * tc,
577                                    vlib_buffer_t * b, u32 offset,
578                                    u8 queue_event, u8 is_in_order)
579 {
580   session_t *s;
581   int enqueued = 0, rv, in_order_off;
582
583   s = session_get (tc->s_index, tc->thread_index);
584
585   if (is_in_order)
586     {
587       enqueued = svm_fifo_enqueue (s->rx_fifo,
588                                    b->current_length,
589                                    vlib_buffer_get_current (b));
590       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT)
591                          && enqueued >= 0))
592         {
593           in_order_off = enqueued > b->current_length ? enqueued : 0;
594           rv = session_enqueue_chain_tail (s, b, in_order_off, 1);
595           if (rv > 0)
596             enqueued += rv;
597         }
598     }
599   else
600     {
601       rv = svm_fifo_enqueue_with_offset (s->rx_fifo, offset,
602                                          b->current_length,
603                                          vlib_buffer_get_current (b));
604       if (PREDICT_FALSE ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && !rv))
605         session_enqueue_chain_tail (s, b, offset + b->current_length, 0);
606       /* if something was enqueued, report even this as success for ooo
607        * segment handling */
608       return rv;
609     }
610
611   if (queue_event)
612     {
613       /* Queue RX event on this fifo. Eventually these will need to be flushed
614        * by calling stream_server_flush_enqueue_events () */
615       session_worker_t *wrk;
616
617       wrk = session_main_get_worker (s->thread_index);
618       if (!(s->flags & SESSION_F_RX_EVT))
619         {
620           s->flags |= SESSION_F_RX_EVT;
621           vec_add1 (wrk->session_to_enqueue[tc->proto], s->session_index);
622         }
623
624       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED, 0);
625     }
626
627   return enqueued;
628 }
629
630 int
631 session_enqueue_dgram_connection (session_t * s,
632                                   session_dgram_hdr_t * hdr,
633                                   vlib_buffer_t * b, u8 proto, u8 queue_event)
634 {
635   int rv;
636
637   ASSERT (svm_fifo_max_enqueue_prod (s->rx_fifo)
638           >= b->current_length + sizeof (*hdr));
639
640   if (PREDICT_TRUE (!(b->flags & VLIB_BUFFER_NEXT_PRESENT)))
641     {
642       /* *INDENT-OFF* */
643       svm_fifo_seg_t segs[2] = {
644           { (u8 *) hdr, sizeof (*hdr) },
645           { vlib_buffer_get_current (b), b->current_length }
646       };
647       /* *INDENT-ON* */
648
649       rv = svm_fifo_enqueue_segments (s->rx_fifo, segs, 2,
650                                       0 /* allow_partial */ );
651     }
652   else
653     {
654       vlib_main_t *vm = vlib_get_main ();
655       svm_fifo_seg_t *segs = 0, *seg;
656       vlib_buffer_t *it = b;
657       u32 n_segs = 1;
658
659       vec_add2 (segs, seg, 1);
660       seg->data = (u8 *) hdr;
661       seg->len = sizeof (*hdr);
662       while (it)
663         {
664           vec_add2 (segs, seg, 1);
665           seg->data = vlib_buffer_get_current (it);
666           seg->len = it->current_length;
667           n_segs++;
668           if (!(it->flags & VLIB_BUFFER_NEXT_PRESENT))
669             break;
670           it = vlib_get_buffer (vm, it->next_buffer);
671         }
672       rv = svm_fifo_enqueue_segments (s->rx_fifo, segs, n_segs,
673                                       0 /* allow partial */ );
674       vec_free (segs);
675     }
676
677   if (queue_event && rv > 0)
678     {
679       /* Queue RX event on this fifo. Eventually these will need to be flushed
680        * by calling stream_server_flush_enqueue_events () */
681       session_worker_t *wrk;
682
683       wrk = session_main_get_worker (s->thread_index);
684       if (!(s->flags & SESSION_F_RX_EVT))
685         {
686           s->flags |= SESSION_F_RX_EVT;
687           vec_add1 (wrk->session_to_enqueue[proto], s->session_index);
688         }
689
690       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED, 0);
691     }
692   return rv > 0 ? rv : 0;
693 }
694
695 int
696 session_tx_fifo_peek_bytes (transport_connection_t * tc, u8 * buffer,
697                             u32 offset, u32 max_bytes)
698 {
699   session_t *s = session_get (tc->s_index, tc->thread_index);
700   return svm_fifo_peek (s->tx_fifo, offset, max_bytes, buffer);
701 }
702
703 u32
704 session_tx_fifo_dequeue_drop (transport_connection_t * tc, u32 max_bytes)
705 {
706   session_t *s = session_get (tc->s_index, tc->thread_index);
707   u32 rv;
708
709   rv = svm_fifo_dequeue_drop (s->tx_fifo, max_bytes);
710   session_fifo_tuning (s, s->tx_fifo, SESSION_FT_ACTION_DEQUEUED, rv);
711
712   if (svm_fifo_needs_deq_ntf (s->tx_fifo, max_bytes))
713     session_dequeue_notify (s);
714
715   return rv;
716 }
717
718 static inline int
719 session_notify_subscribers (u32 app_index, session_t * s,
720                             svm_fifo_t * f, session_evt_type_t evt_type)
721 {
722   app_worker_t *app_wrk;
723   application_t *app;
724   int i;
725
726   app = application_get (app_index);
727   if (!app)
728     return -1;
729
730   for (i = 0; i < f->shr->n_subscribers; i++)
731     {
732       app_wrk = application_get_worker (app, f->shr->subscribers[i]);
733       if (!app_wrk)
734         continue;
735       if (app_worker_lock_and_send_event (app_wrk, s, evt_type))
736         return -1;
737     }
738
739   return 0;
740 }
741
742 /**
743  * Notify session peer that new data has been enqueued.
744  *
745  * @param s     Stream session for which the event is to be generated.
746  * @param lock  Flag to indicate if call should lock message queue.
747  *
748  * @return 0 on success or negative number if failed to send notification.
749  */
750 static inline int
751 session_enqueue_notify_inline (session_t * s)
752 {
753   app_worker_t *app_wrk;
754   u32 session_index;
755   u8 n_subscribers;
756   u32 thread_index;
757
758   session_index = s->session_index;
759   thread_index = s->thread_index;
760   n_subscribers = svm_fifo_n_subscribers (s->rx_fifo);
761
762   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
763   if (PREDICT_FALSE (!app_wrk))
764     {
765       SESSION_DBG ("invalid s->app_index = %d", s->app_wrk_index);
766       return 0;
767     }
768
769   SESSION_EVT (SESSION_EVT_ENQ, s, svm_fifo_max_dequeue_prod (s->rx_fifo));
770
771   s->flags &= ~SESSION_F_RX_EVT;
772
773   /* Application didn't confirm accept yet */
774   if (PREDICT_FALSE (s->session_state == SESSION_STATE_ACCEPTING))
775     return 0;
776
777   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
778                                                      SESSION_IO_EVT_RX)))
779     return -1;
780
781   if (PREDICT_FALSE (n_subscribers))
782     {
783       s = session_get (session_index, thread_index);
784       return session_notify_subscribers (app_wrk->app_index, s,
785                                          s->rx_fifo, SESSION_IO_EVT_RX);
786     }
787
788   return 0;
789 }
790
791 int
792 session_enqueue_notify (session_t * s)
793 {
794   return session_enqueue_notify_inline (s);
795 }
796
797 static void
798 session_enqueue_notify_rpc (void *arg)
799 {
800   u32 session_index = pointer_to_uword (arg);
801   session_t *s;
802
803   s = session_get_if_valid (session_index, vlib_get_thread_index ());
804   if (!s)
805     return;
806
807   session_enqueue_notify (s);
808 }
809
810 /**
811  * Like session_enqueue_notify, but can be called from a thread that does not
812  * own the session.
813  */
814 void
815 session_enqueue_notify_thread (session_handle_t sh)
816 {
817   u32 thread_index = session_thread_from_handle (sh);
818   u32 session_index = session_index_from_handle (sh);
819
820   /*
821    * Pass session index (u32) as opposed to handle (u64) in case pointers
822    * are not 64-bit.
823    */
824   session_send_rpc_evt_to_thread (thread_index,
825                                   session_enqueue_notify_rpc,
826                                   uword_to_pointer (session_index, void *));
827 }
828
829 int
830 session_dequeue_notify (session_t * s)
831 {
832   app_worker_t *app_wrk;
833
834   svm_fifo_clear_deq_ntf (s->tx_fifo);
835
836   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
837   if (PREDICT_FALSE (!app_wrk))
838     return -1;
839
840   if (PREDICT_FALSE (app_worker_lock_and_send_event (app_wrk, s,
841                                                      SESSION_IO_EVT_TX)))
842     return -1;
843
844   if (PREDICT_FALSE (s->tx_fifo->shr->n_subscribers))
845     return session_notify_subscribers (app_wrk->app_index, s,
846                                        s->tx_fifo, SESSION_IO_EVT_TX);
847
848   return 0;
849 }
850
851 /**
852  * Flushes queue of sessions that are to be notified of new data
853  * enqueued events.
854  *
855  * @param thread_index Thread index for which the flush is to be performed.
856  * @return 0 on success or a positive number indicating the number of
857  *         failures due to API queue being full.
858  */
859 int
860 session_main_flush_enqueue_events (u8 transport_proto, u32 thread_index)
861 {
862   session_worker_t *wrk = session_main_get_worker (thread_index);
863   session_t *s;
864   int i, errors = 0;
865   u32 *indices;
866
867   indices = wrk->session_to_enqueue[transport_proto];
868
869   for (i = 0; i < vec_len (indices); i++)
870     {
871       s = session_get_if_valid (indices[i], thread_index);
872       if (PREDICT_FALSE (!s))
873         {
874           errors++;
875           continue;
876         }
877
878       session_fifo_tuning (s, s->rx_fifo, SESSION_FT_ACTION_ENQUEUED,
879                            0 /* TODO/not needed */ );
880
881       if (PREDICT_FALSE (session_enqueue_notify_inline (s)))
882         errors++;
883     }
884
885   vec_reset_length (indices);
886   wrk->session_to_enqueue[transport_proto] = indices;
887
888   return errors;
889 }
890
891 int
892 session_main_flush_all_enqueue_events (u8 transport_proto)
893 {
894   vlib_thread_main_t *vtm = vlib_get_thread_main ();
895   int i, errors = 0;
896   for (i = 0; i < 1 + vtm->n_threads; i++)
897     errors += session_main_flush_enqueue_events (transport_proto, i);
898   return errors;
899 }
900
901 int
902 session_stream_connect_notify (transport_connection_t * tc,
903                                session_error_t err)
904 {
905   u32 opaque = 0, new_ti, new_si;
906   app_worker_t *app_wrk;
907   session_t *s = 0, *ho;
908
909   /*
910    * Cleanup half-open table
911    */
912   session_lookup_del_half_open (tc);
913
914   ho = ho_session_get (tc->s_index);
915   session_set_state (ho, SESSION_STATE_TRANSPORT_CLOSED);
916   opaque = ho->opaque;
917   app_wrk = app_worker_get_if_valid (ho->app_wrk_index);
918   if (!app_wrk)
919     return -1;
920
921   if (err)
922     return app_worker_connect_notify (app_wrk, s, err, opaque);
923
924   s = session_alloc_for_connection (tc);
925   session_set_state (s, SESSION_STATE_CONNECTING);
926   s->app_wrk_index = app_wrk->wrk_index;
927   new_si = s->session_index;
928   new_ti = s->thread_index;
929
930   if ((err = app_worker_init_connected (app_wrk, s)))
931     {
932       session_free (s);
933       app_worker_connect_notify (app_wrk, 0, err, opaque);
934       return -1;
935     }
936
937   s = session_get (new_si, new_ti);
938   session_set_state (s, SESSION_STATE_READY);
939   session_lookup_add_connection (tc, session_handle (s));
940
941   if (app_worker_connect_notify (app_wrk, s, SESSION_E_NONE, opaque))
942     {
943       session_lookup_del_connection (tc);
944       /* Avoid notifying app about rejected session cleanup */
945       s = session_get (new_si, new_ti);
946       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
947       session_free (s);
948       return -1;
949     }
950
951   return 0;
952 }
953
954 typedef union session_switch_pool_reply_args_
955 {
956   struct
957   {
958     u32 session_index;
959     u16 thread_index;
960     u8 is_closed;
961   };
962   u64 as_u64;
963 } session_switch_pool_reply_args_t;
964
965 STATIC_ASSERT (sizeof (session_switch_pool_reply_args_t) <= sizeof (uword),
966                "switch pool reply args size");
967
968 static void
969 session_switch_pool_reply (void *arg)
970 {
971   session_switch_pool_reply_args_t rargs;
972   session_t *s;
973
974   rargs.as_u64 = pointer_to_uword (arg);
975   s = session_get_if_valid (rargs.session_index, rargs.thread_index);
976   if (!s)
977     return;
978
979   /* Session closed during migration. Clean everything up */
980   if (rargs.is_closed)
981     {
982       transport_cleanup (session_get_transport_proto (s), s->connection_index,
983                          s->thread_index);
984       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
985       session_free (s);
986       return;
987     }
988
989   /* Notify app that it has data on the new session */
990   session_enqueue_notify (s);
991 }
992
993 typedef struct _session_switch_pool_args
994 {
995   u32 session_index;
996   u32 thread_index;
997   u32 new_thread_index;
998   u32 new_session_index;
999 } session_switch_pool_args_t;
1000
1001 /**
1002  * Notify old thread of the session pool switch
1003  */
1004 static void
1005 session_switch_pool (void *cb_args)
1006 {
1007   session_switch_pool_args_t *args = (session_switch_pool_args_t *) cb_args;
1008   session_switch_pool_reply_args_t rargs;
1009   session_handle_t new_sh;
1010   segment_manager_t *sm;
1011   app_worker_t *app_wrk;
1012   session_t *s;
1013
1014   ASSERT (args->thread_index == vlib_get_thread_index ());
1015   s = session_get (args->session_index, args->thread_index);
1016
1017   /* Check if session closed during migration */
1018   rargs.is_closed = s->session_state >= SESSION_STATE_TRANSPORT_CLOSING;
1019
1020   transport_cleanup (session_get_transport_proto (s), s->connection_index,
1021                      s->thread_index);
1022
1023   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
1024   if (app_wrk)
1025     {
1026       /* Cleanup fifo segment slice state for fifos */
1027       sm = app_worker_get_connect_segment_manager (app_wrk);
1028       segment_manager_detach_fifo (sm, &s->rx_fifo);
1029       segment_manager_detach_fifo (sm, &s->tx_fifo);
1030
1031       /* Notify app, using old session, about the migration event */
1032       if (!rargs.is_closed)
1033         {
1034           new_sh = session_make_handle (args->new_session_index,
1035                                         args->new_thread_index);
1036           app_worker_migrate_notify (app_wrk, s, new_sh);
1037         }
1038     }
1039
1040   /* Trigger app read and fifo updates on the new thread */
1041   rargs.session_index = args->new_session_index;
1042   rargs.thread_index = args->new_thread_index;
1043   session_send_rpc_evt_to_thread (args->new_thread_index,
1044                                   session_switch_pool_reply,
1045                                   uword_to_pointer (rargs.as_u64, void *));
1046
1047   session_free (s);
1048   clib_mem_free (cb_args);
1049 }
1050
1051 /**
1052  * Move dgram session to the right thread
1053  */
1054 int
1055 session_dgram_connect_notify (transport_connection_t * tc,
1056                               u32 old_thread_index, session_t ** new_session)
1057 {
1058   session_t *new_s;
1059   session_switch_pool_args_t *rpc_args;
1060   segment_manager_t *sm;
1061   app_worker_t *app_wrk;
1062
1063   /*
1064    * Clone half-open session to the right thread.
1065    */
1066   new_s = session_clone_safe (tc->s_index, old_thread_index);
1067   new_s->connection_index = tc->c_index;
1068   session_set_state (new_s, SESSION_STATE_READY);
1069   new_s->flags |= SESSION_F_IS_MIGRATING;
1070
1071   if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
1072     session_lookup_add_connection (tc, session_handle (new_s));
1073
1074   app_wrk = app_worker_get_if_valid (new_s->app_wrk_index);
1075   if (app_wrk)
1076     {
1077       /* New set of fifos attached to the same shared memory */
1078       sm = app_worker_get_connect_segment_manager (app_wrk);
1079       segment_manager_attach_fifo (sm, &new_s->rx_fifo, new_s);
1080       segment_manager_attach_fifo (sm, &new_s->tx_fifo, new_s);
1081     }
1082
1083   /*
1084    * Ask thread owning the old session to clean it up and make us the tx
1085    * fifo owner
1086    */
1087   rpc_args = clib_mem_alloc (sizeof (*rpc_args));
1088   rpc_args->new_session_index = new_s->session_index;
1089   rpc_args->new_thread_index = new_s->thread_index;
1090   rpc_args->session_index = tc->s_index;
1091   rpc_args->thread_index = old_thread_index;
1092   session_send_rpc_evt_to_thread (rpc_args->thread_index, session_switch_pool,
1093                                   rpc_args);
1094
1095   tc->s_index = new_s->session_index;
1096   new_s->connection_index = tc->c_index;
1097   *new_session = new_s;
1098   return 0;
1099 }
1100
1101 /**
1102  * Notification from transport that connection is being closed.
1103  *
1104  * A disconnect is sent to application but state is not removed. Once
1105  * disconnect is acknowledged by application, session disconnect is called.
1106  * Ultimately this leads to close being called on transport (passive close).
1107  */
1108 void
1109 session_transport_closing_notify (transport_connection_t * tc)
1110 {
1111   app_worker_t *app_wrk;
1112   session_t *s;
1113
1114   s = session_get (tc->s_index, tc->thread_index);
1115   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
1116     return;
1117
1118   /* Wait for reply from app before sending notification as the
1119    * accept might be rejected */
1120   if (s->session_state == SESSION_STATE_ACCEPTING)
1121     {
1122       session_set_state (s, SESSION_STATE_TRANSPORT_CLOSING);
1123       return;
1124     }
1125
1126   session_set_state (s, SESSION_STATE_TRANSPORT_CLOSING);
1127   app_wrk = app_worker_get (s->app_wrk_index);
1128   app_worker_close_notify (app_wrk, s);
1129 }
1130
1131 /**
1132  * Notification from transport that connection is being deleted
1133  *
1134  * This removes the session if it is still valid. It should be called only on
1135  * previously fully established sessions. For instance failed connects should
1136  * call stream_session_connect_notify and indicate that the connect has
1137  * failed.
1138  */
1139 void
1140 session_transport_delete_notify (transport_connection_t * tc)
1141 {
1142   session_t *s;
1143
1144   /* App might've been removed already */
1145   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
1146     return;
1147
1148   switch (s->session_state)
1149     {
1150     case SESSION_STATE_CREATED:
1151       /* Session was created but accept notification was not yet sent to the
1152        * app. Cleanup everything. */
1153       session_lookup_del_session (s);
1154       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1155       session_free (s);
1156       break;
1157     case SESSION_STATE_ACCEPTING:
1158     case SESSION_STATE_TRANSPORT_CLOSING:
1159     case SESSION_STATE_CLOSING:
1160     case SESSION_STATE_TRANSPORT_CLOSED:
1161       /* If transport finishes or times out before we get a reply
1162        * from the app, mark transport as closed and wait for reply
1163        * before removing the session. Cleanup session table in advance
1164        * because transport will soon be closed and closed sessions
1165        * are assumed to have been removed from the lookup table */
1166       session_lookup_del_session (s);
1167       session_set_state (s, SESSION_STATE_TRANSPORT_DELETED);
1168       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1169       svm_fifo_dequeue_drop_all (s->tx_fifo);
1170       break;
1171     case SESSION_STATE_APP_CLOSED:
1172       /* Cleanup lookup table as transport needs to still be valid.
1173        * Program transport close to ensure that all session events
1174        * have been cleaned up. Once transport close is called, the
1175        * session is just removed because both transport and app have
1176        * confirmed the close*/
1177       session_lookup_del_session (s);
1178       session_set_state (s, SESSION_STATE_TRANSPORT_DELETED);
1179       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1180       svm_fifo_dequeue_drop_all (s->tx_fifo);
1181       session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1182       break;
1183     case SESSION_STATE_TRANSPORT_DELETED:
1184       break;
1185     case SESSION_STATE_CLOSED:
1186       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1187       session_delete (s);
1188       break;
1189     default:
1190       clib_warning ("session state %u", s->session_state);
1191       session_cleanup_notify (s, SESSION_CLEANUP_TRANSPORT);
1192       session_delete (s);
1193       break;
1194     }
1195 }
1196
1197 /**
1198  * Notification from transport that it is closed
1199  *
1200  * Should be called by transport, prior to calling delete notify, once it
1201  * knows that no more data will be exchanged. This could serve as an
1202  * early acknowledgment of an active close especially if transport delete
1203  * can be delayed a long time, e.g., tcp time-wait.
1204  */
1205 void
1206 session_transport_closed_notify (transport_connection_t * tc)
1207 {
1208   app_worker_t *app_wrk;
1209   session_t *s;
1210
1211   if (!(s = session_get_if_valid (tc->s_index, tc->thread_index)))
1212     return;
1213
1214   /* Transport thinks that app requested close but it actually didn't.
1215    * Can happen for tcp:
1216    * 1)if fin and rst are received in close succession.
1217    * 2)if app shutdown the connection.  */
1218   if (s->session_state == SESSION_STATE_READY)
1219     {
1220       session_transport_closing_notify (tc);
1221       svm_fifo_dequeue_drop_all (s->tx_fifo);
1222       session_set_state (s, SESSION_STATE_TRANSPORT_CLOSED);
1223     }
1224   /* If app close has not been received or has not yet resulted in
1225    * a transport close, only mark the session transport as closed */
1226   else if (s->session_state <= SESSION_STATE_CLOSING)
1227     session_set_state (s, SESSION_STATE_TRANSPORT_CLOSED);
1228   /* If app also closed, switch to closed */
1229   else if (s->session_state == SESSION_STATE_APP_CLOSED)
1230     session_set_state (s, SESSION_STATE_CLOSED);
1231
1232   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
1233   if (app_wrk)
1234     app_worker_transport_closed_notify (app_wrk, s);
1235 }
1236
1237 /**
1238  * Notify application that connection has been reset.
1239  */
1240 void
1241 session_transport_reset_notify (transport_connection_t * tc)
1242 {
1243   app_worker_t *app_wrk;
1244   session_t *s;
1245
1246   s = session_get (tc->s_index, tc->thread_index);
1247   svm_fifo_dequeue_drop_all (s->tx_fifo);
1248   if (s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
1249     return;
1250   if (s->session_state == SESSION_STATE_ACCEPTING)
1251     {
1252       session_set_state (s, SESSION_STATE_TRANSPORT_CLOSING);
1253       return;
1254     }
1255   session_set_state (s, SESSION_STATE_TRANSPORT_CLOSING);
1256   app_wrk = app_worker_get (s->app_wrk_index);
1257   app_worker_reset_notify (app_wrk, s);
1258 }
1259
1260 int
1261 session_stream_accept_notify (transport_connection_t * tc)
1262 {
1263   app_worker_t *app_wrk;
1264   session_t *s;
1265
1266   s = session_get (tc->s_index, tc->thread_index);
1267   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
1268   if (!app_wrk)
1269     return -1;
1270   if (s->session_state != SESSION_STATE_CREATED)
1271     return 0;
1272   session_set_state (s, SESSION_STATE_ACCEPTING);
1273   if (app_worker_accept_notify (app_wrk, s))
1274     {
1275       /* On transport delete, no notifications should be sent. Unless, the
1276        * accept is retried and successful. */
1277       session_set_state (s, SESSION_STATE_CREATED);
1278       return -1;
1279     }
1280   return 0;
1281 }
1282
1283 /**
1284  * Accept a stream session. Optionally ping the server by callback.
1285  */
1286 int
1287 session_stream_accept (transport_connection_t * tc, u32 listener_index,
1288                        u32 thread_index, u8 notify)
1289 {
1290   session_t *s;
1291   int rv;
1292
1293   s = session_alloc_for_connection (tc);
1294   s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
1295   session_set_state (s, SESSION_STATE_CREATED);
1296
1297   if ((rv = app_worker_init_accepted (s)))
1298     {
1299       session_free (s);
1300       return rv;
1301     }
1302
1303   session_lookup_add_connection (tc, session_handle (s));
1304
1305   /* Shoulder-tap the server */
1306   if (notify)
1307     {
1308       app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
1309       if ((rv = app_worker_accept_notify (app_wrk, s)))
1310         {
1311           session_lookup_del_session (s);
1312           segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1313           session_free (s);
1314           return rv;
1315         }
1316     }
1317
1318   return 0;
1319 }
1320
1321 int
1322 session_dgram_accept (transport_connection_t * tc, u32 listener_index,
1323                       u32 thread_index)
1324 {
1325   app_worker_t *app_wrk;
1326   session_t *s;
1327   int rv;
1328
1329   s = session_alloc_for_connection (tc);
1330   s->listener_handle = ((u64) thread_index << 32) | (u64) listener_index;
1331
1332   if ((rv = app_worker_init_accepted (s)))
1333     {
1334       session_free (s);
1335       return rv;
1336     }
1337
1338   session_lookup_add_connection (tc, session_handle (s));
1339   session_set_state (s, SESSION_STATE_ACCEPTING);
1340
1341   app_wrk = app_worker_get (s->app_wrk_index);
1342   if ((rv = app_worker_accept_notify (app_wrk, s)))
1343     {
1344       session_lookup_del_session (s);
1345       segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1346       session_free (s);
1347       return rv;
1348     }
1349
1350   return 0;
1351 }
1352
1353 int
1354 session_open_cl (session_endpoint_cfg_t *rmt, session_handle_t *rsh)
1355 {
1356   transport_connection_t *tc;
1357   transport_endpoint_cfg_t *tep;
1358   app_worker_t *app_wrk;
1359   session_handle_t sh;
1360   session_t *s;
1361   int rv;
1362
1363   tep = session_endpoint_to_transport_cfg (rmt);
1364   rv = transport_connect (rmt->transport_proto, tep);
1365   if (rv < 0)
1366     {
1367       SESSION_DBG ("Transport failed to open connection.");
1368       return rv;
1369     }
1370
1371   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
1372
1373   /* For dgram type of service, allocate session and fifos now */
1374   app_wrk = app_worker_get (rmt->app_wrk_index);
1375   s = session_alloc_for_connection (tc);
1376   s->app_wrk_index = app_wrk->wrk_index;
1377   session_set_state (s, SESSION_STATE_OPENED);
1378   if (app_worker_init_connected (app_wrk, s))
1379     {
1380       session_free (s);
1381       return -1;
1382     }
1383
1384   sh = session_handle (s);
1385   *rsh = sh;
1386
1387   session_lookup_add_connection (tc, sh);
1388   return app_worker_connect_notify (app_wrk, s, SESSION_E_NONE, rmt->opaque);
1389 }
1390
1391 int
1392 session_open_vc (session_endpoint_cfg_t *rmt, session_handle_t *rsh)
1393 {
1394   transport_connection_t *tc;
1395   transport_endpoint_cfg_t *tep;
1396   app_worker_t *app_wrk;
1397   session_t *ho;
1398   int rv;
1399
1400   tep = session_endpoint_to_transport_cfg (rmt);
1401   rv = transport_connect (rmt->transport_proto, tep);
1402   if (rv < 0)
1403     {
1404       SESSION_DBG ("Transport failed to open connection.");
1405       return rv;
1406     }
1407
1408   tc = transport_get_half_open (rmt->transport_proto, (u32) rv);
1409
1410   app_wrk = app_worker_get (rmt->app_wrk_index);
1411
1412   /* If transport offers a vc service, only allocate established
1413    * session once the connection has been established.
1414    * In the meantime allocate half-open session for tracking purposes
1415    * associate half-open connection to it and add session to app-worker
1416    * half-open table. These are needed to allocate the established
1417    * session on transport notification, and to cleanup the half-open
1418    * session if the app detaches before connection establishment.
1419    */
1420   ho = session_alloc_for_half_open (tc);
1421   ho->app_wrk_index = app_wrk->wrk_index;
1422   ho->ho_index = app_worker_add_half_open (app_wrk, session_handle (ho));
1423   ho->opaque = rmt->opaque;
1424   *rsh = session_handle (ho);
1425
1426   if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
1427     session_lookup_add_half_open (tc, tc->c_index);
1428
1429   return 0;
1430 }
1431
1432 int
1433 session_open_app (session_endpoint_cfg_t *rmt, session_handle_t *rsh)
1434 {
1435   transport_endpoint_cfg_t *tep_cfg = session_endpoint_to_transport_cfg (rmt);
1436
1437   /* Not supported for now */
1438   *rsh = SESSION_INVALID_HANDLE;
1439   return transport_connect (rmt->transport_proto, tep_cfg);
1440 }
1441
1442 typedef int (*session_open_service_fn) (session_endpoint_cfg_t *,
1443                                         session_handle_t *);
1444
1445 /* *INDENT-OFF* */
1446 static session_open_service_fn session_open_srv_fns[TRANSPORT_N_SERVICES] = {
1447   session_open_vc,
1448   session_open_cl,
1449   session_open_app,
1450 };
1451 /* *INDENT-ON* */
1452
1453 /**
1454  * Ask transport to open connection to remote transport endpoint.
1455  *
1456  * Stores handle for matching request with reply since the call can be
1457  * asynchronous. For instance, for TCP the 3-way handshake must complete
1458  * before reply comes. Session is only created once connection is established.
1459  *
1460  * @param app_index Index of the application requesting the connect
1461  * @param st Session type requested.
1462  * @param tep Remote transport endpoint
1463  * @param opaque Opaque data (typically, api_context) the application expects
1464  *               on open completion.
1465  */
1466 int
1467 session_open (session_endpoint_cfg_t *rmt, session_handle_t *rsh)
1468 {
1469   transport_service_type_t tst;
1470   tst = transport_protocol_service_type (rmt->transport_proto);
1471   return session_open_srv_fns[tst](rmt, rsh);
1472 }
1473
1474 /**
1475  * Ask transport to listen on session endpoint.
1476  *
1477  * @param s Session for which listen will be called. Note that unlike
1478  *          established sessions, listen sessions are not associated to a
1479  *          thread.
1480  * @param sep Local endpoint to be listened on.
1481  */
1482 int
1483 session_listen (session_t * ls, session_endpoint_cfg_t * sep)
1484 {
1485   transport_endpoint_cfg_t *tep;
1486   int tc_index;
1487   u32 s_index;
1488
1489   /* Transport bind/listen */
1490   tep = session_endpoint_to_transport_cfg (sep);
1491   s_index = ls->session_index;
1492   tc_index = transport_start_listen (session_get_transport_proto (ls),
1493                                      s_index, tep);
1494
1495   if (tc_index < 0)
1496     return tc_index;
1497
1498   /* Attach transport to session. Lookup tables are populated by the app
1499    * worker because local tables (for ct sessions) are not backed by a fib */
1500   ls = listen_session_get (s_index);
1501   ls->connection_index = tc_index;
1502   ls->opaque = sep->opaque;
1503
1504   return 0;
1505 }
1506
1507 /**
1508  * Ask transport to stop listening on local transport endpoint.
1509  *
1510  * @param s Session to stop listening on. It must be in state LISTENING.
1511  */
1512 int
1513 session_stop_listen (session_t * s)
1514 {
1515   transport_proto_t tp = session_get_transport_proto (s);
1516   transport_connection_t *tc;
1517
1518   if (s->session_state != SESSION_STATE_LISTENING)
1519     return SESSION_E_NOLISTEN;
1520
1521   tc = transport_get_listener (tp, s->connection_index);
1522
1523   /* If no transport, assume everything was cleaned up already */
1524   if (!tc)
1525     return SESSION_E_NONE;
1526
1527   if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
1528     session_lookup_del_connection (tc);
1529
1530   transport_stop_listen (tp, s->connection_index);
1531   return 0;
1532 }
1533
1534 /**
1535  * Initialize session half-closing procedure.
1536  *
1537  * Note that half-closing will not change the state of the session.
1538  */
1539 void
1540 session_half_close (session_t *s)
1541 {
1542   if (!s)
1543     return;
1544
1545   session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_HALF_CLOSE);
1546 }
1547
1548 /**
1549  * Initialize session closing procedure.
1550  *
1551  * Request is always sent to session node to ensure that all outstanding
1552  * requests are served before transport is notified.
1553  */
1554 void
1555 session_close (session_t * s)
1556 {
1557   if (!s || (s->flags & SESSION_F_APP_CLOSED))
1558     return;
1559
1560   /* Transports can close and delete their state independent of app closes
1561    * and transport initiated state transitions can hide app closes. Instead
1562    * of extending the state machine to support separate tracking of app and
1563    * transport initiated closes, use a flag. */
1564   s->flags |= SESSION_F_APP_CLOSED;
1565
1566   if (s->session_state >= SESSION_STATE_CLOSING)
1567     {
1568       /* Session will only be removed once both app and transport
1569        * acknowledge the close */
1570       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED
1571           || s->session_state == SESSION_STATE_TRANSPORT_DELETED)
1572         session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1573       return;
1574     }
1575
1576   /* App closed so stop propagating dequeue notifications.
1577    * App might disconnect session before connected, in this case,
1578    * tx_fifo may not be setup yet, so clear only it's inited. */
1579   if (s->tx_fifo)
1580     svm_fifo_clear_deq_ntf (s->tx_fifo);
1581   session_set_state (s, SESSION_STATE_CLOSING);
1582   session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_CLOSE);
1583 }
1584
1585 /**
1586  * Force a close without waiting for data to be flushed
1587  */
1588 void
1589 session_reset (session_t * s)
1590 {
1591   if (s->session_state >= SESSION_STATE_CLOSING)
1592     return;
1593   /* Drop all outstanding tx data
1594    * App might disconnect session before connected, in this case,
1595    * tx_fifo may not be setup yet, so clear only it's inited. */
1596   if (s->tx_fifo)
1597     svm_fifo_dequeue_drop_all (s->tx_fifo);
1598   session_set_state (s, SESSION_STATE_CLOSING);
1599   session_program_transport_ctrl_evt (s, SESSION_CTRL_EVT_RESET);
1600 }
1601
1602 /**
1603  * Notify transport the session can be half-disconnected.
1604  *
1605  * Must be called from the session's thread.
1606  */
1607 void
1608 session_transport_half_close (session_t *s)
1609 {
1610   /* Only READY session can be half-closed */
1611   if (s->session_state != SESSION_STATE_READY)
1612     {
1613       return;
1614     }
1615
1616   transport_half_close (session_get_transport_proto (s), s->connection_index,
1617                         s->thread_index);
1618 }
1619
1620 /**
1621  * Notify transport the session can be disconnected. This should eventually
1622  * result in a delete notification that allows us to cleanup session state.
1623  * Called for both active/passive disconnects.
1624  *
1625  * Must be called from the session's thread.
1626  */
1627 void
1628 session_transport_close (session_t * s)
1629 {
1630   if (s->session_state >= SESSION_STATE_APP_CLOSED)
1631     {
1632       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1633         session_set_state (s, SESSION_STATE_CLOSED);
1634       /* If transport is already deleted, just free the session */
1635       else if (s->session_state >= SESSION_STATE_TRANSPORT_DELETED)
1636         session_free_w_fifos (s);
1637       return;
1638     }
1639
1640   /* If the tx queue wasn't drained, the transport can continue to try
1641    * sending the outstanding data (in closed state it cannot). It MUST however
1642    * at one point, either after sending everything or after a timeout, call
1643    * delete notify. This will finally lead to the complete cleanup of the
1644    * session.
1645    */
1646   session_set_state (s, SESSION_STATE_APP_CLOSED);
1647
1648   transport_close (session_get_transport_proto (s), s->connection_index,
1649                    s->thread_index);
1650 }
1651
1652 /**
1653  * Force transport close
1654  */
1655 void
1656 session_transport_reset (session_t * s)
1657 {
1658   if (s->session_state >= SESSION_STATE_APP_CLOSED)
1659     {
1660       if (s->session_state == SESSION_STATE_TRANSPORT_CLOSED)
1661         session_set_state (s, SESSION_STATE_CLOSED);
1662       else if (s->session_state >= SESSION_STATE_TRANSPORT_DELETED)
1663         session_free_w_fifos (s);
1664       return;
1665     }
1666
1667   session_set_state (s, SESSION_STATE_APP_CLOSED);
1668   transport_reset (session_get_transport_proto (s), s->connection_index,
1669                    s->thread_index);
1670 }
1671
1672 /**
1673  * Cleanup transport and session state.
1674  *
1675  * Notify transport of the cleanup and free the session. This should
1676  * be called only if transport reported some error and is already
1677  * closed.
1678  */
1679 void
1680 session_transport_cleanup (session_t * s)
1681 {
1682   /* Delete from main lookup table before we axe the the transport */
1683   session_lookup_del_session (s);
1684   if (s->session_state != SESSION_STATE_TRANSPORT_DELETED)
1685     transport_cleanup (session_get_transport_proto (s), s->connection_index,
1686                        s->thread_index);
1687   /* Since we called cleanup, no delete notification will come. So, make
1688    * sure the session is properly freed. */
1689   segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1690   session_free (s);
1691 }
1692
1693 /**
1694  * Allocate worker mqs in share-able segment
1695  *
1696  * That can only be a newly created memfd segment, that must be mapped
1697  * by all apps/stack users unless private rx mqs are enabled.
1698  */
1699 void
1700 session_vpp_wrk_mqs_alloc (session_main_t *smm)
1701 {
1702   u32 mq_q_length = 2048, evt_size = sizeof (session_event_t);
1703   fifo_segment_t *mqs_seg = &smm->wrk_mqs_segment;
1704   svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
1705   uword mqs_seg_size;
1706   int i;
1707
1708   mq_q_length = clib_max (mq_q_length, smm->configured_wrk_mq_length);
1709
1710   svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
1711     { mq_q_length, evt_size, 0 }, { mq_q_length >> 1, 256, 0 }
1712   };
1713   cfg->consumer_pid = 0;
1714   cfg->n_rings = 2;
1715   cfg->q_nitems = mq_q_length;
1716   cfg->ring_cfgs = rc;
1717
1718   /*
1719    * Compute mqs segment size based on rings config and leave space
1720    * for passing extended configuration messages, i.e., data allocated
1721    * outside of the rings. If provided with a config value, accept it
1722    * if larger than minimum size.
1723    */
1724   mqs_seg_size = svm_msg_q_size_to_alloc (cfg) * vec_len (smm->wrk);
1725   mqs_seg_size = mqs_seg_size + (1 << 20);
1726   mqs_seg_size = clib_max (mqs_seg_size, smm->wrk_mqs_segment_size);
1727
1728   mqs_seg->ssvm.ssvm_size = mqs_seg_size;
1729   mqs_seg->ssvm.my_pid = getpid ();
1730   mqs_seg->ssvm.name = format (0, "%s%c", "session: wrk-mqs-segment", 0);
1731
1732   if (ssvm_server_init (&mqs_seg->ssvm, SSVM_SEGMENT_MEMFD))
1733     {
1734       clib_warning ("failed to initialize queue segment");
1735       return;
1736     }
1737
1738   fifo_segment_init (mqs_seg);
1739
1740   /* Special fifo segment that's filled only with mqs */
1741   mqs_seg->h->n_mqs = vec_len (smm->wrk);
1742
1743   for (i = 0; i < vec_len (smm->wrk); i++)
1744     smm->wrk[i].vpp_event_queue = fifo_segment_msg_q_alloc (mqs_seg, i, cfg);
1745 }
1746
1747 fifo_segment_t *
1748 session_main_get_wrk_mqs_segment (void)
1749 {
1750   return &session_main.wrk_mqs_segment;
1751 }
1752
1753 u64
1754 session_segment_handle (session_t * s)
1755 {
1756   svm_fifo_t *f;
1757
1758   if (!s->rx_fifo)
1759     return SESSION_INVALID_HANDLE;
1760
1761   f = s->rx_fifo;
1762   return segment_manager_make_segment_handle (f->segment_manager,
1763                                               f->segment_index);
1764 }
1765
1766 void
1767 session_get_original_dst (transport_endpoint_t *i2o_src,
1768                           transport_endpoint_t *i2o_dst,
1769                           transport_proto_t transport_proto, u32 *original_dst,
1770                           u16 *original_dst_port)
1771 {
1772   session_main_t *smm = vnet_get_session_main ();
1773   ip_protocol_t proto =
1774     (transport_proto == TRANSPORT_PROTO_TCP ? IPPROTO_TCP : IPPROTO_UDP);
1775   if (!smm->original_dst_lookup || !i2o_dst->is_ip4)
1776     return;
1777   smm->original_dst_lookup (&i2o_src->ip.ip4, i2o_src->port, &i2o_dst->ip.ip4,
1778                             i2o_dst->port, proto, original_dst,
1779                             original_dst_port);
1780 }
1781
1782 /* *INDENT-OFF* */
1783 static session_fifo_rx_fn *session_tx_fns[TRANSPORT_TX_N_FNS] = {
1784     session_tx_fifo_peek_and_snd,
1785     session_tx_fifo_dequeue_and_snd,
1786     session_tx_fifo_dequeue_internal,
1787     session_tx_fifo_dequeue_and_snd
1788 };
1789 /* *INDENT-ON* */
1790
1791 void
1792 session_register_transport (transport_proto_t transport_proto,
1793                             const transport_proto_vft_t * vft, u8 is_ip4,
1794                             u32 output_node)
1795 {
1796   session_main_t *smm = &session_main;
1797   session_type_t session_type;
1798   u32 next_index = ~0;
1799
1800   session_type = session_type_from_proto_and_ip (transport_proto, is_ip4);
1801
1802   vec_validate (smm->session_type_to_next, session_type);
1803   vec_validate (smm->session_tx_fns, session_type);
1804
1805   if (output_node != ~0)
1806     next_index = vlib_node_add_next (vlib_get_main (),
1807                                      session_queue_node.index, output_node);
1808
1809   smm->session_type_to_next[session_type] = next_index;
1810   smm->session_tx_fns[session_type] =
1811     session_tx_fns[vft->transport_options.tx_type];
1812 }
1813
1814 void
1815 session_register_update_time_fn (session_update_time_fn fn, u8 is_add)
1816 {
1817   session_main_t *smm = &session_main;
1818   session_update_time_fn *fi;
1819   u32 fi_pos = ~0;
1820   u8 found = 0;
1821
1822   vec_foreach (fi, smm->update_time_fns)
1823     {
1824       if (*fi == fn)
1825         {
1826           fi_pos = fi - smm->update_time_fns;
1827           found = 1;
1828           break;
1829         }
1830     }
1831
1832   if (is_add)
1833     {
1834       if (found)
1835         {
1836           clib_warning ("update time fn %p already registered", fn);
1837           return;
1838         }
1839       vec_add1 (smm->update_time_fns, fn);
1840     }
1841   else
1842     {
1843       vec_del1 (smm->update_time_fns, fi_pos);
1844     }
1845 }
1846
1847 transport_proto_t
1848 session_add_transport_proto (void)
1849 {
1850   session_main_t *smm = &session_main;
1851   session_worker_t *wrk;
1852   u32 thread;
1853
1854   smm->last_transport_proto_type += 1;
1855
1856   for (thread = 0; thread < vec_len (smm->wrk); thread++)
1857     {
1858       wrk = session_main_get_worker (thread);
1859       vec_validate (wrk->session_to_enqueue, smm->last_transport_proto_type);
1860     }
1861
1862   return smm->last_transport_proto_type;
1863 }
1864
1865 transport_connection_t *
1866 session_get_transport (session_t * s)
1867 {
1868   if (s->session_state != SESSION_STATE_LISTENING)
1869     return transport_get_connection (session_get_transport_proto (s),
1870                                      s->connection_index, s->thread_index);
1871   else
1872     return transport_get_listener (session_get_transport_proto (s),
1873                                    s->connection_index);
1874 }
1875
1876 void
1877 session_get_endpoint (session_t * s, transport_endpoint_t * tep, u8 is_lcl)
1878 {
1879   if (s->session_state != SESSION_STATE_LISTENING)
1880     return transport_get_endpoint (session_get_transport_proto (s),
1881                                    s->connection_index, s->thread_index, tep,
1882                                    is_lcl);
1883   else
1884     return transport_get_listener_endpoint (session_get_transport_proto (s),
1885                                             s->connection_index, tep, is_lcl);
1886 }
1887
1888 int
1889 session_transport_attribute (session_t *s, u8 is_get,
1890                              transport_endpt_attr_t *attr)
1891 {
1892   if (s->session_state < SESSION_STATE_READY)
1893     return -1;
1894
1895   return transport_connection_attribute (session_get_transport_proto (s),
1896                                          s->connection_index, s->thread_index,
1897                                          is_get, attr);
1898 }
1899
1900 transport_connection_t *
1901 listen_session_get_transport (session_t * s)
1902 {
1903   return transport_get_listener (session_get_transport_proto (s),
1904                                  s->connection_index);
1905 }
1906
1907 void
1908 session_queue_run_on_main_thread (vlib_main_t * vm)
1909 {
1910   ASSERT (vlib_get_thread_index () == 0);
1911   vlib_node_set_interrupt_pending (vm, session_queue_node.index);
1912 }
1913
1914 static void
1915 session_stats_collector_fn (vlib_stats_collector_data_t *d)
1916 {
1917   u32 i, n_workers, n_wrk_sessions, n_sessions = 0;
1918   session_main_t *smm = &session_main;
1919   session_worker_t *wrk;
1920   counter_t **counters;
1921   counter_t *cb;
1922
1923   n_workers = vec_len (smm->wrk);
1924   vlib_stats_validate (d->entry_index, 0, n_workers - 1);
1925   counters = d->entry->data;
1926   cb = counters[0];
1927
1928   for (i = 0; i < vec_len (smm->wrk); i++)
1929     {
1930       wrk = session_main_get_worker (i);
1931       n_wrk_sessions = pool_elts (wrk->sessions);
1932       cb[i] = n_wrk_sessions;
1933       n_sessions += n_wrk_sessions;
1934     }
1935
1936   vlib_stats_set_gauge (d->private_data, n_sessions);
1937 }
1938
1939 static void
1940 session_stats_collector_init (void)
1941 {
1942   vlib_stats_collector_reg_t reg = {};
1943
1944   reg.entry_index =
1945     vlib_stats_add_counter_vector ("/sys/session/sessions_per_worker");
1946   reg.private_data = vlib_stats_add_gauge ("/sys/session/sessions_total");
1947   reg.collect_fn = session_stats_collector_fn;
1948   vlib_stats_register_collector_fn (&reg);
1949   vlib_stats_validate (reg.entry_index, 0, vlib_get_n_threads ());
1950 }
1951
1952 static clib_error_t *
1953 session_manager_main_enable (vlib_main_t * vm)
1954 {
1955   session_main_t *smm = &session_main;
1956   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1957   u32 num_threads, preallocated_sessions_per_worker;
1958   session_worker_t *wrk;
1959   int i;
1960
1961   /* We only initialize once and do not de-initialized on disable */
1962   if (smm->is_initialized)
1963     goto done;
1964
1965   num_threads = 1 /* main thread */  + vtm->n_threads;
1966
1967   if (num_threads < 1)
1968     return clib_error_return (0, "n_thread_stacks not set");
1969
1970   /* Allocate cache line aligned worker contexts */
1971   vec_validate_aligned (smm->wrk, num_threads - 1, CLIB_CACHE_LINE_BYTES);
1972   clib_spinlock_init (&session_main.pool_realloc_lock);
1973
1974   for (i = 0; i < num_threads; i++)
1975     {
1976       wrk = &smm->wrk[i];
1977       wrk->ctrl_head = clib_llist_make_head (wrk->event_elts, evt_list);
1978       wrk->new_head = clib_llist_make_head (wrk->event_elts, evt_list);
1979       wrk->old_head = clib_llist_make_head (wrk->event_elts, evt_list);
1980       wrk->pending_connects = clib_llist_make_head (wrk->event_elts, evt_list);
1981       wrk->evts_pending_main =
1982         clib_llist_make_head (wrk->event_elts, evt_list);
1983       wrk->vm = vlib_get_main_by_index (i);
1984       wrk->last_vlib_time = vlib_time_now (vm);
1985       wrk->last_vlib_us_time = wrk->last_vlib_time * CLIB_US_TIME_FREQ;
1986       wrk->timerfd = -1;
1987       vec_validate (wrk->session_to_enqueue, smm->last_transport_proto_type);
1988
1989       if (!smm->no_adaptive && smm->use_private_rx_mqs)
1990         session_wrk_enable_adaptive_mode (wrk);
1991     }
1992
1993   /* Allocate vpp event queues segment and queue */
1994   session_vpp_wrk_mqs_alloc (smm);
1995
1996   /* Initialize segment manager properties */
1997   segment_manager_main_init ();
1998
1999   /* Preallocate sessions */
2000   if (smm->preallocated_sessions)
2001     {
2002       if (num_threads == 1)
2003         {
2004           pool_init_fixed (smm->wrk[0].sessions, smm->preallocated_sessions);
2005         }
2006       else
2007         {
2008           int j;
2009           preallocated_sessions_per_worker =
2010             (1.1 * (f64) smm->preallocated_sessions /
2011              (f64) (num_threads - 1));
2012
2013           for (j = 1; j < num_threads; j++)
2014             {
2015               pool_init_fixed (smm->wrk[j].sessions,
2016                                preallocated_sessions_per_worker);
2017             }
2018         }
2019     }
2020
2021   session_lookup_init ();
2022   app_namespaces_init ();
2023   transport_init ();
2024   session_stats_collector_init ();
2025   smm->is_initialized = 1;
2026
2027 done:
2028
2029   smm->is_enabled = 1;
2030
2031   /* Enable transports */
2032   transport_enable_disable (vm, 1);
2033   session_debug_init ();
2034
2035   return 0;
2036 }
2037
2038 static void
2039 session_manager_main_disable (vlib_main_t * vm)
2040 {
2041   transport_enable_disable (vm, 0 /* is_en */ );
2042 }
2043
2044 /* in this new callback, cookie hint the index */
2045 void
2046 session_dma_completion_cb (vlib_main_t *vm, struct vlib_dma_batch *batch)
2047 {
2048   session_worker_t *wrk;
2049   wrk = session_main_get_worker (vm->thread_index);
2050   session_dma_transfer *dma_transfer;
2051
2052   dma_transfer = &wrk->dma_trans[wrk->trans_head];
2053   vec_add (wrk->pending_tx_buffers, dma_transfer->pending_tx_buffers,
2054            vec_len (dma_transfer->pending_tx_buffers));
2055   vec_add (wrk->pending_tx_nexts, dma_transfer->pending_tx_nexts,
2056            vec_len (dma_transfer->pending_tx_nexts));
2057   vec_reset_length (dma_transfer->pending_tx_buffers);
2058   vec_reset_length (dma_transfer->pending_tx_nexts);
2059   wrk->trans_head++;
2060   if (wrk->trans_head == wrk->trans_size)
2061     wrk->trans_head = 0;
2062   return;
2063 }
2064
2065 static void
2066 session_prepare_dma_args (vlib_dma_config_t *args)
2067 {
2068   args->max_batches = 16;
2069   args->max_transfers = DMA_TRANS_SIZE;
2070   args->max_transfer_size = 65536;
2071   args->features = 0;
2072   args->sw_fallback = 1;
2073   args->barrier_before_last = 1;
2074   args->callback_fn = session_dma_completion_cb;
2075 }
2076
2077 static void
2078 session_node_enable_dma (u8 is_en, int n_vlibs)
2079 {
2080   vlib_dma_config_t args;
2081   session_prepare_dma_args (&args);
2082   session_worker_t *wrk;
2083   vlib_main_t *vm;
2084
2085   int config_index = -1;
2086
2087   if (is_en)
2088     {
2089       vm = vlib_get_main_by_index (0);
2090       config_index = vlib_dma_config_add (vm, &args);
2091     }
2092   else
2093     {
2094       vm = vlib_get_main_by_index (0);
2095       wrk = session_main_get_worker (0);
2096       if (wrk->config_index >= 0)
2097         vlib_dma_config_del (vm, wrk->config_index);
2098     }
2099   int i;
2100   for (i = 0; i < n_vlibs; i++)
2101     {
2102       vm = vlib_get_main_by_index (i);
2103       wrk = session_main_get_worker (vm->thread_index);
2104       wrk->config_index = config_index;
2105       if (is_en)
2106         {
2107           if (config_index >= 0)
2108             wrk->dma_enabled = true;
2109           wrk->dma_trans = (session_dma_transfer *) clib_mem_alloc (
2110             sizeof (session_dma_transfer) * DMA_TRANS_SIZE);
2111           bzero (wrk->dma_trans,
2112                  sizeof (session_dma_transfer) * DMA_TRANS_SIZE);
2113         }
2114       else
2115         {
2116           if (wrk->dma_trans)
2117             clib_mem_free (wrk->dma_trans);
2118         }
2119       wrk->trans_head = 0;
2120       wrk->trans_tail = 0;
2121       wrk->trans_size = DMA_TRANS_SIZE;
2122     }
2123 }
2124
2125 void
2126 session_node_enable_disable (u8 is_en)
2127 {
2128   u8 mstate = is_en ? VLIB_NODE_STATE_INTERRUPT : VLIB_NODE_STATE_DISABLED;
2129   u8 state = is_en ? VLIB_NODE_STATE_POLLING : VLIB_NODE_STATE_DISABLED;
2130   session_main_t *sm = &session_main;
2131   vlib_main_t *vm;
2132   vlib_node_t *n;
2133   int n_vlibs, i;
2134
2135   n_vlibs = vlib_get_n_threads ();
2136   for (i = 0; i < n_vlibs; i++)
2137     {
2138       vm = vlib_get_main_by_index (i);
2139       /* main thread with workers and not polling */
2140       if (i == 0 && n_vlibs > 1)
2141         {
2142           vlib_node_set_state (vm, session_queue_node.index, mstate);
2143           if (is_en)
2144             {
2145               session_main_get_worker (0)->state = SESSION_WRK_INTERRUPT;
2146               vlib_node_set_state (vm, session_queue_process_node.index,
2147                                    state);
2148               n = vlib_get_node (vm, session_queue_process_node.index);
2149               vlib_start_process (vm, n->runtime_index);
2150             }
2151           else
2152             {
2153               vlib_process_signal_event_mt (vm,
2154                                             session_queue_process_node.index,
2155                                             SESSION_Q_PROCESS_STOP, 0);
2156             }
2157           if (!sm->poll_main)
2158             continue;
2159         }
2160       vlib_node_set_state (vm, session_queue_node.index, state);
2161     }
2162
2163   if (sm->use_private_rx_mqs)
2164     application_enable_rx_mqs_nodes (is_en);
2165
2166   if (sm->dma_enabled)
2167     session_node_enable_dma (is_en, n_vlibs);
2168 }
2169
2170 clib_error_t *
2171 vnet_session_enable_disable (vlib_main_t * vm, u8 is_en)
2172 {
2173   clib_error_t *error = 0;
2174   if (is_en)
2175     {
2176       if (session_main.is_enabled)
2177         return 0;
2178
2179       error = session_manager_main_enable (vm);
2180       session_node_enable_disable (is_en);
2181     }
2182   else
2183     {
2184       session_main.is_enabled = 0;
2185       session_manager_main_disable (vm);
2186       session_node_enable_disable (is_en);
2187     }
2188
2189   return error;
2190 }
2191
2192 clib_error_t *
2193 session_main_init (vlib_main_t * vm)
2194 {
2195   session_main_t *smm = &session_main;
2196
2197   smm->is_enabled = 0;
2198   smm->session_enable_asap = 0;
2199   smm->poll_main = 0;
2200   smm->use_private_rx_mqs = 0;
2201   smm->no_adaptive = 0;
2202   smm->last_transport_proto_type = TRANSPORT_PROTO_HTTP;
2203
2204   return 0;
2205 }
2206
2207 static clib_error_t *
2208 session_main_loop_init (vlib_main_t * vm)
2209 {
2210   session_main_t *smm = &session_main;
2211   if (smm->session_enable_asap)
2212     {
2213       vlib_worker_thread_barrier_sync (vm);
2214       vnet_session_enable_disable (vm, 1 /* is_en */ );
2215       vlib_worker_thread_barrier_release (vm);
2216     }
2217   return 0;
2218 }
2219
2220 VLIB_INIT_FUNCTION (session_main_init);
2221 VLIB_MAIN_LOOP_ENTER_FUNCTION (session_main_loop_init);
2222
2223 static clib_error_t *
2224 session_config_fn (vlib_main_t * vm, unformat_input_t * input)
2225 {
2226   session_main_t *smm = &session_main;
2227   u32 nitems;
2228   uword tmp;
2229
2230   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2231     {
2232       if (unformat (input, "wrk-mq-length %d", &nitems))
2233         {
2234           if (nitems >= 2048)
2235             smm->configured_wrk_mq_length = nitems;
2236           else
2237             clib_warning ("event queue length %d too small, ignored", nitems);
2238         }
2239       else if (unformat (input, "wrk-mqs-segment-size %U",
2240                          unformat_memory_size, &smm->wrk_mqs_segment_size))
2241         ;
2242       else if (unformat (input, "preallocated-sessions %d",
2243                          &smm->preallocated_sessions))
2244         ;
2245       else if (unformat (input, "v4-session-table-buckets %d",
2246                          &smm->configured_v4_session_table_buckets))
2247         ;
2248       else if (unformat (input, "v4-halfopen-table-buckets %d",
2249                          &smm->configured_v4_halfopen_table_buckets))
2250         ;
2251       else if (unformat (input, "v6-session-table-buckets %d",
2252                          &smm->configured_v6_session_table_buckets))
2253         ;
2254       else if (unformat (input, "v6-halfopen-table-buckets %d",
2255                          &smm->configured_v6_halfopen_table_buckets))
2256         ;
2257       else if (unformat (input, "v4-session-table-memory %U",
2258                          unformat_memory_size, &tmp))
2259         {
2260           if (tmp >= 0x100000000)
2261             return clib_error_return (0, "memory size %llx (%lld) too large",
2262                                       tmp, tmp);
2263           smm->configured_v4_session_table_memory = tmp;
2264         }
2265       else if (unformat (input, "v4-halfopen-table-memory %U",
2266                          unformat_memory_size, &tmp))
2267         {
2268           if (tmp >= 0x100000000)
2269             return clib_error_return (0, "memory size %llx (%lld) too large",
2270                                       tmp, tmp);
2271           smm->configured_v4_halfopen_table_memory = tmp;
2272         }
2273       else if (unformat (input, "v6-session-table-memory %U",
2274                          unformat_memory_size, &tmp))
2275         {
2276           if (tmp >= 0x100000000)
2277             return clib_error_return (0, "memory size %llx (%lld) too large",
2278                                       tmp, tmp);
2279           smm->configured_v6_session_table_memory = tmp;
2280         }
2281       else if (unformat (input, "v6-halfopen-table-memory %U",
2282                          unformat_memory_size, &tmp))
2283         {
2284           if (tmp >= 0x100000000)
2285             return clib_error_return (0, "memory size %llx (%lld) too large",
2286                                       tmp, tmp);
2287           smm->configured_v6_halfopen_table_memory = tmp;
2288         }
2289       else if (unformat (input, "local-endpoints-table-memory %U",
2290                          unformat_memory_size, &tmp))
2291         {
2292           if (tmp >= 0x100000000)
2293             return clib_error_return (0, "memory size %llx (%lld) too large",
2294                                       tmp, tmp);
2295           smm->local_endpoints_table_memory = tmp;
2296         }
2297       else if (unformat (input, "local-endpoints-table-buckets %d",
2298                          &smm->local_endpoints_table_buckets))
2299         ;
2300       else if (unformat (input, "enable"))
2301         smm->session_enable_asap = 1;
2302       else if (unformat (input, "use-app-socket-api"))
2303         (void) appns_sapi_enable_disable (1 /* is_enable */);
2304       else if (unformat (input, "poll-main"))
2305         smm->poll_main = 1;
2306       else if (unformat (input, "use-private-rx-mqs"))
2307         smm->use_private_rx_mqs = 1;
2308       else if (unformat (input, "no-adaptive"))
2309         smm->no_adaptive = 1;
2310       else if (unformat (input, "use-dma"))
2311         smm->dma_enabled = 1;
2312       else if (unformat (input, "nat44-original-dst-enable"))
2313         {
2314           smm->original_dst_lookup = vlib_get_plugin_symbol (
2315             "nat_plugin.so", "nat44_original_dst_lookup");
2316         }
2317       /*
2318        * Deprecated but maintained for compatibility
2319        */
2320       else if (unformat (input, "evt_qs_memfd_seg"))
2321         ;
2322       else if (unformat (input, "segment-baseva 0x%lx", &tmp))
2323         ;
2324       else if (unformat (input, "evt_qs_seg_size %U", unformat_memory_size,
2325                          &smm->wrk_mqs_segment_size))
2326         ;
2327       else if (unformat (input, "event-queue-length %d", &nitems))
2328         {
2329           if (nitems >= 2048)
2330             smm->configured_wrk_mq_length = nitems;
2331           else
2332             clib_warning ("event queue length %d too small, ignored", nitems);
2333         }
2334       else
2335         return clib_error_return (0, "unknown input `%U'",
2336                                   format_unformat_error, input);
2337     }
2338   return 0;
2339 }
2340
2341 VLIB_CONFIG_FUNCTION (session_config_fn, "session");
2342
2343 /*
2344  * fd.io coding-style-patch-verification: ON
2345  *
2346  * Local Variables:
2347  * eval: (c-set-style "gnu")
2348  * End:
2349  */