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