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