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