VCL eventlog - track create/delete
[vpp.git] / src / vcl / vppcom.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
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 <stdio.h>
17 #include <stdlib.h>
18 #include <signal.h>
19 #include <svm/svm_fifo_segment.h>
20 #include <vlibmemory/api.h>
21 #include <vpp/api/vpe_msg_enum.h>
22 #include <vnet/session/application_interface.h>
23 #include <vcl/vppcom.h>
24 #include <vlib/unix/unix.h>
25 #include <vppinfra/vec_bootstrap.h>
26 #include <vppinfra/elog.h>
27
28 #define vl_typedefs             /* define message structures */
29 #include <vpp/api/vpe_all_api_h.h>
30 #undef vl_typedefs
31
32 /* declare message handlers for each api */
33
34 #define vl_endianfun            /* define message structures */
35 #include <vpp/api/vpe_all_api_h.h>
36 #undef vl_endianfun
37
38 /* instantiate all the print functions we know about */
39 #define vl_print(handle, ...)
40 #define vl_printfun
41 #include <vpp/api/vpe_all_api_h.h>
42 #undef vl_printfun
43
44 #if (CLIB_DEBUG > 0)
45 /* Set VPPCOM_DEBUG_INIT 2 for connection debug,
46  *                       3 for read/write debug output
47  * or
48  *    export VCL_DEBUG=<#> to set dynamically.
49  */
50 #define VPPCOM_DEBUG_INIT 1
51 #else
52 #define VPPCOM_DEBUG_INIT 0
53 #endif
54
55 #define VPPCOM_DEBUG vcm->debug
56
57 /*
58  * VPPCOM Private definitions and functions.
59  */
60 typedef enum
61 {
62   STATE_APP_START,
63   STATE_APP_CONN_VPP,
64   STATE_APP_ENABLED,
65   STATE_APP_ATTACHED,
66 } app_state_t;
67
68 typedef enum
69 {
70   STATE_START = 0x01,
71   STATE_CONNECT = 0x02,
72   STATE_LISTEN = 0x04,
73   STATE_ACCEPT = 0x08,
74   STATE_CLOSE_ON_EMPTY = 0x10,
75   STATE_DISCONNECT = 0x20,
76   STATE_FAILED = 0x40
77 } session_state_t;
78
79 #define SERVER_STATE_OPEN  (STATE_ACCEPT|STATE_CLOSE_ON_EMPTY)
80 #define CLIENT_STATE_OPEN  (STATE_CONNECT|STATE_CLOSE_ON_EMPTY)
81
82 typedef struct epoll_event vppcom_epoll_event_t;
83
84 typedef struct
85 {
86   u32 next_sid;
87   u32 prev_sid;
88   u32 vep_idx;
89   vppcom_epoll_event_t ev;
90 #define VEP_DEFAULT_ET_MASK  (EPOLLIN|EPOLLOUT)
91 #define VEP_UNSUPPORTED_EVENTS (EPOLLONESHOT|EPOLLEXCLUSIVE)
92   u32 et_mask;
93 } vppcom_epoll_t;
94
95 typedef struct
96 {
97   u8 is_ip4;
98   ip46_address_t ip46;
99 } vppcom_ip46_t;
100
101 typedef struct
102 {
103   volatile session_state_t state;
104
105   svm_fifo_t *server_rx_fifo;
106   svm_fifo_t *server_tx_fifo;
107   u8 *segment_name;
108   u32 sm_seg_index;
109   u32 client_context;
110   u64 vpp_handle;
111   svm_queue_t *vpp_event_queue;
112
113   /* Socket configuration state */
114   /* TBD: covert 'is_*' vars to bit in u8 flags; */
115   u8 is_server;
116   u8 is_listen;
117   u8 is_cut_thru;
118   u8 is_nonblocking;
119   u8 is_vep;
120   u8 is_vep_session;
121   u32 wait_cont_idx;
122   vppcom_epoll_t vep;
123   u32 vrf;
124   vppcom_ip46_t lcl_addr;
125   vppcom_ip46_t peer_addr;
126   u16 lcl_port;                 // network order
127   u16 peer_port;                // network order
128   u8 proto;
129   u64 client_queue_address;
130   u64 options[16];
131   elog_track_t elog_track;
132 } session_t;
133
134 typedef struct vppcom_cfg_t_
135 {
136   u64 heapsize;
137   u32 vpp_api_q_length;
138   u64 segment_baseva;
139   u32 segment_size;
140   u32 add_segment_size;
141   u32 preallocated_fifo_pairs;
142   u32 rx_fifo_size;
143   u32 tx_fifo_size;
144   u32 event_queue_size;
145   u32 listen_queue_size;
146   u8 app_proxy_transport_tcp;
147   u8 app_proxy_transport_udp;
148   u8 app_scope_local;
149   u8 app_scope_global;
150   u8 *namespace_id;
151   u64 namespace_secret;
152   f64 app_timeout;
153   f64 session_timeout;
154   f64 accept_timeout;
155   u32 event_ring_size;
156   char *event_log_path;
157 } vppcom_cfg_t;
158
159 typedef struct vppcom_main_t_
160 {
161   u8 init;
162   u32 debug;
163   u32 *client_session_index_fifo;
164   int main_cpu;
165
166   /* vpe input queue */
167   svm_queue_t *vl_input_queue;
168
169   /* API client handle */
170   u32 my_client_index;
171
172   /* Session pool */
173   clib_spinlock_t sessions_lockp;
174   session_t *sessions;
175
176   /* Hash table for disconnect processing */
177   uword *session_index_by_vpp_handles;
178
179   /* Select bitmaps */
180   clib_bitmap_t *rd_bitmap;
181   clib_bitmap_t *wr_bitmap;
182   clib_bitmap_t *ex_bitmap;
183
184   /* Our event queue */
185   svm_queue_t *app_event_queue;
186
187   /* unique segment name counter */
188   u32 unique_segment_index;
189
190   /* For deadman timers */
191   clib_time_t clib_time;
192
193   /* State of the connection, shared between msg RX thread and main thread */
194   volatile app_state_t app_state;
195
196   vppcom_cfg_t cfg;
197
198   /* Event logging */
199   elog_main_t elog_main;
200   elog_track_t elog_track;
201
202   /* VNET_API_ERROR_FOO -> "Foo" hash table */
203   uword *error_string_by_error_number;
204 } vppcom_main_t;
205
206 /* NOTE: _vppcom_main is only used until the heap is allocated.
207  *       Do not access it directly -- use vcm which will point to
208  *       the heap allocated copy after init.
209  */
210 static vppcom_main_t _vppcom_main = {
211   .debug = VPPCOM_DEBUG_INIT,
212   .my_client_index = ~0
213 };
214
215 static vppcom_main_t *vcm = &_vppcom_main;
216
217 #define VCL_LOCK_AND_GET_SESSION(I, S)                  \
218 do {                                                    \
219   clib_spinlock_lock (&vcm->sessions_lockp);            \
220   rv = vppcom_session_at_index (I, S);                  \
221   if (PREDICT_FALSE (rv))                               \
222     {                                                   \
223       clib_spinlock_unlock (&vcm->sessions_lockp);      \
224       clib_warning ("[%s] ERROR: Invalid ##I (%u)!",    \
225                     getpid (), I);                      \
226       goto done;                                        \
227     }                                                   \
228 } while (0)
229
230 static const char *
231 vppcom_app_state_str (app_state_t state)
232 {
233   char *st;
234
235   switch (state)
236     {
237     case STATE_APP_START:
238       st = "STATE_APP_START";
239       break;
240
241     case STATE_APP_CONN_VPP:
242       st = "STATE_APP_CONN_VPP";
243       break;
244
245     case STATE_APP_ENABLED:
246       st = "STATE_APP_ENABLED";
247       break;
248
249     case STATE_APP_ATTACHED:
250       st = "STATE_APP_ATTACHED";
251       break;
252
253     default:
254       st = "UNKNOWN_APP_STATE";
255       break;
256     }
257
258   return st;
259 }
260
261 static const char *
262 vppcom_session_state_str (session_state_t state)
263 {
264   char *st;
265
266   switch (state)
267     {
268     case STATE_START:
269       st = "STATE_START";
270       break;
271
272     case STATE_CONNECT:
273       st = "STATE_CONNECT";
274       break;
275
276     case STATE_LISTEN:
277       st = "STATE_LISTEN";
278       break;
279
280     case STATE_ACCEPT:
281       st = "STATE_ACCEPT";
282       break;
283
284     case STATE_CLOSE_ON_EMPTY:
285       st = "STATE_CLOSE_ON_EMPTY";
286       break;
287
288     case STATE_DISCONNECT:
289       st = "STATE_DISCONNECT";
290       break;
291
292     case STATE_FAILED:
293       st = "STATE_FAILED";
294       break;
295
296     default:
297       st = "UNKNOWN_STATE";
298       break;
299     }
300
301   return st;
302 }
303
304 /*
305  * VPPCOM Utility Functions
306  */
307 static inline int
308 vppcom_session_at_index (u32 session_index, session_t * volatile *sess)
309 {
310   /* Assumes that caller has acquired spinlock: vcm->sessions_lockp */
311   if (PREDICT_FALSE ((session_index == ~0) ||
312                      pool_is_free_index (vcm->sessions, session_index)))
313     {
314       clib_warning ("[%d] invalid session, sid (%u) has been closed!",
315                     getpid (), session_index);
316       return VPPCOM_EBADFD;
317     }
318   *sess = pool_elt_at_index (vcm->sessions, session_index);
319   return VPPCOM_OK;
320 }
321
322 static inline void
323 vppcom_session_table_add_listener (u64 listener_handle, u32 value)
324 {
325   /* Session and listener handles have different formats. The latter has
326    * the thread index in the upper 32 bits while the former has the session
327    * type. Knowing that, for listeners we just flip the MSB to 1 */
328   listener_handle |= 1ULL << 63;
329   hash_set (vcm->session_index_by_vpp_handles, listener_handle, value);
330 }
331
332 static inline session_t *
333 vppcom_session_table_lookup_listener (u64 listener_handle)
334 {
335   uword *p;
336   u64 handle = listener_handle | (1ULL << 63);
337   session_t *session;
338
339   p = hash_get (vcm->session_index_by_vpp_handles, handle);
340   if (!p)
341     {
342       clib_warning ("[%d] couldn't find listen session: unknown vpp "
343                     "listener handle %llx", getpid (), listener_handle);
344       return 0;
345     }
346   if (pool_is_free_index (vcm->sessions, p[0]))
347     {
348       if (VPPCOM_DEBUG > 1)
349         clib_warning ("[%d] invalid listen session, sid (%u)", getpid (),
350                       p[0]);
351       return 0;
352     }
353
354   session = pool_elt_at_index (vcm->sessions, p[0]);
355   ASSERT (session->is_listen);
356   return session;
357 }
358
359 static inline void
360 vppcom_session_table_del_listener (u64 listener_handle)
361 {
362   listener_handle |= 1ULL << 63;
363   hash_unset (vcm->session_index_by_vpp_handles, listener_handle);
364 }
365
366 static void
367 write_elog (void)
368 {
369   elog_main_t *em = &vcm->elog_main;
370   char *chroot_file;
371   clib_error_t *error = 0;
372
373   chroot_file =
374     (char *) format (0, "%s/%d-%d-vcl-elog%c", vcm->cfg.event_log_path,
375                      vcm->my_client_index, getpid (), 0);
376   error = elog_write_file (em, chroot_file, 1 /* flush ring */ );
377   if (error)
378     {
379       clib_error_report (error);
380     }
381   if (VPPCOM_DEBUG > 0)
382     clib_warning ("[%d] Event Log:'%s' ", getpid (), chroot_file);
383
384 }
385
386 static int
387 vppcom_connect_to_vpp (char *app_name)
388 {
389   api_main_t *am = &api_main;
390   int rv = VPPCOM_OK;
391
392   if (VPPCOM_DEBUG > 0)
393     printf ("\nConnecting to VPP api...");
394   if (vl_client_connect_to_vlib ("/vpe-api", app_name,
395                                  vcm->cfg.vpp_api_q_length) < 0)
396     {
397       clib_warning ("[%d] connect to vpp (%s) failed!", getpid (), app_name);
398       rv = VPPCOM_ECONNREFUSED;
399     }
400   else
401     {
402
403       vcm->vl_input_queue = am->shmem_hdr->vl_input_queue;
404       vcm->my_client_index = am->my_client_index;
405       vcm->app_state = STATE_APP_CONN_VPP;
406
407       if (VPPCOM_DEBUG > 0)
408         printf (" connected!\n");
409     }
410
411   if (VPPCOM_DEBUG > 0)
412     {
413       vcm->elog_main.lock =
414         clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES, CLIB_CACHE_LINE_BYTES);
415       vcm->elog_main.lock[0] = 0;
416       vcm->elog_main.event_ring_size = vcm->cfg.event_ring_size;
417       elog_init (&vcm->elog_main, vcm->elog_main.event_ring_size);
418       elog_enable_disable (&vcm->elog_main, 1);
419
420       vcm->elog_track.name =
421         (char *) format (0, "P:%d:C:%d%c", getpid (),
422                          vcm->my_client_index, 0);
423       elog_track_register (&vcm->elog_main, &vcm->elog_track);
424
425       ELOG_TYPE_DECLARE (e) =
426       {
427       .format = "connect_vpp:rv:%d",.format_args = "i4",};
428       struct
429       {
430         u32 data;
431       } *ed;
432       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, vcm->elog_track);
433       ed->data = rv;
434     }
435
436   return rv;
437 }
438
439 static u8 *
440 format_api_error (u8 * s, va_list * args)
441 {
442   i32 error = va_arg (*args, u32);
443   uword *p;
444
445   p = hash_get (vcm->error_string_by_error_number, -error);
446
447   if (p)
448     s = format (s, "%s (%d)", p[0], error);
449   else
450     s = format (s, "%d", error);
451   return s;
452 }
453
454 static void
455 vppcom_init_error_string_table (void)
456 {
457   vcm->error_string_by_error_number = hash_create (0, sizeof (uword));
458
459 #define _(n,v,s) hash_set (vcm->error_string_by_error_number, -v, s);
460   foreach_vnet_api_error;
461 #undef _
462
463   hash_set (vcm->error_string_by_error_number, 99, "Misc");
464 }
465
466 static inline int
467 vppcom_wait_for_app_state_change (app_state_t app_state)
468 {
469   f64 timeout = clib_time_now (&vcm->clib_time) + vcm->cfg.app_timeout;
470
471   while (clib_time_now (&vcm->clib_time) < timeout)
472     {
473       if (vcm->app_state == app_state)
474         return VPPCOM_OK;
475     }
476   if (VPPCOM_DEBUG > 0)
477     clib_warning ("[%d] timeout waiting for state %s (%d)", getpid (),
478                   vppcom_app_state_str (app_state), app_state);
479   return VPPCOM_ETIMEDOUT;
480 }
481
482 static inline int
483 vppcom_wait_for_session_state_change (u32 session_index,
484                                       session_state_t state,
485                                       f64 wait_for_time)
486 {
487   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
488   session_t *volatile session;
489   int rv;
490
491   do
492     {
493       clib_spinlock_lock (&vcm->sessions_lockp);
494       rv = vppcom_session_at_index (session_index, &session);
495       if (PREDICT_FALSE (rv))
496         {
497           clib_spinlock_unlock (&vcm->sessions_lockp);
498           return rv;
499         }
500       if (session->state == state)
501         {
502           clib_spinlock_unlock (&vcm->sessions_lockp);
503           return VPPCOM_OK;
504         }
505       if (session->state == STATE_FAILED)
506         {
507           clib_spinlock_unlock (&vcm->sessions_lockp);
508           return VPPCOM_ECONNREFUSED;
509         }
510
511       clib_spinlock_unlock (&vcm->sessions_lockp);
512     }
513   while (clib_time_now (&vcm->clib_time) < timeout);
514
515   if (VPPCOM_DEBUG > 0)
516     clib_warning ("[%d] timeout waiting for state 0x%x (%s)", getpid (),
517                   state, vppcom_session_state_str (state));
518   return VPPCOM_ETIMEDOUT;
519 }
520
521 static inline int
522 vppcom_wait_for_client_session_index (f64 wait_for_time)
523 {
524   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
525
526   do
527     {
528       if (clib_fifo_elts (vcm->client_session_index_fifo))
529         return VPPCOM_OK;
530     }
531   while (clib_time_now (&vcm->clib_time) < timeout);
532
533   if (wait_for_time == 0)
534     return VPPCOM_EAGAIN;
535
536   if (VPPCOM_DEBUG > 0)
537     clib_warning ("[%d] timeout waiting for client_session_index", getpid ());
538   return VPPCOM_ETIMEDOUT;
539 }
540
541 /*
542  * VPP-API message functions
543  */
544 static void
545 vppcom_send_session_enable_disable (u8 is_enable)
546 {
547   vl_api_session_enable_disable_t *bmp;
548   bmp = vl_msg_api_alloc (sizeof (*bmp));
549   memset (bmp, 0, sizeof (*bmp));
550
551   bmp->_vl_msg_id = ntohs (VL_API_SESSION_ENABLE_DISABLE);
552   bmp->client_index = vcm->my_client_index;
553   bmp->context = htonl (0xfeedface);
554   bmp->is_enable = is_enable;
555   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
556 }
557
558 static int
559 vppcom_app_session_enable (void)
560 {
561   int rv;
562
563   if (vcm->app_state != STATE_APP_ENABLED)
564     {
565       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
566       rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
567       if (PREDICT_FALSE (rv))
568         {
569           if (VPPCOM_DEBUG > 0)
570             clib_warning ("[%d] application session enable timed out! "
571                           "returning %d (%s)",
572                           getpid (), rv, vppcom_retval_str (rv));
573           return rv;
574         }
575     }
576   return VPPCOM_OK;
577 }
578
579 static void
580   vl_api_session_enable_disable_reply_t_handler
581   (vl_api_session_enable_disable_reply_t * mp)
582 {
583   if (mp->retval)
584     {
585       clib_warning ("[%d] session_enable_disable failed: %U", getpid (),
586                     format_api_error, ntohl (mp->retval));
587     }
588   else
589     vcm->app_state = STATE_APP_ENABLED;
590 }
591
592 static void
593 vppcom_app_send_attach (void)
594 {
595   vl_api_application_attach_t *bmp;
596   u8 nsid_len = vec_len (vcm->cfg.namespace_id);
597   u8 app_is_proxy = (vcm->cfg.app_proxy_transport_tcp ||
598                      vcm->cfg.app_proxy_transport_udp);
599
600   bmp = vl_msg_api_alloc (sizeof (*bmp));
601   memset (bmp, 0, sizeof (*bmp));
602
603   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
604   bmp->client_index = vcm->my_client_index;
605   bmp->context = htonl (0xfeedface);
606   bmp->options[APP_OPTIONS_FLAGS] =
607     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT |
608     (vcm->cfg.app_scope_local ? APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE : 0) |
609     (vcm->cfg.app_scope_global ? APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE : 0) |
610     (app_is_proxy ? APP_OPTIONS_FLAGS_IS_PROXY : 0);
611   bmp->options[APP_OPTIONS_PROXY_TRANSPORT] =
612     (vcm->cfg.app_proxy_transport_tcp ? 1 << TRANSPORT_PROTO_TCP : 0) |
613     (vcm->cfg.app_proxy_transport_udp ? 1 << TRANSPORT_PROTO_UDP : 0);
614   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = vcm->cfg.segment_size;
615   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = vcm->cfg.add_segment_size;
616   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = vcm->cfg.rx_fifo_size;
617   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = vcm->cfg.tx_fifo_size;
618   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] =
619     vcm->cfg.preallocated_fifo_pairs;
620   bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = vcm->cfg.event_queue_size;
621   if (nsid_len)
622     {
623       bmp->namespace_id_len = nsid_len;
624       clib_memcpy (bmp->namespace_id, vcm->cfg.namespace_id, nsid_len);
625       bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = vcm->cfg.namespace_secret;
626     }
627   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
628 }
629
630 static int
631 vppcom_app_attach (void)
632 {
633   int rv;
634
635   vppcom_app_send_attach ();
636   rv = vppcom_wait_for_app_state_change (STATE_APP_ATTACHED);
637   if (PREDICT_FALSE (rv))
638     {
639       if (VPPCOM_DEBUG > 0)
640         clib_warning ("[%d] application attach timed out! returning %d (%s)",
641                       getpid (), rv, vppcom_retval_str (rv));
642       return rv;
643     }
644   return VPPCOM_OK;
645 }
646
647 static void
648 vppcom_app_detach (void)
649 {
650   vl_api_application_detach_t *bmp;
651   bmp = vl_msg_api_alloc (sizeof (*bmp));
652   memset (bmp, 0, sizeof (*bmp));
653
654   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
655   bmp->client_index = vcm->my_client_index;
656   bmp->context = htonl (0xfeedface);
657   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
658 }
659
660 static void
661 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
662                                            mp)
663 {
664   static svm_fifo_segment_create_args_t _a;
665   svm_fifo_segment_create_args_t *a = &_a;
666   int rv;
667
668   memset (a, 0, sizeof (*a));
669   if (mp->retval)
670     {
671       clib_warning ("[%d] attach failed: %U", getpid (),
672                     format_api_error, ntohl (mp->retval));
673       return;
674     }
675
676   if (mp->segment_name_length == 0)
677     {
678       clib_warning ("[%d] segment_name_length zero", getpid ());
679       return;
680     }
681
682   a->segment_name = (char *) mp->segment_name;
683   a->segment_size = mp->segment_size;
684
685   ASSERT (mp->app_event_queue_address);
686
687   /* Attach to the segment vpp created */
688   rv = svm_fifo_segment_attach (a);
689   vec_reset_length (a->new_segment_indices);
690   if (PREDICT_FALSE (rv))
691     {
692       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed", getpid (),
693                     mp->segment_name);
694       return;
695     }
696
697   vcm->app_event_queue =
698     uword_to_pointer (mp->app_event_queue_address, svm_queue_t *);
699
700   vcm->app_state = STATE_APP_ATTACHED;
701 }
702
703 static void
704 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
705                                            mp)
706 {
707   if (mp->retval)
708     clib_warning ("[%d] detach failed: %U", getpid (), format_api_error,
709                   ntohl (mp->retval));
710
711   vcm->app_state = STATE_APP_ENABLED;
712 }
713
714 static void
715 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
716                                            mp)
717 {
718   if (mp->retval)
719     clib_warning ("[%d] vpp handle 0x%llx: disconnect session failed: %U",
720                   getpid (), mp->handle, format_api_error,
721                   ntohl (mp->retval));
722 }
723
724 static void
725 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
726 {
727   static svm_fifo_segment_create_args_t _a;
728   svm_fifo_segment_create_args_t *a = &_a;
729   int rv;
730
731   memset (a, 0, sizeof (*a));
732   a->segment_name = (char *) mp->segment_name;
733   a->segment_size = mp->segment_size;
734   /* Attach to the segment vpp created */
735   rv = svm_fifo_segment_attach (a);
736   vec_reset_length (a->new_segment_indices);
737   if (PREDICT_FALSE (rv))
738     {
739       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed",
740                     getpid (), mp->segment_name);
741       return;
742     }
743   if (VPPCOM_DEBUG > 1)
744     clib_warning ("[%d] mapped new segment '%s' size %d", getpid (),
745                   mp->segment_name, mp->segment_size);
746 }
747
748 static void
749 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
750 {
751   uword *p;
752
753   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
754   if (p)
755     {
756       int rv;
757       session_t *session = 0;
758       u32 session_index = p[0];
759
760       VCL_LOCK_AND_GET_SESSION (session_index, &session);
761       session->state = STATE_CLOSE_ON_EMPTY;
762
763       if (VPPCOM_DEBUG > 1)
764         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
765                       "setting state to 0x%x (%s)",
766                       getpid (), mp->handle, session_index, session->state,
767                       vppcom_session_state_str (session->state));
768       clib_spinlock_unlock (&vcm->sessions_lockp);
769       return;
770
771     done:
772       if (VPPCOM_DEBUG > 1)
773         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
774                       "session lookup failed!",
775                       getpid (), mp->handle, session_index);
776     }
777   else
778     clib_warning ("[%d] vpp handle 0x%llx: session lookup by "
779                   "handle failed!", getpid (), mp->handle);
780 }
781
782 static void
783 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
784 {
785   session_t *session = 0;
786   vl_api_reset_session_reply_t *rmp;
787   uword *p;
788   int rv = 0;
789
790   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
791   if (p)
792     {
793       int rval;
794       clib_spinlock_lock (&vcm->sessions_lockp);
795       rval = vppcom_session_at_index (p[0], &session);
796       if (PREDICT_FALSE (rval))
797         {
798           rv = VNET_API_ERROR_INVALID_VALUE_2;
799           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
800                         "session lookup failed! returning %d %U",
801                         getpid (), mp->handle, p[0],
802                         rv, format_api_error, rv);
803         }
804       else
805         {
806           /* TBD: should this disconnect immediately and
807            * flush the fifos?
808            */
809           session->state = STATE_CLOSE_ON_EMPTY;
810
811           if (VPPCOM_DEBUG > 1)
812             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
813                           "state set to %d (%s)!", getpid (),
814                           mp->handle, p[0], session->state,
815                           vppcom_session_state_str (session->state));
816         }
817       clib_spinlock_unlock (&vcm->sessions_lockp);
818     }
819   else
820     {
821       rv = VNET_API_ERROR_INVALID_VALUE;
822       clib_warning ("[%d] ERROR: vpp handle 0x%llx: session lookup "
823                     "failed! returning %d %U",
824                     getpid (), mp->handle, rv, format_api_error, rv);
825     }
826
827   rmp = vl_msg_api_alloc (sizeof (*rmp));
828   memset (rmp, 0, sizeof (*rmp));
829   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
830   rmp->retval = htonl (rv);
831   rmp->handle = mp->handle;
832   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
833 }
834
835 static void
836 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
837 {
838   session_t *session = 0;
839   u32 session_index;
840   svm_fifo_t *rx_fifo, *tx_fifo;
841   u8 is_cut_thru = 0;
842   int rv;
843
844   session_index = mp->context;
845   VCL_LOCK_AND_GET_SESSION (session_index, &session);
846 done:
847   if (mp->retval)
848     {
849       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
850                     "connect failed! %U",
851                     getpid (), mp->handle, session_index,
852                     format_api_error, ntohl (mp->retval));
853       if (rv == VPPCOM_OK)
854         {
855           session->state = STATE_FAILED;
856           session->vpp_handle = mp->handle;
857         }
858       else
859         {
860           clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
861                         "Invalid session index (%u)!",
862                         getpid (), mp->handle, session_index);
863         }
864       goto done_unlock;
865     }
866
867   if (rv)
868     goto done_unlock;
869
870   /* We've been redirected */
871   if (mp->segment_name_length > 0)
872     {
873       static svm_fifo_segment_create_args_t _a;
874       svm_fifo_segment_create_args_t *a = &_a;
875
876       is_cut_thru = 1;
877       memset (a, 0, sizeof (*a));
878       a->segment_name = (char *) mp->segment_name;
879       if (VPPCOM_DEBUG > 1)
880         clib_warning ("[%d] cut-thru segment: %s\n",
881                       getpid (), a->segment_name);
882
883       rv = svm_fifo_segment_attach (a);
884       vec_reset_length (a->new_segment_indices);
885       if (PREDICT_FALSE (rv))
886         {
887           clib_warning ("[%d] sm_fifo_segment_attach ('%s') failed",
888                         getpid (), a->segment_name);
889           goto done_unlock;
890         }
891     }
892
893   /*
894    * Setup session
895    */
896   session->is_cut_thru = is_cut_thru;
897   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
898                                                svm_queue_t *);
899
900   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
901   rx_fifo->client_session_index = session_index;
902   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
903   tx_fifo->client_session_index = session_index;
904
905   session->server_rx_fifo = rx_fifo;
906   session->server_tx_fifo = tx_fifo;
907   session->vpp_handle = mp->handle;
908   session->lcl_addr.is_ip4 = mp->is_ip4;
909   clib_memcpy (&session->lcl_addr.ip46, mp->lcl_ip,
910                sizeof (session->peer_addr.ip46));
911   session->lcl_port = mp->lcl_port;
912   session->state = STATE_CONNECT;
913
914   /* Add it to lookup table */
915   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
916
917   if (VPPCOM_DEBUG > 1)
918     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connect succeeded!"
919                   " session_rx_fifo %p, refcnt %d,"
920                   " session_tx_fifo %p, refcnt %d",
921                   getpid (), mp->handle, session_index,
922                   session->server_rx_fifo,
923                   session->server_rx_fifo->refcnt,
924                   session->server_tx_fifo, session->server_tx_fifo->refcnt);
925 done_unlock:
926   clib_spinlock_unlock (&vcm->sessions_lockp);
927 }
928
929 static void
930 vppcom_send_connect_sock (session_t * session, u32 session_index)
931 {
932   vl_api_connect_sock_t *cmp;
933
934   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
935   session->is_server = 0;
936   cmp = vl_msg_api_alloc (sizeof (*cmp));
937   memset (cmp, 0, sizeof (*cmp));
938   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK);
939   cmp->client_index = vcm->my_client_index;
940   cmp->context = session_index;
941
942   cmp->vrf = session->vrf;
943   cmp->is_ip4 = session->peer_addr.is_ip4;
944   clib_memcpy (cmp->ip, &session->peer_addr.ip46, sizeof (cmp->ip));
945   cmp->port = session->peer_port;
946   cmp->proto = session->proto;
947   clib_memcpy (cmp->options, session->options, sizeof (cmp->options));
948   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & cmp);
949 }
950
951 static inline void
952 vppcom_send_disconnect_session_reply (u64 vpp_handle, u32 session_index,
953                                       int rv)
954 {
955   vl_api_disconnect_session_reply_t *rmp;
956
957   if (VPPCOM_DEBUG > 1)
958     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending disconnect msg",
959                   getpid (), vpp_handle, session_index);
960
961   rmp = vl_msg_api_alloc (sizeof (*rmp));
962   memset (rmp, 0, sizeof (*rmp));
963
964   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
965   rmp->retval = htonl (rv);
966   rmp->handle = vpp_handle;
967   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
968 }
969
970 static inline void
971 vppcom_send_disconnect_session (u64 vpp_handle, u32 session_index)
972 {
973   vl_api_disconnect_session_t *dmp;
974
975   if (VPPCOM_DEBUG > 1)
976     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending disconnect msg",
977                   getpid (), vpp_handle, session_index);
978
979   dmp = vl_msg_api_alloc (sizeof (*dmp));
980   memset (dmp, 0, sizeof (*dmp));
981   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
982   dmp->client_index = vcm->my_client_index;
983   dmp->handle = vpp_handle;
984   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & dmp);
985 }
986
987 static void
988 vl_api_bind_sock_reply_t_handler (vl_api_bind_sock_reply_t * mp)
989 {
990   session_t *session = 0;
991   u32 session_index = mp->context;
992   int rv;
993
994   VCL_LOCK_AND_GET_SESSION (session_index, &session);
995 done:
996   if (mp->retval)
997     {
998       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: bind failed: %U",
999                     getpid (), mp->handle, session_index, format_api_error,
1000                     ntohl (mp->retval));
1001       rv = vppcom_session_at_index (session_index, &session);
1002       if (rv == VPPCOM_OK)
1003         {
1004           session->state = STATE_FAILED;
1005           session->vpp_handle = mp->handle;
1006         }
1007       else
1008         {
1009           clib_warning ("[%s] ERROR: vpp handle 0x%llx, sid %u: "
1010                         "Invalid session index (%u)!",
1011                         getpid (), mp->handle, session_index);
1012         }
1013       goto done_unlock;
1014     }
1015
1016   session->vpp_handle = mp->handle;
1017   session->lcl_addr.is_ip4 = mp->lcl_is_ip4;
1018   clib_memcpy (&session->lcl_addr.ip46, mp->lcl_ip,
1019                sizeof (session->peer_addr.ip46));
1020   session->lcl_port = mp->lcl_port;
1021   vppcom_session_table_add_listener (mp->handle, session_index);
1022   session->is_listen = 1;
1023   session->state = STATE_LISTEN;
1024
1025   if (VPPCOM_DEBUG > 1)
1026     clib_warning ("[%d] vpp handle 0x%llx, sid %u: bind succeeded!",
1027                   getpid (), mp->handle, mp->context);
1028 done_unlock:
1029   clib_spinlock_unlock (&vcm->sessions_lockp);
1030 }
1031
1032 static void
1033 vl_api_unbind_sock_reply_t_handler (vl_api_unbind_sock_reply_t * mp)
1034 {
1035   if (mp->retval)
1036     clib_warning ("[%d] ERROR: sid %u: unbind failed: %U",
1037                   getpid (), mp->context, format_api_error,
1038                   ntohl (mp->retval));
1039
1040   else if (VPPCOM_DEBUG > 1)
1041     clib_warning ("[%d] sid %u: unbind succeeded!", getpid (), mp->context);
1042 }
1043
1044 u8 *
1045 format_ip4_address (u8 * s, va_list * args)
1046 {
1047   u8 *a = va_arg (*args, u8 *);
1048   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
1049 }
1050
1051 u8 *
1052 format_ip6_address (u8 * s, va_list * args)
1053 {
1054   ip6_address_t *a = va_arg (*args, ip6_address_t *);
1055   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
1056
1057   i_max_n_zero = ARRAY_LEN (a->as_u16);
1058   max_n_zeros = 0;
1059   i_first_zero = i_max_n_zero;
1060   n_zeros = 0;
1061   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1062     {
1063       u32 is_zero = a->as_u16[i] == 0;
1064       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
1065         {
1066           i_first_zero = i;
1067           n_zeros = 0;
1068         }
1069       n_zeros += is_zero;
1070       if ((!is_zero && n_zeros > max_n_zeros)
1071           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
1072         {
1073           i_max_n_zero = i_first_zero;
1074           max_n_zeros = n_zeros;
1075           i_first_zero = ARRAY_LEN (a->as_u16);
1076           n_zeros = 0;
1077         }
1078     }
1079
1080   last_double_colon = 0;
1081   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1082     {
1083       if (i == i_max_n_zero && max_n_zeros > 1)
1084         {
1085           s = format (s, "::");
1086           i += max_n_zeros - 1;
1087           last_double_colon = 1;
1088         }
1089       else
1090         {
1091           s = format (s, "%s%x",
1092                       (last_double_colon || i == 0) ? "" : ":",
1093                       clib_net_to_host_u16 (a->as_u16[i]));
1094           last_double_colon = 0;
1095         }
1096     }
1097
1098   return s;
1099 }
1100
1101 /* Format an IP46 address. */
1102 u8 *
1103 format_ip46_address (u8 * s, va_list * args)
1104 {
1105   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
1106   ip46_type_t type = va_arg (*args, ip46_type_t);
1107   int is_ip4 = 1;
1108
1109   switch (type)
1110     {
1111     case IP46_TYPE_ANY:
1112       is_ip4 = ip46_address_is_ip4 (ip46);
1113       break;
1114     case IP46_TYPE_IP4:
1115       is_ip4 = 1;
1116       break;
1117     case IP46_TYPE_IP6:
1118       is_ip4 = 0;
1119       break;
1120     }
1121
1122   return is_ip4 ?
1123     format (s, "%U", format_ip4_address, &ip46->ip4) :
1124     format (s, "%U", format_ip6_address, &ip46->ip6);
1125 }
1126
1127 static inline void
1128 vppcom_send_accept_session_reply (u64 handle, u32 context, int retval)
1129 {
1130   vl_api_accept_session_reply_t *rmp;
1131
1132   rmp = vl_msg_api_alloc (sizeof (*rmp));
1133   memset (rmp, 0, sizeof (*rmp));
1134   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
1135   rmp->retval = htonl (retval);
1136   rmp->context = context;
1137   rmp->handle = handle;
1138   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1139 }
1140
1141 static void
1142 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
1143 {
1144   svm_fifo_t *rx_fifo, *tx_fifo;
1145   session_t *session, *listen_session;
1146   u32 session_index;
1147
1148   clib_spinlock_lock (&vcm->sessions_lockp);
1149   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1150     {
1151       clib_warning ("[%d] client session queue is full!", getpid ());
1152       vppcom_send_accept_session_reply (mp->handle, mp->context,
1153                                         VNET_API_ERROR_QUEUE_FULL);
1154       clib_spinlock_unlock (&vcm->sessions_lockp);
1155       return;
1156     }
1157
1158   listen_session = vppcom_session_table_lookup_listener (mp->listener_handle);
1159   if (!listen_session)
1160     {
1161       clib_warning ("[%d] ERROR: couldn't find listen session: unknown vpp "
1162                     "listener handle %llx", getpid (), mp->listener_handle);
1163       clib_spinlock_unlock (&vcm->sessions_lockp);
1164       return;
1165     }
1166
1167   /* Allocate local session and set it up */
1168   pool_get (vcm->sessions, session);
1169   memset (session, 0, sizeof (*session));
1170   session_index = session - vcm->sessions;
1171
1172   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
1173   rx_fifo->client_session_index = session_index;
1174   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
1175   tx_fifo->client_session_index = session_index;
1176
1177   session->vpp_handle = mp->handle;
1178   session->client_context = mp->context;
1179   session->server_rx_fifo = rx_fifo;
1180   session->server_tx_fifo = tx_fifo;
1181   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
1182                                                svm_queue_t *);
1183   session->state = STATE_ACCEPT;
1184   session->is_cut_thru = 0;
1185   session->is_server = 1;
1186   session->peer_port = mp->port;
1187   session->peer_addr.is_ip4 = mp->is_ip4;
1188   clib_memcpy (&session->peer_addr.ip46, mp->ip,
1189                sizeof (session->peer_addr.ip46));
1190
1191   /* Add it to lookup table */
1192   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
1193   session->lcl_port = listen_session->lcl_port;
1194   session->lcl_addr = listen_session->lcl_addr;
1195
1196   /* TBD: move client_session_index_fifo into listener session */
1197   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1198
1199   clib_spinlock_unlock (&vcm->sessions_lockp);
1200
1201   if (VPPCOM_DEBUG > 1)
1202     clib_warning ("[%d] vpp handle 0x%llx, sid %u: client accept "
1203                   "request from %s address %U port %d queue %p!", getpid (),
1204                   mp->handle, session_index, mp->is_ip4 ? "IPv4" : "IPv6",
1205                   format_ip46_address, &mp->ip, mp->is_ip4,
1206                   clib_net_to_host_u16 (mp->port), session->vpp_event_queue);
1207
1208   if (VPPCOM_DEBUG > 0)
1209     {
1210       session->elog_track.name =
1211         (char *) format (0, "C:%d:S:%d%c", vcm->my_client_index,
1212                          session_index, 0);
1213       elog_track_register (&vcm->elog_main, &session->elog_track);
1214
1215       if (session->peer_addr.is_ip4)
1216         {
1217           ELOG_TYPE_DECLARE (e) =
1218           {
1219           .format =
1220               "client_accept:handle:%x addr:%d.%d.%d.%d:%d",.format_args =
1221               "i8i1i1i1i1i2",};
1222
1223           CLIB_PACKED (struct
1224                        {
1225                        u64 handle;      //8
1226                        u8 addr[4];      //4
1227                        u16 port;        //2
1228                        }) * ed;
1229
1230           ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
1231
1232           ed->handle = mp->handle;
1233           ed->addr[0] = session->peer_addr.ip46.ip4.as_u8[0];
1234           ed->addr[1] = session->peer_addr.ip46.ip4.as_u8[1];
1235           ed->addr[2] = session->peer_addr.ip46.ip4.as_u8[2];
1236           ed->addr[3] = session->peer_addr.ip46.ip4.as_u8[3];
1237           ed->port = session->peer_port;
1238         }
1239       else
1240         {
1241           clib_warning ("ip6");
1242         }
1243     }
1244
1245 }
1246
1247 static void
1248 vppcom_send_connect_session_reply (session_t * session, u32 session_index,
1249                                    u64 vpp_handle, u32 context, int retval)
1250 {
1251   vl_api_connect_session_reply_t *rmp;
1252   u32 len;
1253   svm_queue_t *client_q;
1254
1255   rmp = vl_msg_api_alloc (sizeof (*rmp));
1256   memset (rmp, 0, sizeof (*rmp));
1257   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SESSION_REPLY);
1258
1259   if (!session)
1260     {
1261       rmp->context = context;
1262       rmp->handle = vpp_handle;
1263       rmp->retval = htonl (retval);
1264       vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1265       return;
1266     }
1267
1268   rmp->context = session->client_context;
1269   rmp->retval = htonl (retval);
1270   rmp->handle = session->vpp_handle;
1271   rmp->server_rx_fifo = pointer_to_uword (session->server_rx_fifo);
1272   rmp->server_tx_fifo = pointer_to_uword (session->server_tx_fifo);
1273   rmp->vpp_event_queue_address = pointer_to_uword (session->vpp_event_queue);
1274   rmp->segment_size = vcm->cfg.segment_size;
1275   len = vec_len (session->segment_name);
1276   rmp->segment_name_length = clib_min (len, sizeof (rmp->segment_name));
1277   clib_memcpy (rmp->segment_name, session->segment_name,
1278                rmp->segment_name_length - 1);
1279   clib_memcpy (rmp->lcl_ip, session->peer_addr.ip46.as_u8,
1280                sizeof (rmp->lcl_ip));
1281   rmp->is_ip4 = session->peer_addr.is_ip4;
1282   rmp->lcl_port = session->peer_port;
1283   client_q = uword_to_pointer (session->client_queue_address, svm_queue_t *);
1284   ASSERT (client_q);
1285   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
1286 }
1287
1288 /*
1289  * Acting as server for redirected connect requests
1290  */
1291 static void
1292 vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
1293 {
1294   u32 session_index;
1295   session_t *session = 0;
1296
1297   clib_spinlock_lock (&vcm->sessions_lockp);
1298   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1299     {
1300       clib_spinlock_unlock (&vcm->sessions_lockp);
1301
1302       if (VPPCOM_DEBUG > 1)
1303         clib_warning ("[%d] client session queue is full!", getpid ());
1304
1305       /* TBD: Fix api to include vpp handle */
1306       vppcom_send_connect_session_reply (0 /* session */ , 0 /* sid */ ,
1307                                          0 /* handle */ , mp->context,
1308                                          VNET_API_ERROR_QUEUE_FULL);
1309       return;
1310     }
1311
1312   pool_get (vcm->sessions, session);
1313   memset (session, 0, sizeof (*session));
1314   session_index = session - vcm->sessions;
1315
1316   session->client_context = mp->context;
1317   session->vpp_handle = session_index;
1318   session->client_queue_address = mp->client_queue_address;
1319   session->is_cut_thru = 1;
1320   session->is_server = 1;
1321   session->lcl_port = mp->port;
1322   session->lcl_addr.is_ip4 = mp->is_ip4;
1323   clib_memcpy (&session->lcl_addr.ip46, mp->ip,
1324                sizeof (session->lcl_addr.ip46));
1325
1326   /* TBD: missing peer info in api msg.
1327    */
1328   session->peer_addr.is_ip4 = mp->is_ip4;
1329   ASSERT (session->lcl_addr.is_ip4 == session->peer_addr.is_ip4);
1330
1331   session->state = STATE_ACCEPT;
1332   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1333   if (VPPCOM_DEBUG > 1)
1334     clib_warning ("[%d] sid %u: Got a cut-thru connect request! "
1335                   "clib_fifo_elts %u!\n", getpid (), session_index,
1336                   clib_fifo_elts (vcm->client_session_index_fifo));
1337
1338   if (VPPCOM_DEBUG > 0)
1339     {
1340       session->elog_track.name =
1341         (char *) format (0, "C:%d:S:%d%c", vcm->my_client_index,
1342                          session_index, 0);
1343       elog_track_register (&vcm->elog_main, &session->elog_track);
1344
1345       ELOG_TYPE_DECLARE (e) =
1346       {
1347       .format = "cut-thru-connect:S:%d clib_fifo_elts:%d",.format_args =
1348           "i4i4",};
1349
1350       struct
1351       {
1352         u32 data[2];
1353       } *ed;
1354
1355       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
1356
1357       ed->data[0] = session_index;
1358       ed->data[1] = clib_fifo_elts (vcm->client_session_index_fifo);
1359     }
1360
1361   clib_spinlock_unlock (&vcm->sessions_lockp);
1362 }
1363
1364 static void
1365 vppcom_send_bind_sock (session_t * session, u32 session_index)
1366 {
1367   vl_api_bind_sock_t *bmp;
1368
1369   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1370   session->is_server = 1;
1371   bmp = vl_msg_api_alloc (sizeof (*bmp));
1372   memset (bmp, 0, sizeof (*bmp));
1373
1374   bmp->_vl_msg_id = ntohs (VL_API_BIND_SOCK);
1375   bmp->client_index = vcm->my_client_index;
1376   bmp->context = session_index;
1377   bmp->vrf = session->vrf;
1378   bmp->is_ip4 = session->lcl_addr.is_ip4;
1379   clib_memcpy (bmp->ip, &session->lcl_addr.ip46, sizeof (bmp->ip));
1380   bmp->port = session->lcl_port;
1381   bmp->proto = session->proto;
1382   clib_memcpy (bmp->options, session->options, sizeof (bmp->options));
1383   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
1384 }
1385
1386 static void
1387 vppcom_send_unbind_sock (u64 vpp_handle)
1388 {
1389   vl_api_unbind_sock_t *ump;
1390
1391   ump = vl_msg_api_alloc (sizeof (*ump));
1392   memset (ump, 0, sizeof (*ump));
1393
1394   ump->_vl_msg_id = ntohs (VL_API_UNBIND_SOCK);
1395   ump->client_index = vcm->my_client_index;
1396   ump->handle = vpp_handle;
1397   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & ump);
1398 }
1399
1400 static int
1401 vppcom_session_unbind (u32 session_index)
1402 {
1403   session_t *session = 0;
1404   int rv;
1405   u64 vpp_handle;
1406
1407   VCL_LOCK_AND_GET_SESSION (session_index, &session);
1408
1409   vpp_handle = session->vpp_handle;
1410   vppcom_session_table_del_listener (vpp_handle);
1411   session->vpp_handle = ~0;
1412   session->state = STATE_DISCONNECT;
1413
1414   clib_spinlock_unlock (&vcm->sessions_lockp);
1415
1416   if (VPPCOM_DEBUG > 1)
1417     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1418                   "sending unbind msg! new state 0x%x (%s)",
1419                   getpid (), vpp_handle, session_index,
1420                   session->state, vppcom_session_state_str (session->state));
1421
1422   if (VPPCOM_DEBUG > 0)
1423     {
1424       ELOG_TYPE_DECLARE (e) =
1425       {
1426       .format = "unbind: handle:%x",.format_args = "i8",};
1427       struct
1428       {
1429         u64 handle;
1430       } *ed;
1431       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
1432       ed->handle = vpp_handle;
1433     }
1434   vppcom_send_unbind_sock (vpp_handle);
1435
1436 done:
1437   return rv;
1438 }
1439
1440 static inline int
1441 vppcom_session_disconnect (u32 session_index)
1442 {
1443   int rv;
1444   session_t *session;
1445   u8 is_cut_thru, is_listen, is_server;
1446   u64 vpp_handle;
1447   session_state_t state;
1448
1449   VCL_LOCK_AND_GET_SESSION (session_index, &session);
1450
1451   vpp_handle = session->vpp_handle;
1452   is_server = session->is_server;
1453   is_listen = session->is_listen;
1454   is_cut_thru = session->is_cut_thru;
1455   state = session->state;
1456   clib_spinlock_unlock (&vcm->sessions_lockp);
1457
1458   if (VPPCOM_DEBUG > 1)
1459     {
1460       clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s state 0x%x (%s), "
1461                     "is_cut_thru %d, is_listen %d",
1462                     getpid (), vpp_handle, session_index,
1463                     is_server ? "server" : "client",
1464                     state, vppcom_session_state_str (state),
1465                     is_cut_thru, is_listen);
1466     }
1467
1468   if (PREDICT_FALSE (is_listen))
1469     {
1470       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
1471                     "Cannot disconnect a listen socket!",
1472                     getpid (), vpp_handle, session_index);
1473       rv = VPPCOM_EBADFD;
1474       goto done;
1475     }
1476
1477   /* Through the VPP host stack...
1478    */
1479   else if (!is_cut_thru)
1480     {
1481       /* The peer has already initiated the close,
1482        * so send the disconnect session reply.
1483        */
1484       if (state & STATE_CLOSE_ON_EMPTY)
1485         {
1486           vppcom_send_disconnect_session_reply (vpp_handle,
1487                                                 session_index, 0 /* rv */ );
1488           if (VPPCOM_DEBUG > 1)
1489             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1490                           "sending disconnect REPLY...",
1491                           getpid (), vpp_handle, session_index);
1492         }
1493
1494       /* Otherwise, send a disconnect session msg...
1495        */
1496       else
1497         {
1498           if (VPPCOM_DEBUG > 1)
1499             clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
1500                           "sending disconnect...",
1501                           getpid (), vpp_handle, session_index);
1502
1503           vppcom_send_disconnect_session (vpp_handle, session_index);
1504         }
1505     }
1506
1507   /* Cut-thru connections...
1508    *
1509    *   server: free fifos and segment allocated during connect/redirect
1510    *   client: no cleanup required
1511    */
1512   else
1513     {
1514       if (is_server)
1515         {
1516           svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
1517           svm_fifo_segment_private_t *seg;
1518
1519           VCL_LOCK_AND_GET_SESSION (session_index, &session);
1520
1521           if (VPPCOM_DEBUG > 1)
1522             clib_warning ("[%d] sid %d: freeing cut-thru fifos in "
1523                           "sm_seg_index %d! "
1524                           " server_rx_fifo %p, refcnt = %d"
1525                           " server_tx_fifo %p, refcnt = %d",
1526                           getpid (), session_index, session->sm_seg_index,
1527                           session->server_rx_fifo,
1528                           session->server_rx_fifo->refcnt,
1529                           session->server_tx_fifo,
1530                           session->server_tx_fifo->refcnt);
1531
1532           seg = vec_elt_at_index (sm->segments, session->sm_seg_index);
1533           svm_fifo_segment_free_fifo (seg, session->server_rx_fifo,
1534                                       FIFO_SEGMENT_RX_FREELIST);
1535           svm_fifo_segment_free_fifo (seg, session->server_tx_fifo,
1536                                       FIFO_SEGMENT_TX_FREELIST);
1537           svm_fifo_segment_delete (seg);
1538
1539           /* TBD: Send cut-thru disconnect event to client */
1540
1541           clib_spinlock_unlock (&vcm->sessions_lockp);
1542         }
1543       else
1544         {
1545           /* TBD: Send cut-thru disconnect event to server */
1546         }
1547     }
1548
1549 done:
1550   return rv;
1551 }
1552
1553 #define foreach_sock_msg                                        \
1554 _(SESSION_ENABLE_DISABLE_REPLY, session_enable_disable_reply)   \
1555 _(BIND_SOCK_REPLY, bind_sock_reply)                             \
1556 _(UNBIND_SOCK_REPLY, unbind_sock_reply)                         \
1557 _(ACCEPT_SESSION, accept_session)                               \
1558 _(CONNECT_SOCK, connect_sock)                                   \
1559 _(CONNECT_SESSION_REPLY, connect_session_reply)                 \
1560 _(DISCONNECT_SESSION, disconnect_session)                       \
1561 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1562 _(RESET_SESSION, reset_session)                                 \
1563 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1564 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1565 _(MAP_ANOTHER_SEGMENT, map_another_segment)
1566
1567 static void
1568 vppcom_api_hookup (void)
1569 {
1570 #define _(N,n)                                                  \
1571     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1572                            vl_api_##n##_t_handler,              \
1573                            vl_noop_handler,                     \
1574                            vl_api_##n##_t_endian,               \
1575                            vl_api_##n##_t_print,                \
1576                            sizeof(vl_api_##n##_t), 1);
1577   foreach_sock_msg;
1578 #undef _
1579 }
1580
1581 static void
1582 vppcom_cfg_init (vppcom_cfg_t * vcl_cfg)
1583 {
1584   ASSERT (vcl_cfg);
1585
1586   vcl_cfg->heapsize = (256ULL << 20);
1587   vcl_cfg->vpp_api_q_length = 1024;
1588   vcl_cfg->segment_baseva = 0x200000000ULL;
1589   vcl_cfg->segment_size = (256 << 20);
1590   vcl_cfg->add_segment_size = (128 << 20);
1591   vcl_cfg->preallocated_fifo_pairs = 8;
1592   vcl_cfg->rx_fifo_size = (1 << 20);
1593   vcl_cfg->tx_fifo_size = (1 << 20);
1594   vcl_cfg->event_queue_size = 2048;
1595   vcl_cfg->listen_queue_size = CLIB_CACHE_LINE_BYTES / sizeof (u32);
1596   vcl_cfg->app_timeout = 10 * 60.0;
1597   vcl_cfg->session_timeout = 10 * 60.0;
1598   vcl_cfg->accept_timeout = 60.0;
1599   vcl_cfg->event_ring_size = (128 << 10);
1600   vcl_cfg->event_log_path = "/dev/shm";
1601 }
1602
1603 static void
1604 vppcom_cfg_heapsize (char *conf_fname)
1605 {
1606   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1607   FILE *fp;
1608   char inbuf[4096];
1609   int argc = 1;
1610   char **argv = NULL;
1611   char *arg = NULL;
1612   char *p;
1613   int i;
1614   u8 *sizep;
1615   u32 size;
1616   void *vcl_mem;
1617   void *heap;
1618
1619   fp = fopen (conf_fname, "r");
1620   if (fp == NULL)
1621     {
1622       if (VPPCOM_DEBUG > 0)
1623         fprintf (stderr, "open configuration file '%s' failed\n", conf_fname);
1624       goto defaulted;
1625     }
1626   argv = calloc (1, sizeof (char *));
1627   if (argv == NULL)
1628     goto defaulted;
1629
1630   while (1)
1631     {
1632       if (fgets (inbuf, 4096, fp) == 0)
1633         break;
1634       p = strtok (inbuf, " \t\n");
1635       while (p != NULL)
1636         {
1637           if (*p == '#')
1638             break;
1639           argc++;
1640           char **tmp = realloc (argv, argc * sizeof (char *));
1641           if (tmp == NULL)
1642             goto defaulted;
1643           argv = tmp;
1644           arg = strndup (p, 1024);
1645           if (arg == NULL)
1646             goto defaulted;
1647           argv[argc - 1] = arg;
1648           p = strtok (NULL, " \t\n");
1649         }
1650     }
1651
1652   fclose (fp);
1653   fp = NULL;
1654
1655   char **tmp = realloc (argv, (argc + 1) * sizeof (char *));
1656   if (tmp == NULL)
1657     goto defaulted;
1658   argv = tmp;
1659   argv[argc] = NULL;
1660
1661   /*
1662    * Look for and parse the "heapsize" config parameter.
1663    * Manual since none of the clib infra has been bootstrapped yet.
1664    *
1665    * Format: heapsize <nn>[mM][gG]
1666    */
1667
1668   for (i = 1; i < (argc - 1); i++)
1669     {
1670       if (!strncmp (argv[i], "heapsize", 8))
1671         {
1672           sizep = (u8 *) argv[i + 1];
1673           size = 0;
1674           while (*sizep >= '0' && *sizep <= '9')
1675             {
1676               size *= 10;
1677               size += *sizep++ - '0';
1678             }
1679           if (size == 0)
1680             {
1681               if (VPPCOM_DEBUG > 0)
1682                 clib_warning ("[%d] parse error '%s %s', "
1683                               "using default heapsize %lld (0x%llx)",
1684                               getpid (), argv[i], argv[i + 1],
1685                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1686               goto defaulted;
1687             }
1688
1689           if (*sizep == 'g' || *sizep == 'G')
1690             vcl_cfg->heapsize = size << 30;
1691           else if (*sizep == 'm' || *sizep == 'M')
1692             vcl_cfg->heapsize = size << 20;
1693           else
1694             {
1695               if (VPPCOM_DEBUG > 0)
1696                 clib_warning ("[%d] parse error '%s %s', "
1697                               "using default heapsize %lld (0x%llx)",
1698                               getpid (), argv[i], argv[i + 1],
1699                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1700               goto defaulted;
1701             }
1702         }
1703     }
1704
1705 defaulted:
1706   if (fp != NULL)
1707     fclose (fp);
1708   if (argv != NULL)
1709     free (argv);
1710
1711   vcl_mem = mmap (0, vcl_cfg->heapsize, PROT_READ | PROT_WRITE,
1712                   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1713   if (vcl_mem == MAP_FAILED)
1714     {
1715       clib_unix_error ("[%d] ERROR: mmap(0, %lld == 0x%llx, "
1716                        "PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, "
1717                        "-1, 0) failed!",
1718                        getpid (), vcl_cfg->heapsize, vcl_cfg->heapsize);
1719       return;
1720     }
1721   heap = clib_mem_init (vcl_mem, vcl_cfg->heapsize);
1722   if (!heap)
1723     {
1724       clib_warning ("[%d] ERROR: clib_mem_init() failed!", getpid ());
1725       return;
1726     }
1727   vcl_mem = clib_mem_alloc (sizeof (_vppcom_main));
1728   if (!vcl_mem)
1729     {
1730       clib_warning ("[%d] ERROR: clib_mem_alloc() failed!", getpid ());
1731       return;
1732     }
1733
1734   clib_memcpy (vcl_mem, &_vppcom_main, sizeof (_vppcom_main));
1735   vcm = vcl_mem;
1736
1737   if (VPPCOM_DEBUG > 0)
1738     clib_warning ("[%d] allocated VCL heap = %p, size %lld (0x%llx)",
1739                   getpid (), heap, vcl_cfg->heapsize, vcl_cfg->heapsize);
1740 }
1741
1742 static void
1743 vppcom_cfg_read (char *conf_fname)
1744 {
1745   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1746   int fd;
1747   unformat_input_t _input, *input = &_input;
1748   unformat_input_t _line_input, *line_input = &_line_input;
1749   u8 vc_cfg_input = 0;
1750   u8 *chroot_path;
1751   struct stat s;
1752   u32 uid, gid, q_len;
1753
1754   fd = open (conf_fname, O_RDONLY);
1755   if (fd < 0)
1756     {
1757       if (VPPCOM_DEBUG > 0)
1758         clib_warning ("[%d] open configuration file '%s' failed!",
1759                       getpid (), conf_fname);
1760       goto file_done;
1761     }
1762
1763   if (fstat (fd, &s) < 0)
1764     {
1765       if (VPPCOM_DEBUG > 0)
1766         clib_warning ("[%d] failed to stat `%s'", getpid (), conf_fname);
1767       goto file_done;
1768     }
1769
1770   if (!(S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
1771     {
1772       if (VPPCOM_DEBUG > 0)
1773         clib_warning ("[%d] not a regular file `%s'", getpid (), conf_fname);
1774       goto file_done;
1775     }
1776
1777   unformat_init_clib_file (input, fd);
1778
1779   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1780     {
1781       (void) unformat_user (input, unformat_line_input, line_input);
1782       unformat_skip_white_space (line_input);
1783
1784       if (unformat (line_input, "vcl {"))
1785         {
1786           vc_cfg_input = 1;
1787           continue;
1788         }
1789
1790       if (vc_cfg_input)
1791         {
1792           if (unformat (line_input, "heapsize %s", &chroot_path))
1793             {
1794               vec_terminate_c_string (chroot_path);
1795               if (VPPCOM_DEBUG > 0)
1796                 clib_warning ("[%d] configured heapsize %s, "
1797                               "actual heapsize %lld (0x%llx)",
1798                               getpid (), chroot_path, vcl_cfg->heapsize,
1799                               vcl_cfg->heapsize);
1800               vec_free (chroot_path);
1801             }
1802           else if (unformat (line_input, "api-prefix %s", &chroot_path))
1803             {
1804               vec_terminate_c_string (chroot_path);
1805               vl_set_memory_root_path ((char *) chroot_path);
1806               if (VPPCOM_DEBUG > 0)
1807                 clib_warning ("[%d] configured api-prefix %s",
1808                               getpid (), chroot_path);
1809               chroot_path = 0;  /* Don't vec_free() it! */
1810             }
1811           else if (unformat (line_input, "vpp-api-q-length %d", &q_len))
1812             {
1813               if (q_len < vcl_cfg->vpp_api_q_length)
1814                 {
1815                   clib_warning ("[%d] ERROR: configured vpp-api-q-length "
1816                                 "(%u) is too small! Using default: %u ",
1817                                 getpid (), q_len, vcl_cfg->vpp_api_q_length);
1818                 }
1819               else
1820                 {
1821                   vcl_cfg->vpp_api_q_length = q_len;
1822
1823                   if (VPPCOM_DEBUG > 0)
1824                     clib_warning ("[%d] configured vpp-api-q-length %u",
1825                                   getpid (), vcl_cfg->vpp_api_q_length);
1826                 }
1827             }
1828           else if (unformat (line_input, "uid %d", &uid))
1829             {
1830               vl_set_memory_uid (uid);
1831               if (VPPCOM_DEBUG > 0)
1832                 clib_warning ("[%d] configured uid %d", getpid (), uid);
1833             }
1834           else if (unformat (line_input, "gid %d", &gid))
1835             {
1836               vl_set_memory_gid (gid);
1837               if (VPPCOM_DEBUG > 0)
1838                 clib_warning ("[%d] configured gid %d", getpid (), gid);
1839             }
1840           else if (unformat (line_input, "segment-baseva 0x%lx",
1841                              &vcl_cfg->segment_baseva))
1842             {
1843               if (VPPCOM_DEBUG > 0)
1844                 clib_warning ("[%d] configured segment_baseva 0x%lx",
1845                               getpid (), vcl_cfg->segment_baseva);
1846             }
1847           else if (unformat (line_input, "segment-size 0x%lx",
1848                              &vcl_cfg->segment_size))
1849             {
1850               if (VPPCOM_DEBUG > 0)
1851                 clib_warning ("[%d] configured segment_size 0x%lx (%ld)",
1852                               getpid (), vcl_cfg->segment_size,
1853                               vcl_cfg->segment_size);
1854             }
1855           else if (unformat (line_input, "segment-size %ld",
1856                              &vcl_cfg->segment_size))
1857             {
1858               if (VPPCOM_DEBUG > 0)
1859                 clib_warning ("[%d] configured segment_size %ld (0x%lx)",
1860                               getpid (), vcl_cfg->segment_size,
1861                               vcl_cfg->segment_size);
1862             }
1863           else if (unformat (line_input, "add-segment-size 0x%lx",
1864                              &vcl_cfg->add_segment_size))
1865             {
1866               if (VPPCOM_DEBUG > 0)
1867                 clib_warning
1868                   ("[%d] configured add_segment_size 0x%lx (%ld)",
1869                    getpid (), vcl_cfg->add_segment_size,
1870                    vcl_cfg->add_segment_size);
1871             }
1872           else if (unformat (line_input, "add-segment-size %ld",
1873                              &vcl_cfg->add_segment_size))
1874             {
1875               if (VPPCOM_DEBUG > 0)
1876                 clib_warning
1877                   ("[%d] configured add_segment_size %ld (0x%lx)",
1878                    getpid (), vcl_cfg->add_segment_size,
1879                    vcl_cfg->add_segment_size);
1880             }
1881           else if (unformat (line_input, "preallocated-fifo-pairs %d",
1882                              &vcl_cfg->preallocated_fifo_pairs))
1883             {
1884               if (VPPCOM_DEBUG > 0)
1885                 clib_warning ("[%d] configured preallocated_fifo_pairs "
1886                               "%d (0x%x)", getpid (),
1887                               vcl_cfg->preallocated_fifo_pairs,
1888                               vcl_cfg->preallocated_fifo_pairs);
1889             }
1890           else if (unformat (line_input, "rx-fifo-size 0x%lx",
1891                              &vcl_cfg->rx_fifo_size))
1892             {
1893               if (VPPCOM_DEBUG > 0)
1894                 clib_warning ("[%d] configured rx_fifo_size 0x%lx (%ld)",
1895                               getpid (), vcl_cfg->rx_fifo_size,
1896                               vcl_cfg->rx_fifo_size);
1897             }
1898           else if (unformat (line_input, "rx-fifo-size %ld",
1899                              &vcl_cfg->rx_fifo_size))
1900             {
1901               if (VPPCOM_DEBUG > 0)
1902                 clib_warning ("[%d] configured rx_fifo_size %ld (0x%lx)",
1903                               getpid (), vcl_cfg->rx_fifo_size,
1904                               vcl_cfg->rx_fifo_size);
1905             }
1906           else if (unformat (line_input, "tx-fifo-size 0x%lx",
1907                              &vcl_cfg->tx_fifo_size))
1908             {
1909               if (VPPCOM_DEBUG > 0)
1910                 clib_warning ("[%d] configured tx_fifo_size 0x%lx (%ld)",
1911                               getpid (), vcl_cfg->tx_fifo_size,
1912                               vcl_cfg->tx_fifo_size);
1913             }
1914           else if (unformat (line_input, "tx-fifo-size %ld",
1915                              &vcl_cfg->tx_fifo_size))
1916             {
1917               if (VPPCOM_DEBUG > 0)
1918                 clib_warning ("[%d] configured tx_fifo_size %ld (0x%lx)",
1919                               getpid (), vcl_cfg->tx_fifo_size,
1920                               vcl_cfg->tx_fifo_size);
1921             }
1922           else if (unformat (line_input, "event-queue-size 0x%lx",
1923                              &vcl_cfg->event_queue_size))
1924             {
1925               if (VPPCOM_DEBUG > 0)
1926                 clib_warning ("[%d] configured event_queue_size 0x%lx (%ld)",
1927                               getpid (), vcl_cfg->event_queue_size,
1928                               vcl_cfg->event_queue_size);
1929             }
1930           else if (unformat (line_input, "event-queue-size %ld",
1931                              &vcl_cfg->event_queue_size))
1932             {
1933               if (VPPCOM_DEBUG > 0)
1934                 clib_warning ("[%d] configured event_queue_size %ld (0x%lx)",
1935                               getpid (), vcl_cfg->event_queue_size,
1936                               vcl_cfg->event_queue_size);
1937             }
1938           else if (unformat (line_input, "listen-queue-size 0x%lx",
1939                              &vcl_cfg->listen_queue_size))
1940             {
1941               if (VPPCOM_DEBUG > 0)
1942                 clib_warning ("[%d] configured listen_queue_size 0x%lx (%ld)",
1943                               getpid (), vcl_cfg->listen_queue_size,
1944                               vcl_cfg->listen_queue_size);
1945             }
1946           else if (unformat (line_input, "listen-queue-size %ld",
1947                              &vcl_cfg->listen_queue_size))
1948             {
1949               if (VPPCOM_DEBUG > 0)
1950                 clib_warning ("[%d] configured listen_queue_size %ld (0x%lx)",
1951                               getpid (), vcl_cfg->listen_queue_size,
1952                               vcl_cfg->listen_queue_size);
1953             }
1954           else if (unformat (line_input, "app-timeout %f",
1955                              &vcl_cfg->app_timeout))
1956             {
1957               if (VPPCOM_DEBUG > 0)
1958                 clib_warning ("[%d] configured app_timeout %f",
1959                               getpid (), vcl_cfg->app_timeout);
1960             }
1961           else if (unformat (line_input, "session-timeout %f",
1962                              &vcl_cfg->session_timeout))
1963             {
1964               if (VPPCOM_DEBUG > 0)
1965                 clib_warning ("[%d] configured session_timeout %f",
1966                               getpid (), vcl_cfg->session_timeout);
1967             }
1968           else if (unformat (line_input, "accept-timeout %f",
1969                              &vcl_cfg->accept_timeout))
1970             {
1971               if (VPPCOM_DEBUG > 0)
1972                 clib_warning ("[%d] configured accept_timeout %f",
1973                               getpid (), vcl_cfg->accept_timeout);
1974             }
1975           else if (unformat (line_input, "app-proxy-transport-tcp"))
1976             {
1977               vcl_cfg->app_proxy_transport_tcp = 1;
1978               if (VPPCOM_DEBUG > 0)
1979                 clib_warning ("[%d] configured app_proxy_transport_tcp (%d)",
1980                               getpid (), vcl_cfg->app_proxy_transport_tcp);
1981             }
1982           else if (unformat (line_input, "app-proxy-transport-udp"))
1983             {
1984               vcl_cfg->app_proxy_transport_udp = 1;
1985               if (VPPCOM_DEBUG > 0)
1986                 clib_warning ("[%d] configured app_proxy_transport_udp (%d)",
1987                               getpid (), vcl_cfg->app_proxy_transport_udp);
1988             }
1989           else if (unformat (line_input, "app-scope-local"))
1990             {
1991               vcl_cfg->app_scope_local = 1;
1992               if (VPPCOM_DEBUG > 0)
1993                 clib_warning ("[%d] configured app_scope_local (%d)",
1994                               getpid (), vcl_cfg->app_scope_local);
1995             }
1996           else if (unformat (line_input, "app-scope-global"))
1997             {
1998               vcl_cfg->app_scope_global = 1;
1999               if (VPPCOM_DEBUG > 0)
2000                 clib_warning ("[%d] configured app_scope_global (%d)",
2001                               getpid (), vcl_cfg->app_scope_global);
2002             }
2003           else if (unformat (line_input, "namespace-secret %lu",
2004                              &vcl_cfg->namespace_secret))
2005             {
2006               if (VPPCOM_DEBUG > 0)
2007                 clib_warning
2008                   ("[%d] configured namespace_secret %lu (0x%lx)",
2009                    getpid (), vcl_cfg->namespace_secret,
2010                    vcl_cfg->namespace_secret);
2011             }
2012           else if (unformat (line_input, "namespace-id %v",
2013                              &vcl_cfg->namespace_id))
2014             {
2015               vl_api_application_attach_t *mp;
2016               u32 max_nsid_vec_len = sizeof (mp->namespace_id) - 1;
2017               u32 nsid_vec_len = vec_len (vcl_cfg->namespace_id);
2018               if (nsid_vec_len > max_nsid_vec_len)
2019                 {
2020                   _vec_len (vcl_cfg->namespace_id) = max_nsid_vec_len;
2021                   if (VPPCOM_DEBUG > 0)
2022                     clib_warning ("[%d] configured namespace_id is too long,"
2023                                   " truncated to %d characters!", getpid (),
2024                                   max_nsid_vec_len);
2025                 }
2026
2027               if (VPPCOM_DEBUG > 0)
2028                 clib_warning ("[%d] configured namespace_id %v",
2029                               getpid (), vcl_cfg->namespace_id);
2030             }
2031           else if (unformat (line_input, "}"))
2032             {
2033               vc_cfg_input = 0;
2034               if (VPPCOM_DEBUG > 0)
2035                 clib_warning ("[%d] completed parsing vppcom config!",
2036                               getpid ());
2037               goto input_done;
2038             }
2039           else
2040             {
2041               if (line_input->buffer[line_input->index] != '#')
2042                 {
2043                   clib_warning ("[%d] Unknown vppcom config option: '%s'",
2044                                 getpid (), (char *)
2045                                 &line_input->buffer[line_input->index]);
2046                 }
2047             }
2048         }
2049     }
2050
2051 input_done:
2052   unformat_free (input);
2053
2054 file_done:
2055   if (fd >= 0)
2056     close (fd);
2057 }
2058
2059 /*
2060  * VPPCOM Public API functions
2061  */
2062 int
2063 vppcom_app_create (char *app_name)
2064 {
2065   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
2066   u8 *heap;
2067   mheap_t *h;
2068   int rv;
2069
2070   if (!vcm->init)
2071     {
2072       char *conf_fname;
2073       char *env_var_str;
2074
2075       vcm->init = 1;
2076       vppcom_cfg_init (vcl_cfg);
2077       env_var_str = getenv (VPPCOM_ENV_DEBUG);
2078       if (env_var_str)
2079         {
2080           u32 tmp;
2081           if (sscanf (env_var_str, "%u", &tmp) != 1)
2082             clib_warning ("[%d] Invalid debug level specified in "
2083                           "the environment variable "
2084                           VPPCOM_ENV_DEBUG
2085                           " (%s)!\n", getpid (), env_var_str);
2086           else
2087             {
2088               vcm->debug = tmp;
2089               clib_warning ("[%d] configured debug level (%u) from "
2090                             VPPCOM_ENV_DEBUG "!", getpid (), vcm->debug);
2091             }
2092         }
2093       conf_fname = getenv (VPPCOM_ENV_CONF);
2094       if (!conf_fname)
2095         {
2096           conf_fname = VPPCOM_CONF_DEFAULT;
2097           if (VPPCOM_DEBUG > 0)
2098             clib_warning ("[%d] getenv '%s' failed!", getpid (),
2099                           VPPCOM_ENV_CONF);
2100         }
2101       vppcom_cfg_heapsize (conf_fname);
2102       clib_fifo_validate (vcm->client_session_index_fifo,
2103                           vcm->cfg.listen_queue_size);
2104       vppcom_cfg_read (conf_fname);
2105       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_ID);
2106       if (env_var_str)
2107         {
2108           u32 ns_id_vec_len = strlen (env_var_str);
2109
2110           vec_reset_length (vcm->cfg.namespace_id);
2111           vec_validate (vcm->cfg.namespace_id, ns_id_vec_len - 1);
2112           clib_memcpy (vcm->cfg.namespace_id, env_var_str, ns_id_vec_len);
2113
2114           if (VPPCOM_DEBUG > 0)
2115             clib_warning ("[%d] configured namespace_id (%v) from "
2116                           VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
2117                           vcm->cfg.namespace_id);
2118         }
2119       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_SECRET);
2120       if (env_var_str)
2121         {
2122           u64 tmp;
2123           if (sscanf (env_var_str, "%lu", &tmp) != 1)
2124             clib_warning ("[%d] Invalid namespace secret specified in "
2125                           "the environment variable "
2126                           VPPCOM_ENV_APP_NAMESPACE_SECRET
2127                           " (%s)!\n", getpid (), env_var_str);
2128           else
2129             {
2130               vcm->cfg.namespace_secret = tmp;
2131               if (VPPCOM_DEBUG > 0)
2132                 clib_warning ("[%d] configured namespace secret (%lu) from "
2133                               VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
2134                               vcm->cfg.namespace_secret);
2135             }
2136         }
2137       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP))
2138         {
2139           vcm->cfg.app_proxy_transport_tcp = 1;
2140           if (VPPCOM_DEBUG > 0)
2141             clib_warning ("[%d] configured app_proxy_transport_tcp (%u) from "
2142                           VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP "!", getpid (),
2143                           vcm->cfg.app_proxy_transport_tcp);
2144         }
2145       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP))
2146         {
2147           vcm->cfg.app_proxy_transport_udp = 1;
2148           if (VPPCOM_DEBUG > 0)
2149             clib_warning ("[%d] configured app_proxy_transport_udp (%u) from "
2150                           VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP "!", getpid (),
2151                           vcm->cfg.app_proxy_transport_udp);
2152         }
2153       if (getenv (VPPCOM_ENV_APP_SCOPE_LOCAL))
2154         {
2155           vcm->cfg.app_scope_local = 1;
2156           if (VPPCOM_DEBUG > 0)
2157             clib_warning ("[%d] configured app_scope_local (%u) from "
2158                           VPPCOM_ENV_APP_SCOPE_LOCAL "!", getpid (),
2159                           vcm->cfg.app_scope_local);
2160         }
2161       if (getenv (VPPCOM_ENV_APP_SCOPE_GLOBAL))
2162         {
2163           vcm->cfg.app_scope_global = 1;
2164           if (VPPCOM_DEBUG > 0)
2165             clib_warning ("[%d] configured app_scope_global (%u) from "
2166                           VPPCOM_ENV_APP_SCOPE_GLOBAL "!", getpid (),
2167                           vcm->cfg.app_scope_global);
2168         }
2169
2170       vcm->main_cpu = os_get_thread_index ();
2171       heap = clib_mem_get_per_cpu_heap ();
2172       h = mheap_header (heap);
2173
2174       /* make the main heap thread-safe */
2175       h->flags |= MHEAP_FLAG_THREAD_SAFE;
2176
2177       vcm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
2178
2179       clib_time_init (&vcm->clib_time);
2180       vppcom_init_error_string_table ();
2181       svm_fifo_segment_init (vcl_cfg->segment_baseva,
2182                              20 /* timeout in secs */ );
2183       clib_spinlock_init (&vcm->sessions_lockp);
2184       vppcom_api_hookup ();
2185     }
2186
2187   if (vcm->my_client_index == ~0)
2188     {
2189       vcm->app_state = STATE_APP_START;
2190       rv = vppcom_connect_to_vpp (app_name);
2191       if (rv)
2192         {
2193           clib_warning ("[%d] ERROR: couldn't connect to VPP!", getpid ());
2194           return rv;
2195         }
2196
2197       if (VPPCOM_DEBUG > 0)
2198         clib_warning ("[%d] sending session enable", getpid ());
2199
2200       rv = vppcom_app_session_enable ();
2201       if (rv)
2202         {
2203           clib_warning ("[%d] ERROR: vppcom_app_session_enable() failed!",
2204                         getpid ());
2205           return rv;
2206         }
2207
2208       if (VPPCOM_DEBUG > 0)
2209         clib_warning ("[%d] sending app attach", getpid ());
2210
2211       rv = vppcom_app_attach ();
2212       if (rv)
2213         {
2214           clib_warning ("[%d] ERROR: vppcom_app_attach() failed!", getpid ());
2215           return rv;
2216         }
2217
2218       if (VPPCOM_DEBUG > 0)
2219         clib_warning ("[%d] app_name '%s', my_client_index %d (0x%x)",
2220                       getpid (), app_name, vcm->my_client_index,
2221                       vcm->my_client_index);
2222     }
2223
2224   return VPPCOM_OK;
2225 }
2226
2227 void
2228 vppcom_app_destroy (void)
2229 {
2230   int rv;
2231
2232   if (vcm->my_client_index == ~0)
2233     return;
2234
2235   if (VPPCOM_DEBUG > 0)
2236     clib_warning ("[%d] detaching from VPP, my_client_index %d (0x%x)",
2237                   getpid (), vcm->my_client_index, vcm->my_client_index);
2238
2239   if (VPPCOM_DEBUG > 0)
2240     {
2241       ELOG_TYPE_DECLARE (e) =
2242       {
2243       .format = "app_detach:C:%d",.format_args = "i4",};
2244       struct
2245       {
2246         u32 data;
2247       } *ed;
2248       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, vcm->elog_track);
2249       ed->data = vcm->my_client_index;
2250     }
2251
2252   vppcom_app_detach ();
2253   rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
2254   if (PREDICT_FALSE (rv))
2255     {
2256       if (VPPCOM_DEBUG > 0)
2257         clib_warning ("[%d] application detach timed out! returning %d (%s)",
2258                       getpid (), rv, vppcom_retval_str (rv));
2259     }
2260
2261   /* Finished with logging before client gets reset to ~0 */
2262   if (VPPCOM_DEBUG > 0)
2263     write_elog ();
2264
2265   vl_client_disconnect_from_vlib ();
2266   vcm->my_client_index = ~0;
2267   vcm->app_state = STATE_APP_START;
2268 }
2269
2270 int
2271 vppcom_session_create (u32 vrf, u8 proto, u8 is_nonblocking)
2272 {
2273   session_t *session;
2274   u32 session_index;
2275
2276   clib_spinlock_lock (&vcm->sessions_lockp);
2277   pool_get (vcm->sessions, session);
2278   memset (session, 0, sizeof (*session));
2279   session_index = session - vcm->sessions;
2280
2281   session->vrf = vrf;
2282   session->proto = proto;
2283   session->state = STATE_START;
2284   session->is_nonblocking = is_nonblocking ? 1 : 0;
2285   session->vpp_handle = ~0;
2286   clib_spinlock_unlock (&vcm->sessions_lockp);
2287
2288   if (VPPCOM_DEBUG > 0)
2289     clib_warning ("[%d] sid %u", getpid (), session_index);
2290
2291   if (VPPCOM_DEBUG > 0)
2292     {
2293       session->elog_track.name =
2294         (char *) format (0, "C:%d:S:%d%c", vcm->my_client_index,
2295                          session_index, 0);
2296       elog_track_register (&vcm->elog_main, &session->elog_track);
2297
2298       ELOG_TYPE_DECLARE (e) =
2299       {
2300       .format =
2301           "session_create:vrf:%d proto:%d state:%d is_nonblocking:%d",.format_args
2302           = "i4i4i4i4",};
2303       struct
2304       {
2305         u32 data[4];
2306       } *ed;
2307       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
2308       ed->data[0] = session->vrf;
2309       ed->data[1] = session->proto;
2310       ed->data[2] = session->state;
2311       ed->data[3] = session->is_nonblocking;
2312     }
2313
2314   return (int) session_index;
2315 }
2316
2317 int
2318 vppcom_session_close (uint32_t session_index)
2319 {
2320   session_t *session = 0;
2321   int rv;
2322   u8 is_listen;
2323   u8 is_vep;
2324   u8 is_vep_session;
2325   u32 next_sid;
2326   u32 vep_idx;
2327   u64 vpp_handle;
2328   uword *p;
2329   session_state_t state;
2330
2331   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2332   is_listen = session->is_listen;
2333   is_vep = session->is_vep;
2334   is_vep_session = session->is_vep_session;
2335   next_sid = session->vep.next_sid;
2336   vep_idx = session->vep.vep_idx;
2337   state = session->state;
2338   vpp_handle = session->vpp_handle;
2339   clib_spinlock_unlock (&vcm->sessions_lockp);
2340
2341   if (VPPCOM_DEBUG > 0)
2342     {
2343       if (is_vep)
2344         clib_warning ("[%d] vep_idx %u / sid %u: closing epoll session...",
2345                       getpid (), session_index, session_index);
2346       else
2347         clib_warning ("[%d] vpp handle 0x%llx, sid %d: closing session...",
2348                       getpid (), vpp_handle, session_index);
2349     }
2350
2351   if (is_vep)
2352     {
2353       while (next_sid != ~0)
2354         {
2355           rv = vppcom_epoll_ctl (session_index, EPOLL_CTL_DEL, next_sid, 0);
2356           if ((VPPCOM_DEBUG > 0) && PREDICT_FALSE (rv < 0))
2357             clib_warning ("[%d] vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL "
2358                           "vep_idx %u failed! rv %d (%s)", getpid (),
2359                           vpp_handle, next_sid, vep_idx,
2360                           rv, vppcom_retval_str (rv));
2361
2362           VCL_LOCK_AND_GET_SESSION (session_index, &session);
2363           next_sid = session->vep.next_sid;
2364           clib_spinlock_unlock (&vcm->sessions_lockp);
2365         }
2366     }
2367   else
2368     {
2369       if (is_vep_session)
2370         {
2371           rv = vppcom_epoll_ctl (vep_idx, EPOLL_CTL_DEL, session_index, 0);
2372           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2373             clib_warning ("[%d] vpp handle 0x%llx, sid %u: EPOLL_CTL_DEL "
2374                           "vep_idx %u failed! rv %d (%s)",
2375                           getpid (), vpp_handle, session_index,
2376                           vep_idx, rv, vppcom_retval_str (rv));
2377         }
2378
2379       if (is_listen)
2380         {
2381           if (state == STATE_LISTEN)
2382             {
2383               rv = vppcom_session_unbind (session_index);
2384               if (PREDICT_FALSE (rv < 0))
2385                 {
2386                   if (VPPCOM_DEBUG > 0)
2387                     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2388                                   "listener unbind failed! rv %d (%s)",
2389                                   getpid (), vpp_handle, session_index,
2390                                   rv, vppcom_retval_str (rv));
2391                 }
2392             }
2393         }
2394
2395       else if (state & (CLIENT_STATE_OPEN | SERVER_STATE_OPEN))
2396         {
2397           rv = vppcom_session_disconnect (session_index);
2398           if (PREDICT_FALSE (rv < 0))
2399             clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2400                           "session disconnect failed! rv %d (%s)",
2401                           getpid (), vpp_handle, session_index,
2402                           rv, vppcom_retval_str (rv));
2403         }
2404     }
2405
2406   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2407   vpp_handle = session->vpp_handle;
2408   if (vpp_handle != ~0)
2409     {
2410       p = hash_get (vcm->session_index_by_vpp_handles, vpp_handle);
2411       if (p)
2412         hash_unset (vcm->session_index_by_vpp_handles, vpp_handle);
2413     }
2414   pool_put_index (vcm->sessions, session_index);
2415   clib_spinlock_unlock (&vcm->sessions_lockp);
2416
2417   if (VPPCOM_DEBUG > 0)
2418     {
2419       if (is_vep)
2420         clib_warning ("[%d] vep_idx %u / sid %u: epoll session removed.",
2421                       getpid (), session_index, session_index);
2422       else
2423         clib_warning ("[%d] vpp handle 0x%llx, sid %u: session removed.",
2424                       getpid (), vpp_handle, session_index);
2425     }
2426 done:
2427
2428   if (VPPCOM_DEBUG > 0)
2429     {
2430       ELOG_TYPE_DECLARE (e) =
2431       {
2432       .format = "session_close:rv:%d",.format_args = "i4",};
2433       struct
2434       {
2435         u32 data;
2436       } *ed;
2437       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
2438       ed->data = rv;
2439     }
2440
2441   return rv;
2442 }
2443
2444 int
2445 vppcom_session_bind (uint32_t session_index, vppcom_endpt_t * ep)
2446 {
2447   session_t *session = 0;
2448   int rv;
2449
2450   if (!ep || !ep->ip)
2451     return VPPCOM_EINVAL;
2452
2453   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2454
2455   if (session->is_vep)
2456     {
2457       clib_spinlock_unlock (&vcm->sessions_lockp);
2458       clib_warning ("[%d] ERROR: sid %u: cannot bind to an epoll session!",
2459                     getpid (), session_index);
2460       rv = VPPCOM_EBADFD;
2461       goto done;
2462     }
2463
2464   session->vrf = ep->vrf;
2465   session->lcl_addr.is_ip4 = ep->is_ip4;
2466   session->lcl_addr.ip46 = to_ip46 (!ep->is_ip4, ep->ip);
2467   session->lcl_port = ep->port;
2468
2469   if (VPPCOM_DEBUG > 0)
2470     clib_warning ("[%d] sid %u: binding to local %s address %U "
2471                   "port %u, proto %s", getpid (), session_index,
2472                   session->lcl_addr.is_ip4 ? "IPv4" : "IPv6",
2473                   format_ip46_address, &session->lcl_addr.ip46,
2474                   session->lcl_addr.is_ip4,
2475                   clib_net_to_host_u16 (session->lcl_port),
2476                   session->proto ? "UDP" : "TCP");
2477
2478   if (VPPCOM_DEBUG > 0)
2479     {
2480       if (session->lcl_addr.is_ip4)
2481         {
2482           ELOG_TYPE_DECLARE (e) =
2483           {
2484             .format = "bind local:%s:%d.%d.%d.%d:%d ",.format_args =
2485               "t1i1i1i1i1i2",.n_enum_strings = 2,.enum_strings =
2486             {
2487             "TCP", "UDP",}
2488           ,};
2489           CLIB_PACKED (struct
2490                        {
2491                        u8 proto;
2492                        u8 addr[4];
2493                        u16 port;
2494                        }) * ed;
2495           ed = ELOG_TRACK_DATA (&vcm->elog_main, e, session->elog_track);
2496           ed->proto = session->proto;
2497           ed->addr[0] = session->lcl_addr.ip46.ip4.as_u8[0];
2498           ed->addr[1] = session->lcl_addr.ip46.ip4.as_u8[1];
2499           ed->addr[2] = session->lcl_addr.ip46.ip4.as_u8[2];
2500           ed->addr[3] = session->lcl_addr.ip46.ip4.as_u8[3];
2501           ed->port = clib_net_to_host_u16 (session->lcl_port);
2502         }
2503     }
2504
2505   clib_spinlock_unlock (&vcm->sessions_lockp);
2506 done:
2507   return rv;
2508 }
2509
2510 int
2511 vppcom_session_listen (uint32_t listen_session_index, uint32_t q_len)
2512 {
2513   session_t *listen_session = 0;
2514   u64 listen_vpp_handle;
2515   int rv, retval;
2516
2517   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2518
2519   if (listen_session->is_vep)
2520     {
2521       clib_spinlock_unlock (&vcm->sessions_lockp);
2522       clib_warning ("[%d] ERROR: sid %u: cannot listen on an "
2523                     "epoll session!", getpid (), listen_session_index);
2524       rv = VPPCOM_EBADFD;
2525       goto done;
2526     }
2527
2528   listen_vpp_handle = listen_session->vpp_handle;
2529   if (listen_session->is_listen)
2530     {
2531       clib_spinlock_unlock (&vcm->sessions_lockp);
2532       if (VPPCOM_DEBUG > 0)
2533         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
2534                       "already in listen state!",
2535                       getpid (), listen_vpp_handle, listen_session_index);
2536       rv = VPPCOM_OK;
2537       goto done;
2538     }
2539
2540   if (VPPCOM_DEBUG > 0)
2541     clib_warning ("[%d] vpp handle 0x%llx, sid %u: sending bind request...",
2542                   getpid (), listen_vpp_handle, listen_session_index);
2543
2544   vppcom_send_bind_sock (listen_session, listen_session_index);
2545   clib_spinlock_unlock (&vcm->sessions_lockp);
2546   retval =
2547     vppcom_wait_for_session_state_change (listen_session_index, STATE_LISTEN,
2548                                           vcm->cfg.session_timeout);
2549
2550   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2551   if (PREDICT_FALSE (retval))
2552     {
2553       if (VPPCOM_DEBUG > 0)
2554         clib_warning ("[%d] vpp handle 0x%llx, sid %u: bind failed! "
2555                       "returning %d (%s)", getpid (),
2556                       listen_session->vpp_handle, listen_session_index,
2557                       retval, vppcom_retval_str (retval));
2558       clib_spinlock_unlock (&vcm->sessions_lockp);
2559       rv = retval;
2560       goto done;
2561     }
2562
2563   clib_fifo_validate (vcm->client_session_index_fifo, q_len);
2564   clib_spinlock_unlock (&vcm->sessions_lockp);
2565 done:
2566   return rv;
2567 }
2568
2569 int
2570 vppcom_session_accept (uint32_t listen_session_index, vppcom_endpt_t * ep,
2571                        uint32_t flags, double wait_for_time)
2572 {
2573   session_t *listen_session = 0;
2574   session_t *client_session = 0;
2575   u32 client_session_index = ~0;
2576   int rv;
2577   f64 wait_for;
2578   char *cut_thru_str;
2579   u64 listen_vpp_handle;
2580
2581   VCL_LOCK_AND_GET_SESSION (listen_session_index, &listen_session);
2582
2583   if (listen_session->is_vep)
2584     {
2585       clib_spinlock_unlock (&vcm->sessions_lockp);
2586       clib_warning ("[%d] ERROR: sid %u: cannot accept on an "
2587                     "epoll session!", getpid (), listen_session_index);
2588       rv = VPPCOM_EBADFD;
2589       goto done;
2590     }
2591
2592   listen_vpp_handle = listen_session->vpp_handle;
2593   if (listen_session->state != STATE_LISTEN)
2594     {
2595       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2596                     "not in listen state! state 0x%x (%s)", getpid (),
2597                     listen_vpp_handle, listen_session_index,
2598                     listen_session->state,
2599                     vppcom_session_state_str (listen_session->state));
2600       clib_spinlock_unlock (&vcm->sessions_lockp);
2601       rv = VPPCOM_EBADFD;
2602       goto done;
2603     }
2604   wait_for = ((listen_session->is_nonblocking) ? 0 :
2605               (wait_for_time < 0) ? vcm->cfg.accept_timeout : wait_for_time);
2606
2607   clib_spinlock_unlock (&vcm->sessions_lockp);
2608
2609   while (1)
2610     {
2611       rv = vppcom_wait_for_client_session_index (wait_for);
2612       if (rv)
2613         {
2614           if ((VPPCOM_DEBUG > 0))
2615             clib_warning ("[%d] vpp handle 0x%llx, sid %u: accept failed! "
2616                           "returning %d (%s)", getpid (),
2617                           listen_vpp_handle, listen_session_index,
2618                           rv, vppcom_retval_str (rv));
2619           if ((wait_for == 0) || (wait_for_time > 0))
2620             goto done;
2621         }
2622       else
2623         break;
2624     }
2625
2626   clib_spinlock_lock (&vcm->sessions_lockp);
2627   clib_fifo_sub1 (vcm->client_session_index_fifo, client_session_index);
2628   rv = vppcom_session_at_index (client_session_index, &client_session);
2629   if (PREDICT_FALSE (rv))
2630     {
2631       rv = VPPCOM_ECONNABORTED;
2632       clib_warning ("[%d] vpp handle 0x%llx, sid %u: client sid %u "
2633                     "lookup failed! returning %d (%s)", getpid (),
2634                     listen_vpp_handle, listen_session_index,
2635                     client_session_index, rv, vppcom_retval_str (rv));
2636       goto done;
2637     }
2638
2639   client_session->is_nonblocking = (flags & O_NONBLOCK) ? 1 : 0;
2640   if (VPPCOM_DEBUG > 0)
2641     clib_warning ("[%d] vpp handle 0x%llx, sid %u: Got a client request! "
2642                   "vpp handle 0x%llx, sid %u, flags %d, is_nonblocking %u",
2643                   getpid (), listen_vpp_handle, listen_session_index,
2644                   client_session->vpp_handle, client_session_index,
2645                   flags, client_session->is_nonblocking);
2646
2647   ep->vrf = client_session->vrf;
2648   ep->is_cut_thru = client_session->is_cut_thru;
2649   ep->is_ip4 = client_session->peer_addr.is_ip4;
2650   ep->port = client_session->peer_port;
2651   if (client_session->peer_addr.is_ip4)
2652     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip4,
2653                  sizeof (ip4_address_t));
2654   else
2655     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip6,
2656                  sizeof (ip6_address_t));
2657
2658   if (client_session->is_server && client_session->is_cut_thru)
2659     {
2660       static svm_fifo_segment_create_args_t _a;
2661       svm_fifo_segment_create_args_t *a = &_a;
2662       svm_fifo_segment_private_t *seg;
2663
2664       cut_thru_str = " cut-thru ";
2665
2666       /* Create the segment */
2667       memset (a, 0, sizeof (*a));
2668       a->segment_name = (char *)
2669         format ((u8 *) a->segment_name, "%d:segment%d%c",
2670                 getpid (), vcm->unique_segment_index++, 0);
2671       a->segment_size = vcm->cfg.segment_size;
2672       a->preallocated_fifo_pairs = vcm->cfg.preallocated_fifo_pairs;
2673       a->rx_fifo_size = vcm->cfg.rx_fifo_size;
2674       a->tx_fifo_size = vcm->cfg.tx_fifo_size;
2675
2676       rv = svm_fifo_segment_create (a);
2677       if (PREDICT_FALSE (rv))
2678         {
2679           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2680                         "client sid %u svm_fifo_segment_create ('%s') "
2681                         "failed! rv %d", getpid (), listen_vpp_handle,
2682                         listen_session_index, client_session_index,
2683                         a->segment_name, rv);
2684           vec_reset_length (a->new_segment_indices);
2685           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2686           vppcom_send_connect_session_reply (client_session,
2687                                              client_session_index,
2688                                              client_session->vpp_handle,
2689                                              client_session->client_context,
2690                                              rv);
2691           clib_spinlock_unlock (&vcm->sessions_lockp);
2692           rv = VPPCOM_ENOMEM;
2693           goto done;
2694         }
2695
2696       client_session->segment_name = vec_dup ((u8 *) a->segment_name);
2697       client_session->sm_seg_index = a->new_segment_indices[0];
2698       vec_free (a->new_segment_indices);
2699
2700       seg = svm_fifo_segment_get_segment (client_session->sm_seg_index);
2701       client_session->server_rx_fifo =
2702         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.rx_fifo_size,
2703                                      FIFO_SEGMENT_RX_FREELIST);
2704       if (PREDICT_FALSE (!client_session->server_rx_fifo))
2705         {
2706           svm_fifo_segment_delete (seg);
2707           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2708                         "client sid %u rx fifo alloc failed! "
2709                         "size %ld (0x%lx)", getpid (), listen_vpp_handle,
2710                         listen_session_index, client_session_index,
2711                         vcm->cfg.rx_fifo_size, vcm->cfg.rx_fifo_size);
2712           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2713           vppcom_send_connect_session_reply (client_session,
2714                                              client_session_index,
2715                                              client_session->vpp_handle,
2716                                              client_session->client_context,
2717                                              rv);
2718           clib_spinlock_unlock (&vcm->sessions_lockp);
2719           rv = VPPCOM_ENOMEM;
2720           goto done;
2721         }
2722       client_session->server_rx_fifo->master_session_index =
2723         client_session_index;
2724
2725       client_session->server_tx_fifo =
2726         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.tx_fifo_size,
2727                                      FIFO_SEGMENT_TX_FREELIST);
2728       if (PREDICT_FALSE (!client_session->server_tx_fifo))
2729         {
2730           svm_fifo_segment_delete (seg);
2731           clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
2732                         "client sid %u tx fifo alloc failed! "
2733                         "size %ld (0x%lx)", getpid (), listen_vpp_handle,
2734                         listen_session_index, client_session_index,
2735                         vcm->cfg.tx_fifo_size, vcm->cfg.tx_fifo_size);
2736           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2737           vppcom_send_connect_session_reply (client_session,
2738                                              client_session_index,
2739                                              client_session->vpp_handle,
2740                                              client_session->client_context,
2741                                              rv);
2742           clib_spinlock_unlock (&vcm->sessions_lockp);
2743           rv = VPPCOM_ENOMEM;
2744           goto done;
2745         }
2746       client_session->server_tx_fifo->master_session_index =
2747         client_session_index;
2748
2749       if (VPPCOM_DEBUG > 1)
2750         clib_warning ("[%d] vpp handle 0x%llx, sid %u: client sid %u "
2751                       "created segment '%s', rx_fifo %p, tx_fifo %p",
2752                       getpid (), listen_vpp_handle, listen_session_index,
2753                       client_session_index, client_session->segment_name,
2754                       client_session->server_rx_fifo,
2755                       client_session->server_tx_fifo);
2756
2757 #ifdef CUT_THRU_EVENT_QUEUE     /* TBD */
2758       {
2759         void *oldheap;
2760         ssvm_shared_header_t *sh = seg->ssvm.sh;
2761
2762         ssvm_lock_non_recursive (sh, 1);
2763         oldheap = ssvm_push_heap (sh);
2764         event_q = client_session->vpp_event_queue =
2765           svm_queue_init (vcm->cfg.event_queue_size,
2766                           sizeof (session_fifo_event_t),
2767                           getpid (), 0 /* signal not sent */ );
2768         ssvm_pop_heap (oldheap);
2769         ssvm_unlock_non_recursive (sh);
2770       }
2771 #endif
2772       vppcom_send_connect_session_reply (client_session,
2773                                          client_session_index,
2774                                          client_session->vpp_handle,
2775                                          client_session->client_context,
2776                                          0 /* retval OK */ );
2777     }
2778   else
2779     {
2780       cut_thru_str = " ";
2781       vppcom_send_accept_session_reply (client_session->vpp_handle,
2782                                         client_session->client_context,
2783                                         0 /* retval OK */ );
2784     }
2785
2786   if (VPPCOM_DEBUG > 0)
2787     clib_warning ("[%d] vpp handle 0x%llx, sid %u: accepted vpp handle "
2788                   "0x%llx, sid %u%sconnection to local %s address "
2789                   "%U port %u", getpid (), listen_vpp_handle,
2790                   listen_session_index, client_session->vpp_handle,
2791                   client_session_index, cut_thru_str,
2792                   client_session->lcl_addr.is_ip4 ? "IPv4" : "IPv6",
2793                   format_ip46_address, &client_session->lcl_addr.ip46,
2794                   client_session->lcl_addr.is_ip4,
2795                   clib_net_to_host_u16 (client_session->lcl_port));
2796
2797   if (VPPCOM_DEBUG > 0)
2798     {
2799       client_session->elog_track.name =
2800         (char *) format (0, "C:%d:S:%d%c", vcm->my_client_index,
2801                          client_session_index, 0);
2802       elog_track_register (&vcm->elog_main, &client_session->elog_track);
2803
2804       ELOG_TYPE_DECLARE (e) =
2805       {
2806       .format =
2807           "accept cut-thru: listen_handle:%x from_handle:%x",.format_args =
2808           "i8i8",};
2809       struct
2810       {
2811         u64 handle[2];
2812       } *ed;
2813       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, client_session->elog_track);
2814       ed->handle[0] = listen_vpp_handle;
2815       ed->handle[1] = client_session->vpp_handle;
2816
2817       if (client_session->lcl_addr.is_ip4)
2818         {
2819           ELOG_TYPE_DECLARE (e2) =
2820           {
2821           .format = "accept cut-thru: S:%d %d.%d.%d.%d:%d ",.format_args =
2822               "i4i1i1i1i1i2",};
2823           CLIB_PACKED (struct
2824                        {
2825                        u32 session;
2826                        u8 addr[4];
2827                        u16 port;
2828                        }) * ed2;
2829           ed2 =
2830             ELOG_TRACK_DATA (&vcm->elog_main, e2, client_session->elog_track);
2831           ed2->session = client_session_index;
2832           ed2->addr[0] = client_session->lcl_addr.ip46.ip4.as_u8[0];
2833           ed2->addr[1] = client_session->lcl_addr.ip46.ip4.as_u8[1];
2834           ed2->addr[2] = client_session->lcl_addr.ip46.ip4.as_u8[2];
2835           ed2->addr[3] = client_session->lcl_addr.ip46.ip4.as_u8[3];
2836           ed2->port = clib_net_to_host_u16 (client_session->lcl_port);
2837         }
2838     }
2839
2840   clib_spinlock_unlock (&vcm->sessions_lockp);
2841   rv = (int) client_session_index;
2842 done:
2843   return rv;
2844 }
2845
2846 int
2847 vppcom_session_connect (uint32_t session_index, vppcom_endpt_t * server_ep)
2848 {
2849   session_t *session = 0;
2850   int rv, retval = VPPCOM_OK;
2851   u64 vpp_handle = ~0;
2852
2853   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2854
2855   if (PREDICT_FALSE (session->is_vep))
2856     {
2857       clib_spinlock_unlock (&vcm->sessions_lockp);
2858       clib_warning ("[%d] ERROR: sid %u: cannot connect on an epoll session!",
2859                     getpid (), session_index);
2860       rv = VPPCOM_EBADFD;
2861       goto done;
2862     }
2863
2864   vpp_handle = session->vpp_handle;
2865   if (PREDICT_FALSE (session->is_server))
2866     {
2867       clib_spinlock_unlock (&vcm->sessions_lockp);
2868       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: is in use "
2869                     "as a server session!", getpid (), vpp_handle,
2870                     session_index);
2871       rv = VPPCOM_EBADFD;
2872       goto done;
2873     }
2874
2875   if (PREDICT_FALSE (session->state & CLIENT_STATE_OPEN))
2876     {
2877       if (VPPCOM_DEBUG > 0)
2878         clib_warning ("[%d] vpp handle 0x%llx, sid %u: session already "
2879                       "connected to %s %U port %d proto %s, state 0x%x (%s)",
2880                       getpid (), vpp_handle, session_index,
2881                       session->peer_addr.is_ip4 ? "IPv4" : "IPv6",
2882                       format_ip46_address,
2883                       &session->peer_addr.ip46, session->peer_addr.is_ip4,
2884                       clib_net_to_host_u16 (session->peer_port),
2885                       session->proto ? "UDP" : "TCP", session->state,
2886                       vppcom_session_state_str (session->state));
2887
2888       clib_spinlock_unlock (&vcm->sessions_lockp);
2889       goto done;
2890     }
2891
2892   session->vrf = server_ep->vrf;
2893   session->peer_addr.is_ip4 = server_ep->is_ip4;
2894   session->peer_addr.ip46 = to_ip46 (!server_ep->is_ip4, server_ep->ip);
2895   session->peer_port = server_ep->port;
2896
2897   if (VPPCOM_DEBUG > 0)
2898     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connecting to server "
2899                   "%s %U port %d proto %s",
2900                   getpid (), vpp_handle, session_index,
2901                   session->peer_addr.is_ip4 ? "IPv4" : "IPv6",
2902                   format_ip46_address,
2903                   &session->peer_addr.ip46, session->peer_addr.is_ip4,
2904                   clib_net_to_host_u16 (session->peer_port),
2905                   session->proto ? "UDP" : "TCP");
2906
2907   vppcom_send_connect_sock (session, session_index);
2908   clib_spinlock_unlock (&vcm->sessions_lockp);
2909
2910   retval =
2911     vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
2912                                           vcm->cfg.session_timeout);
2913
2914   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2915   vpp_handle = session->vpp_handle;
2916   clib_spinlock_unlock (&vcm->sessions_lockp);
2917
2918 done:
2919   if (PREDICT_FALSE (retval))
2920     {
2921       rv = retval;
2922       if (VPPCOM_DEBUG > 0)
2923         clib_warning ("[%d] vpp handle 0x%llx, sid %u: connect failed! "
2924                       "returning %d (%s)", getpid (), vpp_handle,
2925                       session_index, rv, vppcom_retval_str (rv));
2926     }
2927   else if (VPPCOM_DEBUG > 0)
2928     clib_warning ("[%d] vpp handle 0x%llx, sid %u: connected!",
2929                   getpid (), vpp_handle, session_index);
2930
2931   return rv;
2932 }
2933
2934 static inline int
2935 vppcom_session_read_internal (uint32_t session_index, void *buf, int n,
2936                               u8 peek)
2937 {
2938   session_t *session = 0;
2939   svm_fifo_t *rx_fifo;
2940   int n_read = 0;
2941   int rv;
2942   char *fifo_str;
2943   u32 poll_et;
2944   session_state_t state;
2945   u8 is_server;
2946   u8 is_nonblocking;
2947   u64 vpp_handle;
2948
2949   ASSERT (buf);
2950
2951   VCL_LOCK_AND_GET_SESSION (session_index, &session);
2952
2953   if (PREDICT_FALSE (session->is_vep))
2954     {
2955       clib_spinlock_unlock (&vcm->sessions_lockp);
2956       clib_warning ("[%d] ERROR: sid %u: cannot read from an epoll session!",
2957                     getpid (), session_index);
2958       rv = VPPCOM_EBADFD;
2959       goto done;
2960     }
2961
2962   vpp_handle = session->vpp_handle;
2963   is_server = session->is_server;
2964   is_nonblocking = session->is_nonblocking;
2965   state = session->state;
2966   if (PREDICT_FALSE (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN))))
2967     {
2968       clib_spinlock_unlock (&vcm->sessions_lockp);
2969       rv = ((state == STATE_DISCONNECT) ?
2970             VPPCOM_ECONNRESET : VPPCOM_ENOTCONN);
2971
2972       if (VPPCOM_DEBUG > 0)
2973         clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s session is "
2974                       "not open! state 0x%x (%s), returning %d (%s)",
2975                       getpid (), vpp_handle, session_index,
2976                       is_server ? "server" : "client", state,
2977                       vppcom_session_state_str (state),
2978                       rv, vppcom_retval_str (rv));
2979       goto done;
2980     }
2981
2982   rx_fifo = ((!session->is_cut_thru || is_server) ?
2983              session->server_rx_fifo : session->server_tx_fifo);
2984   fifo_str = ((!session->is_cut_thru || is_server) ?
2985               "server_rx_fifo" : "server_tx_fifo");
2986   clib_spinlock_unlock (&vcm->sessions_lockp);
2987
2988   do
2989     {
2990       if (peek)
2991         n_read = svm_fifo_peek (rx_fifo, 0, n, buf);
2992       else
2993         n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2994     }
2995   while (!is_nonblocking && (n_read <= 0));
2996
2997   if (n_read <= 0)
2998     {
2999       VCL_LOCK_AND_GET_SESSION (session_index, &session);
3000
3001       poll_et = (((EPOLLET | EPOLLIN) & session->vep.ev.events) ==
3002                  (EPOLLET | EPOLLIN));
3003       if (poll_et)
3004         session->vep.et_mask |= EPOLLIN;
3005
3006       if (state == STATE_CLOSE_ON_EMPTY)
3007         {
3008           session_state_t new_state = STATE_DISCONNECT;
3009           rv = VPPCOM_ECONNRESET;
3010
3011           if (VPPCOM_DEBUG > 1)
3012             {
3013               clib_warning ("[%d] vpp handle 0x%llx, sid %u: Empty fifo "
3014                             "with %s session state 0x%x (%s)!"
3015                             "  Setting state to 0x%x (%s), returning %d (%s)",
3016                             getpid (), vpp_handle, session_index,
3017                             is_server ? "server" : "client",
3018                             state, vppcom_session_state_str (state),
3019                             new_state, vppcom_session_state_str (new_state),
3020                             rv, vppcom_retval_str (rv));
3021             }
3022
3023           session->state = new_state;
3024         }
3025       else
3026         rv = VPPCOM_EAGAIN;
3027
3028       clib_spinlock_unlock (&vcm->sessions_lockp);
3029     }
3030   else
3031     rv = n_read;
3032
3033   if (VPPCOM_DEBUG > 2)
3034     {
3035       if (rv > 0)
3036         clib_warning ("[%d] vpp handle 0x%llx, sid %u: read %d bytes "
3037                       "from %s (%p)", getpid (), vpp_handle,
3038                       session_index, n_read, fifo_str, rx_fifo);
3039       else
3040         clib_warning ("[%d] vpp handle 0x%llx, sid %u: nothing read! "
3041                       "returning %d (%s)", getpid (), vpp_handle,
3042                       session_index, rv, vppcom_retval_str (rv));
3043     }
3044 done:
3045   return rv;
3046 }
3047
3048 int
3049 vppcom_session_read (uint32_t session_index, void *buf, int n)
3050 {
3051   return (vppcom_session_read_internal (session_index, buf, n, 0));
3052 }
3053
3054 static int
3055 vppcom_session_peek (uint32_t session_index, void *buf, int n)
3056 {
3057   return (vppcom_session_read_internal (session_index, buf, n, 1));
3058 }
3059
3060 static inline int
3061 vppcom_session_read_ready (session_t * session, u32 session_index)
3062 {
3063   svm_fifo_t *rx_fifo = 0;
3064   int ready = 0;
3065   u32 poll_et;
3066   int rv;
3067   u8 is_server = session->is_server;
3068   session_state_t state = session->state;
3069   u64 vpp_handle = session->vpp_handle;
3070
3071   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
3072   if (PREDICT_FALSE (session->is_vep))
3073     {
3074       clib_warning ("[%d] ERROR: sid %u: cannot read from an "
3075                     "epoll session!", getpid (), session_index);
3076       rv = VPPCOM_EBADFD;
3077       goto done;
3078     }
3079
3080   if (session->is_listen)
3081     ready = clib_fifo_elts (vcm->client_session_index_fifo);
3082   else
3083     {
3084       if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN | STATE_LISTEN)))
3085         {
3086           rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
3087                 VPPCOM_ENOTCONN);
3088
3089           if (VPPCOM_DEBUG > 1)
3090             clib_warning ("[%d] vpp handle 0x%llx, sid %u: %s session is "
3091                           "not open! state 0x%x (%s), returning %d (%s)",
3092                           getpid (), vpp_handle, session_index,
3093                           is_server ? "server" : "client",
3094                           state, vppcom_session_state_str (state),
3095                           rv, vppcom_retval_str (rv));
3096           goto done;
3097         }
3098
3099       rx_fifo = ((!session->is_cut_thru || is_server) ?
3100                  session->server_rx_fifo : session->server_tx_fifo);
3101
3102       ready = svm_fifo_max_dequeue (rx_fifo);
3103     }
3104
3105   if (ready == 0)
3106     {
3107       poll_et =
3108         ((EPOLLET | EPOLLIN) & session->vep.ev.events) == (EPOLLET | EPOLLIN);
3109       if (poll_et)
3110         session->vep.et_mask |= EPOLLIN;
3111
3112       if (state == STATE_CLOSE_ON_EMPTY)
3113         {
3114           rv = VPPCOM_ECONNRESET;
3115           session_state_t new_state = STATE_DISCONNECT;
3116
3117           if (VPPCOM_DEBUG > 1)
3118             {
3119               clib_warning ("[%d] vpp handle 0x%llx, sid %u: Empty fifo with"
3120                             " %s session state 0x%x (%s)! Setting state to "
3121                             "0x%x (%s), returning %d (%s)",
3122                             getpid (), session_index, vpp_handle,
3123                             is_server ? "server" : "client",
3124                             state, vppcom_session_state_str (state),
3125                             new_state, vppcom_session_state_str (new_state),
3126                             rv, vppcom_retval_str (rv));
3127             }
3128           session->state = new_state;
3129           goto done;
3130         }
3131     }
3132   rv = ready;
3133
3134   if (vcm->app_event_queue->cursize &&
3135       !pthread_mutex_trylock (&vcm->app_event_queue->mutex))
3136     {
3137       u32 i, n_to_dequeue = vcm->app_event_queue->cursize;
3138       session_fifo_event_t e;
3139
3140       for (i = 0; i < n_to_dequeue; i++)
3141         svm_queue_sub_raw (vcm->app_event_queue, (u8 *) & e);
3142
3143       pthread_mutex_unlock (&vcm->app_event_queue->mutex);
3144     }
3145
3146 done:
3147   return rv;
3148 }
3149
3150 int
3151 vppcom_session_write (uint32_t session_index, void *buf, int n)
3152 {
3153   session_t *session = 0;
3154   svm_fifo_t *tx_fifo;
3155   svm_queue_t *q;
3156   session_fifo_event_t evt;
3157   int rv, n_write;
3158   char *fifo_str;
3159   u32 poll_et;
3160   u8 is_server;
3161   u8 is_nonblocking;
3162   session_state_t state;
3163   u64 vpp_handle;
3164
3165   ASSERT (buf);
3166
3167   VCL_LOCK_AND_GET_SESSION (session_index, &session);
3168
3169   if (PREDICT_FALSE (session->is_vep))
3170     {
3171       clib_spinlock_unlock (&vcm->sessions_lockp);
3172       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3173                     "cannot write to an epoll session!",
3174                     getpid (), session->vpp_handle, session_index);
3175
3176       rv = VPPCOM_EBADFD;
3177       goto done;
3178     }
3179
3180   is_server = session->is_server;
3181   is_nonblocking = session->is_nonblocking;
3182   vpp_handle = session->vpp_handle;
3183   state = session->state;
3184   if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN)))
3185     {
3186       rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
3187             VPPCOM_ENOTCONN);
3188
3189       clib_spinlock_unlock (&vcm->sessions_lockp);
3190       if (VPPCOM_DEBUG > 1)
3191         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3192                       "%s session is not open! state 0x%x (%s)",
3193                       getpid (), vpp_handle, session_index,
3194                       is_server ? "server" : "client", state,
3195                       vppcom_session_state_str (state));
3196       goto done;
3197     }
3198
3199   tx_fifo = ((!session->is_cut_thru || is_server) ?
3200              session->server_tx_fifo : session->server_rx_fifo);
3201   fifo_str = ((!session->is_cut_thru || is_server) ?
3202               "server_tx_fifo" : "server_rx_fifo");
3203   clib_spinlock_unlock (&vcm->sessions_lockp);
3204
3205   do
3206     {
3207       n_write = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
3208     }
3209   while (!is_nonblocking && (n_write <= 0));
3210
3211   /* If event wasn't set, add one */
3212   if (!session->is_cut_thru && (n_write > 0) && svm_fifo_set_event (tx_fifo))
3213     {
3214       /* Fabricate TX event, send to vpp */
3215       evt.fifo = tx_fifo;
3216       evt.event_type = FIFO_EVENT_APP_TX;
3217
3218       VCL_LOCK_AND_GET_SESSION (session_index, &session);
3219       q = session->vpp_event_queue;
3220       ASSERT (q);
3221       svm_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
3222       clib_spinlock_unlock (&vcm->sessions_lockp);
3223       if (VPPCOM_DEBUG > 1)
3224         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3225                       "added FIFO_EVENT_APP_TX to "
3226                       "vpp_event_q %p, n_write %d", getpid (),
3227                       vpp_handle, session_index, q, n_write);
3228     }
3229
3230   if (n_write <= 0)
3231     {
3232       VCL_LOCK_AND_GET_SESSION (session_index, &session);
3233
3234       poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
3235                  (EPOLLET | EPOLLOUT));
3236       if (poll_et)
3237         session->vep.et_mask |= EPOLLOUT;
3238
3239       if (state == STATE_CLOSE_ON_EMPTY)
3240         {
3241           session_state_t new_state = STATE_DISCONNECT;
3242           rv = VPPCOM_ECONNRESET;
3243
3244           if (VPPCOM_DEBUG > 1)
3245             {
3246               clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3247                             "Empty fifo with %s session state 0x%x (%s)!"
3248                             "  Setting state to 0x%x (%s), returning %d (%s)",
3249                             getpid (), vpp_handle, session_index,
3250                             is_server ? "server" : "client",
3251                             state, vppcom_session_state_str (state),
3252                             new_state, vppcom_session_state_str (new_state),
3253                             rv, vppcom_retval_str (rv));
3254             }
3255
3256           session->state = new_state;
3257         }
3258       else
3259         rv = VPPCOM_EAGAIN;
3260
3261       clib_spinlock_unlock (&vcm->sessions_lockp);
3262     }
3263   else
3264     rv = n_write;
3265
3266   if (VPPCOM_DEBUG > 2)
3267     {
3268       if (n_write <= 0)
3269         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3270                       "FIFO-FULL %s (%p)", getpid (), vpp_handle,
3271                       session_index, fifo_str, tx_fifo);
3272       else
3273         clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3274                       "wrote %d bytes to %s (%p)", getpid (), vpp_handle,
3275                       session_index, n_write, fifo_str, tx_fifo);
3276     }
3277 done:
3278   return rv;
3279 }
3280
3281 static inline int
3282 vppcom_session_write_ready (session_t * session, u32 session_index)
3283 {
3284   svm_fifo_t *tx_fifo;
3285   char *fifo_str;
3286   int ready;
3287   u32 poll_et;
3288   int rv;
3289   u8 is_server = session->is_server;
3290   session_state_t state = session->state;
3291
3292   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
3293   if (PREDICT_FALSE (session->is_vep))
3294     {
3295       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3296                     "cannot write to an epoll session!",
3297                     getpid (), session->vpp_handle, session_index);
3298       rv = VPPCOM_EBADFD;
3299       goto done;
3300     }
3301
3302   if (PREDICT_FALSE (session->is_listen))
3303     {
3304       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3305                     "cannot write to a listen session!",
3306                     getpid (), session->vpp_handle, session_index);
3307       rv = VPPCOM_EBADFD;
3308       goto done;
3309     }
3310
3311   if (!(state & (SERVER_STATE_OPEN | CLIENT_STATE_OPEN)))
3312     {
3313       session_state_t state = session->state;
3314
3315       rv = ((state == STATE_DISCONNECT) ? VPPCOM_ECONNRESET :
3316             VPPCOM_ENOTCONN);
3317
3318       clib_warning ("[%d] ERROR: vpp handle 0x%llx, sid %u: "
3319                     "%s session is not open! state 0x%x (%s), "
3320                     "returning %d (%s)", getpid (), session->vpp_handle,
3321                     session_index, is_server ? "server" : "client",
3322                     state, vppcom_session_state_str (state),
3323                     rv, vppcom_retval_str (rv));
3324       goto done;
3325     }
3326
3327   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
3328              session->server_tx_fifo : session->server_rx_fifo);
3329   fifo_str = ((!session->is_cut_thru || session->is_server) ?
3330               "server_tx_fifo" : "server_rx_fifo");
3331
3332   ready = svm_fifo_max_enqueue (tx_fifo);
3333
3334   if (VPPCOM_DEBUG > 3)
3335     clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3336                   "peek %s (%p), ready = %d", getpid (),
3337                   session->vpp_handle, session_index,
3338                   fifo_str, tx_fifo, ready);
3339
3340   if (ready == 0)
3341     {
3342       poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
3343                  (EPOLLET | EPOLLOUT));
3344       if (poll_et)
3345         session->vep.et_mask |= EPOLLOUT;
3346
3347       if (state == STATE_CLOSE_ON_EMPTY)
3348         {
3349           rv = VPPCOM_ECONNRESET;
3350           session_state_t new_state = STATE_DISCONNECT;
3351
3352           if (VPPCOM_DEBUG > 1)
3353             {
3354               clib_warning ("[%d] vpp handle 0x%llx, sid %u: "
3355                             "Empty fifo with %s session "
3356                             "state 0x%x (%s)! Setting state to 0x%x (%s), "
3357                             "returning %d (%s)", getpid (),
3358                             session->vpp_handle, session_index,
3359                             is_server ? "server" : "client",
3360                             state, vppcom_session_state_str (state),
3361                             new_state, vppcom_session_state_str (new_state),
3362                             rv, vppcom_retval_str (rv));
3363             }
3364           session->state = new_state;
3365           goto done;
3366         }
3367     }
3368   rv = ready;
3369 done:
3370   return rv;
3371 }
3372
3373 int
3374 vppcom_select (unsigned long n_bits, unsigned long *read_map,
3375                unsigned long *write_map, unsigned long *except_map,
3376                double time_to_wait)
3377 {
3378   u32 session_index;
3379   session_t *session = 0;
3380   int rv, bits_set = 0;
3381   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
3382   u32 minbits = clib_max (n_bits, BITS (uword));
3383
3384   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
3385
3386   if (n_bits && read_map)
3387     {
3388       clib_bitmap_validate (vcm->rd_bitmap, minbits);
3389       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
3390       memset (read_map, 0, vec_len (vcm->rd_bitmap));
3391     }
3392   if (n_bits && write_map)
3393     {
3394       clib_bitmap_validate (vcm->wr_bitmap, minbits);
3395       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
3396       memset (write_map, 0, vec_len (vcm->wr_bitmap));
3397     }
3398   if (n_bits && except_map)
3399     {
3400       clib_bitmap_validate (vcm->ex_bitmap, minbits);
3401       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
3402       memset (except_map, 0, vec_len (vcm->ex_bitmap));
3403     }
3404
3405   do
3406     {
3407       /* *INDENT-OFF* */
3408       if (n_bits)
3409         {
3410           if (read_map)
3411             {
3412               clib_bitmap_foreach (session_index, vcm->rd_bitmap,
3413                 ({
3414                   clib_spinlock_lock (&vcm->sessions_lockp);
3415                   rv = vppcom_session_at_index (session_index, &session);
3416                   if (rv < 0)
3417                     {
3418                       clib_spinlock_unlock (&vcm->sessions_lockp);
3419                       if (VPPCOM_DEBUG > 1)
3420                         clib_warning ("[%d] session %d specified in "
3421                                       "read_map is closed.", getpid (),
3422                                       session_index);
3423                       bits_set = VPPCOM_EBADFD;
3424                       goto select_done;
3425                     }
3426
3427                   rv = vppcom_session_read_ready (session, session_index);
3428                   clib_spinlock_unlock (&vcm->sessions_lockp);
3429                   if (except_map && vcm->ex_bitmap &&
3430                       clib_bitmap_get (vcm->ex_bitmap, session_index) &&
3431                       (rv < 0))
3432                     {
3433                       // TBD: clib_warning
3434                       clib_bitmap_set_no_check (except_map, session_index, 1);
3435                       bits_set++;
3436                     }
3437                   else if (rv > 0)
3438                     {
3439                       // TBD: clib_warning
3440                       clib_bitmap_set_no_check (read_map, session_index, 1);
3441                       bits_set++;
3442                     }
3443                 }));
3444             }
3445
3446           if (write_map)
3447             {
3448               clib_bitmap_foreach (session_index, vcm->wr_bitmap,
3449                 ({
3450                   clib_spinlock_lock (&vcm->sessions_lockp);
3451                   rv = vppcom_session_at_index (session_index, &session);
3452                   if (rv < 0)
3453                     {
3454                       clib_spinlock_unlock (&vcm->sessions_lockp);
3455                       if (VPPCOM_DEBUG > 0)
3456                         clib_warning ("[%d] session %d specified in "
3457                                       "write_map is closed.", getpid (),
3458                                       session_index);
3459                       bits_set = VPPCOM_EBADFD;
3460                       goto select_done;
3461                     }
3462
3463                   rv = vppcom_session_write_ready (session, session_index);
3464                   clib_spinlock_unlock (&vcm->sessions_lockp);
3465                   if (write_map && (rv > 0))
3466                     {
3467                       // TBD: clib_warning
3468                       clib_bitmap_set_no_check (write_map, session_index, 1);
3469                       bits_set++;
3470                     }
3471                 }));
3472             }
3473
3474           if (except_map)
3475             {
3476               clib_bitmap_foreach (session_index, vcm->ex_bitmap,
3477                 ({
3478                   clib_spinlock_lock (&vcm->sessions_lockp);
3479                   rv = vppcom_session_at_index (session_index, &session);
3480                   if (rv < 0)
3481                     {
3482                       clib_spinlock_unlock (&vcm->sessions_lockp);
3483                       if (VPPCOM_DEBUG > 1)
3484                         clib_warning ("[%d] session %d specified in "
3485                                       "except_map is closed.", getpid (),
3486                                       session_index);
3487                       bits_set = VPPCOM_EBADFD;
3488                       goto select_done;
3489                     }
3490
3491                   rv = vppcom_session_read_ready (session, session_index);
3492                   clib_spinlock_unlock (&vcm->sessions_lockp);
3493                   if (rv < 0)
3494                     {
3495                       // TBD: clib_warning
3496                       clib_bitmap_set_no_check (except_map, session_index, 1);
3497                       bits_set++;
3498                     }
3499                 }));
3500             }
3501         }
3502       /* *INDENT-ON* */
3503     }
3504   while (clib_time_now (&vcm->clib_time) < timeout);
3505
3506 select_done:
3507   return (bits_set);
3508 }
3509
3510 static inline void
3511 vep_verify_epoll_chain (u32 vep_idx)
3512 {
3513   session_t *session;
3514   vppcom_epoll_t *vep;
3515   int rv;
3516   u32 sid = vep_idx;
3517
3518   if (VPPCOM_DEBUG <= 1)
3519     return;
3520
3521   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
3522   rv = vppcom_session_at_index (vep_idx, &session);
3523   if (PREDICT_FALSE (rv))
3524     {
3525       clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", getpid (), vep_idx);
3526       goto done;
3527     }
3528   if (PREDICT_FALSE (!session->is_vep))
3529     {
3530       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!", getpid (),
3531                     vep_idx);
3532       goto done;
3533     }
3534   vep = &session->vep;
3535   clib_warning ("[%d] vep_idx (%u): Dumping epoll chain\n"
3536                 "{\n"
3537                 "   is_vep         = %u\n"
3538                 "   is_vep_session = %u\n"
3539                 "   next_sid       = 0x%x (%u)\n"
3540                 "   wait_cont_idx  = 0x%x (%u)\n"
3541                 "}\n", getpid (), vep_idx,
3542                 session->is_vep, session->is_vep_session,
3543                 vep->next_sid, vep->next_sid,
3544                 session->wait_cont_idx, session->wait_cont_idx);
3545
3546   for (sid = vep->next_sid; sid != ~0; sid = vep->next_sid)
3547     {
3548       rv = vppcom_session_at_index (sid, &session);
3549       if (PREDICT_FALSE (rv))
3550         {
3551           clib_warning ("[%d] ERROR: Invalid sid (%u)!", getpid (), sid);
3552           goto done;
3553         }
3554       if (PREDICT_FALSE (session->is_vep))
3555         clib_warning ("[%d] ERROR: sid (%u) is a vep!", getpid (), vep_idx);
3556       else if (PREDICT_FALSE (!session->is_vep_session))
3557         {
3558           clib_warning ("[%d] ERROR: session (%u) is not a vep session!",
3559                         getpid (), sid);
3560           goto done;
3561         }
3562       vep = &session->vep;
3563       if (PREDICT_FALSE (vep->vep_idx != vep_idx))
3564         clib_warning ("[%d] ERROR: session (%u) vep_idx (%u) != "
3565                       "vep_idx (%u)!", getpid (),
3566                       sid, session->vep.vep_idx, vep_idx);
3567       if (session->is_vep_session)
3568         {
3569           clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
3570                         "{\n"
3571                         "   next_sid       = 0x%x (%u)\n"
3572                         "   prev_sid       = 0x%x (%u)\n"
3573                         "   vep_idx        = 0x%x (%u)\n"
3574                         "   ev.events      = 0x%x\n"
3575                         "   ev.data.u64    = 0x%llx\n"
3576                         "   et_mask        = 0x%x\n"
3577                         "}\n",
3578                         vep_idx, sid, sid,
3579                         vep->next_sid, vep->next_sid,
3580                         vep->prev_sid, vep->prev_sid,
3581                         vep->vep_idx, vep->vep_idx,
3582                         vep->ev.events, vep->ev.data.u64, vep->et_mask);
3583         }
3584     }
3585
3586 done:
3587   clib_warning ("[%d] vep_idx (%u): Dump complete!\n", getpid (), vep_idx);
3588 }
3589
3590 int
3591 vppcom_epoll_create (void)
3592 {
3593   session_t *vep_session;
3594   u32 vep_idx;
3595
3596   clib_spinlock_lock (&vcm->sessions_lockp);
3597   pool_get (vcm->sessions, vep_session);
3598   memset (vep_session, 0, sizeof (*vep_session));
3599   vep_idx = vep_session - vcm->sessions;
3600
3601   vep_session->is_vep = 1;
3602   vep_session->vep.vep_idx = ~0;
3603   vep_session->vep.next_sid = ~0;
3604   vep_session->vep.prev_sid = ~0;
3605   vep_session->wait_cont_idx = ~0;
3606   vep_session->vpp_handle = ~0;
3607   clib_spinlock_unlock (&vcm->sessions_lockp);
3608
3609   if (VPPCOM_DEBUG > 0)
3610     clib_warning ("[%d] Created vep_idx %u / sid %u!",
3611                   getpid (), vep_idx, vep_idx);
3612
3613   if (VPPCOM_DEBUG > 0)
3614     {
3615       vep_session->elog_track.name =
3616         (char *) format (0, "C:%d:VEP:%d%c", vcm->my_client_index,
3617                          vep_idx, 0);
3618       elog_track_register (&vcm->elog_main, &vep_session->elog_track);
3619
3620       ELOG_TYPE_DECLARE (e) =
3621       {
3622       .format = "created epoll session:%d",.format_args = "i4",};
3623       struct
3624       {
3625         u32 data;
3626       } *ed;
3627       ed = ELOG_TRACK_DATA (&vcm->elog_main, e, vep_session->elog_track);
3628       ed->data = vep_idx;
3629     }
3630
3631   return (vep_idx);
3632 }
3633
3634 int
3635 vppcom_epoll_ctl (uint32_t vep_idx, int op, uint32_t session_index,
3636                   struct epoll_event *event)
3637 {
3638   session_t *vep_session;
3639   session_t *session;
3640   int rv;
3641
3642   if (vep_idx == session_index)
3643     {
3644       clib_warning ("[%d] ERROR: vep_idx == session_index (%u)!",
3645                     getpid (), vep_idx);
3646       return VPPCOM_EINVAL;
3647     }
3648
3649   clib_spinlock_lock (&vcm->sessions_lockp);
3650   rv = vppcom_session_at_index (vep_idx, &vep_session);
3651   if (PREDICT_FALSE (rv))
3652     {
3653       clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", vep_idx);
3654       goto done;
3655     }
3656   if (PREDICT_FALSE (!vep_session->is_vep))
3657     {
3658       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3659                     getpid (), vep_idx);
3660       rv = VPPCOM_EINVAL;
3661       goto done;
3662     }
3663
3664   ASSERT (vep_session->vep.vep_idx == ~0);
3665   ASSERT (vep_session->vep.prev_sid == ~0);
3666
3667   rv = vppcom_session_at_index (session_index, &session);
3668   if (PREDICT_FALSE (rv))
3669     {
3670       if (VPPCOM_DEBUG > 0)
3671         clib_warning ("[%d] ERROR: Invalid session_index (%u)!",
3672                       getpid (), session_index);
3673       goto done;
3674     }
3675   if (PREDICT_FALSE (session->is_vep))
3676     {
3677       clib_warning ("ERROR: session_index (%u) is a vep!", vep_idx);
3678       rv = VPPCOM_EINVAL;
3679       goto done;
3680     }
3681
3682   switch (op)
3683     {
3684     case EPOLL_CTL_ADD:
3685       if (PREDICT_FALSE (!event))
3686         {
3687           clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: NULL pointer to "
3688                         "epoll_event structure!", getpid ());
3689           rv = VPPCOM_EINVAL;
3690           goto done;
3691         }
3692       if (vep_session->vep.next_sid != ~0)
3693         {
3694           session_t *next_session;
3695           rv = vppcom_session_at_index (vep_session->vep.next_sid,
3696                                         &next_session);
3697           if (PREDICT_FALSE (rv))
3698             {
3699               clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: Invalid "
3700                             "vep.next_sid (%u) on vep_idx (%u)!",
3701                             getpid (), vep_session->vep.next_sid, vep_idx);
3702               goto done;
3703             }
3704           ASSERT (next_session->vep.prev_sid == vep_idx);
3705           next_session->vep.prev_sid = session_index;
3706         }
3707       session->vep.next_sid = vep_session->vep.next_sid;
3708       session->vep.prev_sid = vep_idx;
3709       session->vep.vep_idx = vep_idx;
3710       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3711       session->vep.ev = *event;
3712       session->is_vep = 0;
3713       session->is_vep_session = 1;
3714       vep_session->vep.next_sid = session_index;
3715       if (VPPCOM_DEBUG > 1)
3716         clib_warning ("[%d] EPOLL_CTL_ADD: vep_idx %u, sid %u, events 0x%x,"
3717                       " data 0x%llx!", getpid (), vep_idx, session_index,
3718                       event->events, event->data.u64);
3719       break;
3720
3721     case EPOLL_CTL_MOD:
3722       if (PREDICT_FALSE (!event))
3723         {
3724           clib_warning ("[%d] ERROR: EPOLL_CTL_MOD: NULL pointer to "
3725                         "epoll_event structure!", getpid ());
3726           rv = VPPCOM_EINVAL;
3727           goto done;
3728         }
3729       else if (PREDICT_FALSE (!session->is_vep_session))
3730         {
3731           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_MOD: "
3732                         "not a vep session!", getpid (), session_index);
3733           rv = VPPCOM_EINVAL;
3734           goto done;
3735         }
3736       else if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
3737         {
3738           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_MOD: "
3739                         "vep_idx (%u) != vep_idx (%u)!",
3740                         getpid (), session_index,
3741                         session->vep.vep_idx, vep_idx);
3742           rv = VPPCOM_EINVAL;
3743           goto done;
3744         }
3745       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3746       session->vep.ev = *event;
3747       if (VPPCOM_DEBUG > 1)
3748         clib_warning ("[%d] EPOLL_CTL_MOD: vep_idx %u, sid %u, events 0x%x,"
3749                       " data 0x%llx!", getpid (), vep_idx, session_index,
3750                       event->events, event->data.u64);
3751       break;
3752
3753     case EPOLL_CTL_DEL:
3754       if (PREDICT_FALSE (!session->is_vep_session))
3755         {
3756           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_DEL: "
3757                         "not a vep session!", getpid (), session_index);
3758           rv = VPPCOM_EINVAL;
3759           goto done;
3760         }
3761       else if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
3762         {
3763           clib_warning ("[%d] ERROR: sid %u EPOLL_CTL_DEL: "
3764                         "vep_idx (%u) != vep_idx (%u)!",
3765                         getpid (), session_index,
3766                         session->vep.vep_idx, vep_idx);
3767           rv = VPPCOM_EINVAL;
3768           goto done;
3769         }
3770
3771       vep_session->wait_cont_idx =
3772         (vep_session->wait_cont_idx == session_index) ?
3773         session->vep.next_sid : vep_session->wait_cont_idx;
3774
3775       if (session->vep.prev_sid == vep_idx)
3776         vep_session->vep.next_sid = session->vep.next_sid;
3777       else
3778         {
3779           session_t *prev_session;
3780           rv = vppcom_session_at_index (session->vep.prev_sid, &prev_session);
3781           if (PREDICT_FALSE (rv))
3782             {
3783               clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3784                             "vep.prev_sid (%u) on sid (%u)!",
3785                             getpid (), session->vep.prev_sid, session_index);
3786               goto done;
3787             }
3788           ASSERT (prev_session->vep.next_sid == session_index);
3789           prev_session->vep.next_sid = session->vep.next_sid;
3790         }
3791       if (session->vep.next_sid != ~0)
3792         {
3793           session_t *next_session;
3794           rv = vppcom_session_at_index (session->vep.next_sid, &next_session);
3795           if (PREDICT_FALSE (rv))
3796             {
3797               clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3798                             "vep.next_sid (%u) on sid (%u)!",
3799                             getpid (), session->vep.next_sid, session_index);
3800               goto done;
3801             }
3802           ASSERT (next_session->vep.prev_sid == session_index);
3803           next_session->vep.prev_sid = session->vep.prev_sid;
3804         }
3805
3806       memset (&session->vep, 0, sizeof (session->vep));
3807       session->vep.next_sid = ~0;
3808       session->vep.prev_sid = ~0;
3809       session->vep.vep_idx = ~0;
3810       session->is_vep_session = 0;
3811       if (VPPCOM_DEBUG > 1)
3812         clib_warning ("[%d] EPOLL_CTL_DEL: vep_idx %u, sid %u!",
3813                       getpid (), vep_idx, session_index);
3814       break;
3815
3816     default:
3817       clib_warning ("[%d] ERROR: Invalid operation (%d)!", getpid (), op);
3818       rv = VPPCOM_EINVAL;
3819     }
3820
3821   vep_verify_epoll_chain (vep_idx);
3822
3823 done:
3824   clib_spinlock_unlock (&vcm->sessions_lockp);
3825   return rv;
3826 }
3827
3828 int
3829 vppcom_epoll_wait (uint32_t vep_idx, struct epoll_event *events,
3830                    int maxevents, double wait_for_time)
3831 {
3832   session_t *vep_session;
3833   int rv;
3834   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
3835   u32 keep_trying = 1;
3836   int num_ev = 0;
3837   u32 vep_next_sid, wait_cont_idx;
3838   u8 is_vep;
3839
3840   if (PREDICT_FALSE (maxevents <= 0))
3841     {
3842       clib_warning ("[%d] ERROR: Invalid maxevents (%d)!",
3843                     getpid (), maxevents);
3844       return VPPCOM_EINVAL;
3845     }
3846   memset (events, 0, sizeof (*events) * maxevents);
3847
3848   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3849   vep_next_sid = vep_session->vep.next_sid;
3850   is_vep = vep_session->is_vep;
3851   wait_cont_idx = vep_session->wait_cont_idx;
3852   clib_spinlock_unlock (&vcm->sessions_lockp);
3853
3854   if (PREDICT_FALSE (!is_vep))
3855     {
3856       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3857                     getpid (), vep_idx);
3858       rv = VPPCOM_EINVAL;
3859       goto done;
3860     }
3861   if (PREDICT_FALSE (vep_next_sid == ~0))
3862     {
3863       if (VPPCOM_DEBUG > 0)
3864         clib_warning ("[%d] WARNING: vep_idx (%u) is empty!",
3865                       getpid (), vep_idx);
3866       goto done;
3867     }
3868
3869   do
3870     {
3871       u32 sid;
3872       u32 next_sid = ~0;
3873       session_t *session;
3874
3875       for (sid = (wait_cont_idx == ~0) ? vep_next_sid : wait_cont_idx;
3876            sid != ~0; sid = next_sid)
3877         {
3878           u32 session_events, et_mask, clear_et_mask, session_vep_idx;
3879           u8 add_event, is_vep_session;
3880           int ready;
3881           u64 session_ev_data;
3882
3883           VCL_LOCK_AND_GET_SESSION (sid, &session);
3884           next_sid = session->vep.next_sid;
3885           session_events = session->vep.ev.events;
3886           et_mask = session->vep.et_mask;
3887           is_vep = session->is_vep;
3888           is_vep_session = session->is_vep_session;
3889           session_vep_idx = session->vep.vep_idx;
3890           session_ev_data = session->vep.ev.data.u64;
3891           clib_spinlock_unlock (&vcm->sessions_lockp);
3892
3893           if (PREDICT_FALSE (is_vep))
3894             {
3895               if (VPPCOM_DEBUG > 0)
3896                 clib_warning ("[%d] ERROR: sid (%u) is a vep!",
3897                               getpid (), vep_idx);
3898               rv = VPPCOM_EINVAL;
3899               goto done;
3900             }
3901           if (PREDICT_FALSE (!is_vep_session))
3902             {
3903               if (VPPCOM_DEBUG > 0)
3904                 clib_warning ("[%d] ERROR: session (%u) is not "
3905                               "a vep session!", getpid (), sid);
3906               rv = VPPCOM_EINVAL;
3907               goto done;
3908             }
3909           if (PREDICT_FALSE (session_vep_idx != vep_idx))
3910             {
3911               clib_warning ("[%d] ERROR: session (%u) "
3912                             "vep_idx (%u) != vep_idx (%u)!",
3913                             getpid (), sid, session->vep.vep_idx, vep_idx);
3914               rv = VPPCOM_EINVAL;
3915               goto done;
3916             }
3917
3918           add_event = clear_et_mask = 0;
3919
3920           if (EPOLLIN & session_events)
3921             {
3922               VCL_LOCK_AND_GET_SESSION (sid, &session);
3923               ready = vppcom_session_read_ready (session, sid);
3924               clib_spinlock_unlock (&vcm->sessions_lockp);
3925               if ((ready > 0) && (EPOLLIN & et_mask))
3926                 {
3927                   add_event = 1;
3928                   events[num_ev].events |= EPOLLIN;
3929                   if (((EPOLLET | EPOLLIN) & session_events) ==
3930                       (EPOLLET | EPOLLIN))
3931                     clear_et_mask |= EPOLLIN;
3932                 }
3933               else if (ready < 0)
3934                 {
3935                   add_event = 1;
3936                   switch (ready)
3937                     {
3938                     case VPPCOM_ECONNRESET:
3939                       events[num_ev].events |= EPOLLHUP | EPOLLRDHUP;
3940                       break;
3941
3942                     default:
3943                       events[num_ev].events |= EPOLLERR;
3944                       break;
3945                     }
3946                 }
3947             }
3948
3949           if (EPOLLOUT & session_events)
3950             {
3951               VCL_LOCK_AND_GET_SESSION (sid, &session);
3952               ready = vppcom_session_write_ready (session, sid);
3953               clib_spinlock_unlock (&vcm->sessions_lockp);
3954               if ((ready > 0) && (EPOLLOUT & et_mask))
3955                 {
3956                   add_event = 1;
3957                   events[num_ev].events |= EPOLLOUT;
3958                   if (((EPOLLET | EPOLLOUT) & session_events) ==
3959                       (EPOLLET | EPOLLOUT))
3960                     clear_et_mask |= EPOLLOUT;
3961                 }
3962               else if (ready < 0)
3963                 {
3964                   add_event = 1;
3965                   switch (ready)
3966                     {
3967                     case VPPCOM_ECONNRESET:
3968                       events[num_ev].events |= EPOLLHUP;
3969                       break;
3970
3971                     default:
3972                       events[num_ev].events |= EPOLLERR;
3973                       break;
3974                     }
3975                 }
3976             }
3977
3978           if (add_event)
3979             {
3980               events[num_ev].data.u64 = session_ev_data;
3981               if (EPOLLONESHOT & session_events)
3982                 {
3983                   VCL_LOCK_AND_GET_SESSION (sid, &session);
3984                   session->vep.ev.events = 0;
3985                   clib_spinlock_unlock (&vcm->sessions_lockp);
3986                 }
3987               num_ev++;
3988               if (num_ev == maxevents)
3989                 {
3990                   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3991                   vep_session->wait_cont_idx = next_sid;
3992                   clib_spinlock_unlock (&vcm->sessions_lockp);
3993                   goto done;
3994                 }
3995             }
3996           if (wait_cont_idx != ~0)
3997             {
3998               if (next_sid == ~0)
3999                 next_sid = vep_next_sid;
4000               else if (next_sid == wait_cont_idx)
4001                 next_sid = ~0;
4002             }
4003         }
4004       if (wait_for_time != -1)
4005         keep_trying = (clib_time_now (&vcm->clib_time) <= timeout) ? 1 : 0;
4006     }
4007   while ((num_ev == 0) && keep_trying);
4008
4009   if (wait_cont_idx != ~0)
4010     {
4011       VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
4012       vep_session->wait_cont_idx = ~0;
4013       clib_spinlock_unlock (&vcm->sessions_lockp);
4014     }
4015 done:
4016   return (rv != VPPCOM_OK) ? rv : num_ev;
4017 }
4018
4019 int
4020 vppcom_session_attr (uint32_t session_index, uint32_t op,
4021                      void *buffer, uint32_t * buflen)
4022 {
4023   session_t *session;
4024   int rv = VPPCOM_OK;
4025   u32 *flags = buffer;
4026   vppcom_endpt_t *ep = buffer;
4027
4028   VCL_LOCK_AND_GET_SESSION (session_index, &session);
4029   switch (op)
4030     {
4031     case VPPCOM_ATTR_GET_NREAD:
4032       rv = vppcom_session_read_ready (session, session_index);
4033       if (VPPCOM_DEBUG > 2)
4034         clib_warning ("[%d] VPPCOM_ATTR_GET_NREAD: sid %u, nread = %d",
4035                       getpid (), rv);
4036       break;
4037
4038     case VPPCOM_ATTR_GET_NWRITE:
4039       rv = vppcom_session_write_ready (session, session_index);
4040       if (VPPCOM_DEBUG > 2)
4041         clib_warning ("[%d] VPPCOM_ATTR_GET_NWRITE: sid %u, nwrite = %d",
4042                       getpid (), session_index, rv);
4043       break;
4044
4045     case VPPCOM_ATTR_GET_FLAGS:
4046       if (buffer && buflen && (*buflen >= sizeof (*flags)))
4047         {
4048           *flags = O_RDWR | ((session->is_nonblocking) ? O_NONBLOCK : 0);
4049           *buflen = sizeof (*flags);
4050           if (VPPCOM_DEBUG > 2)
4051             clib_warning ("[%d] VPPCOM_ATTR_GET_FLAGS: sid %u, "
4052                           "flags = 0x%08x, is_nonblocking = %u", getpid (),
4053                           session_index, *flags, session->is_nonblocking);
4054         }
4055       else
4056         rv = VPPCOM_EINVAL;
4057       break;
4058
4059     case VPPCOM_ATTR_SET_FLAGS:
4060       if (buffer && buflen && (*buflen >= sizeof (*flags)))
4061         {
4062           session->is_nonblocking = (*flags & O_NONBLOCK) ? 1 : 0;
4063           if (VPPCOM_DEBUG > 2)
4064             clib_warning ("[%d] VPPCOM_ATTR_SET_FLAGS: sid %u, "
4065                           "flags = 0x%08x, is_nonblocking = %u",
4066                           getpid (), session_index, *flags,
4067                           session->is_nonblocking);
4068         }
4069       else
4070         rv = VPPCOM_EINVAL;
4071       break;
4072
4073     case VPPCOM_ATTR_GET_PEER_ADDR:
4074       if (buffer && buflen && (*buflen >= sizeof (*ep)) && ep->ip)
4075         {
4076           ep->vrf = session->vrf;
4077           ep->is_ip4 = session->peer_addr.is_ip4;
4078           ep->port = session->peer_port;
4079           if (session->peer_addr.is_ip4)
4080             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
4081                          sizeof (ip4_address_t));
4082           else
4083             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
4084                          sizeof (ip6_address_t));
4085           *buflen = sizeof (*ep);
4086           if (VPPCOM_DEBUG > 1)
4087             clib_warning ("[%d] VPPCOM_ATTR_GET_PEER_ADDR: sid %u, is_ip4 = "
4088                           "%u, addr = %U, port %u", getpid (),
4089                           session_index, ep->is_ip4, format_ip46_address,
4090                           &session->peer_addr.ip46, ep->is_ip4,
4091                           clib_net_to_host_u16 (ep->port));
4092         }
4093       else
4094         rv = VPPCOM_EINVAL;
4095       break;
4096
4097     case VPPCOM_ATTR_GET_LCL_ADDR:
4098       if (buffer && buflen && (*buflen >= sizeof (*ep)) && ep->ip)
4099         {
4100           ep->vrf = session->vrf;
4101           ep->is_ip4 = session->lcl_addr.is_ip4;
4102           ep->port = session->lcl_port;
4103           if (session->lcl_addr.is_ip4)
4104             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip4,
4105                          sizeof (ip4_address_t));
4106           else
4107             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip6,
4108                          sizeof (ip6_address_t));
4109           *buflen = sizeof (*ep);
4110           if (VPPCOM_DEBUG > 1)
4111             clib_warning ("[%d] VPPCOM_ATTR_GET_LCL_ADDR: sid %u, is_ip4 = "
4112                           "%u, addr = %U port %d", getpid (),
4113                           session_index, ep->is_ip4, format_ip46_address,
4114                           &session->lcl_addr.ip46, ep->is_ip4,
4115                           clib_net_to_host_u16 (ep->port));
4116         }
4117       else
4118         rv = VPPCOM_EINVAL;
4119       break;
4120
4121     case VPPCOM_ATTR_SET_REUSEADDR:
4122       break;
4123
4124     case VPPCOM_ATTR_SET_BROADCAST:
4125       break;
4126
4127     case VPPCOM_ATTR_SET_V6ONLY:
4128       break;
4129
4130     case VPPCOM_ATTR_SET_KEEPALIVE:
4131       break;
4132
4133     case VPPCOM_ATTR_SET_TCP_KEEPIDLE:
4134       break;
4135
4136     case VPPCOM_ATTR_SET_TCP_KEEPINTVL:
4137       break;
4138
4139     default:
4140       rv = VPPCOM_EINVAL;
4141       break;
4142     }
4143
4144 done:
4145   clib_spinlock_unlock (&vcm->sessions_lockp);
4146   return rv;
4147 }
4148
4149 int
4150 vppcom_session_recvfrom (uint32_t session_index, void *buffer,
4151                          uint32_t buflen, int flags, vppcom_endpt_t * ep)
4152 {
4153   int rv = VPPCOM_OK;
4154   session_t *session = 0;
4155
4156   if (ep)
4157     {
4158       clib_spinlock_lock (&vcm->sessions_lockp);
4159       rv = vppcom_session_at_index (session_index, &session);
4160       if (PREDICT_FALSE (rv))
4161         {
4162           clib_spinlock_unlock (&vcm->sessions_lockp);
4163           if (VPPCOM_DEBUG > 0)
4164             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
4165                           getpid (), session_index);
4166           rv = VPPCOM_EBADFD;
4167           clib_spinlock_unlock (&vcm->sessions_lockp);
4168           goto done;
4169         }
4170       ep->vrf = session->vrf;
4171       ep->is_ip4 = session->peer_addr.is_ip4;
4172       ep->port = session->peer_port;
4173       if (session->peer_addr.is_ip4)
4174         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
4175                      sizeof (ip4_address_t));
4176       else
4177         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
4178                      sizeof (ip6_address_t));
4179       clib_spinlock_unlock (&vcm->sessions_lockp);
4180     }
4181
4182   if (flags == 0)
4183     rv = vppcom_session_read (session_index, buffer, buflen);
4184   else if (flags & MSG_PEEK)
4185     rv = vppcom_session_peek (session_index, buffer, buflen);
4186   else
4187     {
4188       clib_warning ("[%d] Unsupport flags for recvfrom %d", getpid (), flags);
4189       rv = VPPCOM_EAFNOSUPPORT;
4190     }
4191
4192 done:
4193   return rv;
4194 }
4195
4196 int
4197 vppcom_session_sendto (uint32_t session_index, void *buffer,
4198                        uint32_t buflen, int flags, vppcom_endpt_t * ep)
4199 {
4200   if (!buffer)
4201     return VPPCOM_EINVAL;
4202
4203   if (ep)
4204     {
4205       // TBD
4206       return VPPCOM_EINVAL;
4207     }
4208
4209   if (flags)
4210     {
4211       // TBD check the flags and do the right thing
4212       if (VPPCOM_DEBUG > 2)
4213         clib_warning ("[%d] handling flags 0x%u (%d) not implemented yet.",
4214                       getpid (), flags, flags);
4215     }
4216
4217   return (vppcom_session_write (session_index, buffer, buflen));
4218 }
4219
4220 /*
4221  * fd.io coding-style-patch-verification: ON
4222  *
4223  * Local Variables:
4224  * eval: (c-set-style "gnu")
4225  * End:
4226  */