session: safe pools for cut-through sessions
[vpp.git] / src / vnet / session / application_local.c
1 /*
2  * Copyright (c) 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 #include <vnet/session/application_local.h>
17 #include <vnet/session/session.h>
18
19 typedef enum ct_segment_flags_
20 {
21   CT_SEGMENT_F_CLIENT_DETACHED = 1 << 0,
22   CT_SEGMENT_F_SERVER_DETACHED = 1 << 1,
23 } ct_segment_flags_t;
24
25 typedef struct ct_segment_
26 {
27   u32 client_n_sessions;
28   u32 server_n_sessions;
29   u32 seg_ctx_index;
30   u32 ct_seg_index;
31   u32 segment_index;
32   ct_segment_flags_t flags;
33 } ct_segment_t;
34
35 typedef struct ct_segments_
36 {
37   u32 sm_index;
38   u32 server_wrk;
39   u32 client_wrk;
40   u32 fifo_pair_bytes;
41   ct_segment_t *segments;
42 } ct_segments_ctx_t;
43
44 typedef struct ct_cleanup_req_
45 {
46   u32 ct_index;
47 } ct_cleanup_req_t;
48
49 typedef struct ct_worker_
50 {
51   ct_connection_t *connections;       /**< Per-worker connection pools */
52   u32 *pending_connects;              /**< Fifo of pending ho indices */
53   ct_cleanup_req_t *pending_cleanups; /**< Fifo of pending indices */
54   u8 have_connects;                   /**< Set if connect rpc pending */
55   u8 have_cleanups;                   /**< Set if cleanup rpc pending */
56 } ct_worker_t;
57
58 typedef struct ct_main_
59 {
60   ct_worker_t *wrk;                     /**< Per-worker state */
61   u32 n_workers;                        /**< Number of vpp workers */
62   u32 n_sessions;                       /**< Cumulative sessions counter */
63   u32 *ho_reusable;                     /**< Vector of reusable ho indices */
64   clib_spinlock_t ho_reuseable_lock;    /**< Lock for reusable ho indices */
65   clib_rwlock_t app_segs_lock;          /**< RW lock for seg contexts */
66   uword *app_segs_ctxs_table;           /**< App handle to segment pool map */
67   ct_segments_ctx_t *app_seg_ctxs;      /**< Pool of ct segment contexts */
68 } ct_main_t;
69
70 static ct_main_t ct_main;
71
72 static inline ct_worker_t *
73 ct_worker_get (u32 thread_index)
74 {
75   return &ct_main.wrk[thread_index];
76 }
77
78 static ct_connection_t *
79 ct_connection_alloc (u32 thread_index)
80 {
81   ct_worker_t *wrk = ct_worker_get (thread_index);
82   ct_connection_t *ct;
83
84   pool_get_aligned_safe (wrk->connections, ct, CLIB_CACHE_LINE_BYTES);
85   clib_memset (ct, 0, sizeof (*ct));
86   ct->c_c_index = ct - wrk->connections;
87   ct->c_thread_index = thread_index;
88   ct->client_wrk = ~0;
89   ct->server_wrk = ~0;
90   ct->seg_ctx_index = ~0;
91   ct->ct_seg_index = ~0;
92   return ct;
93 }
94
95 static ct_connection_t *
96 ct_connection_get (u32 ct_index, u32 thread_index)
97 {
98   ct_worker_t *wrk = ct_worker_get (thread_index);
99
100   if (pool_is_free_index (wrk->connections, ct_index))
101     return 0;
102   return pool_elt_at_index (wrk->connections, ct_index);
103 }
104
105 static void
106 ct_connection_free (ct_connection_t * ct)
107 {
108   ct_worker_t *wrk = ct_worker_get (ct->c_thread_index);
109
110   if (CLIB_DEBUG)
111     {
112       clib_memset (ct, 0xfc, sizeof (*ct));
113       pool_put (wrk->connections, ct);
114       return;
115     }
116   pool_put (wrk->connections, ct);
117 }
118
119 static ct_connection_t *
120 ct_half_open_alloc (void)
121 {
122   ct_main_t *cm = &ct_main;
123   u32 *hip;
124
125   clib_spinlock_lock (&cm->ho_reuseable_lock);
126   vec_foreach (hip, cm->ho_reusable)
127     pool_put_index (cm->wrk[0].connections, *hip);
128   vec_reset_length (cm->ho_reusable);
129   clib_spinlock_unlock (&cm->ho_reuseable_lock);
130
131   return ct_connection_alloc (0);
132 }
133
134 void
135 ct_half_open_add_reusable (u32 ho_index)
136 {
137   ct_main_t *cm = &ct_main;
138
139   clib_spinlock_lock (&cm->ho_reuseable_lock);
140   vec_add1 (cm->ho_reusable, ho_index);
141   clib_spinlock_unlock (&cm->ho_reuseable_lock);
142 }
143
144 session_t *
145 ct_session_get_peer (session_t * s)
146 {
147   ct_connection_t *ct, *peer_ct;
148   ct = ct_connection_get (s->connection_index, s->thread_index);
149   peer_ct = ct_connection_get (ct->peer_index, s->thread_index);
150   return session_get (peer_ct->c_s_index, s->thread_index);
151 }
152
153 void
154 ct_session_endpoint (session_t * ll, session_endpoint_t * sep)
155 {
156   ct_connection_t *ct;
157   ct = (ct_connection_t *) session_get_transport (ll);
158   sep->transport_proto = ct->actual_tp;
159   sep->port = ct->c_lcl_port;
160   sep->is_ip4 = ct->c_is_ip4;
161   ip_copy (&sep->ip, &ct->c_lcl_ip, ct->c_is_ip4);
162 }
163
164 static void
165 ct_set_invalid_app_wrk (ct_connection_t *ct, u8 is_client)
166 {
167   ct_connection_t *peer_ct;
168
169   peer_ct = ct_connection_get (ct->peer_index, ct->c_thread_index);
170
171   if (is_client)
172     {
173       ct->client_wrk = APP_INVALID_INDEX;
174       if (peer_ct)
175         ct->client_wrk = APP_INVALID_INDEX;
176     }
177   else
178     {
179       ct->server_wrk = APP_INVALID_INDEX;
180       if (peer_ct)
181         ct->server_wrk = APP_INVALID_INDEX;
182     }
183 }
184
185 static void
186 ct_session_dealloc_fifos (ct_connection_t *ct, svm_fifo_t *rx_fifo,
187                           svm_fifo_t *tx_fifo)
188 {
189   ct_segments_ctx_t *seg_ctx;
190   ct_main_t *cm = &ct_main;
191   segment_manager_t *sm;
192   app_worker_t *app_wrk;
193   ct_segment_t *ct_seg;
194   fifo_segment_t *fs;
195   u32 seg_index;
196   session_t *s;
197   int cnt;
198
199   /*
200    * Cleanup fifos
201    */
202
203   sm = segment_manager_get (rx_fifo->segment_manager);
204   seg_index = rx_fifo->segment_index;
205
206   fs = segment_manager_get_segment_w_lock (sm, seg_index);
207   fifo_segment_free_fifo (fs, rx_fifo);
208   fifo_segment_free_fifo (fs, tx_fifo);
209   segment_manager_segment_reader_unlock (sm);
210
211   /*
212    * Atomically update segment context with readers lock
213    */
214
215   clib_rwlock_reader_lock (&cm->app_segs_lock);
216
217   seg_ctx = pool_elt_at_index (cm->app_seg_ctxs, ct->seg_ctx_index);
218   ct_seg = pool_elt_at_index (seg_ctx->segments, ct->ct_seg_index);
219
220   if (ct->flags & CT_CONN_F_CLIENT)
221     {
222       cnt =
223         __atomic_sub_fetch (&ct_seg->client_n_sessions, 1, __ATOMIC_RELAXED);
224     }
225   else
226     {
227       cnt =
228         __atomic_sub_fetch (&ct_seg->server_n_sessions, 1, __ATOMIC_RELAXED);
229     }
230
231   clib_rwlock_reader_unlock (&cm->app_segs_lock);
232
233   /*
234    * No need to do any app updates, return
235    */
236   ASSERT (cnt >= 0);
237   if (cnt)
238     return;
239
240   /*
241    * Grab exclusive lock and update flags unless some other thread
242    * added more sessions
243    */
244   clib_rwlock_writer_lock (&cm->app_segs_lock);
245
246   seg_ctx = pool_elt_at_index (cm->app_seg_ctxs, ct->seg_ctx_index);
247   ct_seg = pool_elt_at_index (seg_ctx->segments, ct->ct_seg_index);
248   if (ct->flags & CT_CONN_F_CLIENT)
249     {
250       cnt = ct_seg->client_n_sessions;
251       if (cnt)
252         goto done;
253       ct_seg->flags |= CT_SEGMENT_F_CLIENT_DETACHED;
254       s = session_get (ct->c_s_index, ct->c_thread_index);
255       if (s->app_wrk_index == APP_INVALID_INDEX)
256         ct_set_invalid_app_wrk (ct, 1 /* is_client */);
257     }
258   else
259     {
260       cnt = ct_seg->server_n_sessions;
261       if (cnt)
262         goto done;
263       ct_seg->flags |= CT_SEGMENT_F_SERVER_DETACHED;
264       s = session_get (ct->c_s_index, ct->c_thread_index);
265       if (s->app_wrk_index == APP_INVALID_INDEX)
266         ct_set_invalid_app_wrk (ct, 0 /* is_client */);
267     }
268
269   if (!(ct_seg->flags & CT_SEGMENT_F_CLIENT_DETACHED) ||
270       !(ct_seg->flags & CT_SEGMENT_F_SERVER_DETACHED))
271     goto done;
272
273   /*
274    * Remove segment context because both client and server detached
275    */
276
277   pool_put_index (seg_ctx->segments, ct->ct_seg_index);
278
279   /*
280    * No more segment indices left, remove the segments context
281    */
282   if (!pool_elts (seg_ctx->segments))
283     {
284       u64 table_handle = seg_ctx->client_wrk << 16 | seg_ctx->server_wrk;
285       table_handle = (u64) seg_ctx->sm_index << 32 | table_handle;
286       hash_unset (cm->app_segs_ctxs_table, table_handle);
287       pool_free (seg_ctx->segments);
288       pool_put_index (cm->app_seg_ctxs, ct->seg_ctx_index);
289     }
290
291   /*
292    * Segment to be removed so notify both apps
293    */
294
295   app_wrk = app_worker_get_if_valid (ct->client_wrk);
296   /* Determine if client app still needs notification, i.e., if it is
297    * still attached. If client detached and this is the last ct session
298    * on this segment, then its connects segment manager should also be
299    * detached, so do not send notification */
300   if (app_wrk)
301     {
302       segment_manager_t *csm;
303       csm = app_worker_get_connect_segment_manager (app_wrk);
304       if (!segment_manager_app_detached (csm))
305         app_worker_del_segment_notify (app_wrk, ct->segment_handle);
306     }
307
308   /* Notify server app and free segment */
309   segment_manager_lock_and_del_segment (sm, seg_index);
310
311   /* Cleanup segment manager if needed. If server detaches there's a chance
312    * the client's sessions will hold up segment removal */
313   if (segment_manager_app_detached (sm) && !segment_manager_has_fifos (sm))
314     segment_manager_free_safe (sm);
315
316 done:
317
318   clib_rwlock_writer_unlock (&cm->app_segs_lock);
319 }
320
321 static void
322 ct_session_force_disconnect_server (ct_connection_t *sct)
323 {
324   sct->peer_index = ~0;
325   session_transport_closing_notify (&sct->connection);
326 }
327
328 int
329 ct_session_connect_notify (session_t *ss, session_error_t err)
330 {
331   u32 ss_index, opaque, thread_index;
332   ct_connection_t *sct, *cct;
333   app_worker_t *client_wrk;
334   session_t *cs;
335
336   ss_index = ss->session_index;
337   thread_index = ss->thread_index;
338   sct = (ct_connection_t *) session_get_transport (ss);
339   client_wrk = app_worker_get (sct->client_wrk);
340   opaque = sct->client_opaque;
341
342   cct = ct_connection_get (sct->peer_index, thread_index);
343
344   /* Client closed while waiting for reply from server */
345   if (PREDICT_FALSE (!cct))
346     {
347       ct_session_force_disconnect_server (sct);
348       return 0;
349     }
350
351   session_half_open_delete_notify (&cct->connection);
352   cct->flags &= ~CT_CONN_F_HALF_OPEN;
353
354   if (PREDICT_FALSE (err))
355     goto connect_error;
356
357   /*
358    * Alloc client session, server session assumed to be established
359    */
360
361   ASSERT (ss->session_state >= SESSION_STATE_READY);
362
363   cs = session_alloc (thread_index);
364   ss = session_get (ss_index, thread_index);
365   cs->session_type = ss->session_type;
366   cs->listener_handle = SESSION_INVALID_HANDLE;
367   session_set_state (cs, SESSION_STATE_CONNECTING);
368   cs->app_wrk_index = client_wrk->wrk_index;
369   cs->connection_index = cct->c_c_index;
370   cct->c_s_index = cs->session_index;
371
372   /* This will allocate fifos for the session. They won't be used for
373    * exchanging data but they will be used to close the connection if
374    * the segment manager/worker is freed */
375   if ((err = app_worker_init_connected (client_wrk, cs)))
376     {
377       session_free (cs);
378       ct_session_force_disconnect_server (sct);
379       err = SESSION_E_ALLOC;
380       goto connect_error;
381     }
382
383   session_set_state (cs, SESSION_STATE_CONNECTING);
384
385   if (app_worker_connect_notify (client_wrk, cs, 0, opaque))
386     {
387       segment_manager_dealloc_fifos (cs->rx_fifo, cs->tx_fifo);
388       session_free (cs);
389       ct_session_force_disconnect_server (sct);
390       goto cleanup_client;
391     }
392
393   cs = session_get (cct->c_s_index, cct->c_thread_index);
394   session_set_state (cs, SESSION_STATE_READY);
395
396   return 0;
397
398 connect_error:
399
400   app_worker_connect_notify (client_wrk, 0, err, cct->client_opaque);
401
402 cleanup_client:
403
404   if (cct->client_rx_fifo)
405     ct_session_dealloc_fifos (cct, cct->client_rx_fifo, cct->client_tx_fifo);
406   ct_connection_free (cct);
407   return -1;
408 }
409
410 static inline ct_segment_t *
411 ct_lookup_free_segment (ct_main_t *cm, segment_manager_t *sm,
412                         u32 seg_ctx_index)
413 {
414   uword free_bytes, max_free_bytes;
415   ct_segment_t *ct_seg, *res = 0;
416   ct_segments_ctx_t *seg_ctx;
417   fifo_segment_t *fs;
418   u32 max_fifos;
419
420   seg_ctx = pool_elt_at_index (cm->app_seg_ctxs, seg_ctx_index);
421   max_free_bytes = seg_ctx->fifo_pair_bytes;
422
423   pool_foreach (ct_seg, seg_ctx->segments)
424     {
425       /* Client or server has detached so segment cannot be used */
426       fs = segment_manager_get_segment (sm, ct_seg->segment_index);
427       free_bytes = fifo_segment_available_bytes (fs);
428       max_fifos = fifo_segment_size (fs) / seg_ctx->fifo_pair_bytes;
429       if (free_bytes > max_free_bytes &&
430           fifo_segment_num_fifos (fs) / 2 < max_fifos)
431         {
432           max_free_bytes = free_bytes;
433           res = ct_seg;
434         }
435     }
436
437   return res;
438 }
439
440 static ct_segment_t *
441 ct_alloc_segment (ct_main_t *cm, app_worker_t *server_wrk, u64 table_handle,
442                   segment_manager_t *sm, u32 client_wrk_index)
443 {
444   u32 seg_ctx_index = ~0, sm_index, pair_bytes;
445   segment_manager_props_t *props;
446   const u32 margin = 16 << 10;
447   ct_segments_ctx_t *seg_ctx;
448   app_worker_t *client_wrk;
449   u64 seg_size, seg_handle;
450   application_t *server;
451   ct_segment_t *ct_seg;
452   uword *spp;
453   int fs_index;
454
455   server = application_get (server_wrk->app_index);
456   props = application_segment_manager_properties (server);
457   sm_index = segment_manager_index (sm);
458   pair_bytes = props->rx_fifo_size + props->tx_fifo_size + margin;
459
460   /*
461    * Make sure another thread did not alloc a segment while acquiring the lock
462    */
463
464   spp = hash_get (cm->app_segs_ctxs_table, table_handle);
465   if (spp)
466     {
467       seg_ctx_index = *spp;
468       ct_seg = ct_lookup_free_segment (cm, sm, seg_ctx_index);
469       if (ct_seg)
470         return ct_seg;
471     }
472
473   /*
474    * No segment, try to alloc one and notify the server and the client.
475    * Make sure the segment is not used for other fifos
476    */
477   seg_size = clib_max (props->segment_size, 128 << 20);
478   fs_index =
479     segment_manager_add_segment2 (sm, seg_size, FIFO_SEGMENT_F_CUSTOM_USE);
480   if (fs_index < 0)
481     return 0;
482
483   if (seg_ctx_index == ~0)
484     {
485       pool_get_zero (cm->app_seg_ctxs, seg_ctx);
486       seg_ctx_index = seg_ctx - cm->app_seg_ctxs;
487       hash_set (cm->app_segs_ctxs_table, table_handle, seg_ctx_index);
488       seg_ctx->server_wrk = server_wrk->wrk_index;
489       seg_ctx->client_wrk = client_wrk_index;
490       seg_ctx->sm_index = sm_index;
491       seg_ctx->fifo_pair_bytes = pair_bytes;
492     }
493   else
494     {
495       seg_ctx = pool_elt_at_index (cm->app_seg_ctxs, seg_ctx_index);
496     }
497
498   pool_get_zero (seg_ctx->segments, ct_seg);
499   ct_seg->segment_index = fs_index;
500   ct_seg->server_n_sessions = 0;
501   ct_seg->client_n_sessions = 0;
502   ct_seg->ct_seg_index = ct_seg - seg_ctx->segments;
503   ct_seg->seg_ctx_index = seg_ctx_index;
504
505   /* New segment, notify the server and client */
506   seg_handle = segment_manager_make_segment_handle (sm_index, fs_index);
507   if (app_worker_add_segment_notify (server_wrk, seg_handle))
508     goto error;
509
510   client_wrk = app_worker_get (client_wrk_index);
511   if (app_worker_add_segment_notify (client_wrk, seg_handle))
512     {
513       app_worker_del_segment_notify (server_wrk, seg_handle);
514       goto error;
515     }
516
517   return ct_seg;
518
519 error:
520
521   segment_manager_lock_and_del_segment (sm, fs_index);
522   pool_put_index (seg_ctx->segments, ct_seg->seg_ctx_index);
523   return 0;
524 }
525
526 static int
527 ct_init_accepted_session (app_worker_t *server_wrk, ct_connection_t *ct,
528                           session_t *ls, session_t *ll)
529 {
530   segment_manager_props_t *props;
531   u64 seg_handle, table_handle;
532   u32 sm_index, fs_index = ~0;
533   ct_segments_ctx_t *seg_ctx;
534   ct_main_t *cm = &ct_main;
535   application_t *server;
536   segment_manager_t *sm;
537   ct_segment_t *ct_seg;
538   fifo_segment_t *fs;
539   uword *spp;
540   int rv;
541
542   sm = app_worker_get_listen_segment_manager (server_wrk, ll);
543   sm_index = segment_manager_index (sm);
544   server = application_get (server_wrk->app_index);
545   props = application_segment_manager_properties (server);
546
547   table_handle = ct->client_wrk << 16 | server_wrk->wrk_index;
548   table_handle = (u64) sm_index << 32 | table_handle;
549
550   /*
551    * Check if we already have a segment that can hold the fifos
552    */
553
554   clib_rwlock_reader_lock (&cm->app_segs_lock);
555
556   spp = hash_get (cm->app_segs_ctxs_table, table_handle);
557   if (spp)
558     {
559       ct_seg = ct_lookup_free_segment (cm, sm, *spp);
560       if (ct_seg)
561         {
562           ct->seg_ctx_index = ct_seg->seg_ctx_index;
563           ct->ct_seg_index = ct_seg->ct_seg_index;
564           fs_index = ct_seg->segment_index;
565           ct_seg->flags &=
566             ~(CT_SEGMENT_F_SERVER_DETACHED | CT_SEGMENT_F_CLIENT_DETACHED);
567           __atomic_add_fetch (&ct_seg->server_n_sessions, 1, __ATOMIC_RELAXED);
568           __atomic_add_fetch (&ct_seg->client_n_sessions, 1, __ATOMIC_RELAXED);
569         }
570     }
571
572   clib_rwlock_reader_unlock (&cm->app_segs_lock);
573
574   /*
575    * If not, grab exclusive lock and allocate segment
576    */
577   if (fs_index == ~0)
578     {
579       clib_rwlock_writer_lock (&cm->app_segs_lock);
580
581       ct_seg =
582         ct_alloc_segment (cm, server_wrk, table_handle, sm, ct->client_wrk);
583       if (!ct_seg)
584         {
585           clib_rwlock_writer_unlock (&cm->app_segs_lock);
586           return -1;
587         }
588
589       ct->seg_ctx_index = ct_seg->seg_ctx_index;
590       ct->ct_seg_index = ct_seg->ct_seg_index;
591       ct_seg->server_n_sessions += 1;
592       ct_seg->client_n_sessions += 1;
593       fs_index = ct_seg->segment_index;
594
595       clib_rwlock_writer_unlock (&cm->app_segs_lock);
596     }
597
598   /*
599    * Allocate and initialize the fifos
600    */
601   fs = segment_manager_get_segment_w_lock (sm, fs_index);
602   rv = segment_manager_try_alloc_fifos (
603     fs, ls->thread_index, props->rx_fifo_size, props->tx_fifo_size,
604     &ls->rx_fifo, &ls->tx_fifo);
605   if (rv)
606     {
607       segment_manager_segment_reader_unlock (sm);
608
609       clib_rwlock_reader_lock (&cm->app_segs_lock);
610
611       seg_ctx = pool_elt_at_index (cm->app_seg_ctxs, ct->seg_ctx_index);
612       ct_seg = pool_elt_at_index (seg_ctx->segments, ct->ct_seg_index);
613       __atomic_sub_fetch (&ct_seg->server_n_sessions, 1, __ATOMIC_RELAXED);
614       __atomic_sub_fetch (&ct_seg->client_n_sessions, 1, __ATOMIC_RELAXED);
615
616       clib_rwlock_reader_unlock (&cm->app_segs_lock);
617
618       return rv;
619     }
620
621   ls->rx_fifo->shr->master_session_index = ls->session_index;
622   ls->tx_fifo->shr->master_session_index = ls->session_index;
623   ls->rx_fifo->master_thread_index = ls->thread_index;
624   ls->tx_fifo->master_thread_index = ls->thread_index;
625
626   seg_handle = segment_manager_segment_handle (sm, fs);
627   segment_manager_segment_reader_unlock (sm);
628
629   ct->segment_handle = seg_handle;
630
631   return 0;
632 }
633
634 static void
635 ct_accept_one (u32 thread_index, u32 ho_index)
636 {
637   ct_connection_t *sct, *cct, *ho;
638   transport_connection_t *ll_ct;
639   app_worker_t *server_wrk;
640   u32 cct_index, ll_index;
641   session_t *ss, *ll;
642
643   /*
644    * Alloc client ct and initialize from ho
645    */
646   cct = ct_connection_alloc (thread_index);
647   cct_index = cct->c_c_index;
648
649   ho = ct_connection_get (ho_index, 0);
650
651   /* Unlikely but half-open session and transport could have been freed */
652   if (PREDICT_FALSE (!ho))
653     {
654       ct_connection_free (cct);
655       return;
656     }
657
658   clib_memcpy (cct, ho, sizeof (*ho));
659   cct->c_c_index = cct_index;
660   cct->c_thread_index = thread_index;
661   cct->flags |= CT_CONN_F_HALF_OPEN;
662
663   /* Notify session layer that half-open is on a different thread
664    * and mark ho connection index reusable. Avoids another rpc
665    */
666   session_half_open_migrate_notify (&cct->connection);
667   session_half_open_migrated_notify (&cct->connection);
668   ct_half_open_add_reusable (ho_index);
669
670   /*
671    * Alloc and init server transport
672    */
673
674   ll_index = cct->peer_index;
675   ll = listen_session_get (ll_index);
676   sct = ct_connection_alloc (thread_index);
677   /* Transport not necessarily ct but it might, so grab after sct alloc */
678   ll_ct = listen_session_get_transport (ll);
679
680   /* Make sure cct is valid after sct alloc */
681   cct = ct_connection_get (cct_index, thread_index);
682
683   sct->c_rmt_port = 0;
684   sct->c_lcl_port = ll_ct->lcl_port;
685   sct->c_is_ip4 = cct->c_is_ip4;
686   clib_memcpy (&sct->c_lcl_ip, &cct->c_rmt_ip, sizeof (cct->c_rmt_ip));
687   sct->client_wrk = cct->client_wrk;
688   sct->c_proto = TRANSPORT_PROTO_NONE;
689   sct->client_opaque = cct->client_opaque;
690   sct->actual_tp = cct->actual_tp;
691
692   sct->peer_index = cct->c_c_index;
693   cct->peer_index = sct->c_c_index;
694
695   /*
696    * Accept server session. Client session is created only after
697    * server confirms accept.
698    */
699   ss = session_alloc (thread_index);
700   ll = listen_session_get (ll_index);
701   ss->session_type = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE,
702                                                      sct->c_is_ip4);
703   ss->connection_index = sct->c_c_index;
704   ss->listener_handle = listen_session_get_handle (ll);
705   session_set_state (ss, SESSION_STATE_CREATED);
706
707   server_wrk = application_listener_select_worker (ll);
708   ss->app_wrk_index = server_wrk->wrk_index;
709
710   sct->c_s_index = ss->session_index;
711   sct->server_wrk = ss->app_wrk_index;
712
713   if (ct_init_accepted_session (server_wrk, sct, ss, ll))
714     {
715       ct_session_connect_notify (ss, SESSION_E_ALLOC);
716       ct_connection_free (sct);
717       session_free (ss);
718       return;
719     }
720
721   cct->server_wrk = sct->server_wrk;
722   cct->seg_ctx_index = sct->seg_ctx_index;
723   cct->ct_seg_index = sct->ct_seg_index;
724   cct->client_rx_fifo = ss->tx_fifo;
725   cct->client_tx_fifo = ss->rx_fifo;
726   cct->client_rx_fifo->refcnt++;
727   cct->client_tx_fifo->refcnt++;
728   cct->segment_handle = sct->segment_handle;
729
730   session_set_state (ss, SESSION_STATE_ACCEPTING);
731   if (app_worker_accept_notify (server_wrk, ss))
732     {
733       ct_session_connect_notify (ss, SESSION_E_REFUSED);
734       ct_session_dealloc_fifos (sct, ss->rx_fifo, ss->tx_fifo);
735       ct_connection_free (sct);
736       session_free (ss);
737     }
738 }
739
740 static void
741 ct_accept_rpc_wrk_handler (void *rpc_args)
742 {
743   u32 thread_index, ho_index, n_connects, i, n_pending;
744   const u32 max_connects = 32;
745   ct_worker_t *wrk;
746
747   thread_index = pointer_to_uword (rpc_args);
748   wrk = ct_worker_get (thread_index);
749
750   /* Sub without lock as main enqueues with worker barrier */
751   n_pending = clib_fifo_elts (wrk->pending_connects);
752   n_connects = clib_min (n_pending, max_connects);
753
754   for (i = 0; i < n_connects; i++)
755     {
756       clib_fifo_sub1 (wrk->pending_connects, ho_index);
757       ct_accept_one (thread_index, ho_index);
758     }
759
760   if (n_pending == n_connects)
761     wrk->have_connects = 0;
762   else
763     session_send_rpc_evt_to_thread_force (
764       thread_index, ct_accept_rpc_wrk_handler,
765       uword_to_pointer (thread_index, void *));
766 }
767
768 static int
769 ct_connect (app_worker_t * client_wrk, session_t * ll,
770             session_endpoint_cfg_t * sep)
771 {
772   u32 thread_index, ho_index;
773   ct_main_t *cm = &ct_main;
774   ct_connection_t *ho;
775   ct_worker_t *wrk;
776
777   /* Simple round-robin policy for spreading sessions over workers. We skip
778    * thread index 0, i.e., offset the index by 1, when we have workers as it
779    * is the one dedicated to main thread. Note that n_workers does not include
780    * main thread */
781   cm->n_sessions += 1;
782   thread_index = cm->n_workers ? (cm->n_sessions % cm->n_workers) + 1 : 0;
783
784   /*
785    * Alloc and init client half-open transport
786    */
787
788   ho = ct_half_open_alloc ();
789   ho_index = ho->c_c_index;
790   ho->c_rmt_port = sep->port;
791   ho->c_lcl_port = 0;
792   ho->c_is_ip4 = sep->is_ip4;
793   ho->client_opaque = sep->opaque;
794   ho->client_wrk = client_wrk->wrk_index;
795   ho->peer_index = ll->session_index;
796   ho->c_proto = TRANSPORT_PROTO_NONE;
797   ho->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
798   clib_memcpy (&ho->c_rmt_ip, &sep->ip, sizeof (sep->ip));
799   ho->flags |= CT_CONN_F_CLIENT;
800   ho->c_s_index = ~0;
801   ho->actual_tp = sep->original_tp;
802
803   /*
804    * Accept connection on thread selected above. Connected reply comes
805    * after server accepts the connection.
806    */
807
808   wrk = ct_worker_get (thread_index);
809
810   /* Worker barrier held, add without additional lock */
811   clib_fifo_add1 (wrk->pending_connects, ho_index);
812   if (!wrk->have_connects)
813     {
814       wrk->have_connects = 1;
815       session_send_rpc_evt_to_thread_force (
816         thread_index, ct_accept_rpc_wrk_handler,
817         uword_to_pointer (thread_index, void *));
818     }
819
820   return ho_index;
821 }
822
823 static u32
824 ct_start_listen (u32 app_listener_index, transport_endpoint_cfg_t *tep)
825 {
826   session_endpoint_cfg_t *sep;
827   ct_connection_t *ct;
828
829   sep = (session_endpoint_cfg_t *) tep;
830   ct = ct_connection_alloc (0);
831   ct->server_wrk = sep->app_wrk_index;
832   ct->c_is_ip4 = sep->is_ip4;
833   clib_memcpy (&ct->c_lcl_ip, &sep->ip, sizeof (sep->ip));
834   ct->c_lcl_port = sep->port;
835   ct->c_s_index = app_listener_index;
836   ct->actual_tp = sep->transport_proto;
837   return ct->c_c_index;
838 }
839
840 static u32
841 ct_stop_listen (u32 ct_index)
842 {
843   ct_connection_t *ct;
844   ct = ct_connection_get (ct_index, 0);
845   ct_connection_free (ct);
846   return 0;
847 }
848
849 static transport_connection_t *
850 ct_listener_get (u32 ct_index)
851 {
852   return (transport_connection_t *) ct_connection_get (ct_index, 0);
853 }
854
855 static transport_connection_t *
856 ct_half_open_get (u32 ct_index)
857 {
858   return (transport_connection_t *) ct_connection_get (ct_index, 0);
859 }
860
861 static void
862 ct_session_cleanup (u32 conn_index, u32 thread_index)
863 {
864   ct_connection_t *ct, *peer_ct;
865
866   ct = ct_connection_get (conn_index, thread_index);
867   if (!ct)
868     return;
869
870   peer_ct = ct_connection_get (ct->peer_index, thread_index);
871   if (peer_ct)
872     peer_ct->peer_index = ~0;
873
874   ct_connection_free (ct);
875 }
876
877 static void
878 ct_cleanup_ho (u32 ho_index)
879 {
880   ct_connection_free (ct_connection_get (ho_index, 0));
881 }
882
883 static int
884 ct_session_connect (transport_endpoint_cfg_t * tep)
885 {
886   session_endpoint_cfg_t *sep_ext;
887   session_endpoint_t _sep, *sep = &_sep;
888   app_worker_t *app_wrk;
889   session_handle_t lh;
890   application_t *app;
891   app_listener_t *al;
892   u32 table_index;
893   session_t *ll;
894   u8 fib_proto;
895
896   sep_ext = (session_endpoint_cfg_t *) tep;
897   _sep = *(session_endpoint_t *) tep;
898   app_wrk = app_worker_get (sep_ext->app_wrk_index);
899   app = application_get (app_wrk->app_index);
900
901   sep->transport_proto = sep_ext->original_tp;
902   table_index = application_local_session_table (app);
903   lh = session_lookup_local_endpoint (table_index, sep);
904   if (lh == SESSION_DROP_HANDLE)
905     return SESSION_E_FILTERED;
906
907   if (lh == SESSION_INVALID_HANDLE)
908     goto global_scope;
909
910   ll = listen_session_get_from_handle (lh);
911   al = app_listener_get_w_session (ll);
912
913   /*
914    * Break loop if rule in local table points to connecting app. This
915    * can happen if client is a generic proxy. Route connect through
916    * global table instead.
917    */
918   if (al->app_index == app->app_index)
919     goto global_scope;
920
921   return ct_connect (app_wrk, ll, sep_ext);
922
923   /*
924    * If nothing found, check the global scope for locally attached
925    * destinations. Make sure first that we're allowed to.
926    */
927
928 global_scope:
929   if (session_endpoint_is_local (sep))
930     return SESSION_E_NOROUTE;
931
932   if (!application_has_global_scope (app))
933     return SESSION_E_SCOPE;
934
935   fib_proto = session_endpoint_fib_proto (sep);
936   table_index = session_lookup_get_index_for_fib (fib_proto, sep->fib_index);
937   ll = session_lookup_listener_wildcard (table_index, sep);
938
939   /* Avoid connecting app to own listener */
940   if (ll && ll->app_index != app->app_index)
941     return ct_connect (app_wrk, ll, sep_ext);
942
943   /* Failed to connect but no error */
944   return SESSION_E_LOCAL_CONNECT;
945 }
946
947 static inline int
948 ct_close_is_reset (ct_connection_t *ct, session_t *s)
949 {
950   if (ct->flags & CT_CONN_F_CLIENT)
951     return (svm_fifo_max_dequeue (ct->client_rx_fifo) > 0);
952   else
953     return (svm_fifo_max_dequeue (s->rx_fifo) > 0);
954 }
955
956 static void
957 ct_session_postponed_cleanup (ct_connection_t *ct)
958 {
959   ct_connection_t *peer_ct;
960   app_worker_t *app_wrk;
961   session_t *s;
962
963   s = session_get (ct->c_s_index, ct->c_thread_index);
964   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
965
966   peer_ct = ct_connection_get (ct->peer_index, ct->c_thread_index);
967   if (peer_ct)
968     {
969       if (ct_close_is_reset (ct, s))
970         session_transport_reset_notify (&peer_ct->connection);
971       else
972         session_transport_closing_notify (&peer_ct->connection);
973     }
974   session_transport_closed_notify (&ct->connection);
975
976   if (ct->flags & CT_CONN_F_CLIENT)
977     {
978       if (app_wrk)
979         app_worker_cleanup_notify (app_wrk, s, SESSION_CLEANUP_TRANSPORT);
980
981       /* Normal free for client session as the fifos are allocated through
982        * the connects segment manager in a segment that's not shared with
983        * the server */
984       ct_session_dealloc_fifos (ct, ct->client_rx_fifo, ct->client_tx_fifo);
985       session_free_w_fifos (s);
986     }
987   else
988     {
989       /* Manual session and fifo segment cleanup to avoid implicit
990        * segment manager cleanups and notifications */
991       app_wrk = app_worker_get_if_valid (s->app_wrk_index);
992       if (app_wrk)
993         {
994           app_worker_cleanup_notify (app_wrk, s, SESSION_CLEANUP_TRANSPORT);
995           app_worker_cleanup_notify (app_wrk, s, SESSION_CLEANUP_SESSION);
996         }
997
998       ct_session_dealloc_fifos (ct, s->rx_fifo, s->tx_fifo);
999       session_free (s);
1000     }
1001
1002   ct_connection_free (ct);
1003 }
1004
1005 static void
1006 ct_handle_cleanups (void *args)
1007 {
1008   uword thread_index = pointer_to_uword (args);
1009   const u32 max_cleanups = 100;
1010   ct_cleanup_req_t *req;
1011   ct_connection_t *ct;
1012   u32 n_to_handle = 0;
1013   ct_worker_t *wrk;
1014   session_t *s;
1015
1016   wrk = ct_worker_get (thread_index);
1017   wrk->have_cleanups = 0;
1018   n_to_handle = clib_fifo_elts (wrk->pending_cleanups);
1019   n_to_handle = clib_min (n_to_handle, max_cleanups);
1020
1021   while (n_to_handle)
1022     {
1023       clib_fifo_sub2 (wrk->pending_cleanups, req);
1024       ct = ct_connection_get (req->ct_index, thread_index);
1025       s = session_get (ct->c_s_index, ct->c_thread_index);
1026       if (!svm_fifo_has_event (s->tx_fifo))
1027         ct_session_postponed_cleanup (ct);
1028       else
1029         clib_fifo_add1 (wrk->pending_cleanups, *req);
1030       n_to_handle -= 1;
1031     }
1032
1033   if (clib_fifo_elts (wrk->pending_cleanups))
1034     {
1035       wrk->have_cleanups = 1;
1036       session_send_rpc_evt_to_thread_force (
1037         thread_index, ct_handle_cleanups,
1038         uword_to_pointer (thread_index, void *));
1039     }
1040 }
1041
1042 static void
1043 ct_program_cleanup (ct_connection_t *ct)
1044 {
1045   ct_cleanup_req_t *req;
1046   uword thread_index;
1047   ct_worker_t *wrk;
1048
1049   thread_index = ct->c_thread_index;
1050   wrk = ct_worker_get (ct->c_thread_index);
1051
1052   clib_fifo_add2 (wrk->pending_cleanups, req);
1053   req->ct_index = ct->c_c_index;
1054
1055   if (wrk->have_cleanups)
1056     return;
1057
1058   wrk->have_cleanups = 1;
1059   session_send_rpc_evt_to_thread_force (
1060     thread_index, ct_handle_cleanups, uword_to_pointer (thread_index, void *));
1061 }
1062
1063 static void
1064 ct_session_close (u32 ct_index, u32 thread_index)
1065 {
1066   ct_connection_t *ct, *peer_ct;
1067   session_t *s;
1068
1069   ct = ct_connection_get (ct_index, thread_index);
1070   s = session_get (ct->c_s_index, ct->c_thread_index);
1071   peer_ct = ct_connection_get (ct->peer_index, thread_index);
1072   if (peer_ct)
1073     {
1074       peer_ct->peer_index = ~0;
1075       /* Make sure session was allocated */
1076       if (peer_ct->flags & CT_CONN_F_HALF_OPEN)
1077         {
1078           ct_session_connect_notify (s, SESSION_E_REFUSED);
1079           ct->peer_index = ~0;
1080         }
1081       else if (peer_ct->c_s_index == ~0)
1082         {
1083           /* should not happen */
1084           clib_warning ("ct peer without session");
1085           ct_connection_free (peer_ct);
1086         }
1087     }
1088
1089   /* Do not send closed notify to make sure pending tx events are
1090    * still delivered and program cleanup */
1091   ct_program_cleanup (ct);
1092 }
1093
1094 static transport_connection_t *
1095 ct_session_get (u32 ct_index, u32 thread_index)
1096 {
1097   return (transport_connection_t *) ct_connection_get (ct_index,
1098                                                        thread_index);
1099 }
1100
1101 static u8 *
1102 format_ct_connection_id (u8 * s, va_list * args)
1103 {
1104   ct_connection_t *ct = va_arg (*args, ct_connection_t *);
1105   if (!ct)
1106     return s;
1107   if (ct->c_is_ip4)
1108     {
1109       s = format (s, "[%d:%d][CT:%U] %U:%d->%U:%d", ct->c_thread_index,
1110                   ct->c_s_index, format_transport_proto_short, ct->actual_tp,
1111                   format_ip4_address, &ct->c_lcl_ip4,
1112                   clib_net_to_host_u16 (ct->c_lcl_port), format_ip4_address,
1113                   &ct->c_rmt_ip4, clib_net_to_host_u16 (ct->c_rmt_port));
1114     }
1115   else
1116     {
1117       s = format (s, "[%d:%d][CT:%U] %U:%d->%U:%d", ct->c_thread_index,
1118                   ct->c_s_index, format_transport_proto_short, ct->actual_tp,
1119                   format_ip6_address, &ct->c_lcl_ip6,
1120                   clib_net_to_host_u16 (ct->c_lcl_port), format_ip6_address,
1121                   &ct->c_rmt_ip6, clib_net_to_host_u16 (ct->c_rmt_port));
1122     }
1123
1124   return s;
1125 }
1126
1127 static int
1128 ct_custom_tx (void *session, transport_send_params_t * sp)
1129 {
1130   session_t *s = (session_t *) session;
1131   if (session_has_transport (s))
1132     return 0;
1133   /* If event enqueued towards peer, remove from scheduler and remove
1134    * session tx flag, i.e., accept new tx events. Unset fifo flag now to
1135    * avoid missing events if peer did not clear fifo flag yet, which is
1136    * interpreted as successful notification and session is descheduled. */
1137   svm_fifo_unset_event (s->tx_fifo);
1138   if (!ct_session_tx (s))
1139     sp->flags = TRANSPORT_SND_F_DESCHED;
1140
1141   /* The scheduler uses packet count as a means of upper bounding the amount
1142    * of work done per dispatch. So make it look like we have sent something */
1143   return 1;
1144 }
1145
1146 static int
1147 ct_app_rx_evt (transport_connection_t * tc)
1148 {
1149   ct_connection_t *ct = (ct_connection_t *) tc, *peer_ct;
1150   session_t *ps, *s;
1151
1152   s = session_get (ct->c_s_index, ct->c_thread_index);
1153   if (session_has_transport (s) || s->session_state < SESSION_STATE_READY)
1154     return -1;
1155   peer_ct = ct_connection_get (ct->peer_index, tc->thread_index);
1156   if (!peer_ct || (peer_ct->flags & CT_CONN_F_HALF_OPEN))
1157     return -1;
1158   ps = session_get (peer_ct->c_s_index, peer_ct->c_thread_index);
1159   if (ps->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
1160     return -1;
1161   return session_dequeue_notify (ps);
1162 }
1163
1164 static u8 *
1165 format_ct_listener (u8 * s, va_list * args)
1166 {
1167   u32 tc_index = va_arg (*args, u32);
1168   u32 __clib_unused thread_index = va_arg (*args, u32);
1169   u32 __clib_unused verbose = va_arg (*args, u32);
1170   ct_connection_t *ct = ct_connection_get (tc_index, 0);
1171   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_ct_connection_id, ct);
1172   if (verbose)
1173     s = format (s, "%-" SESSION_CLI_STATE_LEN "s", "LISTEN");
1174   return s;
1175 }
1176
1177 static u8 *
1178 format_ct_half_open (u8 *s, va_list *args)
1179 {
1180   u32 ho_index = va_arg (*args, u32);
1181   u32 verbose = va_arg (*args, u32);
1182   ct_connection_t *ct = ct_connection_get (ho_index, 0);
1183   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_ct_connection_id, ct);
1184   if (verbose)
1185     s = format (s, "%-" SESSION_CLI_STATE_LEN "s", "HALF-OPEN");
1186   return s;
1187 }
1188
1189 static u8 *
1190 format_ct_connection (u8 * s, va_list * args)
1191 {
1192   ct_connection_t *ct = va_arg (*args, ct_connection_t *);
1193   u32 verbose = va_arg (*args, u32);
1194
1195   if (!ct)
1196     return s;
1197   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_ct_connection_id, ct);
1198   if (verbose)
1199     {
1200       s = format (s, "%-" SESSION_CLI_STATE_LEN "s", "ESTABLISHED");
1201       if (verbose > 1)
1202         {
1203           s = format (s, "\n");
1204         }
1205     }
1206   return s;
1207 }
1208
1209 static u8 *
1210 format_ct_session (u8 * s, va_list * args)
1211 {
1212   u32 ct_index = va_arg (*args, u32);
1213   u32 thread_index = va_arg (*args, u32);
1214   u32 verbose = va_arg (*args, u32);
1215   ct_connection_t *ct;
1216
1217   ct = ct_connection_get (ct_index, thread_index);
1218   if (!ct)
1219     {
1220       s = format (s, "empty\n");
1221       return s;
1222     }
1223
1224   s = format (s, "%U", format_ct_connection, ct, verbose);
1225   return s;
1226 }
1227
1228 clib_error_t *
1229 ct_enable_disable (vlib_main_t * vm, u8 is_en)
1230 {
1231   vlib_thread_main_t *vtm = &vlib_thread_main;
1232   ct_main_t *cm = &ct_main;
1233
1234   cm->n_workers = vlib_num_workers ();
1235   vec_validate (cm->wrk, vtm->n_vlib_mains);
1236   clib_spinlock_init (&cm->ho_reuseable_lock);
1237   clib_rwlock_init (&cm->app_segs_lock);
1238   return 0;
1239 }
1240
1241 /* *INDENT-OFF* */
1242 static const transport_proto_vft_t cut_thru_proto = {
1243   .enable = ct_enable_disable,
1244   .start_listen = ct_start_listen,
1245   .stop_listen = ct_stop_listen,
1246   .get_connection = ct_session_get,
1247   .get_listener = ct_listener_get,
1248   .get_half_open = ct_half_open_get,
1249   .cleanup = ct_session_cleanup,
1250   .cleanup_ho = ct_cleanup_ho,
1251   .connect = ct_session_connect,
1252   .close = ct_session_close,
1253   .custom_tx = ct_custom_tx,
1254   .app_rx_evt = ct_app_rx_evt,
1255   .format_listener = format_ct_listener,
1256   .format_half_open = format_ct_half_open,
1257   .format_connection = format_ct_session,
1258   .transport_options = {
1259     .name = "ct",
1260     .short_name = "C",
1261     .tx_type = TRANSPORT_TX_INTERNAL,
1262     .service_type = TRANSPORT_SERVICE_VC,
1263   },
1264 };
1265 /* *INDENT-ON* */
1266
1267 static inline int
1268 ct_session_can_tx (session_t *s)
1269 {
1270   return (s->session_state == SESSION_STATE_READY ||
1271           s->session_state == SESSION_STATE_CLOSING ||
1272           s->session_state == SESSION_STATE_APP_CLOSED);
1273 }
1274
1275 int
1276 ct_session_tx (session_t * s)
1277 {
1278   ct_connection_t *ct, *peer_ct;
1279   session_t *peer_s;
1280
1281   if (!ct_session_can_tx (s))
1282     return 0;
1283   ct = (ct_connection_t *) session_get_transport (s);
1284   peer_ct = ct_connection_get (ct->peer_index, ct->c_thread_index);
1285   if (!peer_ct)
1286     return 0;
1287   peer_s = session_get (peer_ct->c_s_index, peer_ct->c_thread_index);
1288   if (peer_s->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
1289     return 0;
1290   return session_enqueue_notify (peer_s);
1291 }
1292
1293 static clib_error_t *
1294 ct_transport_init (vlib_main_t * vm)
1295 {
1296   transport_register_protocol (TRANSPORT_PROTO_NONE, &cut_thru_proto,
1297                                FIB_PROTOCOL_IP4, ~0);
1298   transport_register_protocol (TRANSPORT_PROTO_NONE, &cut_thru_proto,
1299                                FIB_PROTOCOL_IP6, ~0);
1300   return 0;
1301 }
1302
1303 VLIB_INIT_FUNCTION (ct_transport_init);
1304
1305 /*
1306  * fd.io coding-style-patch-verification: ON
1307  *
1308  * Local Variables:
1309  * eval: (c-set-style "gnu")
1310  * End:
1311  */