session/vcl: support worker ownership change for listeners
[vpp.git] / src / vnet / session / application.c
1 /*
2  * Copyright (c) 2017 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.h>
17 #include <vnet/session/application_interface.h>
18 #include <vnet/session/application_namespace.h>
19 #include <vnet/session/session.h>
20
21 static app_main_t app_main;
22
23 static app_listener_t *
24 app_listener_alloc (application_t * app)
25 {
26   app_listener_t *app_listener;
27   pool_get (app->listeners, app_listener);
28   clib_memset (app_listener, 0, sizeof (*app_listener));
29   app_listener->al_index = app_listener - app->listeners;
30   return app_listener;
31 }
32
33 static app_listener_t *
34 app_listener_get (application_t * app, u32 app_listener_index)
35 {
36   return pool_elt_at_index (app->listeners, app_listener_index);
37 }
38
39 static void
40 app_listener_free (application_t * app, app_listener_t * app_listener)
41 {
42   clib_bitmap_free (app_listener->workers);
43   pool_put (app->listeners, app_listener);
44   if (CLIB_DEBUG)
45     clib_memset (app_listener, 0xfa, sizeof (*app_listener));
46 }
47
48 static app_listener_t *
49 app_local_listener_alloc (application_t * app)
50 {
51   app_listener_t *app_listener;
52   pool_get (app->local_listeners, app_listener);
53   clib_memset (app_listener, 0, sizeof (*app_listener));
54   app_listener->al_index = app_listener - app->local_listeners;
55   return app_listener;
56 }
57
58 static app_listener_t *
59 app_local_listener_get (application_t * app, u32 app_listener_index)
60 {
61   return pool_elt_at_index (app->local_listeners, app_listener_index);
62 }
63
64 static void
65 app_local_listener_free (application_t * app, app_listener_t * app_listener)
66 {
67   clib_bitmap_free (app_listener->workers);
68   pool_put (app->local_listeners, app_listener);
69   if (CLIB_DEBUG)
70     clib_memset (app_listener, 0xfa, sizeof (*app_listener));
71 }
72
73 static app_worker_map_t *
74 app_worker_map_alloc (application_t * app)
75 {
76   app_worker_map_t *map;
77   pool_get (app->worker_maps, map);
78   clib_memset (map, 0, sizeof (*map));
79   return map;
80 }
81
82 static u32
83 app_worker_map_index (application_t * app, app_worker_map_t * map)
84 {
85   return (map - app->worker_maps);
86 }
87
88 static void
89 app_worker_map_free (application_t * app, app_worker_map_t * map)
90 {
91   pool_put (app->worker_maps, map);
92 }
93
94 static app_worker_map_t *
95 app_worker_map_get (application_t * app, u32 map_index)
96 {
97   if (pool_is_free_index (app->worker_maps, map_index))
98     return 0;
99   return pool_elt_at_index (app->worker_maps, map_index);
100 }
101
102 static const u8 *
103 app_get_name (application_t * app)
104 {
105   return app->name;
106 }
107
108 u32
109 application_session_table (application_t * app, u8 fib_proto)
110 {
111   app_namespace_t *app_ns;
112   app_ns = app_namespace_get (app->ns_index);
113   if (!application_has_global_scope (app))
114     return APP_INVALID_INDEX;
115   if (fib_proto == FIB_PROTOCOL_IP4)
116     return session_lookup_get_index_for_fib (fib_proto,
117                                              app_ns->ip4_fib_index);
118   else
119     return session_lookup_get_index_for_fib (fib_proto,
120                                              app_ns->ip6_fib_index);
121 }
122
123 u32
124 application_local_session_table (application_t * app)
125 {
126   app_namespace_t *app_ns;
127   if (!application_has_local_scope (app))
128     return APP_INVALID_INDEX;
129   app_ns = app_namespace_get (app->ns_index);
130   return app_ns->local_table_index;
131 }
132
133 static void
134 application_local_listener_session_endpoint (local_session_t * ll,
135                                              session_endpoint_t * sep)
136 {
137   sep->transport_proto =
138     session_type_transport_proto (ll->listener_session_type);
139   sep->port = ll->port;
140   sep->is_ip4 = ll->listener_session_type & 1;
141 }
142
143 /**
144  * Returns app name for app-index
145  */
146 const u8 *
147 application_name_from_index (u32 app_index)
148 {
149   application_t *app = application_get (app_index);
150   if (!app)
151     return 0;
152   return app_get_name (app);
153 }
154
155 static void
156 application_api_table_add (u32 app_index, u32 api_client_index)
157 {
158   if (api_client_index != APP_INVALID_INDEX)
159     hash_set (app_main.app_by_api_client_index, api_client_index, app_index);
160 }
161
162 static void
163 application_api_table_del (u32 api_client_index)
164 {
165   hash_unset (app_main.app_by_api_client_index, api_client_index);
166 }
167
168 static void
169 application_name_table_add (application_t * app)
170 {
171   hash_set_mem (app_main.app_by_name, app->name, app->app_index);
172 }
173
174 static void
175 application_name_table_del (application_t * app)
176 {
177   hash_unset_mem (app_main.app_by_name, app->name);
178 }
179
180 application_t *
181 application_lookup (u32 api_client_index)
182 {
183   uword *p;
184   p = hash_get (app_main.app_by_api_client_index, api_client_index);
185   if (p)
186     return application_get_if_valid (p[0]);
187
188   return 0;
189 }
190
191 application_t *
192 application_lookup_name (const u8 * name)
193 {
194   uword *p;
195   p = hash_get_mem (app_main.app_by_name, name);
196   if (p)
197     return application_get (p[0]);
198
199   return 0;
200 }
201
202 application_t *
203 application_alloc (void)
204 {
205   application_t *app;
206   pool_get (app_main.app_pool, app);
207   clib_memset (app, 0, sizeof (*app));
208   app->app_index = app - app_main.app_pool;
209   return app;
210 }
211
212 application_t *
213 application_get (u32 app_index)
214 {
215   if (app_index == APP_INVALID_INDEX)
216     return 0;
217   return pool_elt_at_index (app_main.app_pool, app_index);
218 }
219
220 application_t *
221 application_get_if_valid (u32 app_index)
222 {
223   if (pool_is_free_index (app_main.app_pool, app_index))
224     return 0;
225
226   return pool_elt_at_index (app_main.app_pool, app_index);
227 }
228
229 static void
230 application_verify_cb_fns (session_cb_vft_t * cb_fns)
231 {
232   if (cb_fns->session_accept_callback == 0)
233     clib_warning ("No accept callback function provided");
234   if (cb_fns->session_connected_callback == 0)
235     clib_warning ("No session connected callback function provided");
236   if (cb_fns->session_disconnect_callback == 0)
237     clib_warning ("No session disconnect callback function provided");
238   if (cb_fns->session_reset_callback == 0)
239     clib_warning ("No session reset callback function provided");
240 }
241
242 /**
243  * Check app config for given segment type
244  *
245  * Returns 1 on success and 0 otherwise
246  */
247 static u8
248 application_verify_cfg (ssvm_segment_type_t st)
249 {
250   u8 is_valid;
251   if (st == SSVM_SEGMENT_MEMFD)
252     {
253       is_valid = (session_manager_get_evt_q_segment () != 0);
254       if (!is_valid)
255         clib_warning ("memfd seg: vpp's event qs IN binary api svm region");
256       return is_valid;
257     }
258   else if (st == SSVM_SEGMENT_SHM)
259     {
260       is_valid = (session_manager_get_evt_q_segment () == 0);
261       if (!is_valid)
262         clib_warning ("shm seg: vpp's event qs NOT IN binary api svm region");
263       return is_valid;
264     }
265   else
266     return 1;
267 }
268
269 int
270 application_alloc_and_init (app_init_args_t * a)
271 {
272   ssvm_segment_type_t seg_type = SSVM_SEGMENT_MEMFD;
273   segment_manager_properties_t *props;
274   vl_api_registration_t *reg;
275   application_t *app;
276   u64 *options;
277
278   app = application_alloc ();
279   options = a->options;
280   /*
281    * Make sure we support the requested configuration
282    */
283   if (!(options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_IS_BUILTIN))
284     {
285       reg = vl_api_client_index_to_registration (a->api_client_index);
286       if (!reg)
287         return VNET_API_ERROR_APP_UNSUPPORTED_CFG;
288       if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
289         seg_type = SSVM_SEGMENT_SHM;
290     }
291   else
292     {
293       if (options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
294         {
295           clib_warning ("mq eventfds can only be used if socket transport is "
296                         "used for api");
297           return VNET_API_ERROR_APP_UNSUPPORTED_CFG;
298         }
299       seg_type = SSVM_SEGMENT_PRIVATE;
300     }
301
302   if (!application_verify_cfg (seg_type))
303     return VNET_API_ERROR_APP_UNSUPPORTED_CFG;
304
305   /* Check that the obvious things are properly set up */
306   application_verify_cb_fns (a->session_cb_vft);
307
308   app->flags = options[APP_OPTIONS_FLAGS];
309   app->cb_fns = *a->session_cb_vft;
310   app->ns_index = options[APP_OPTIONS_NAMESPACE];
311   app->proxied_transports = options[APP_OPTIONS_PROXY_TRANSPORT];
312   app->name = vec_dup (a->name);
313
314   /* If no scope enabled, default to global */
315   if (!application_has_global_scope (app)
316       && !application_has_local_scope (app))
317     app->flags |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
318
319   props = application_segment_manager_properties (app);
320   segment_manager_properties_init (props);
321   props->segment_size = options[APP_OPTIONS_ADD_SEGMENT_SIZE];
322   props->prealloc_fifos = options[APP_OPTIONS_PREALLOC_FIFO_PAIRS];
323   if (options[APP_OPTIONS_ADD_SEGMENT_SIZE])
324     {
325       props->add_segment_size = options[APP_OPTIONS_ADD_SEGMENT_SIZE];
326       props->add_segment = 1;
327     }
328   if (options[APP_OPTIONS_RX_FIFO_SIZE])
329     props->rx_fifo_size = options[APP_OPTIONS_RX_FIFO_SIZE];
330   if (options[APP_OPTIONS_TX_FIFO_SIZE])
331     props->tx_fifo_size = options[APP_OPTIONS_TX_FIFO_SIZE];
332   if (options[APP_OPTIONS_EVT_QUEUE_SIZE])
333     props->evt_q_size = options[APP_OPTIONS_EVT_QUEUE_SIZE];
334   if (options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
335     props->use_mq_eventfd = 1;
336   if (options[APP_OPTIONS_TLS_ENGINE])
337     app->tls_engine = options[APP_OPTIONS_TLS_ENGINE];
338   props->segment_type = seg_type;
339
340   /* Add app to lookup by api_client_index table */
341   if (!application_is_builtin (app))
342     application_api_table_add (app->app_index, a->api_client_index);
343   else
344     application_name_table_add (app);
345
346   a->app_index = app->app_index;
347
348   APP_DBG ("New app name: %v api index: %u index %u", app->name,
349            app->api_client_index, app->app_index);
350
351   return 0;
352 }
353
354 void
355 application_free (application_t * app)
356 {
357   app_worker_map_t *wrk_map;
358   app_worker_t *app_wrk;
359   u32 table_index;
360   local_session_t *ll;
361   session_endpoint_t sep;
362
363   /*
364    * The app event queue allocated in first segment is cleared with
365    * the segment manager. No need to explicitly free it.
366    */
367   APP_DBG ("Delete app name %v api index: %d index: %d", app->name,
368            app->api_client_index, app->app_index);
369
370   if (application_is_proxy (app))
371     application_remove_proxy (app);
372
373   /*
374    * Free workers
375    */
376
377   /* *INDENT-OFF* */
378   pool_flush (wrk_map, app->worker_maps, ({
379     app_wrk = app_worker_get (wrk_map->wrk_index);
380     app_worker_free (app_wrk);
381   }));
382   /* *INDENT-ON* */
383   pool_free (app->worker_maps);
384
385   /*
386    * Free local listeners. Global table unbinds stop local listeners
387    * as well, but if we have only local binds, these won't be cleaned up.
388    * Don't bother with local accepted sessions, we clean them when
389    * cleaning up the worker.
390    */
391   table_index = application_local_session_table (app);
392   /* *INDENT-OFF* */
393   pool_foreach (ll, app->local_listen_sessions, ({
394     application_local_listener_session_endpoint (ll, &sep);
395     session_lookup_del_session_endpoint (table_index, &sep);
396   }));
397   /* *INDENT-ON* */
398   pool_free (app->local_listen_sessions);
399
400   /*
401    * Cleanup remaining state
402    */
403   if (application_is_builtin (app))
404     application_name_table_del (app);
405   vec_free (app->name);
406   vec_free (app->tls_cert);
407   vec_free (app->tls_key);
408   pool_put (app_main.app_pool, app);
409 }
410
411 void
412 application_detach_process (application_t * app, u32 api_client_index)
413 {
414   vnet_app_worker_add_del_args_t _args = { 0 }, *args = &_args;
415   app_worker_map_t *wrk_map;
416   u32 *wrks = 0, *wrk_index;
417   app_worker_t *app_wrk;
418
419   if (api_client_index == ~0)
420     {
421       application_free (app);
422       return;
423     }
424
425   APP_DBG ("Detaching for app %v index %u api client index %u", app->name,
426            app->app_index, app->api_client_index);
427
428   /* *INDENT-OFF* */
429   pool_foreach (wrk_map, app->worker_maps, ({
430     app_wrk = app_worker_get (wrk_map->wrk_index);
431     if (app_wrk->api_client_index == api_client_index)
432       vec_add1 (wrks, app_wrk->wrk_index);
433   }));
434   /* *INDENT-ON* */
435
436   if (!vec_len (wrks))
437     {
438       clib_warning ("no workers for app %u api_index %u", app->app_index,
439                     api_client_index);
440       return;
441     }
442
443   args->app_index = app->app_index;
444   args->api_client_index = api_client_index;
445   vec_foreach (wrk_index, wrks)
446   {
447     app_wrk = app_worker_get (wrk_index[0]);
448     args->wrk_map_index = app_wrk->wrk_map_index;
449     args->is_add = 0;
450     vnet_app_worker_add_del (args);
451   }
452   vec_free (wrks);
453 }
454
455 app_worker_t *
456 application_get_worker (application_t * app, u32 wrk_map_index)
457 {
458   app_worker_map_t *map;
459   map = app_worker_map_get (app, wrk_map_index);
460   if (!map)
461     return 0;
462   return app_worker_get (map->wrk_index);
463 }
464
465 app_worker_t *
466 application_get_default_worker (application_t * app)
467 {
468   return application_get_worker (app, 0);
469 }
470
471 u32
472 application_n_workers (application_t * app)
473 {
474   return pool_elts (app->worker_maps);
475 }
476
477 app_worker_t *
478 application_listener_select_worker (stream_session_t * ls, u8 is_local)
479 {
480   app_listener_t *app_listener;
481   application_t *app;
482   u32 wrk_index;
483
484   app = application_get (ls->app_index);
485   if (!is_local)
486     app_listener = app_listener_get (app, ls->listener_db_index);
487   else
488     app_listener = app_local_listener_get (app, ls->listener_db_index);
489
490   wrk_index = clib_bitmap_next_set (app_listener->workers,
491                                     app_listener->accept_rotor + 1);
492   if (wrk_index == ~0)
493     wrk_index = clib_bitmap_first_set (app_listener->workers);
494
495   ASSERT (wrk_index != ~0);
496   app_listener->accept_rotor = wrk_index;
497   return application_get_worker (app, wrk_index);
498 }
499
500 app_worker_t *
501 app_worker_alloc (application_t * app)
502 {
503   app_worker_t *app_wrk;
504   pool_get (app_main.workers, app_wrk);
505   clib_memset (app_wrk, 0, sizeof (*app_wrk));
506   app_wrk->wrk_index = app_wrk - app_main.workers;
507   app_wrk->app_index = app->app_index;
508   app_wrk->wrk_map_index = ~0;
509   app_wrk->connects_seg_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
510   app_wrk->first_segment_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
511   app_wrk->local_segment_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
512   APP_DBG ("New app %v worker %u", app_get_name (app), app_wrk->wrk_index);
513   return app_wrk;
514 }
515
516 app_worker_t *
517 app_worker_get (u32 wrk_index)
518 {
519   return pool_elt_at_index (app_main.workers, wrk_index);
520 }
521
522 app_worker_t *
523 app_worker_get_if_valid (u32 wrk_index)
524 {
525   if (pool_is_free_index (app_main.workers, wrk_index))
526     return 0;
527   return pool_elt_at_index (app_main.workers, wrk_index);
528 }
529
530 void
531 app_worker_free (app_worker_t * app_wrk)
532 {
533   application_t *app = application_get (app_wrk->app_index);
534   vnet_unbind_args_t _a, *a = &_a;
535   u64 handle, *handles = 0;
536   segment_manager_t *sm;
537   u32 sm_index;
538   int i;
539
540   /*
541    *  Listener cleanup
542    */
543
544   /* *INDENT-OFF* */
545   hash_foreach (handle, sm_index, app_wrk->listeners_table,
546   ({
547     vec_add1 (handles, handle);
548     sm = segment_manager_get (sm_index);
549     sm->app_wrk_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
550   }));
551   /* *INDENT-ON* */
552
553   for (i = 0; i < vec_len (handles); i++)
554     {
555       a->app_index = app->app_index;
556       a->wrk_map_index = app_wrk->wrk_map_index;
557       a->handle = handles[i];
558       /* seg manager is removed when unbind completes */
559       vnet_unbind (a);
560     }
561
562   /*
563    * Connects segment manager cleanup
564    */
565
566   if (app_wrk->connects_seg_manager != APP_INVALID_SEGMENT_MANAGER_INDEX)
567     {
568       sm = segment_manager_get (app_wrk->connects_seg_manager);
569       sm->app_wrk_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
570       segment_manager_init_del (sm);
571     }
572
573   /* If first segment manager is used by a listener */
574   if (app_wrk->first_segment_manager != APP_INVALID_SEGMENT_MANAGER_INDEX
575       && app_wrk->first_segment_manager != app_wrk->connects_seg_manager)
576     {
577       sm = segment_manager_get (app_wrk->first_segment_manager);
578       sm->first_is_protected = 0;
579       sm->app_wrk_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
580       /* .. and has no fifos, e.g. it might be used for redirected sessions,
581        * remove it */
582       if (!segment_manager_has_fifos (sm))
583         segment_manager_del (sm);
584     }
585
586   /*
587    * Local sessions
588    */
589   app_worker_local_sessions_free (app_wrk);
590
591   pool_put (app_main.workers, app_wrk);
592   if (CLIB_DEBUG)
593     clib_memset (app_wrk, 0xfe, sizeof (*app_wrk));
594 }
595
596 int
597 app_worker_alloc_and_init (application_t * app, app_worker_t ** wrk)
598 {
599   app_worker_map_t *wrk_map;
600   app_worker_t *app_wrk;
601   segment_manager_t *sm;
602   int rv;
603
604   app_wrk = app_worker_alloc (app);
605   wrk_map = app_worker_map_alloc (app);
606   wrk_map->wrk_index = app_wrk->wrk_index;
607   app_wrk->wrk_map_index = app_worker_map_index (app, wrk_map);
608
609   /*
610    * Setup first segment manager
611    */
612   sm = segment_manager_new ();
613   sm->app_wrk_index = app_wrk->wrk_index;
614
615   if ((rv = segment_manager_init (sm, app->sm_properties.segment_size,
616                                   app->sm_properties.prealloc_fifos)))
617     {
618       app_worker_free (app_wrk);
619       return rv;
620     }
621   sm->first_is_protected = 1;
622
623   /*
624    * Setup app worker
625    */
626   app_wrk->first_segment_manager = segment_manager_index (sm);
627   app_wrk->listeners_table = hash_create (0, sizeof (u64));
628   app_wrk->event_queue = segment_manager_event_queue (sm);
629   app_wrk->app_is_builtin = application_is_builtin (app);
630
631   /*
632    * Segment manager for local sessions
633    */
634   sm = segment_manager_new ();
635   sm->app_wrk_index = app_wrk->wrk_index;
636   app_wrk->local_segment_manager = segment_manager_index (sm);
637   app_wrk->local_connects = hash_create (0, sizeof (u64));
638
639   *wrk = app_wrk;
640
641   return 0;
642 }
643
644 application_t *
645 app_worker_get_app (u32 wrk_index)
646 {
647   app_worker_t *app_wrk;
648   app_wrk = app_worker_get_if_valid (wrk_index);
649   if (!app_wrk)
650     return 0;
651   return application_get_if_valid (app_wrk->app_index);
652 }
653
654 static segment_manager_t *
655 app_worker_alloc_segment_manager (app_worker_t * app_wrk)
656 {
657   segment_manager_t *sm = 0;
658
659   /* If the first segment manager is not in use, don't allocate a new one */
660   if (app_wrk->first_segment_manager != APP_INVALID_SEGMENT_MANAGER_INDEX
661       && app_wrk->first_segment_manager_in_use == 0)
662     {
663       sm = segment_manager_get (app_wrk->first_segment_manager);
664       app_wrk->first_segment_manager_in_use = 1;
665       return sm;
666     }
667
668   sm = segment_manager_new ();
669   sm->app_wrk_index = app_wrk->wrk_index;
670
671   return sm;
672 }
673
674 int
675 app_worker_start_listen (app_worker_t * app_wrk, stream_session_t * ls)
676 {
677   segment_manager_t *sm;
678
679   /* Allocate segment manager. All sessions derived out of a listen session
680    * have fifos allocated by the same segment manager. */
681   if (!(sm = app_worker_alloc_segment_manager (app_wrk)))
682     return -1;
683
684   /* Add to app's listener table. Useful to find all child listeners
685    * when app goes down, although, just for unbinding this is not needed */
686   hash_set (app_wrk->listeners_table, listen_session_get_handle (ls),
687             segment_manager_index (sm));
688
689   if (!ls->server_rx_fifo
690       && session_transport_service_type (ls) == TRANSPORT_SERVICE_CL)
691     {
692       if (session_alloc_fifos (sm, ls))
693         return -1;
694     }
695   return 0;
696 }
697
698 int
699 app_worker_stop_listen (app_worker_t * app_wrk, session_handle_t handle)
700 {
701   segment_manager_t *sm;
702   uword *sm_indexp;
703
704   sm_indexp = hash_get (app_wrk->listeners_table, handle);
705   if (PREDICT_FALSE (!sm_indexp))
706     {
707       clib_warning ("listener handle was removed %llu!", handle);
708       return -1;
709     }
710
711   sm = segment_manager_get (*sm_indexp);
712   if (app_wrk->first_segment_manager == *sm_indexp)
713     {
714       /* Delete sessions but don't remove segment manager */
715       app_wrk->first_segment_manager_in_use = 0;
716       segment_manager_del_sessions (sm);
717     }
718   else
719     {
720       segment_manager_init_del (sm);
721     }
722   hash_unset (app_wrk->listeners_table, handle);
723
724   return 0;
725 }
726
727 int
728 app_worker_own_session (app_worker_t * app_wrk, stream_session_t * s)
729 {
730   segment_manager_t *sm;
731   svm_fifo_t *rxf, *txf;
732
733   if (s->session_state == SESSION_STATE_LISTENING)
734     {
735       app_worker_t *old_wrk = app_worker_get (s->app_wrk_index);
736       u64 lsh = listen_session_get_handle (s);
737       app_listener_t *app_listener;
738       application_t *app;
739
740       if (!old_wrk)
741         return -1;
742
743       hash_unset (old_wrk->listeners_table, lsh);
744       if (!(sm = app_worker_alloc_segment_manager (app_wrk)))
745         return -1;
746
747       hash_set (app_wrk->listeners_table, lsh, segment_manager_index (sm));
748       s->app_wrk_index = app_wrk->wrk_index;
749
750       app = application_get (old_wrk->app_index);
751       if (!app)
752         return -1;
753
754       app_listener = app_listener_get (app, s->listener_db_index);
755       app_listener->workers = clib_bitmap_set (app_listener->workers,
756                                                app_wrk->wrk_map_index, 1);
757       app_listener->workers = clib_bitmap_set (app_listener->workers,
758                                                old_wrk->wrk_map_index, 0);
759       return 0;
760     }
761
762   s->app_wrk_index = app_wrk->wrk_index;
763
764   rxf = s->server_rx_fifo;
765   txf = s->server_tx_fifo;
766
767   if (!rxf || !txf)
768     return 0;
769
770   s->server_rx_fifo = 0;
771   s->server_tx_fifo = 0;
772
773   sm = app_worker_get_or_alloc_connect_segment_manager (app_wrk);
774   if (session_alloc_fifos (sm, s))
775     return -1;
776
777   if (!svm_fifo_is_empty (rxf))
778     {
779       clib_memcpy_fast (s->server_rx_fifo->data, rxf->data, rxf->nitems);
780       s->server_rx_fifo->head = rxf->head;
781       s->server_rx_fifo->tail = rxf->tail;
782       s->server_rx_fifo->cursize = rxf->cursize;
783     }
784
785   if (!svm_fifo_is_empty (txf))
786     {
787       clib_memcpy_fast (s->server_tx_fifo->data, txf->data, txf->nitems);
788       s->server_tx_fifo->head = txf->head;
789       s->server_tx_fifo->tail = txf->tail;
790       s->server_tx_fifo->cursize = txf->cursize;
791     }
792
793   segment_manager_dealloc_fifos (rxf->segment_index, rxf, txf);
794
795   return 0;
796 }
797
798 /**
799  * Start listening local transport endpoint for requested transport.
800  *
801  * Creates a 'dummy' stream session with state LISTENING to be used in session
802  * lookups, prior to establishing connection. Requests transport to build
803  * it's own specific listening connection.
804  */
805 int
806 application_start_listen (application_t * app,
807                           session_endpoint_cfg_t * sep_ext,
808                           session_handle_t * res)
809 {
810   app_listener_t *app_listener;
811   u32 table_index, fib_proto;
812   session_endpoint_t *sep;
813   app_worker_t *app_wrk;
814   stream_session_t *ls;
815   session_handle_t lh;
816   session_type_t sst;
817
818   /*
819    * Check if sep is already listened on
820    */
821   sep = (session_endpoint_t *) sep_ext;
822   fib_proto = session_endpoint_fib_proto (sep);
823   table_index = application_session_table (app, fib_proto);
824   lh = session_lookup_endpoint_listener (table_index, sep, 1);
825   if (lh != SESSION_INVALID_HANDLE)
826     {
827       ls = listen_session_get_from_handle (lh);
828       if (ls->app_index != app->app_index)
829         return VNET_API_ERROR_ADDRESS_IN_USE;
830
831       app_wrk = app_worker_get (sep_ext->app_wrk_index);
832       if (ls->app_wrk_index == app_wrk->wrk_index)
833         return VNET_API_ERROR_ADDRESS_IN_USE;
834
835       if (app_worker_start_listen (app_wrk, ls))
836         return -1;
837
838       app_listener = app_listener_get (app, ls->listener_db_index);
839       app_listener->workers = clib_bitmap_set (app_listener->workers,
840                                                app_wrk->wrk_map_index, 1);
841
842       *res = listen_session_get_handle (ls);
843       return 0;
844     }
845
846   /*
847    * Allocate new listener for application
848    */
849   sst = session_type_from_proto_and_ip (sep_ext->transport_proto,
850                                         sep_ext->is_ip4);
851   ls = listen_session_new (0, sst);
852   ls->app_index = app->app_index;
853   lh = listen_session_get_handle (ls);
854   if (session_listen (ls, sep_ext))
855     goto err;
856
857
858   ls = listen_session_get_from_handle (lh);
859   app_listener = app_listener_alloc (app);
860   ls->listener_db_index = app_listener->al_index;
861
862   /*
863    * Setup app worker as a listener
864    */
865   app_wrk = app_worker_get (sep_ext->app_wrk_index);
866   ls->app_wrk_index = app_wrk->wrk_index;
867   if (app_worker_start_listen (app_wrk, ls))
868     goto err;
869   app_listener->workers = clib_bitmap_set (app_listener->workers,
870                                            app_wrk->wrk_map_index, 1);
871
872   *res = lh;
873   return 0;
874
875 err:
876   listen_session_del (ls);
877   return -1;
878 }
879
880 /**
881  * Stop listening on session associated to handle
882  *
883  * @param handle        listener handle
884  * @param app_index     index of the app owning the handle.
885  * @param app_wrk_index index of the worker requesting the stop
886  */
887 int
888 application_stop_listen (u32 app_index, u32 app_wrk_index,
889                          session_handle_t handle)
890 {
891   app_listener_t *app_listener;
892   stream_session_t *listener;
893   app_worker_t *app_wrk;
894   application_t *app;
895
896   listener = listen_session_get_from_handle (handle);
897   app = application_get (app_index);
898   if (PREDICT_FALSE (!app || app->app_index != listener->app_index))
899     {
900       clib_warning ("app doesn't own handle %llu!", handle);
901       return -1;
902     }
903
904   app_listener = app_listener_get (app, listener->listener_db_index);
905   if (!clib_bitmap_get (app_listener->workers, app_wrk_index))
906     {
907       clib_warning ("worker %u not listening on handle %lu", app_wrk_index,
908                     handle);
909       return 0;
910     }
911
912   app_wrk = application_get_worker (app, app_wrk_index);
913   app_worker_stop_listen (app_wrk, handle);
914   clib_bitmap_set_no_check (app_listener->workers, app_wrk_index, 0);
915
916   if (clib_bitmap_is_zero (app_listener->workers))
917     {
918       session_stop_listen (listener);
919       app_listener_free (app, app_listener);
920       listen_session_del (listener);
921     }
922
923   return 0;
924 }
925
926 int
927 app_worker_open_session (app_worker_t * app, session_endpoint_t * sep,
928                          u32 api_context)
929 {
930   int rv;
931
932   /* Make sure we have a segment manager for connects */
933   app_worker_alloc_connects_segment_manager (app);
934
935   if ((rv = session_open (app->wrk_index, sep, api_context)))
936     return rv;
937
938   return 0;
939 }
940
941 int
942 app_worker_alloc_connects_segment_manager (app_worker_t * app_wrk)
943 {
944   segment_manager_t *sm;
945
946   if (app_wrk->connects_seg_manager == APP_INVALID_SEGMENT_MANAGER_INDEX)
947     {
948       sm = app_worker_alloc_segment_manager (app_wrk);
949       if (sm == 0)
950         return -1;
951       app_wrk->connects_seg_manager = segment_manager_index (sm);
952     }
953   return 0;
954 }
955
956 segment_manager_t *
957 app_worker_get_connect_segment_manager (app_worker_t * app)
958 {
959   ASSERT (app->connects_seg_manager != (u32) ~ 0);
960   return segment_manager_get (app->connects_seg_manager);
961 }
962
963 segment_manager_t *
964 app_worker_get_or_alloc_connect_segment_manager (app_worker_t * app_wrk)
965 {
966   if (app_wrk->connects_seg_manager == (u32) ~ 0)
967     app_worker_alloc_connects_segment_manager (app_wrk);
968   return segment_manager_get (app_wrk->connects_seg_manager);
969 }
970
971 segment_manager_t *
972 app_worker_get_listen_segment_manager (app_worker_t * app,
973                                        stream_session_t * listener)
974 {
975   uword *smp;
976   smp = hash_get (app->listeners_table, listen_session_get_handle (listener));
977   ASSERT (smp != 0);
978   return segment_manager_get (*smp);
979 }
980
981 clib_error_t *
982 vnet_app_worker_add_del (vnet_app_worker_add_del_args_t * a)
983 {
984   svm_fifo_segment_private_t *fs;
985   app_worker_map_t *wrk_map;
986   app_worker_t *app_wrk;
987   segment_manager_t *sm;
988   application_t *app;
989   int rv;
990
991   app = application_get (a->app_index);
992   if (!app)
993     return clib_error_return_code (0, VNET_API_ERROR_INVALID_VALUE, 0,
994                                    "App %u does not exist", a->app_index);
995
996   if (a->is_add)
997     {
998       if ((rv = app_worker_alloc_and_init (app, &app_wrk)))
999         return clib_error_return_code (0, rv, 0, "app wrk init: %d", rv);
1000
1001       /* Map worker api index to the app */
1002       app_wrk->api_client_index = a->api_client_index;
1003       application_api_table_add (app->app_index, a->api_client_index);
1004
1005       sm = segment_manager_get (app_wrk->first_segment_manager);
1006       fs = segment_manager_get_segment_w_lock (sm, 0);
1007       a->segment = &fs->ssvm;
1008       a->segment_handle = segment_manager_segment_handle (sm, fs);
1009       segment_manager_segment_reader_unlock (sm);
1010       a->evt_q = app_wrk->event_queue;
1011       a->wrk_map_index = app_wrk->wrk_map_index;
1012     }
1013   else
1014     {
1015       wrk_map = app_worker_map_get (app, a->wrk_map_index);
1016       if (!wrk_map)
1017         return clib_error_return_code (0, VNET_API_ERROR_INVALID_VALUE, 0,
1018                                        "App %u does not have worker %u",
1019                                        app->app_index, a->wrk_map_index);
1020       app_wrk = app_worker_get (wrk_map->wrk_index);
1021       if (!app_wrk)
1022         return clib_error_return_code (0, VNET_API_ERROR_INVALID_VALUE, 0,
1023                                        "No worker %u", a->wrk_map_index);
1024       application_api_table_del (app_wrk->api_client_index);
1025       app_worker_free (app_wrk);
1026       app_worker_map_free (app, wrk_map);
1027       if (application_n_workers (app) == 0)
1028         application_free (app);
1029     }
1030   return 0;
1031 }
1032
1033 segment_manager_t *
1034 application_get_local_segment_manager (app_worker_t * app)
1035 {
1036   return segment_manager_get (app->local_segment_manager);
1037 }
1038
1039 segment_manager_t *
1040 application_get_local_segment_manager_w_session (app_worker_t * app,
1041                                                  local_session_t * ls)
1042 {
1043   stream_session_t *listener;
1044   if (application_local_session_listener_has_transport (ls))
1045     {
1046       listener = listen_session_get (ls->listener_index);
1047       return app_worker_get_listen_segment_manager (app, listener);
1048     }
1049   return segment_manager_get (app->local_segment_manager);
1050 }
1051
1052 int
1053 application_is_proxy (application_t * app)
1054 {
1055   return (app->flags & APP_OPTIONS_FLAGS_IS_PROXY);
1056 }
1057
1058 int
1059 application_is_builtin (application_t * app)
1060 {
1061   return (app->flags & APP_OPTIONS_FLAGS_IS_BUILTIN);
1062 }
1063
1064 int
1065 application_is_builtin_proxy (application_t * app)
1066 {
1067   return (application_is_proxy (app) && application_is_builtin (app));
1068 }
1069
1070 u8
1071 application_has_local_scope (application_t * app)
1072 {
1073   return app->flags & APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
1074 }
1075
1076 u8
1077 application_has_global_scope (application_t * app)
1078 {
1079   return app->flags & APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1080 }
1081
1082 u8
1083 application_use_mq_for_ctrl (application_t * app)
1084 {
1085   return app->flags & APP_OPTIONS_FLAGS_USE_MQ_FOR_CTRL_MSGS;
1086 }
1087
1088 /**
1089  * Send an API message to the external app, to map new segment
1090  */
1091 int
1092 app_worker_add_segment_notify (u32 app_wrk_index, u64 segment_handle)
1093 {
1094   app_worker_t *app_wrk = app_worker_get (app_wrk_index);
1095   application_t *app = application_get (app_wrk->app_index);
1096   return app->cb_fns.add_segment_callback (app_wrk->api_client_index,
1097                                            segment_handle);
1098 }
1099
1100 u32
1101 application_n_listeners (app_worker_t * app)
1102 {
1103   return hash_elts (app->listeners_table);
1104 }
1105
1106 stream_session_t *
1107 app_worker_first_listener (app_worker_t * app, u8 fib_proto,
1108                            u8 transport_proto)
1109 {
1110   stream_session_t *listener;
1111   u64 handle;
1112   u32 sm_index;
1113   u8 sst;
1114
1115   sst = session_type_from_proto_and_ip (transport_proto,
1116                                         fib_proto == FIB_PROTOCOL_IP4);
1117
1118   /* *INDENT-OFF* */
1119    hash_foreach (handle, sm_index, app->listeners_table, ({
1120      listener = listen_session_get_from_handle (handle);
1121      if (listener->session_type == sst
1122          && listener->enqueue_epoch != SESSION_PROXY_LISTENER_INDEX)
1123        return listener;
1124    }));
1125   /* *INDENT-ON* */
1126
1127   return 0;
1128 }
1129
1130 u8
1131 app_worker_application_is_builtin (app_worker_t * app_wrk)
1132 {
1133   return app_wrk->app_is_builtin;
1134 }
1135
1136 stream_session_t *
1137 application_proxy_listener (app_worker_t * app, u8 fib_proto,
1138                             u8 transport_proto)
1139 {
1140   stream_session_t *listener;
1141   u64 handle;
1142   u32 sm_index;
1143   u8 sst;
1144
1145   sst = session_type_from_proto_and_ip (transport_proto,
1146                                         fib_proto == FIB_PROTOCOL_IP4);
1147
1148   /* *INDENT-OFF* */
1149    hash_foreach (handle, sm_index, app->listeners_table, ({
1150      listener = listen_session_get_from_handle (handle);
1151      if (listener->session_type == sst
1152          && listener->enqueue_epoch == SESSION_PROXY_LISTENER_INDEX)
1153        return listener;
1154    }));
1155   /* *INDENT-ON* */
1156
1157   return 0;
1158 }
1159
1160 static clib_error_t *
1161 application_start_stop_proxy_fib_proto (application_t * app, u8 fib_proto,
1162                                         u8 transport_proto, u8 is_start)
1163 {
1164   app_namespace_t *app_ns = app_namespace_get (app->ns_index);
1165   u8 is_ip4 = (fib_proto == FIB_PROTOCOL_IP4);
1166   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
1167   transport_connection_t *tc;
1168   app_worker_t *app_wrk;
1169   stream_session_t *s;
1170   u64 handle;
1171
1172   /* TODO decide if we want proxy to be enabled for all workers */
1173   app_wrk = application_get_default_worker (app);
1174   if (is_start)
1175     {
1176       s = app_worker_first_listener (app_wrk, fib_proto, transport_proto);
1177       if (!s)
1178         {
1179           sep.is_ip4 = is_ip4;
1180           sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
1181           sep.sw_if_index = app_ns->sw_if_index;
1182           sep.transport_proto = transport_proto;
1183           sep.app_wrk_index = app_wrk->wrk_index;       /* only default */
1184           application_start_listen (app, &sep, &handle);
1185           s = listen_session_get_from_handle (handle);
1186           s->enqueue_epoch = SESSION_PROXY_LISTENER_INDEX;
1187         }
1188     }
1189   else
1190     {
1191       s = application_proxy_listener (app_wrk, fib_proto, transport_proto);
1192       ASSERT (s);
1193     }
1194
1195   tc = listen_session_get_transport (s);
1196
1197   if (!ip_is_zero (&tc->lcl_ip, 1))
1198     {
1199       u32 sti;
1200       sep.is_ip4 = is_ip4;
1201       sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
1202       sep.transport_proto = transport_proto;
1203       sep.port = 0;
1204       sti = session_lookup_get_index_for_fib (fib_proto, sep.fib_index);
1205       if (is_start)
1206         session_lookup_add_session_endpoint (sti,
1207                                              (session_endpoint_t *) & sep,
1208                                              s->session_index);
1209       else
1210         session_lookup_del_session_endpoint (sti,
1211                                              (session_endpoint_t *) & sep);
1212     }
1213
1214   return 0;
1215 }
1216
1217 static void
1218 application_start_stop_proxy_local_scope (application_t * app,
1219                                           u8 transport_proto, u8 is_start)
1220 {
1221   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
1222   app_namespace_t *app_ns;
1223   app_ns = app_namespace_get (app->ns_index);
1224   sep.is_ip4 = 1;
1225   sep.transport_proto = transport_proto;
1226   sep.port = 0;
1227
1228   if (is_start)
1229     {
1230       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
1231                                            app->app_index);
1232       sep.is_ip4 = 0;
1233       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
1234                                            app->app_index);
1235     }
1236   else
1237     {
1238       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
1239       sep.is_ip4 = 0;
1240       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
1241     }
1242 }
1243
1244 void
1245 application_start_stop_proxy (application_t * app,
1246                               transport_proto_t transport_proto, u8 is_start)
1247 {
1248   if (application_has_local_scope (app))
1249     application_start_stop_proxy_local_scope (app, transport_proto, is_start);
1250
1251   if (application_has_global_scope (app))
1252     {
1253       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP4,
1254                                               transport_proto, is_start);
1255       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP6,
1256                                               transport_proto, is_start);
1257     }
1258 }
1259
1260 void
1261 application_setup_proxy (application_t * app)
1262 {
1263   u16 transports = app->proxied_transports;
1264   transport_proto_t tp;
1265
1266   ASSERT (application_is_proxy (app));
1267
1268   /* *INDENT-OFF* */
1269   transport_proto_foreach (tp, ({
1270     if (transports & (1 << tp))
1271       application_start_stop_proxy (app, tp, 1);
1272   }));
1273   /* *INDENT-ON* */
1274 }
1275
1276 void
1277 application_remove_proxy (application_t * app)
1278 {
1279   u16 transports = app->proxied_transports;
1280   transport_proto_t tp;
1281
1282   ASSERT (application_is_proxy (app));
1283
1284   /* *INDENT-OFF* */
1285   transport_proto_foreach (tp, ({
1286     if (transports & (1 << tp))
1287       application_start_stop_proxy (app, tp, 0);
1288   }));
1289   /* *INDENT-ON* */
1290 }
1291
1292 segment_manager_properties_t *
1293 application_segment_manager_properties (application_t * app)
1294 {
1295   return &app->sm_properties;
1296 }
1297
1298 segment_manager_properties_t *
1299 application_get_segment_manager_properties (u32 app_index)
1300 {
1301   application_t *app = application_get (app_index);
1302   return &app->sm_properties;
1303 }
1304
1305 static inline int
1306 app_enqueue_evt (svm_msg_q_t * mq, svm_msg_q_msg_t * msg, u8 lock)
1307 {
1308   if (PREDICT_FALSE (svm_msg_q_is_full (mq)))
1309     {
1310       clib_warning ("evt q full");
1311       svm_msg_q_free_msg (mq, msg);
1312       if (lock)
1313         svm_msg_q_unlock (mq);
1314       return -1;
1315     }
1316
1317   if (lock)
1318     {
1319       svm_msg_q_add_and_unlock (mq, msg);
1320       return 0;
1321     }
1322
1323   /* Even when not locking the ring, we must wait for queue mutex */
1324   if (svm_msg_q_add (mq, msg, SVM_Q_WAIT))
1325     {
1326       clib_warning ("msg q add returned");
1327       return -1;
1328     }
1329   return 0;
1330 }
1331
1332 static inline int
1333 app_send_io_evt_rx (app_worker_t * app_wrk, stream_session_t * s, u8 lock)
1334 {
1335   session_event_t *evt;
1336   svm_msg_q_msg_t msg;
1337   svm_msg_q_t *mq;
1338
1339   if (PREDICT_FALSE (s->session_state != SESSION_STATE_READY
1340                      && s->session_state != SESSION_STATE_LISTENING))
1341     {
1342       /* Session is closed so app will never clean up. Flush rx fifo */
1343       if (s->session_state == SESSION_STATE_CLOSED)
1344         svm_fifo_dequeue_drop_all (s->server_rx_fifo);
1345       return 0;
1346     }
1347
1348   if (app_worker_application_is_builtin (app_wrk))
1349     {
1350       application_t *app = application_get (app_wrk->app_index);
1351       return app->cb_fns.builtin_app_rx_callback (s);
1352     }
1353
1354   if (svm_fifo_has_event (s->server_rx_fifo)
1355       || svm_fifo_is_empty (s->server_rx_fifo))
1356     return 0;
1357
1358   mq = app_wrk->event_queue;
1359   if (lock)
1360     svm_msg_q_lock (mq);
1361
1362   if (PREDICT_FALSE (svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
1363     {
1364       clib_warning ("evt q rings full");
1365       if (lock)
1366         svm_msg_q_unlock (mq);
1367       return -1;
1368     }
1369
1370   msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
1371   ASSERT (!svm_msg_q_msg_is_invalid (&msg));
1372
1373   evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
1374   evt->fifo = s->server_rx_fifo;
1375   evt->event_type = FIFO_EVENT_APP_RX;
1376
1377   (void) svm_fifo_set_event (s->server_rx_fifo);
1378
1379   if (app_enqueue_evt (mq, &msg, lock))
1380     return -1;
1381   return 0;
1382 }
1383
1384 static inline int
1385 app_send_io_evt_tx (app_worker_t * app_wrk, stream_session_t * s, u8 lock)
1386 {
1387   svm_msg_q_t *mq;
1388   session_event_t *evt;
1389   svm_msg_q_msg_t msg;
1390
1391   if (app_worker_application_is_builtin (app_wrk))
1392     return 0;
1393
1394   mq = app_wrk->event_queue;
1395   if (lock)
1396     svm_msg_q_lock (mq);
1397
1398   if (PREDICT_FALSE (svm_msg_q_ring_is_full (mq, SESSION_MQ_IO_EVT_RING)))
1399     {
1400       clib_warning ("evt q rings full");
1401       if (lock)
1402         svm_msg_q_unlock (mq);
1403       return -1;
1404     }
1405
1406   msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
1407   ASSERT (!svm_msg_q_msg_is_invalid (&msg));
1408
1409   evt = (session_event_t *) svm_msg_q_msg_data (mq, &msg);
1410   evt->event_type = FIFO_EVENT_APP_TX;
1411   evt->fifo = s->server_tx_fifo;
1412
1413   return app_enqueue_evt (mq, &msg, lock);
1414 }
1415
1416 /* *INDENT-OFF* */
1417 typedef int (app_send_evt_handler_fn) (app_worker_t *app,
1418                                        stream_session_t *s,
1419                                        u8 lock);
1420 static app_send_evt_handler_fn * const app_send_evt_handler_fns[3] = {
1421     app_send_io_evt_rx,
1422     0,
1423     app_send_io_evt_tx,
1424 };
1425 /* *INDENT-ON* */
1426
1427 /**
1428  * Send event to application
1429  *
1430  * Logic from queue perspective is non-blocking. If there's
1431  * not enough space to enqueue a message, we return.
1432  */
1433 int
1434 app_worker_send_event (app_worker_t * app, stream_session_t * s, u8 evt_type)
1435 {
1436   ASSERT (app && evt_type <= FIFO_EVENT_APP_TX);
1437   return app_send_evt_handler_fns[evt_type] (app, s, 0 /* lock */ );
1438 }
1439
1440 /**
1441  * Send event to application
1442  *
1443  * Logic from queue perspective is blocking. However, if queue is full,
1444  * we return.
1445  */
1446 int
1447 app_worker_lock_and_send_event (app_worker_t * app, stream_session_t * s,
1448                                 u8 evt_type)
1449 {
1450   return app_send_evt_handler_fns[evt_type] (app, s, 1 /* lock */ );
1451 }
1452
1453 local_session_t *
1454 application_local_session_alloc (app_worker_t * app_wrk)
1455 {
1456   local_session_t *s;
1457   pool_get (app_wrk->local_sessions, s);
1458   clib_memset (s, 0, sizeof (*s));
1459   s->app_wrk_index = app_wrk->wrk_index;
1460   s->session_index = s - app_wrk->local_sessions;
1461   s->session_type = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE, 0);
1462   return s;
1463 }
1464
1465 void
1466 application_local_session_free (app_worker_t * app, local_session_t * s)
1467 {
1468   pool_put (app->local_sessions, s);
1469   if (CLIB_DEBUG)
1470     clib_memset (s, 0xfc, sizeof (*s));
1471 }
1472
1473 local_session_t *
1474 application_get_local_session (app_worker_t * app_wrk, u32 session_index)
1475 {
1476   if (pool_is_free_index (app_wrk->local_sessions, session_index))
1477     return 0;
1478   return pool_elt_at_index (app_wrk->local_sessions, session_index);
1479 }
1480
1481 local_session_t *
1482 application_get_local_session_from_handle (session_handle_t handle)
1483 {
1484   app_worker_t *server_wrk;
1485   u32 session_index, server_wrk_index;
1486   local_session_parse_handle (handle, &server_wrk_index, &session_index);
1487   server_wrk = app_worker_get_if_valid (server_wrk_index);
1488   if (!server_wrk)
1489     return 0;
1490   return application_get_local_session (server_wrk, session_index);
1491 }
1492
1493 local_session_t *
1494 application_local_listen_session_alloc (application_t * app)
1495 {
1496   local_session_t *ll;
1497   pool_get (app->local_listen_sessions, ll);
1498   clib_memset (ll, 0, sizeof (*ll));
1499   return ll;
1500 }
1501
1502 u32
1503 application_local_listener_index (application_t * app, local_session_t * ll)
1504 {
1505   return (ll - app->local_listen_sessions);
1506 }
1507
1508 void
1509 application_local_listen_session_free (application_t * app,
1510                                        local_session_t * ll)
1511 {
1512   pool_put (app->local_listen_sessions, ll);
1513   if (CLIB_DEBUG)
1514     clib_memset (ll, 0xfb, sizeof (*ll));
1515 }
1516
1517 int
1518 application_start_local_listen (application_t * app,
1519                                 session_endpoint_cfg_t * sep_ext,
1520                                 session_handle_t * handle)
1521 {
1522   app_listener_t *app_listener;
1523   session_endpoint_t *sep;
1524   app_worker_t *app_wrk;
1525   session_handle_t lh;
1526   local_session_t *ll;
1527   u32 table_index;
1528
1529   sep = (session_endpoint_t *) sep_ext;
1530   table_index = application_local_session_table (app);
1531   app_wrk = app_worker_get (sep_ext->app_wrk_index);
1532
1533   /* An exact sep match, as opposed to session_lookup_local_listener */
1534   lh = session_lookup_endpoint_listener (table_index, sep, 1);
1535   if (lh != SESSION_INVALID_HANDLE)
1536     {
1537       ll = application_get_local_listener_w_handle (lh);
1538       if (ll->app_index != app->app_index)
1539         return VNET_API_ERROR_ADDRESS_IN_USE;
1540
1541       if (ll->app_wrk_index == app_wrk->wrk_index)
1542         return VNET_API_ERROR_ADDRESS_IN_USE;
1543
1544       app_listener = app_local_listener_get (app, ll->listener_db_index);
1545       app_listener->workers = clib_bitmap_set (app_listener->workers,
1546                                                app_wrk->wrk_map_index, 1);
1547       *handle = application_local_session_handle (ll);
1548       return 0;
1549     }
1550
1551   ll = application_local_listen_session_alloc (app);
1552   ll->session_type = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE, 0);
1553   ll->app_wrk_index = app_wrk->app_index;
1554   ll->session_index = application_local_listener_index (app, ll);
1555   ll->port = sep_ext->port;
1556   /* Store the original session type for the unbind */
1557   ll->listener_session_type =
1558     session_type_from_proto_and_ip (sep_ext->transport_proto,
1559                                     sep_ext->is_ip4);
1560   ll->transport_listener_index = ~0;
1561   ll->app_index = app->app_index;
1562
1563   app_listener = app_local_listener_alloc (app);
1564   ll->listener_db_index = app_listener->al_index;
1565   app_listener->workers = clib_bitmap_set (app_listener->workers,
1566                                            app_wrk->wrk_map_index, 1);
1567
1568   *handle = application_local_session_handle (ll);
1569   session_lookup_add_session_endpoint (table_index, sep, *handle);
1570
1571   return 0;
1572 }
1573
1574 /**
1575  * Clean up local session table. If we have a listener session use it to
1576  * find the port and proto. If not, the handle must be a local table handle
1577  * so parse it.
1578  */
1579 int
1580 application_stop_local_listen (u32 app_index, u32 wrk_map_index,
1581                                session_handle_t lh)
1582 {
1583   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
1584   u32 table_index, ll_index, server_index;
1585   app_listener_t *app_listener;
1586   app_worker_t *server_wrk;
1587   stream_session_t *sl = 0;
1588   local_session_t *ll, *ls;
1589   application_t *server;
1590
1591   server = application_get (app_index);
1592   table_index = application_local_session_table (server);
1593
1594   /* We have both local and global table binds. Figure from global what
1595    * the sep we should be cleaning up is.
1596    */
1597   if (!session_handle_is_local (lh))
1598     {
1599       sl = listen_session_get_from_handle (lh);
1600       if (!sl || listen_session_get_local_session_endpoint (sl, &sep))
1601         {
1602           clib_warning ("broken listener");
1603           return -1;
1604         }
1605       lh = session_lookup_endpoint_listener (table_index, &sep, 0);
1606       if (lh == SESSION_INVALID_HANDLE)
1607         return -1;
1608     }
1609
1610   local_session_parse_handle (lh, &server_index, &ll_index);
1611   if (PREDICT_FALSE (server_index != app_index))
1612     {
1613       clib_warning ("app %u does not own local handle 0x%lx", app_index, lh);
1614       return -1;
1615     }
1616
1617   ll = application_get_local_listen_session (server, ll_index);
1618   if (PREDICT_FALSE (!ll))
1619     {
1620       clib_warning ("no local listener");
1621       return -1;
1622     }
1623
1624   app_listener = app_local_listener_get (server, ll->listener_db_index);
1625   if (!clib_bitmap_get (app_listener->workers, wrk_map_index))
1626     {
1627       clib_warning ("app wrk %u not listening on handle %lu", wrk_map_index,
1628                     lh);
1629       return -1;
1630     }
1631
1632   server_wrk = application_get_worker (server, wrk_map_index);
1633   /* *INDENT-OFF* */
1634   pool_foreach (ls, server_wrk->local_sessions, ({
1635     if (ls->listener_index == ll->session_index)
1636       application_local_session_disconnect (server_wrk->app_index, ls);
1637   }));
1638   /* *INDENT-ON* */
1639
1640   clib_bitmap_set_no_check (app_listener->workers, wrk_map_index, 0);
1641   if (clib_bitmap_is_zero (app_listener->workers))
1642     {
1643       app_local_listener_free (server, app_listener);
1644       application_local_listener_session_endpoint (ll, &sep);
1645       session_lookup_del_session_endpoint (table_index, &sep);
1646       application_local_listen_session_free (server, ll);
1647     }
1648
1649   return 0;
1650 }
1651
1652 static void
1653 application_local_session_fix_eventds (svm_msg_q_t * sq, svm_msg_q_t * cq)
1654 {
1655   int fd;
1656
1657   /*
1658    * segment manager initializes only the producer eventds, since vpp is
1659    * typically the producer. But for local sessions, we also pass to the
1660    * apps the mqs they listen on for events from peer apps, so they are also
1661    * consumer fds.
1662    */
1663   fd = svm_msg_q_get_producer_eventfd (sq);
1664   svm_msg_q_set_consumer_eventfd (sq, fd);
1665   fd = svm_msg_q_get_producer_eventfd (cq);
1666   svm_msg_q_set_consumer_eventfd (cq, fd);
1667 }
1668
1669 int
1670 application_local_session_connect (app_worker_t * client_wrk,
1671                                    app_worker_t * server_wrk,
1672                                    local_session_t * ll, u32 opaque)
1673 {
1674   u32 seg_size, evt_q_sz, evt_q_elts, margin = 16 << 10;
1675   u32 round_rx_fifo_sz, round_tx_fifo_sz, sm_index;
1676   segment_manager_properties_t *props, *cprops;
1677   int rv, has_transport, seg_index;
1678   svm_fifo_segment_private_t *seg;
1679   application_t *server, *client;
1680   segment_manager_t *sm;
1681   local_session_t *ls;
1682   svm_msg_q_t *sq, *cq;
1683   u64 segment_handle;
1684
1685   ls = application_local_session_alloc (server_wrk);
1686   server = application_get (server_wrk->app_index);
1687   client = application_get (client_wrk->app_index);
1688
1689   props = application_segment_manager_properties (server);
1690   cprops = application_segment_manager_properties (client);
1691   evt_q_elts = props->evt_q_size + cprops->evt_q_size;
1692   evt_q_sz = segment_manager_evt_q_expected_size (evt_q_elts);
1693   round_rx_fifo_sz = 1 << max_log2 (props->rx_fifo_size);
1694   round_tx_fifo_sz = 1 << max_log2 (props->tx_fifo_size);
1695   seg_size = round_rx_fifo_sz + round_tx_fifo_sz + evt_q_sz + margin;
1696
1697   has_transport = session_has_transport ((stream_session_t *) ll);
1698   if (!has_transport)
1699     {
1700       /* Local sessions don't have backing transport */
1701       ls->port = ll->port;
1702       sm = application_get_local_segment_manager (server_wrk);
1703     }
1704   else
1705     {
1706       stream_session_t *sl = (stream_session_t *) ll;
1707       transport_connection_t *tc;
1708       tc = listen_session_get_transport (sl);
1709       ls->port = tc->lcl_port;
1710       sm = app_worker_get_listen_segment_manager (server_wrk, sl);
1711     }
1712
1713   seg_index = segment_manager_add_segment (sm, seg_size);
1714   if (seg_index < 0)
1715     {
1716       clib_warning ("failed to add new cut-through segment");
1717       return seg_index;
1718     }
1719   seg = segment_manager_get_segment_w_lock (sm, seg_index);
1720   sq = segment_manager_alloc_queue (seg, props);
1721   cq = segment_manager_alloc_queue (seg, cprops);
1722
1723   if (props->use_mq_eventfd)
1724     application_local_session_fix_eventds (sq, cq);
1725
1726   ls->server_evt_q = pointer_to_uword (sq);
1727   ls->client_evt_q = pointer_to_uword (cq);
1728   rv = segment_manager_try_alloc_fifos (seg, props->rx_fifo_size,
1729                                         props->tx_fifo_size,
1730                                         &ls->server_rx_fifo,
1731                                         &ls->server_tx_fifo);
1732   if (rv)
1733     {
1734       clib_warning ("failed to add fifos in cut-through segment");
1735       segment_manager_segment_reader_unlock (sm);
1736       goto failed;
1737     }
1738   sm_index = segment_manager_index (sm);
1739   ls->server_rx_fifo->ct_session_index = ls->session_index;
1740   ls->server_tx_fifo->ct_session_index = ls->session_index;
1741   ls->server_rx_fifo->segment_manager = sm_index;
1742   ls->server_tx_fifo->segment_manager = sm_index;
1743   ls->server_rx_fifo->segment_index = seg_index;
1744   ls->server_tx_fifo->segment_index = seg_index;
1745   ls->svm_segment_index = seg_index;
1746   ls->listener_index = ll->session_index;
1747   ls->client_wrk_index = client_wrk->wrk_index;
1748   ls->client_opaque = opaque;
1749   ls->listener_session_type = ll->session_type;
1750   ls->session_state = SESSION_STATE_READY;
1751
1752   segment_handle = segment_manager_segment_handle (sm, seg);
1753   if ((rv = server->cb_fns.add_segment_callback (server_wrk->api_client_index,
1754                                                  segment_handle)))
1755     {
1756       clib_warning ("failed to notify server of new segment");
1757       segment_manager_segment_reader_unlock (sm);
1758       goto failed;
1759     }
1760   segment_manager_segment_reader_unlock (sm);
1761   if ((rv = server->cb_fns.session_accept_callback ((stream_session_t *) ls)))
1762     {
1763       clib_warning ("failed to send accept cut-through notify to server");
1764       goto failed;
1765     }
1766   if (server->flags & APP_OPTIONS_FLAGS_IS_BUILTIN)
1767     application_local_session_connect_notify (ls);
1768
1769   return 0;
1770
1771 failed:
1772   if (!has_transport)
1773     segment_manager_del_segment (sm, seg);
1774   return rv;
1775 }
1776
1777 static u64
1778 application_client_local_connect_key (local_session_t * ls)
1779 {
1780   return (((u64) ls->app_wrk_index) << 32 | (u64) ls->session_index);
1781 }
1782
1783 static void
1784 application_client_local_connect_key_parse (u64 key, u32 * app_wrk_index,
1785                                             u32 * session_index)
1786 {
1787   *app_wrk_index = key >> 32;
1788   *session_index = key & 0xFFFFFFFF;
1789 }
1790
1791 int
1792 application_local_session_connect_notify (local_session_t * ls)
1793 {
1794   svm_fifo_segment_private_t *seg;
1795   app_worker_t *client_wrk, *server_wrk;
1796   segment_manager_t *sm;
1797   application_t *client;
1798   int rv, is_fail = 0;
1799   u64 segment_handle;
1800   u64 client_key;
1801
1802   client_wrk = app_worker_get (ls->client_wrk_index);
1803   server_wrk = app_worker_get (ls->app_wrk_index);
1804   client = application_get (client_wrk->app_index);
1805
1806   sm = application_get_local_segment_manager_w_session (server_wrk, ls);
1807   seg = segment_manager_get_segment_w_lock (sm, ls->svm_segment_index);
1808   segment_handle = segment_manager_segment_handle (sm, seg);
1809   if ((rv = client->cb_fns.add_segment_callback (client_wrk->api_client_index,
1810                                                  segment_handle)))
1811     {
1812       clib_warning ("failed to notify client %u of new segment",
1813                     ls->client_wrk_index);
1814       segment_manager_segment_reader_unlock (sm);
1815       application_local_session_disconnect (ls->client_wrk_index, ls);
1816       is_fail = 1;
1817     }
1818   else
1819     {
1820       segment_manager_segment_reader_unlock (sm);
1821     }
1822
1823   client->cb_fns.session_connected_callback (client_wrk->wrk_index,
1824                                              ls->client_opaque,
1825                                              (stream_session_t *) ls,
1826                                              is_fail);
1827
1828   client_key = application_client_local_connect_key (ls);
1829   hash_set (client_wrk->local_connects, client_key, client_key);
1830   return 0;
1831 }
1832
1833 int
1834 application_local_session_cleanup (app_worker_t * client_wrk,
1835                                    app_worker_t * server_wrk,
1836                                    local_session_t * ls)
1837 {
1838   svm_fifo_segment_private_t *seg;
1839   stream_session_t *listener;
1840   segment_manager_t *sm;
1841   u64 client_key;
1842   u8 has_transport;
1843
1844   /* Retrieve listener transport type as it is the one that decides where
1845    * the fifos are allocated */
1846   has_transport = application_local_session_listener_has_transport (ls);
1847   if (!has_transport)
1848     sm = application_get_local_segment_manager_w_session (server_wrk, ls);
1849   else
1850     {
1851       listener = listen_session_get (ls->listener_index);
1852       sm = app_worker_get_listen_segment_manager (server_wrk, listener);
1853     }
1854
1855   seg = segment_manager_get_segment (sm, ls->svm_segment_index);
1856   if (client_wrk)
1857     {
1858       client_key = application_client_local_connect_key (ls);
1859       hash_unset (client_wrk->local_connects, client_key);
1860     }
1861
1862   if (!has_transport)
1863     {
1864       application_t *server = application_get (server_wrk->app_index);
1865       u64 segment_handle = segment_manager_segment_handle (sm, seg);
1866       server->cb_fns.del_segment_callback (server_wrk->api_client_index,
1867                                            segment_handle);
1868       if (client_wrk)
1869         {
1870           application_t *client = application_get (client_wrk->app_index);
1871           client->cb_fns.del_segment_callback (client_wrk->api_client_index,
1872                                                segment_handle);
1873         }
1874       segment_manager_del_segment (sm, seg);
1875     }
1876
1877   application_local_session_free (server_wrk, ls);
1878
1879   return 0;
1880 }
1881
1882 int
1883 application_local_session_disconnect (u32 app_index, local_session_t * ls)
1884 {
1885   app_worker_t *client_wrk, *server_wrk;
1886   u8 is_server = 0, is_client = 0;
1887   application_t *app;
1888
1889   app = application_get_if_valid (app_index);
1890   if (!app)
1891     return 0;
1892
1893   client_wrk = app_worker_get_if_valid (ls->client_wrk_index);
1894   server_wrk = app_worker_get (ls->app_wrk_index);
1895
1896   if (server_wrk->app_index == app_index)
1897     is_server = 1;
1898   else if (client_wrk && client_wrk->app_index == app_index)
1899     is_client = 1;
1900
1901   if (!is_server && !is_client)
1902     {
1903       clib_warning ("app %u is neither client nor server for session 0x%lx",
1904                     app_index, application_local_session_handle (ls));
1905       return VNET_API_ERROR_INVALID_VALUE;
1906     }
1907
1908   if (ls->session_state == SESSION_STATE_CLOSED)
1909     return application_local_session_cleanup (client_wrk, server_wrk, ls);
1910
1911   if (app_index == ls->client_wrk_index)
1912     {
1913       mq_send_local_session_disconnected_cb (ls->app_wrk_index, ls);
1914     }
1915   else
1916     {
1917       if (!client_wrk)
1918         {
1919           return application_local_session_cleanup (client_wrk, server_wrk,
1920                                                     ls);
1921         }
1922       else if (ls->session_state < SESSION_STATE_READY)
1923         {
1924           application_t *client = application_get (client_wrk->app_index);
1925           client->cb_fns.session_connected_callback (client_wrk->wrk_index,
1926                                                      ls->client_opaque,
1927                                                      (stream_session_t *) ls,
1928                                                      1 /* is_fail */ );
1929           ls->session_state = SESSION_STATE_CLOSED;
1930           return application_local_session_cleanup (client_wrk, server_wrk,
1931                                                     ls);
1932         }
1933       else
1934         {
1935           mq_send_local_session_disconnected_cb (client_wrk->wrk_index, ls);
1936         }
1937     }
1938
1939   ls->session_state = SESSION_STATE_CLOSED;
1940
1941   return 0;
1942 }
1943
1944 int
1945 application_local_session_disconnect_w_index (u32 app_wrk_index, u32 ls_index)
1946 {
1947   app_worker_t *app_wrk;
1948   local_session_t *ls;
1949   app_wrk = app_worker_get (app_wrk_index);
1950   ls = application_get_local_session (app_wrk, ls_index);
1951   return application_local_session_disconnect (app_wrk_index, ls);
1952 }
1953
1954 void
1955 app_worker_local_sessions_free (app_worker_t * app_wrk)
1956 {
1957   u32 index, server_wrk_index, session_index;
1958   u64 handle, *handles = 0;
1959   app_worker_t *server_wrk;
1960   segment_manager_t *sm;
1961   local_session_t *ls;
1962   int i;
1963
1964   /*
1965    * Local sessions
1966    */
1967   if (app_wrk->local_sessions)
1968     {
1969       /* *INDENT-OFF* */
1970       pool_foreach (ls, app_wrk->local_sessions, ({
1971         application_local_session_disconnect (app_wrk->wrk_index, ls);
1972       }));
1973       /* *INDENT-ON* */
1974     }
1975
1976   /*
1977    * Local connects
1978    */
1979   vec_reset_length (handles);
1980   /* *INDENT-OFF* */
1981   hash_foreach (handle, index, app_wrk->local_connects, ({
1982     vec_add1 (handles, handle);
1983   }));
1984   /* *INDENT-ON* */
1985
1986   for (i = 0; i < vec_len (handles); i++)
1987     {
1988       application_client_local_connect_key_parse (handles[i],
1989                                                   &server_wrk_index,
1990                                                   &session_index);
1991       server_wrk = app_worker_get_if_valid (server_wrk_index);
1992       if (server_wrk)
1993         {
1994           ls = application_get_local_session (server_wrk, session_index);
1995           application_local_session_disconnect (app_wrk->wrk_index, ls);
1996         }
1997     }
1998
1999   sm = segment_manager_get (app_wrk->local_segment_manager);
2000   sm->app_wrk_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
2001   segment_manager_del (sm);
2002 }
2003
2004 clib_error_t *
2005 vnet_app_add_tls_cert (vnet_app_add_tls_cert_args_t * a)
2006 {
2007   application_t *app;
2008   app = application_get (a->app_index);
2009   if (!app)
2010     return clib_error_return_code (0, VNET_API_ERROR_APPLICATION_NOT_ATTACHED,
2011                                    0, "app %u doesn't exist", a->app_index);
2012   app->tls_cert = vec_dup (a->cert);
2013   return 0;
2014 }
2015
2016 clib_error_t *
2017 vnet_app_add_tls_key (vnet_app_add_tls_key_args_t * a)
2018 {
2019   application_t *app;
2020   app = application_get (a->app_index);
2021   if (!app)
2022     return clib_error_return_code (0, VNET_API_ERROR_APPLICATION_NOT_ATTACHED,
2023                                    0, "app %u doesn't exist", a->app_index);
2024   app->tls_key = vec_dup (a->key);
2025   return 0;
2026 }
2027
2028 u8 *
2029 format_app_worker_listener (u8 * s, va_list * args)
2030 {
2031   app_worker_t *app_wrk = va_arg (*args, app_worker_t *);
2032   u64 handle = va_arg (*args, u64);
2033   u32 sm_index = va_arg (*args, u32);
2034   int verbose = va_arg (*args, int);
2035   stream_session_t *listener;
2036   const u8 *app_name;
2037   u8 *str;
2038
2039   if (!app_wrk)
2040     {
2041       if (verbose)
2042         s = format (s, "%-40s%-25s%=10s%-15s%-15s%-10s", "Connection", "App",
2043                     "Wrk", "API Client", "ListenerID", "SegManager");
2044       else
2045         s = format (s, "%-40s%-25s%=10s", "Connection", "App", "Wrk");
2046
2047       return s;
2048     }
2049
2050   app_name = application_name_from_index (app_wrk->app_index);
2051   listener = listen_session_get_from_handle (handle);
2052   str = format (0, "%U", format_stream_session, listener, verbose);
2053
2054   if (verbose)
2055     {
2056       char buf[32];
2057       sprintf (buf, "%u(%u)", app_wrk->wrk_map_index, app_wrk->wrk_index);
2058       s = format (s, "%-40s%-25s%=10s%-15u%-15u%-10u", str, app_name,
2059                   buf, app_wrk->api_client_index, handle, sm_index);
2060     }
2061   else
2062     s = format (s, "%-40s%-25s%=10u", str, app_name, app_wrk->wrk_map_index);
2063
2064   return s;
2065 }
2066
2067 static void
2068 application_format_listeners (application_t * app, int verbose)
2069 {
2070   vlib_main_t *vm = vlib_get_main ();
2071   app_worker_map_t *wrk_map;
2072   app_worker_t *app_wrk;
2073   u32 sm_index;
2074   u64 handle;
2075
2076   if (!app)
2077     {
2078       vlib_cli_output (vm, "%U", format_app_worker_listener, 0 /* header */ ,
2079                        0, 0, verbose);
2080       return;
2081     }
2082
2083   /* *INDENT-OFF* */
2084   pool_foreach (wrk_map, app->worker_maps, ({
2085     app_wrk = app_worker_get (wrk_map->wrk_index);
2086     if (hash_elts (app_wrk->listeners_table) == 0)
2087       continue;
2088     hash_foreach (handle, sm_index, app_wrk->listeners_table, ({
2089       vlib_cli_output (vm, "%U", format_app_worker_listener, app_wrk,
2090                        handle, sm_index, verbose);
2091     }));
2092   }));
2093   /* *INDENT-ON* */
2094 }
2095
2096 static void
2097 app_worker_format_connects (app_worker_t * app_wrk, int verbose)
2098 {
2099   svm_fifo_segment_private_t *fifo_segment;
2100   vlib_main_t *vm = vlib_get_main ();
2101   segment_manager_t *sm;
2102   const u8 *app_name;
2103   u8 *s = 0;
2104
2105   /* Header */
2106   if (!app_wrk)
2107     {
2108       if (verbose)
2109         vlib_cli_output (vm, "%-40s%-20s%-15s%-10s", "Connection", "App",
2110                          "API Client", "SegManager");
2111       else
2112         vlib_cli_output (vm, "%-40s%-20s", "Connection", "App");
2113       return;
2114     }
2115
2116   if (app_wrk->connects_seg_manager == (u32) ~ 0)
2117     return;
2118
2119   app_name = application_name_from_index (app_wrk->app_index);
2120
2121   /* Across all fifo segments */
2122   sm = segment_manager_get (app_wrk->connects_seg_manager);
2123
2124   /* *INDENT-OFF* */
2125   segment_manager_foreach_segment_w_lock (fifo_segment, sm, ({
2126     svm_fifo_t *fifo;
2127     u8 *str;
2128
2129     fifo = svm_fifo_segment_get_fifo_list (fifo_segment);
2130     while (fifo)
2131       {
2132         u32 session_index, thread_index;
2133         stream_session_t *session;
2134
2135         session_index = fifo->master_session_index;
2136         thread_index = fifo->master_thread_index;
2137
2138         session = session_get (session_index, thread_index);
2139         str = format (0, "%U", format_stream_session, session, verbose);
2140
2141         if (verbose)
2142           s = format (s, "%-40s%-20s%-15u%-10u", str, app_name,
2143                       app_wrk->api_client_index, app_wrk->connects_seg_manager);
2144         else
2145           s = format (s, "%-40s%-20s", str, app_name);
2146
2147         vlib_cli_output (vm, "%v", s);
2148         vec_reset_length (s);
2149         vec_free (str);
2150
2151         fifo = fifo->next;
2152       }
2153     vec_free (s);
2154   }));
2155   /* *INDENT-ON* */
2156
2157 }
2158
2159 static void
2160 application_format_connects (application_t * app, int verbose)
2161 {
2162   app_worker_map_t *wrk_map;
2163   app_worker_t *app_wrk;
2164
2165   if (!app)
2166     {
2167       app_worker_format_connects (0, verbose);
2168       return;
2169     }
2170
2171   /* *INDENT-OFF* */
2172   pool_foreach (wrk_map, app->worker_maps, ({
2173     app_wrk = app_worker_get (wrk_map->wrk_index);
2174     app_worker_format_connects (app_wrk, verbose);
2175   }));
2176   /* *INDENT-ON* */
2177 }
2178
2179 static void
2180 app_worker_format_local_sessions (app_worker_t * app_wrk, int verbose)
2181 {
2182   vlib_main_t *vm = vlib_get_main ();
2183   local_session_t *ls;
2184   transport_proto_t tp;
2185   u8 *conn = 0;
2186
2187   /* Header */
2188   if (app_wrk == 0)
2189     {
2190       vlib_cli_output (vm, "%-40s%-15s%-20s", "Connection", "ServerApp",
2191                        "ClientApp");
2192       return;
2193     }
2194
2195   if (!pool_elts (app_wrk->local_sessions)
2196       && !pool_elts (app_wrk->local_connects))
2197     return;
2198
2199   /* *INDENT-OFF* */
2200   pool_foreach (ls, app_wrk->local_sessions, ({
2201     tp = session_type_transport_proto(ls->listener_session_type);
2202     conn = format (0, "[L][%U] *:%u", format_transport_proto_short, tp,
2203                    ls->port);
2204     vlib_cli_output (vm, "%-40v%-15u%-20u", conn, ls->app_wrk_index,
2205                      ls->client_wrk_index);
2206     vec_reset_length (conn);
2207   }));
2208   /* *INDENT-ON* */
2209
2210   vec_free (conn);
2211 }
2212
2213 static void
2214 application_format_local_sessions (application_t * app, int verbose)
2215 {
2216   vlib_main_t *vm = vlib_get_main ();
2217   app_worker_map_t *wrk_map;
2218   app_worker_t *app_wrk;
2219   transport_proto_t tp;
2220   local_session_t *ls;
2221   u8 *conn = 0;
2222
2223   if (!app)
2224     {
2225       app_worker_format_local_sessions (0, verbose);
2226       return;
2227     }
2228
2229   /*
2230    * Format local listeners
2231    */
2232
2233   /* *INDENT-OFF* */
2234   pool_foreach (ls, app->local_listen_sessions, ({
2235     tp = session_type_transport_proto (ls->listener_session_type);
2236     conn = format (0, "[L][%U] *:%u", format_transport_proto_short, tp,
2237                    ls->port);
2238     vlib_cli_output (vm, "%-40v%-15u%-20s", conn, ls->app_wrk_index, "*");
2239     vec_reset_length (conn);
2240   }));
2241   /* *INDENT-ON* */
2242
2243   /*
2244    * Format local accepted/connected sessions
2245    */
2246   /* *INDENT-OFF* */
2247   pool_foreach (wrk_map, app->worker_maps, ({
2248     app_wrk = app_worker_get (wrk_map->wrk_index);
2249     app_worker_format_local_sessions (app_wrk, verbose);
2250   }));
2251   /* *INDENT-ON* */
2252 }
2253
2254 static void
2255 app_worker_format_local_connects (app_worker_t * app, int verbose)
2256 {
2257   vlib_main_t *vm = vlib_get_main ();
2258   u32 app_wrk_index, session_index;
2259   app_worker_t *server_wrk;
2260   local_session_t *ls;
2261   u64 client_key;
2262   u64 value;
2263
2264   /* Header */
2265   if (app == 0)
2266     {
2267       if (verbose)
2268         vlib_cli_output (vm, "%-40s%-15s%-20s%-10s", "Connection", "App",
2269                          "Peer App", "SegManager");
2270       else
2271         vlib_cli_output (vm, "%-40s%-15s%-20s", "Connection", "App",
2272                          "Peer App");
2273       return;
2274     }
2275
2276   if (!app->local_connects)
2277     return;
2278
2279   /* *INDENT-OFF* */
2280   hash_foreach (client_key, value, app->local_connects, ({
2281     application_client_local_connect_key_parse (client_key, &app_wrk_index,
2282                                                 &session_index);
2283     server_wrk = app_worker_get (app_wrk_index);
2284     ls = application_get_local_session (server_wrk, session_index);
2285     vlib_cli_output (vm, "%-40s%-15s%-20s", "TODO", ls->app_wrk_index,
2286                      ls->client_wrk_index);
2287   }));
2288   /* *INDENT-ON* */
2289 }
2290
2291 static void
2292 application_format_local_connects (application_t * app, int verbose)
2293 {
2294   app_worker_map_t *wrk_map;
2295   app_worker_t *app_wrk;
2296
2297   if (!app)
2298     {
2299       app_worker_format_local_connects (0, verbose);
2300       return;
2301     }
2302
2303   /* *INDENT-OFF* */
2304   pool_foreach (wrk_map, app->worker_maps, ({
2305     app_wrk = app_worker_get (wrk_map->wrk_index);
2306     app_worker_format_local_connects (app_wrk, verbose);
2307   }));
2308   /* *INDENT-ON* */
2309 }
2310
2311 u8 *
2312 format_application_worker (u8 * s, va_list * args)
2313 {
2314   app_worker_t *app_wrk = va_arg (*args, app_worker_t *);
2315   u32 indent = 1;
2316
2317   s = format (s, "%U wrk-index %u app-index %u map-index %u "
2318               "api-client-index %d\n", format_white_space, indent,
2319               app_wrk->wrk_index, app_wrk->app_index, app_wrk->wrk_map_index,
2320               app_wrk->api_client_index);
2321   return s;
2322 }
2323
2324 u8 *
2325 format_application (u8 * s, va_list * args)
2326 {
2327   application_t *app = va_arg (*args, application_t *);
2328   CLIB_UNUSED (int verbose) = va_arg (*args, int);
2329   segment_manager_properties_t *props;
2330   const u8 *app_ns_name, *app_name;
2331   app_worker_map_t *wrk_map;
2332   app_worker_t *app_wrk;
2333
2334   if (app == 0)
2335     {
2336       if (!verbose)
2337         s = format (s, "%-10s%-20s%-40s", "Index", "Name", "Namespace");
2338       return s;
2339     }
2340
2341   app_name = app_get_name (app);
2342   app_ns_name = app_namespace_id_from_index (app->ns_index);
2343   props = application_segment_manager_properties (app);
2344   if (!verbose)
2345     {
2346       s = format (s, "%-10u%-20s%-40s", app->app_index, app_name,
2347                   app_ns_name);
2348       return s;
2349     }
2350
2351   s = format (s, "app-name %s app-index %u ns-index %u seg-size %U\n",
2352               app_name, app->app_index, app->ns_index,
2353               format_memory_size, props->add_segment_size);
2354   s = format (s, "rx-fifo-size %U tx-fifo-size %U workers:\n",
2355               format_memory_size, props->rx_fifo_size,
2356               format_memory_size, props->tx_fifo_size);
2357
2358   /* *INDENT-OFF* */
2359   pool_foreach (wrk_map, app->worker_maps, ({
2360       app_wrk = app_worker_get (wrk_map->wrk_index);
2361       s = format (s, "%U", format_application_worker, app_wrk);
2362   }));
2363   /* *INDENT-ON* */
2364
2365   return s;
2366 }
2367
2368 void
2369 application_format_all_listeners (vlib_main_t * vm, int do_local, int verbose)
2370 {
2371   application_t *app;
2372
2373   if (!pool_elts (app_main.app_pool))
2374     {
2375       vlib_cli_output (vm, "No active server bindings");
2376       return;
2377     }
2378
2379   if (do_local)
2380     {
2381       application_format_local_sessions (0, verbose);
2382       /* *INDENT-OFF* */
2383       pool_foreach (app, app_main.app_pool, ({
2384         application_format_local_sessions (app, verbose);
2385       }));
2386       /* *INDENT-ON* */
2387     }
2388   else
2389     {
2390       application_format_listeners (0, verbose);
2391
2392       /* *INDENT-OFF* */
2393       pool_foreach (app, app_main.app_pool, ({
2394         application_format_listeners (app, verbose);
2395       }));
2396       /* *INDENT-ON* */
2397     }
2398 }
2399
2400 void
2401 application_format_all_clients (vlib_main_t * vm, int do_local, int verbose)
2402 {
2403   application_t *app;
2404
2405   if (!pool_elts (app_main.app_pool))
2406     {
2407       vlib_cli_output (vm, "No active apps");
2408       return;
2409     }
2410
2411   if (do_local)
2412     {
2413       application_format_local_connects (0, verbose);
2414
2415       /* *INDENT-OFF* */
2416       pool_foreach (app, app_main.app_pool, ({
2417         application_format_local_connects (app, verbose);
2418       }));
2419       /* *INDENT-ON* */
2420     }
2421   else
2422     {
2423       application_format_connects (0, verbose);
2424
2425       /* *INDENT-OFF* */
2426       pool_foreach (app, app_main.app_pool, ({
2427         application_format_connects (app, verbose);
2428       }));
2429       /* *INDENT-ON* */
2430     }
2431 }
2432
2433 static clib_error_t *
2434 show_app_command_fn (vlib_main_t * vm, unformat_input_t * input,
2435                      vlib_cli_command_t * cmd)
2436 {
2437   int do_server = 0, do_client = 0, do_local = 0;
2438   application_t *app;
2439   u32 app_index = ~0;
2440   int verbose = 0;
2441
2442   session_cli_return_if_not_enabled ();
2443
2444   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2445     {
2446       if (unformat (input, "server"))
2447         do_server = 1;
2448       else if (unformat (input, "client"))
2449         do_client = 1;
2450       else if (unformat (input, "local"))
2451         do_local = 1;
2452       else if (unformat (input, "%u", &app_index))
2453         ;
2454       else if (unformat (input, "verbose"))
2455         verbose = 1;
2456       else
2457         return clib_error_return (0, "unknown input `%U'",
2458                                   format_unformat_error, input);
2459     }
2460
2461   if (do_server)
2462     {
2463       application_format_all_listeners (vm, do_local, verbose);
2464       return 0;
2465     }
2466
2467   if (do_client)
2468     {
2469       application_format_all_clients (vm, do_local, verbose);
2470       return 0;
2471     }
2472
2473   if (app_index != ~0)
2474     {
2475       app = application_get_if_valid (app_index);
2476       if (!app)
2477         return clib_error_return (0, "No app with index %u", app_index);
2478
2479       vlib_cli_output (vm, "%U", format_application, app, /* verbose */ 1);
2480       return 0;
2481     }
2482
2483   /* Print app related info */
2484   if (!do_server && !do_client)
2485     {
2486       vlib_cli_output (vm, "%U", format_application, 0, 0);
2487       /* *INDENT-OFF* */
2488       pool_foreach (app, app_main.app_pool, ({
2489         vlib_cli_output (vm, "%U", format_application, app, 0);
2490       }));
2491       /* *INDENT-ON* */
2492     }
2493
2494   return 0;
2495 }
2496
2497 /* *INDENT-OFF* */
2498 VLIB_CLI_COMMAND (show_app_command, static) =
2499 {
2500   .path = "show app",
2501   .short_help = "show app [server|client] [verbose]",
2502   .function = show_app_command_fn,
2503 };
2504 /* *INDENT-ON* */
2505
2506 /*
2507  * fd.io coding-style-patch-verification: ON
2508  *
2509  * Local Variables:
2510  * eval: (c-set-style "gnu")
2511  * End:
2512  */