session: add support for application namespacing
[vpp.git] / src / uri / 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 <uri/vppcom.h>
24 #include <vlib/unix/unix.h>
25 #include <vppinfra/vec_bootstrap.h>
26
27 #define vl_typedefs             /* define message structures */
28 #include <vpp/api/vpe_all_api_h.h>
29 #undef vl_typedefs
30
31 /* declare message handlers for each api */
32
33 #define vl_endianfun            /* define message structures */
34 #include <vpp/api/vpe_all_api_h.h>
35 #undef vl_endianfun
36
37 /* instantiate all the print functions we know about */
38 #define vl_print(handle, ...)
39 #define vl_printfun
40 #include <vpp/api/vpe_all_api_h.h>
41 #undef vl_printfun
42
43 #if (CLIB_DEBUG > 0)
44 /* Set VPPCOM_DEBUG 2 for connection debug, 3 for read/write debug output */
45 #define VPPCOM_DEBUG 1
46 #else
47 #define VPPCOM_DEBUG 0
48 #endif
49
50 /*
51  * VPPCOM Private definitions and functions.
52  */
53 typedef enum
54 {
55   STATE_APP_START,
56   STATE_APP_CONN_VPP,
57   STATE_APP_ENABLED,
58   STATE_APP_ATTACHED,
59 } app_state_t;
60
61 typedef enum
62 {
63   STATE_START,
64   STATE_CONNECT,
65   STATE_LISTEN,
66   STATE_ACCEPT,
67   STATE_DISCONNECT,
68   STATE_FAILED
69 } session_state_t;
70
71 typedef struct epoll_event vppcom_epoll_event_t;
72
73 typedef struct
74 {
75   u32 next_sid;
76   u32 prev_sid;
77   u32 vep_idx;
78   vppcom_epoll_event_t ev;
79 #define VEP_DEFAULT_ET_MASK  (EPOLLIN|EPOLLOUT)
80   u32 et_mask;
81 } vppcom_epoll_t;
82
83 typedef struct
84 {
85   volatile session_state_t state;
86
87   svm_fifo_t *server_rx_fifo;
88   svm_fifo_t *server_tx_fifo;
89   u32 sm_seg_index;
90   u64 vpp_session_handle;
91   unix_shared_memory_queue_t *vpp_event_queue;
92
93   /* Socket configuration state */
94   /* TBD: covert 'is_*' vars to bit in u8 flags; */
95   u8 is_server;
96   u8 is_listen;
97   u8 is_cut_thru;
98   u8 is_nonblocking;
99   u8 is_vep;
100   u8 is_vep_session;
101   u32 wait_cont_idx;
102   vppcom_epoll_t vep;
103   u32 vrf;
104   u8 is_ip4;
105   u8 ip[16];
106   u16 port;
107   u8 proto;
108   u64 client_queue_address;
109   u64 options[16];
110 } session_t;
111
112 typedef struct vppcom_cfg_t_
113 {
114   u64 heapsize;
115   u64 segment_baseva;
116   u32 segment_size;
117   u32 add_segment_size;
118   u32 preallocated_fifo_pairs;
119   u32 rx_fifo_size;
120   u32 tx_fifo_size;
121   u32 event_queue_size;
122   u32 listen_queue_size;
123   f64 app_timeout;
124   f64 session_timeout;
125   f64 accept_timeout;
126 } vppcom_cfg_t;
127
128 typedef struct vppcom_main_t_
129 {
130   u8 init;
131   u32 *client_session_index_fifo;
132   volatile u32 bind_session_index;
133   u32 tx_event_id;
134   int main_cpu;
135
136   /* vpe input queue */
137   unix_shared_memory_queue_t *vl_input_queue;
138
139   /* API client handle */
140   u32 my_client_index;
141
142   /* Session pool */
143   clib_spinlock_t sessions_lockp;
144   session_t *sessions;
145
146   /* Hash table for disconnect processing */
147   uword *session_index_by_vpp_handles;
148
149   /* Select bitmaps */
150   clib_bitmap_t *rd_bitmap;
151   clib_bitmap_t *wr_bitmap;
152   clib_bitmap_t *ex_bitmap;
153
154   /* Our event queue */
155   unix_shared_memory_queue_t *app_event_queue;
156
157   /* unique segment name counter */
158   u32 unique_segment_index;
159
160   pid_t my_pid;
161
162   /* For deadman timers */
163   clib_time_t clib_time;
164
165   /* State of the connection, shared between msg RX thread and main thread */
166   volatile app_state_t app_state;
167
168   vppcom_cfg_t cfg;
169
170   /* VNET_API_ERROR_FOO -> "Foo" hash table */
171   uword *error_string_by_error_number;
172 } vppcom_main_t;
173
174 vppcom_main_t vppcom_main = {.my_client_index = ~0 };
175
176 static const char *
177 vppcom_app_state_str (app_state_t state)
178 {
179   char *st;
180
181   switch (state)
182     {
183     case STATE_APP_START:
184       st = "STATE_APP_START";
185       break;
186
187     case STATE_APP_CONN_VPP:
188       st = "STATE_APP_CONN_VPP";
189       break;
190
191     case STATE_APP_ENABLED:
192       st = "STATE_APP_ENABLED";
193       break;
194
195     case STATE_APP_ATTACHED:
196       st = "STATE_APP_ATTACHED";
197       break;
198
199     default:
200       st = "UNKNOWN_APP_STATE";
201       break;
202     }
203
204   return st;
205 }
206
207 static const char *
208 vppcom_session_state_str (session_state_t state)
209 {
210   char *st;
211
212   switch (state)
213     {
214     case STATE_START:
215       st = "STATE_START";
216       break;
217
218     case STATE_CONNECT:
219       st = "STATE_CONNECT";
220       break;
221
222     case STATE_LISTEN:
223       st = "STATE_LISTEN";
224       break;
225
226     case STATE_ACCEPT:
227       st = "STATE_ACCEPT";
228       break;
229
230     case STATE_DISCONNECT:
231       st = "STATE_DISCONNECT";
232       break;
233
234     case STATE_FAILED:
235       st = "STATE_FAILED";
236       break;
237
238     default:
239       st = "UNKNOWN_STATE";
240       break;
241     }
242
243   return st;
244 }
245
246 /*
247  * VPPCOM Utility Functions
248  */
249 static inline int
250 vppcom_session_at_index (u32 session_index, session_t * volatile *sess)
251 {
252   vppcom_main_t *vcm = &vppcom_main;
253
254   /* Assumes that caller has acquired spinlock: vcm->sessions_lockp */
255   if (PREDICT_FALSE ((session_index == ~0) ||
256                      pool_is_free_index (vcm->sessions, session_index)))
257     {
258       clib_warning ("[%d] invalid session, sid (%u) has been closed!",
259                     vcm->my_pid, session_index);
260       return VPPCOM_EBADFD;
261     }
262   *sess = pool_elt_at_index (vcm->sessions, session_index);
263   return VPPCOM_OK;
264 }
265
266 static int
267 vppcom_connect_to_vpp (char *app_name)
268 {
269   api_main_t *am = &api_main;
270   vppcom_main_t *vcm = &vppcom_main;
271
272   if (VPPCOM_DEBUG > 0)
273     printf ("\nConnecting to VPP api...");
274   if (vl_client_connect_to_vlib ("/vpe-api", app_name, 32) < 0)
275     {
276       clib_warning ("[%d] connect to vpp (%s) failed!",
277                     vcm->my_pid, app_name);
278       return VPPCOM_ECONNREFUSED;
279     }
280
281   vcm->vl_input_queue = am->shmem_hdr->vl_input_queue;
282   vcm->my_client_index = am->my_client_index;
283   if (VPPCOM_DEBUG > 0)
284     printf (" connected!\n");
285
286   vcm->app_state = STATE_APP_CONN_VPP;
287   return VPPCOM_OK;
288 }
289
290 static u8 *
291 format_api_error (u8 * s, va_list * args)
292 {
293   vppcom_main_t *vcm = &vppcom_main;
294   i32 error = va_arg (*args, u32);
295   uword *p;
296
297   p = hash_get (vcm->error_string_by_error_number, -error);
298
299   if (p)
300     s = format (s, "%s (%d)", p[0], error);
301   else
302     s = format (s, "%d", error);
303   return s;
304 }
305
306 static void
307 vppcom_init_error_string_table (void)
308 {
309   vppcom_main_t *vcm = &vppcom_main;
310
311   vcm->error_string_by_error_number = hash_create (0, sizeof (uword));
312
313 #define _(n,v,s) hash_set (vcm->error_string_by_error_number, -v, s);
314   foreach_vnet_api_error;
315 #undef _
316
317   hash_set (vcm->error_string_by_error_number, 99, "Misc");
318 }
319
320 static inline int
321 vppcom_wait_for_app_state_change (app_state_t app_state)
322 {
323   vppcom_main_t *vcm = &vppcom_main;
324   f64 timeout = clib_time_now (&vcm->clib_time) + vcm->cfg.app_timeout;
325
326   while (clib_time_now (&vcm->clib_time) < timeout)
327     {
328       if (vcm->app_state == app_state)
329         return VPPCOM_OK;
330     }
331   if (VPPCOM_DEBUG > 0)
332     clib_warning ("[%d] timeout waiting for state %s (%d)", vcm->my_pid,
333                   vppcom_app_state_str (app_state), app_state);
334   return VPPCOM_ETIMEDOUT;
335 }
336
337 static inline int
338 vppcom_wait_for_session_state_change (u32 session_index,
339                                       session_state_t state,
340                                       f64 wait_for_time)
341 {
342   vppcom_main_t *vcm = &vppcom_main;
343   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
344   session_t *volatile session;
345   int rv;
346
347   do
348     {
349       clib_spinlock_lock (&vcm->sessions_lockp);
350       rv = vppcom_session_at_index (session_index, &session);
351       if (PREDICT_FALSE (rv))
352         {
353           clib_spinlock_unlock (&vcm->sessions_lockp);
354           return rv;
355         }
356       if (session->state == state)
357         {
358           clib_spinlock_unlock (&vcm->sessions_lockp);
359           return VPPCOM_OK;
360         }
361       clib_spinlock_unlock (&vcm->sessions_lockp);
362     }
363   while (clib_time_now (&vcm->clib_time) < timeout);
364
365   if (VPPCOM_DEBUG > 0)
366     clib_warning ("[%d] timeout waiting for state %s (%d)", vcm->my_pid,
367                   vppcom_session_state_str (state), state);
368   return VPPCOM_ETIMEDOUT;
369 }
370
371 static inline int
372 vppcom_wait_for_client_session_index (f64 wait_for_time)
373 {
374   vppcom_main_t *vcm = &vppcom_main;
375   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
376
377   do
378     {
379       if (clib_fifo_elts (vcm->client_session_index_fifo))
380         return VPPCOM_OK;
381     }
382   while (clib_time_now (&vcm->clib_time) < timeout);
383
384   if (wait_for_time == 0)
385     return VPPCOM_EAGAIN;
386
387   if (VPPCOM_DEBUG > 0)
388     clib_warning ("[%d] timeout waiting for client_session_index",
389                   vcm->my_pid);
390   return VPPCOM_ETIMEDOUT;
391 }
392
393 /*
394  * VPP-API message functions
395  */
396 static void
397 vppcom_send_session_enable_disable (u8 is_enable)
398 {
399   vppcom_main_t *vcm = &vppcom_main;
400   vl_api_session_enable_disable_t *bmp;
401   bmp = vl_msg_api_alloc (sizeof (*bmp));
402   memset (bmp, 0, sizeof (*bmp));
403
404   bmp->_vl_msg_id = ntohs (VL_API_SESSION_ENABLE_DISABLE);
405   bmp->client_index = vcm->my_client_index;
406   bmp->context = htonl (0xfeedface);
407   bmp->is_enable = is_enable;
408   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
409 }
410
411 static int
412 vppcom_app_session_enable (void)
413 {
414   vppcom_main_t *vcm = &vppcom_main;
415   int rv;
416
417   if (vcm->app_state != STATE_APP_ENABLED)
418     {
419       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
420       rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
421       if (PREDICT_FALSE (rv))
422         {
423           if (VPPCOM_DEBUG > 0)
424             clib_warning ("[%d] Session enable timed out, rv = %s (%d)",
425                           vcm->my_pid, vppcom_retval_str (rv), rv);
426           return rv;
427         }
428     }
429   return VPPCOM_OK;
430 }
431
432 static void
433   vl_api_session_enable_disable_reply_t_handler
434   (vl_api_session_enable_disable_reply_t * mp)
435 {
436   vppcom_main_t *vcm = &vppcom_main;
437
438   if (mp->retval)
439     {
440       clib_warning ("[%d] session_enable_disable failed: %U", vcm->my_pid,
441                     format_api_error, ntohl (mp->retval));
442     }
443   else
444     vcm->app_state = STATE_APP_ENABLED;
445 }
446
447 static void
448 vppcom_app_send_attach (void)
449 {
450   vppcom_main_t *vcm = &vppcom_main;
451   vl_api_application_attach_t *bmp;
452   bmp = vl_msg_api_alloc (sizeof (*bmp));
453   memset (bmp, 0, sizeof (*bmp));
454
455   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
456   bmp->client_index = vcm->my_client_index;
457   bmp->context = htonl (0xfeedface);
458   bmp->options[APP_OPTIONS_FLAGS] =
459     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT |
460     APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE | APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
461   bmp->options[SESSION_OPTIONS_SEGMENT_SIZE] = vcm->cfg.segment_size;
462   bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = vcm->cfg.add_segment_size;
463   bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = vcm->cfg.rx_fifo_size;
464   bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = vcm->cfg.tx_fifo_size;
465   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
466 }
467
468 static int
469 vppcom_app_attach (void)
470 {
471   vppcom_main_t *vcm = &vppcom_main;
472   int rv;
473
474   vppcom_app_send_attach ();
475   rv = vppcom_wait_for_app_state_change (STATE_APP_ATTACHED);
476   if (PREDICT_FALSE (rv))
477     {
478       if (VPPCOM_DEBUG > 0)
479         clib_warning ("[%d] application attach timed out, rv = %s (%d)",
480                       vcm->my_pid, vppcom_retval_str (rv), rv);
481       return rv;
482     }
483   return VPPCOM_OK;
484 }
485
486 static void
487 vppcom_app_detach (void)
488 {
489   vppcom_main_t *vcm = &vppcom_main;
490   vl_api_application_detach_t *bmp;
491   bmp = vl_msg_api_alloc (sizeof (*bmp));
492   memset (bmp, 0, sizeof (*bmp));
493
494   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
495   bmp->client_index = vcm->my_client_index;
496   bmp->context = htonl (0xfeedface);
497   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
498 }
499
500 static void
501 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
502                                            mp)
503 {
504   vppcom_main_t *vcm = &vppcom_main;
505   static svm_fifo_segment_create_args_t _a;
506   svm_fifo_segment_create_args_t *a = &_a;
507   int rv;
508
509   memset (a, 0, sizeof (*a));
510   if (mp->retval)
511     {
512       clib_warning ("[%d] attach failed: %U", vcm->my_pid,
513                     format_api_error, ntohl (mp->retval));
514       return;
515     }
516
517   if (mp->segment_name_length == 0)
518     {
519       clib_warning ("[%d] segment_name_length zero", vcm->my_pid);
520       return;
521     }
522
523   a->segment_name = (char *) mp->segment_name;
524   a->segment_size = mp->segment_size;
525
526   ASSERT (mp->app_event_queue_address);
527
528   /* Attach to the segment vpp created */
529   rv = svm_fifo_segment_attach (a);
530   vec_reset_length (a->new_segment_indices);
531   if (PREDICT_FALSE (rv))
532     {
533       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed", vcm->my_pid,
534                     mp->segment_name);
535       return;
536     }
537
538   vcm->app_event_queue =
539     uword_to_pointer (mp->app_event_queue_address,
540                       unix_shared_memory_queue_t *);
541
542   vcm->app_state = STATE_APP_ATTACHED;
543 }
544
545 static void
546 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
547                                            mp)
548 {
549   vppcom_main_t *vcm = &vppcom_main;
550
551   if (mp->retval)
552     clib_warning ("[%d] detach failed: %U", vcm->my_pid, format_api_error,
553                   ntohl (mp->retval));
554
555   vcm->app_state = STATE_APP_ENABLED;
556 }
557
558 static void
559 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
560                                            mp)
561 {
562   vppcom_main_t *vcm = &vppcom_main;
563   uword *p;
564
565   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
566   if (p)
567     {
568       session_t *session = 0;
569       int rv;
570       clib_spinlock_lock (&vcm->sessions_lockp);
571       rv = vppcom_session_at_index (p[0], &session);
572       if (PREDICT_FALSE (rv))
573         {
574           if (VPPCOM_DEBUG > 1)
575             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
576                           vcm->my_pid, p[0]);
577         }
578       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
579       session->state = STATE_DISCONNECT;
580       clib_spinlock_unlock (&vcm->sessions_lockp);
581     }
582   else
583     {
584       if (VPPCOM_DEBUG > 1)
585         clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
586                       mp->handle);
587     }
588
589   if (mp->retval)
590     clib_warning ("[%d] disconnect_session failed: %U", vcm->my_pid,
591                   format_api_error, ntohl (mp->retval));
592 }
593
594 static void
595 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
596 {
597   vppcom_main_t *vcm = &vppcom_main;
598   static svm_fifo_segment_create_args_t _a;
599   svm_fifo_segment_create_args_t *a = &_a;
600   int rv;
601
602   memset (a, 0, sizeof (*a));
603   a->segment_name = (char *) mp->segment_name;
604   a->segment_size = mp->segment_size;
605   /* Attach to the segment vpp created */
606   rv = svm_fifo_segment_attach (a);
607   vec_reset_length (a->new_segment_indices);
608   if (PREDICT_FALSE (rv))
609     {
610       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed",
611                     vcm->my_pid, mp->segment_name);
612       return;
613     }
614   if (VPPCOM_DEBUG > 1)
615     clib_warning ("[%d] mapped new segment '%s' size %d", vcm->my_pid,
616                   mp->segment_name, mp->segment_size);
617 }
618
619 static void
620 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
621 {
622   vppcom_main_t *vcm = &vppcom_main;
623   session_t *session = 0;
624   vl_api_disconnect_session_reply_t *rmp;
625   uword *p;
626   int rv = 0;
627
628   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
629   if (p)
630     {
631       int rval;
632       clib_spinlock_lock (&vcm->sessions_lockp);
633       rval = vppcom_session_at_index (p[0], &session);
634       if (PREDICT_FALSE (rval))
635         {
636           if (VPPCOM_DEBUG > 1)
637             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
638                           vcm->my_pid, p[0]);
639         }
640       else
641         pool_put (vcm->sessions, session);
642       clib_spinlock_unlock (&vcm->sessions_lockp);
643       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
644     }
645   else
646     {
647       clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
648                     mp->handle);
649       rv = -11;
650     }
651
652   rmp = vl_msg_api_alloc (sizeof (*rmp));
653   memset (rmp, 0, sizeof (*rmp));
654
655   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
656   rmp->retval = htonl (rv);
657   rmp->handle = mp->handle;
658   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
659 }
660
661 static void
662 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
663 {
664   vppcom_main_t *vcm = &vppcom_main;
665   session_t *session = 0;
666   vl_api_reset_session_reply_t *rmp;
667   uword *p;
668   int rv = 0;
669
670   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
671   if (p)
672     {
673       int rval;
674       clib_spinlock_lock (&vcm->sessions_lockp);
675       rval = vppcom_session_at_index (p[0], &session);
676       if (PREDICT_FALSE (rval))
677         {
678           if (VPPCOM_DEBUG > 1)
679             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
680                           vcm->my_pid, p[0]);
681         }
682       else
683         pool_put (vcm->sessions, session);
684       clib_spinlock_unlock (&vcm->sessions_lockp);
685       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
686     }
687   else
688     {
689       clib_warning ("[%d] couldn't find session key %llx", vcm->my_pid,
690                     mp->handle);
691       rv = -11;
692     }
693
694   rmp = vl_msg_api_alloc (sizeof (*rmp));
695   memset (rmp, 0, sizeof (*rmp));
696   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
697   rmp->retval = htonl (rv);
698   rmp->handle = mp->handle;
699   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
700 }
701
702 static void
703 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
704 {
705   vppcom_main_t *vcm = &vppcom_main;
706   session_t *session;
707   u32 session_index;
708   svm_fifo_t *rx_fifo, *tx_fifo;
709   u8 is_cut_thru = 0;
710   int rv;
711
712   if (mp->retval)
713     {
714       clib_warning ("[%d] connect failed: %U", vcm->my_pid, format_api_error,
715                     ntohl (mp->retval));
716       return;
717     }
718
719   session_index = mp->context;
720   if (VPPCOM_DEBUG > 1)
721     clib_warning ("[%d] session_index = %d 0x%08x", vcm->my_pid,
722                   session_index, session_index);
723
724   clib_spinlock_lock (&vcm->sessions_lockp);
725   if (pool_is_free_index (vcm->sessions, session_index))
726     {
727       clib_spinlock_unlock (&vcm->sessions_lockp);
728       if (VPPCOM_DEBUG > 1)
729         clib_warning ("[%d] invalid session, sid %d is closed!",
730                       vcm->my_pid, session_index);
731       return;
732     }
733
734   /* We've been redirected */
735   if (mp->segment_name_length > 0)
736     {
737       static svm_fifo_segment_create_args_t _a;
738       svm_fifo_segment_create_args_t *a = &_a;
739
740       is_cut_thru = 1;
741       memset (a, 0, sizeof (*a));
742       a->segment_name = (char *) mp->segment_name;
743       if (VPPCOM_DEBUG > 1)
744         clib_warning ("[%d] cut-thru segment: %s", vcm->my_pid,
745                       a->segment_name);
746       rv = svm_fifo_segment_attach (a);
747       vec_reset_length (a->new_segment_indices);
748       if (PREDICT_FALSE (rv))
749         {
750           clib_spinlock_unlock (&vcm->sessions_lockp);
751           clib_warning ("[%d] sm_fifo_segment_attach ('%s') failed",
752                         vcm->my_pid, a->segment_name);
753           return;
754         }
755     }
756
757   /*
758    * Setup session
759    */
760   if (VPPCOM_DEBUG > 1)
761     clib_warning ("[%d] client sid %d", vcm->my_pid, session_index);
762
763   session = pool_elt_at_index (vcm->sessions, session_index);
764   session->is_cut_thru = is_cut_thru;
765   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
766                                                unix_shared_memory_queue_t *);
767
768   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
769   rx_fifo->client_session_index = session_index;
770   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
771   tx_fifo->client_session_index = session_index;
772
773   session->server_rx_fifo = rx_fifo;
774   session->server_tx_fifo = tx_fifo;
775   session->vpp_session_handle = mp->handle;
776   session->state = STATE_CONNECT;
777
778   /* Add it to lookup table */
779   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
780   clib_spinlock_unlock (&vcm->sessions_lockp);
781 }
782
783 static void
784 vppcom_send_connect_sock (session_t * session, u32 session_index)
785 {
786   vppcom_main_t *vcm = &vppcom_main;
787   vl_api_connect_sock_t *cmp;
788
789   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
790   session->is_server = 0;
791   cmp = vl_msg_api_alloc (sizeof (*cmp));
792   memset (cmp, 0, sizeof (*cmp));
793   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK);
794   cmp->client_index = vcm->my_client_index;
795   cmp->context = session_index;
796
797   if (VPPCOM_DEBUG > 1)
798     clib_warning ("[%d] session_index = %d 0x%08x",
799                   vcm->my_pid, session_index, session_index);
800
801   cmp->vrf = session->vrf;
802   cmp->is_ip4 = session->is_ip4;
803   clib_memcpy (cmp->ip, session->ip, sizeof (cmp->ip));
804   cmp->port = session->port;
805   cmp->proto = session->proto;
806   clib_memcpy (cmp->options, session->options, sizeof (cmp->options));
807   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & cmp);
808 }
809
810 static int
811 vppcom_send_disconnect (u32 session_index)
812 {
813   vppcom_main_t *vcm = &vppcom_main;
814   vl_api_disconnect_session_t *dmp;
815   session_t *session = 0;
816   int rv;
817
818   clib_spinlock_lock (&vcm->sessions_lockp);
819   rv = vppcom_session_at_index (session_index, &session);
820   if (PREDICT_FALSE (rv))
821     {
822       clib_spinlock_unlock (&vcm->sessions_lockp);
823       if (VPPCOM_DEBUG > 1)
824         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
825                       vcm->my_pid, session_index);
826       return rv;
827     }
828
829   dmp = vl_msg_api_alloc (sizeof (*dmp));
830   memset (dmp, 0, sizeof (*dmp));
831   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
832   dmp->client_index = vcm->my_client_index;
833   dmp->handle = session->vpp_session_handle;
834   clib_spinlock_unlock (&vcm->sessions_lockp);
835   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & dmp);
836   return VPPCOM_OK;
837 }
838
839 static void
840 vl_api_bind_sock_reply_t_handler (vl_api_bind_sock_reply_t * mp)
841 {
842   vppcom_main_t *vcm = &vppcom_main;
843   session_t *session = 0;
844   int rv;
845
846   if (mp->retval)
847     clib_warning ("[%d] bind failed: %U", vcm->my_pid, format_api_error,
848                   ntohl (mp->retval));
849
850   ASSERT (vcm->bind_session_index != ~0);
851
852   clib_spinlock_lock (&vcm->sessions_lockp);
853   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
854   if (rv == VPPCOM_OK)
855     {
856       session->vpp_session_handle = mp->handle;
857       hash_set (vcm->session_index_by_vpp_handles, mp->handle,
858                 vcm->bind_session_index);
859       session->state = mp->retval ? STATE_FAILED : STATE_LISTEN;
860       vcm->bind_session_index = ~0;
861     }
862   clib_spinlock_unlock (&vcm->sessions_lockp);
863 }
864
865 static void
866 vl_api_unbind_sock_reply_t_handler (vl_api_unbind_sock_reply_t * mp)
867 {
868   vppcom_main_t *vcm = &vppcom_main;
869   session_t *session = 0;
870   int rv;
871
872   clib_spinlock_lock (&vcm->sessions_lockp);
873   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
874   if (rv == VPPCOM_OK)
875     {
876       if ((VPPCOM_DEBUG > 1) && (mp->retval))
877         clib_warning ("[%d] unbind failed: %U", vcm->my_pid, format_api_error,
878                       ntohl (mp->retval));
879
880       vcm->bind_session_index = ~0;
881       session->state = STATE_START;
882     }
883   clib_spinlock_unlock (&vcm->sessions_lockp);
884 }
885
886 u8 *
887 format_ip4_address (u8 * s, va_list * args)
888 {
889   u8 *a = va_arg (*args, u8 *);
890   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
891 }
892
893 u8 *
894 format_ip6_address (u8 * s, va_list * args)
895 {
896   ip6_address_t *a = va_arg (*args, ip6_address_t *);
897   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
898
899   i_max_n_zero = ARRAY_LEN (a->as_u16);
900   max_n_zeros = 0;
901   i_first_zero = i_max_n_zero;
902   n_zeros = 0;
903   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
904     {
905       u32 is_zero = a->as_u16[i] == 0;
906       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
907         {
908           i_first_zero = i;
909           n_zeros = 0;
910         }
911       n_zeros += is_zero;
912       if ((!is_zero && n_zeros > max_n_zeros)
913           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
914         {
915           i_max_n_zero = i_first_zero;
916           max_n_zeros = n_zeros;
917           i_first_zero = ARRAY_LEN (a->as_u16);
918           n_zeros = 0;
919         }
920     }
921
922   last_double_colon = 0;
923   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
924     {
925       if (i == i_max_n_zero && max_n_zeros > 1)
926         {
927           s = format (s, "::");
928           i += max_n_zeros - 1;
929           last_double_colon = 1;
930         }
931       else
932         {
933           s = format (s, "%s%x",
934                       (last_double_colon || i == 0) ? "" : ":",
935                       clib_net_to_host_u16 (a->as_u16[i]));
936           last_double_colon = 0;
937         }
938     }
939
940   return s;
941 }
942
943 /* Format an IP46 address. */
944 u8 *
945 format_ip46_address (u8 * s, va_list * args)
946 {
947   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
948   ip46_type_t type = va_arg (*args, ip46_type_t);
949   int is_ip4 = 1;
950
951   switch (type)
952     {
953     case IP46_TYPE_ANY:
954       is_ip4 = ip46_address_is_ip4 (ip46);
955       break;
956     case IP46_TYPE_IP4:
957       is_ip4 = 1;
958       break;
959     case IP46_TYPE_IP6:
960       is_ip4 = 0;
961       break;
962     }
963
964   return is_ip4 ?
965     format (s, "%U", format_ip4_address, &ip46->ip4) :
966     format (s, "%U", format_ip6_address, &ip46->ip6);
967 }
968
969 static void
970 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
971 {
972   vppcom_main_t *vcm = &vppcom_main;
973   vl_api_accept_session_reply_t *rmp;
974   svm_fifo_t *rx_fifo, *tx_fifo;
975   session_t *session;
976   u32 session_index;
977   int rv = 0;
978
979   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
980     {
981       clib_warning ("[%d] client session queue is full!", vcm->my_pid);
982       rv = VNET_API_ERROR_QUEUE_FULL;
983       goto send_reply;
984     }
985
986   if (VPPCOM_DEBUG > 1)
987     {
988       u8 *ip_str = format (0, "%U", format_ip46_address, &mp->ip, mp->is_ip4);
989       clib_warning ("[%d] accepted session from: %s:%d", vcm->my_pid, ip_str,
990                     clib_net_to_host_u16 (mp->port));
991       vec_free (ip_str);
992     }
993
994   clib_spinlock_lock (&vcm->sessions_lockp);
995   /* Allocate local session and set it up */
996   pool_get (vcm->sessions, session);
997   memset (session, 0, sizeof (*session));
998   session_index = session - vcm->sessions;
999
1000   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
1001   rx_fifo->client_session_index = session_index;
1002   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
1003   tx_fifo->client_session_index = session_index;
1004
1005   session->server_rx_fifo = rx_fifo;
1006   session->server_tx_fifo = tx_fifo;
1007   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
1008                                                unix_shared_memory_queue_t *);
1009   session->state = STATE_ACCEPT;
1010   session->is_cut_thru = 0;
1011   session->is_server = 1;
1012   session->port = ntohs (mp->port);
1013   session->is_ip4 = mp->is_ip4;
1014   clib_memcpy (session->ip, mp->ip, sizeof (session->ip));
1015
1016   /* Add it to lookup table */
1017   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
1018
1019   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1020   clib_spinlock_unlock (&vcm->sessions_lockp);
1021
1022   /*
1023    * Send accept reply to vpp
1024    */
1025 send_reply:
1026   rmp = vl_msg_api_alloc (sizeof (*rmp));
1027   memset (rmp, 0, sizeof (*rmp));
1028   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
1029   rmp->retval = htonl (rv);
1030   rmp->handle = mp->handle;
1031   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1032 }
1033
1034 /*
1035  * Acting as server for redirected connect requests
1036  */
1037 static void
1038 vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
1039 {
1040   static svm_fifo_segment_create_args_t _a;
1041   svm_fifo_segment_create_args_t *a = &_a;
1042   vppcom_main_t *vcm = &vppcom_main;
1043   u32 session_index;
1044   svm_fifo_segment_private_t *seg;
1045   unix_shared_memory_queue_t *client_q;
1046   vl_api_connect_session_reply_t *rmp;
1047   session_t *session = 0;
1048   int rv = 0;
1049   svm_fifo_t *rx_fifo;
1050   svm_fifo_t *tx_fifo;
1051   unix_shared_memory_queue_t *event_q = 0;
1052
1053   clib_spinlock_lock (&vcm->sessions_lockp);
1054   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1055     {
1056       if (VPPCOM_DEBUG > 1)
1057         clib_warning ("[%d] client session queue is full!", vcm->my_pid);
1058       rv = VNET_API_ERROR_QUEUE_FULL;
1059       clib_spinlock_unlock (&vcm->sessions_lockp);
1060       goto send_reply;
1061     }
1062
1063   /* Create the segment */
1064   memset (a, 0, sizeof (*a));
1065   a->segment_name = (char *) format ((u8 *) a->segment_name, "%d:segment%d%c",
1066                                      vcm->my_pid, vcm->unique_segment_index++,
1067                                      0);
1068   a->segment_size = vcm->cfg.segment_size;
1069   a->preallocated_fifo_pairs = vcm->cfg.preallocated_fifo_pairs;
1070   a->rx_fifo_size = vcm->cfg.rx_fifo_size;
1071   a->tx_fifo_size = vcm->cfg.tx_fifo_size;
1072
1073   rv = svm_fifo_segment_create (a);
1074   if (PREDICT_FALSE (rv))
1075     {
1076       if (VPPCOM_DEBUG > 1)
1077         clib_warning ("[%d] svm_fifo_segment_create ('%s') failed",
1078                       vcm->my_pid, a->segment_name);
1079       vec_reset_length (a->new_segment_indices);
1080       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1081       goto send_reply;
1082     }
1083
1084   if (VPPCOM_DEBUG > 1)
1085     clib_warning ("[%d] created segment '%s'", vcm->my_pid, a->segment_name);
1086
1087   pool_get (vcm->sessions, session);
1088   memset (session, 0, sizeof (*session));
1089   session_index = session - vcm->sessions;
1090
1091   session->sm_seg_index = a->new_segment_indices[0];
1092   vec_reset_length (a->new_segment_indices);
1093
1094   seg = svm_fifo_segment_get_segment (session->sm_seg_index);
1095   rx_fifo = session->server_rx_fifo =
1096     svm_fifo_segment_alloc_fifo (seg, vcm->cfg.rx_fifo_size,
1097                                  FIFO_SEGMENT_RX_FREELIST);
1098   if (PREDICT_FALSE (!session->server_rx_fifo))
1099     {
1100       svm_fifo_segment_delete (seg);
1101       clib_warning ("[%d] rx fifo alloc failed, size %ld (0x%lx)",
1102                     vcm->my_pid, vcm->cfg.rx_fifo_size,
1103                     vcm->cfg.rx_fifo_size);
1104       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1105       clib_spinlock_unlock (&vcm->sessions_lockp);
1106       goto send_reply;
1107     }
1108
1109   tx_fifo = session->server_tx_fifo =
1110     svm_fifo_segment_alloc_fifo (seg, vcm->cfg.tx_fifo_size,
1111                                  FIFO_SEGMENT_TX_FREELIST);
1112   if (PREDICT_FALSE (!session->server_tx_fifo))
1113     {
1114       svm_fifo_segment_delete (seg);
1115       if (VPPCOM_DEBUG > 1)
1116         clib_warning ("[%d] tx fifo alloc failed, size %ld (0x%lx)",
1117                       vcm->my_pid, vcm->cfg.tx_fifo_size,
1118                       vcm->cfg.tx_fifo_size);
1119       rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
1120       clib_spinlock_unlock (&vcm->sessions_lockp);
1121       goto send_reply;
1122     }
1123
1124   session->server_rx_fifo->master_session_index = session_index;
1125   session->server_tx_fifo->master_session_index = session_index;
1126   session->client_queue_address = mp->client_queue_address;
1127   session->is_cut_thru = 1;
1128   session->is_server = 1;
1129   session->is_ip4 = mp->is_ip4;
1130   session->port = mp->port;
1131   {
1132     void *oldheap;
1133     ssvm_shared_header_t *sh = seg->ssvm.sh;
1134
1135     ssvm_lock_non_recursive (sh, 1);
1136     oldheap = ssvm_push_heap (sh);
1137     event_q = session->vpp_event_queue =
1138       unix_shared_memory_queue_init (vcm->cfg.event_queue_size,
1139                                      sizeof (session_fifo_event_t),
1140                                      vcm->my_pid, 0 /* signal not sent */ );
1141     ssvm_pop_heap (oldheap);
1142     ssvm_unlock_non_recursive (sh);
1143   }
1144   clib_memcpy (session->ip, mp->ip, sizeof (session->ip));
1145
1146   session->state = STATE_ACCEPT;
1147   if (VPPCOM_DEBUG > 1)
1148     clib_warning ("[%d] Connected cut-thru to client: sid %d",
1149                   vcm->my_pid, session_index);
1150   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1151   clib_spinlock_unlock (&vcm->sessions_lockp);
1152
1153 send_reply:
1154   rmp = vl_msg_api_alloc (sizeof (*rmp));
1155   memset (rmp, 0, sizeof (*rmp));
1156
1157   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SESSION_REPLY);
1158   rmp->context = mp->context;
1159   rmp->retval = htonl (rv);
1160   rmp->segment_name_length = vec_len (a->segment_name);
1161   clib_memcpy (rmp->segment_name, a->segment_name, vec_len (a->segment_name));
1162   vec_reset_length (a->segment_name);
1163
1164   if (event_q)
1165     {
1166       rmp->vpp_event_queue_address = pointer_to_uword (event_q);
1167       rmp->server_rx_fifo = pointer_to_uword (rx_fifo);
1168       rmp->server_tx_fifo = pointer_to_uword (tx_fifo);
1169     }
1170   client_q =
1171     uword_to_pointer (mp->client_queue_address, unix_shared_memory_queue_t *);
1172
1173   ASSERT (client_q);
1174   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
1175 }
1176
1177 static void
1178 vppcom_send_bind_sock (session_t * session)
1179 {
1180   vppcom_main_t *vcm = &vppcom_main;
1181   vl_api_bind_sock_t *bmp;
1182
1183   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1184   session->is_server = 1;
1185   bmp = vl_msg_api_alloc (sizeof (*bmp));
1186   memset (bmp, 0, sizeof (*bmp));
1187
1188   bmp->_vl_msg_id = ntohs (VL_API_BIND_SOCK);
1189   bmp->client_index = vcm->my_client_index;
1190   bmp->context = htonl (0xfeedface);
1191   bmp->vrf = session->vrf;
1192   bmp->is_ip4 = session->is_ip4;
1193   clib_memcpy (bmp->ip, session->ip, sizeof (bmp->ip));
1194   bmp->port = session->port;
1195   bmp->proto = session->proto;
1196   clib_memcpy (bmp->options, session->options, sizeof (bmp->options));
1197   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
1198 }
1199
1200 static void
1201 vppcom_send_unbind_sock (u32 session_index)
1202 {
1203   vppcom_main_t *vcm = &vppcom_main;
1204   vl_api_unbind_sock_t *ump;
1205   session_t *session = 0;
1206   int rv;
1207
1208   clib_spinlock_lock (&vcm->sessions_lockp);
1209   rv = vppcom_session_at_index (session_index, &session);
1210   if (PREDICT_FALSE (rv))
1211     {
1212       clib_spinlock_unlock (&vcm->sessions_lockp);
1213       if (VPPCOM_DEBUG > 0)
1214         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1215                       vcm->my_pid, session_index);
1216       return;
1217     }
1218
1219   ump = vl_msg_api_alloc (sizeof (*ump));
1220   memset (ump, 0, sizeof (*ump));
1221
1222   ump->_vl_msg_id = ntohs (VL_API_UNBIND_SOCK);
1223   ump->client_index = vcm->my_client_index;
1224   ump->handle = session->vpp_session_handle;
1225   clib_spinlock_unlock (&vcm->sessions_lockp);
1226   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & ump);
1227 }
1228
1229 static int
1230 vppcom_session_unbind_cut_thru (session_t * session)
1231 {
1232   svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
1233   svm_fifo_segment_private_t *seg;
1234   int rv = VPPCOM_OK;
1235
1236   seg = vec_elt_at_index (sm->segments, session->sm_seg_index);
1237   svm_fifo_segment_free_fifo (seg, session->server_rx_fifo,
1238                               FIFO_SEGMENT_RX_FREELIST);
1239   svm_fifo_segment_free_fifo (seg, session->server_tx_fifo,
1240                               FIFO_SEGMENT_TX_FREELIST);
1241   svm_fifo_segment_delete (seg);
1242
1243   return rv;
1244 }
1245
1246 static int
1247 vppcom_session_unbind (u32 session_index)
1248 {
1249   vppcom_main_t *vcm = &vppcom_main;
1250   int rv;
1251
1252   clib_spinlock_lock (&vcm->sessions_lockp);
1253   if (PREDICT_FALSE (pool_is_free_index (vcm->sessions, session_index)))
1254     {
1255       clib_spinlock_unlock (&vcm->sessions_lockp);
1256       if (VPPCOM_DEBUG > 1)
1257         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1258                       vcm->my_pid, session_index);
1259       return VPPCOM_EBADFD;
1260     }
1261   clib_spinlock_unlock (&vcm->sessions_lockp);
1262
1263   vcm->bind_session_index = session_index;
1264   vppcom_send_unbind_sock (session_index);
1265   rv = vppcom_wait_for_session_state_change (session_index, STATE_START,
1266                                              vcm->cfg.session_timeout);
1267   if (PREDICT_FALSE (rv))
1268     {
1269       vcm->bind_session_index = ~0;
1270       if (VPPCOM_DEBUG > 0)
1271         clib_warning ("[%d] server unbind timed out, rv = %s (%d)",
1272                       vcm->my_pid, vppcom_retval_str (rv), rv);
1273       return rv;
1274     }
1275   return VPPCOM_OK;
1276 }
1277
1278 static int
1279 vppcom_session_disconnect (u32 session_index)
1280 {
1281   vppcom_main_t *vcm = &vppcom_main;
1282   int rv;
1283
1284   rv = vppcom_send_disconnect (session_index);
1285   if (PREDICT_FALSE (rv))
1286     return rv;
1287
1288   rv = vppcom_wait_for_session_state_change (session_index, STATE_DISCONNECT,
1289                                              vcm->cfg.session_timeout);
1290   if (PREDICT_FALSE (rv))
1291     {
1292       if (VPPCOM_DEBUG > 0)
1293         clib_warning ("[%d] client disconnect timed out, rv = %s (%d)",
1294                       vcm->my_pid, vppcom_retval_str (rv), rv);
1295       return rv;
1296     }
1297   return VPPCOM_OK;
1298 }
1299
1300 #define foreach_sock_msg                                        \
1301 _(SESSION_ENABLE_DISABLE_REPLY, session_enable_disable_reply)   \
1302 _(BIND_SOCK_REPLY, bind_sock_reply)                             \
1303 _(UNBIND_SOCK_REPLY, unbind_sock_reply)                         \
1304 _(ACCEPT_SESSION, accept_session)                               \
1305 _(CONNECT_SOCK, connect_sock)                                   \
1306 _(CONNECT_SESSION_REPLY, connect_session_reply)                 \
1307 _(DISCONNECT_SESSION, disconnect_session)                       \
1308 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1309 _(RESET_SESSION, reset_session)                                 \
1310 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1311 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1312 _(MAP_ANOTHER_SEGMENT, map_another_segment)
1313
1314 static void
1315 vppcom_api_hookup (void)
1316 {
1317 #define _(N,n)                                                  \
1318     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1319                            vl_api_##n##_t_handler,              \
1320                            vl_noop_handler,                     \
1321                            vl_api_##n##_t_endian,               \
1322                            vl_api_##n##_t_print,                \
1323                            sizeof(vl_api_##n##_t), 1);
1324   foreach_sock_msg;
1325 #undef _
1326 }
1327
1328 static void
1329 vppcom_cfg_init (vppcom_cfg_t * vcl_cfg)
1330 {
1331   ASSERT (vcl_cfg);
1332
1333   vcl_cfg->heapsize = (256ULL << 20);
1334   vcl_cfg->segment_baseva = 0x200000000ULL;
1335   vcl_cfg->segment_size = (256 << 20);
1336   vcl_cfg->add_segment_size = (128 << 20);
1337   vcl_cfg->preallocated_fifo_pairs = 8;
1338   vcl_cfg->rx_fifo_size = (1 << 20);
1339   vcl_cfg->tx_fifo_size = (1 << 20);
1340   vcl_cfg->event_queue_size = 2048;
1341   vcl_cfg->listen_queue_size = CLIB_CACHE_LINE_BYTES / sizeof (u32);
1342   vcl_cfg->app_timeout = 10 * 60.0;
1343   vcl_cfg->session_timeout = 10 * 60.0;
1344   vcl_cfg->accept_timeout = 60.0;
1345 }
1346
1347 static void
1348 vppcom_cfg_heapsize (char *conf_fname)
1349 {
1350   vppcom_main_t *vcm = &vppcom_main;
1351   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1352   FILE *fp;
1353   char inbuf[4096];
1354   int argc = 1;
1355   char **argv = NULL;
1356   char *arg = NULL;
1357   char *p;
1358   int i;
1359   u8 *sizep;
1360   u32 size;
1361
1362   fp = fopen (conf_fname, "r");
1363   if (fp == NULL)
1364     {
1365       if (VPPCOM_DEBUG > 0)
1366         fprintf (stderr, "open configuration file '%s' failed\n", conf_fname);
1367       goto defaulted;
1368     }
1369   argv = calloc (1, sizeof (char *));
1370   if (argv == NULL)
1371     goto defaulted;
1372
1373   while (1)
1374     {
1375       if (fgets (inbuf, 4096, fp) == 0)
1376         break;
1377       p = strtok (inbuf, " \t\n");
1378       while (p != NULL)
1379         {
1380           if (*p == '#')
1381             break;
1382           argc++;
1383           char **tmp = realloc (argv, argc * sizeof (char *));
1384           if (tmp == NULL)
1385             goto defaulted;
1386           argv = tmp;
1387           arg = strndup (p, 1024);
1388           if (arg == NULL)
1389             goto defaulted;
1390           argv[argc - 1] = arg;
1391           p = strtok (NULL, " \t\n");
1392         }
1393     }
1394
1395   fclose (fp);
1396   fp = NULL;
1397
1398   char **tmp = realloc (argv, (argc + 1) * sizeof (char *));
1399   if (tmp == NULL)
1400     goto defaulted;
1401   argv = tmp;
1402   argv[argc] = NULL;
1403
1404   /*
1405    * Look for and parse the "heapsize" config parameter.
1406    * Manual since none of the clib infra has been bootstrapped yet.
1407    *
1408    * Format: heapsize <nn>[mM][gG]
1409    */
1410
1411   for (i = 1; i < (argc - 1); i++)
1412     {
1413       if (!strncmp (argv[i], "heapsize", 8))
1414         {
1415           sizep = (u8 *) argv[i + 1];
1416           size = 0;
1417           while (*sizep >= '0' && *sizep <= '9')
1418             {
1419               size *= 10;
1420               size += *sizep++ - '0';
1421             }
1422           if (size == 0)
1423             {
1424               if (VPPCOM_DEBUG > 0)
1425                 clib_warning ("[%d] parse error '%s %s', "
1426                               "using default heapsize %lld (0x%llx)",
1427                               vcm->my_pid, argv[i], argv[i + 1],
1428                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1429               goto defaulted;
1430             }
1431
1432           if (*sizep == 'g' || *sizep == 'G')
1433             vcl_cfg->heapsize = size << 30;
1434           else if (*sizep == 'm' || *sizep == 'M')
1435             vcl_cfg->heapsize = size << 20;
1436           else
1437             {
1438               if (VPPCOM_DEBUG > 0)
1439                 clib_warning ("[%d] parse error '%s %s', "
1440                               "using default heapsize %lld (0x%llx)",
1441                               vcm->my_pid, argv[i], argv[i + 1],
1442                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1443               goto defaulted;
1444             }
1445         }
1446     }
1447
1448 defaulted:
1449   if (fp != NULL)
1450     fclose (fp);
1451   if (argv != NULL)
1452     free (argv);
1453   if (!clib_mem_init (0, vcl_cfg->heapsize))
1454     clib_warning ("[%d] vppcom heap allocation failure!", vcm->my_pid);
1455   else if (VPPCOM_DEBUG > 0)
1456     clib_warning ("[%d] allocated vppcom heapsize %lld (0x%llx)",
1457                   vcm->my_pid, vcl_cfg->heapsize, vcl_cfg->heapsize);
1458 }
1459
1460 static void
1461 vppcom_cfg_read (char *conf_fname)
1462 {
1463   vppcom_main_t *vcm = &vppcom_main;
1464   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1465   int fd;
1466   unformat_input_t _input, *input = &_input;
1467   unformat_input_t _line_input, *line_input = &_line_input;
1468   u8 vc_cfg_input = 0;
1469   u8 *chroot_path;
1470   struct stat s;
1471   u32 uid, gid;
1472
1473   fd = open (conf_fname, O_RDONLY);
1474   if (fd < 0)
1475     {
1476       if (VPPCOM_DEBUG > 0)
1477         clib_warning ("[%d] open configuration file '%s' failed!",
1478                       vcm->my_pid, conf_fname);
1479       goto file_done;
1480     }
1481
1482   if (fstat (fd, &s) < 0)
1483     {
1484       if (VPPCOM_DEBUG > 0)
1485         clib_warning ("[%d] failed to stat `%s'", vcm->my_pid, conf_fname);
1486       goto file_done;
1487     }
1488
1489   if (!(S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
1490     {
1491       if (VPPCOM_DEBUG > 0)
1492         clib_warning ("[%d] not a regular file `%s'", vcm->my_pid,
1493                       conf_fname);
1494       goto file_done;
1495     }
1496
1497   unformat_init_clib_file (input, fd);
1498
1499   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1500     {
1501       (void) unformat_user (input, unformat_line_input, line_input);
1502       unformat_skip_white_space (line_input);
1503
1504       if (unformat (line_input, "vppcom {"))
1505         {
1506           vc_cfg_input = 1;
1507           continue;
1508         }
1509
1510       if (vc_cfg_input)
1511         {
1512           if (unformat (line_input, "heapsize %s", &chroot_path))
1513             {
1514               vec_terminate_c_string (chroot_path);
1515               if (VPPCOM_DEBUG > 0)
1516                 clib_warning ("[%d] configured heapsize %s, "
1517                               "actual heapsize %lld (0x%llx)",
1518                               vcm->my_pid, chroot_path, vcl_cfg->heapsize,
1519                               vcl_cfg->heapsize);
1520               vec_free (chroot_path);
1521             }
1522           else if (unformat (line_input, "api-prefix %s", &chroot_path))
1523             {
1524               vec_terminate_c_string (chroot_path);
1525               vl_set_memory_root_path ((char *) chroot_path);
1526               if (VPPCOM_DEBUG > 0)
1527                 clib_warning ("[%d] configured api-prefix %s",
1528                               vcm->my_pid, chroot_path);
1529               chroot_path = 0;  /* Don't vec_free() it! */
1530             }
1531           else if (unformat (line_input, "uid %d", &uid))
1532             {
1533               vl_set_memory_uid (uid);
1534               if (VPPCOM_DEBUG > 0)
1535                 clib_warning ("[%d] configured uid %d", vcm->my_pid, uid);
1536             }
1537           else if (unformat (line_input, "gid %d", &gid))
1538             {
1539               vl_set_memory_gid (gid);
1540               if (VPPCOM_DEBUG > 0)
1541                 clib_warning ("[%d] configured gid %d", vcm->my_pid, gid);
1542             }
1543           else if (unformat (line_input, "segment-baseva 0x%llx",
1544                              &vcl_cfg->segment_baseva))
1545             {
1546               if (VPPCOM_DEBUG > 0)
1547                 clib_warning ("[%d] configured segment_baseva 0x%llx",
1548                               vcm->my_pid, vcl_cfg->segment_baseva);
1549             }
1550           else if (unformat (line_input, "segment-size 0x%lx",
1551                              &vcl_cfg->segment_size))
1552             {
1553               if (VPPCOM_DEBUG > 0)
1554                 clib_warning ("[%d] configured segment_size 0x%lx (%ld)",
1555                               vcm->my_pid, vcl_cfg->segment_size,
1556                               vcl_cfg->segment_size);
1557             }
1558           else if (unformat (line_input, "segment-size %ld",
1559                              &vcl_cfg->segment_size))
1560             {
1561               if (VPPCOM_DEBUG > 0)
1562                 clib_warning ("[%d] configured segment_size %ld (0x%lx)",
1563                               vcm->my_pid, vcl_cfg->segment_size,
1564                               vcl_cfg->segment_size);
1565             }
1566           else if (unformat (line_input, "add-segment-size 0x%lx",
1567                              &vcl_cfg->add_segment_size))
1568             {
1569               if (VPPCOM_DEBUG > 0)
1570                 clib_warning
1571                   ("[%d] configured add_segment_size 0x%lx (%ld)",
1572                    vcm->my_pid, vcl_cfg->add_segment_size,
1573                    vcl_cfg->add_segment_size);
1574             }
1575           else if (unformat (line_input, "add-segment-size %ld",
1576                              &vcl_cfg->add_segment_size))
1577             {
1578               if (VPPCOM_DEBUG > 0)
1579                 clib_warning
1580                   ("[%d] configured add_segment_size %ld (0x%lx)",
1581                    vcm->my_pid, vcl_cfg->add_segment_size,
1582                    vcl_cfg->add_segment_size);
1583             }
1584           else if (unformat (line_input, "preallocated-fifo-pairs %d",
1585                              &vcl_cfg->preallocated_fifo_pairs))
1586             {
1587               if (VPPCOM_DEBUG > 0)
1588                 clib_warning ("[%d] configured preallocated_fifo_pairs "
1589                               "%d (0x%x)", vcm->my_pid,
1590                               vcl_cfg->preallocated_fifo_pairs,
1591                               vcl_cfg->preallocated_fifo_pairs);
1592             }
1593           else if (unformat (line_input, "rx-fifo-size 0x%lx",
1594                              &vcl_cfg->rx_fifo_size))
1595             {
1596               if (VPPCOM_DEBUG > 0)
1597                 clib_warning ("[%d] configured rx_fifo_size 0x%lx (%ld)",
1598                               vcm->my_pid, vcl_cfg->rx_fifo_size,
1599                               vcl_cfg->rx_fifo_size);
1600             }
1601           else if (unformat (line_input, "rx-fifo-size %ld",
1602                              &vcl_cfg->rx_fifo_size))
1603             {
1604               if (VPPCOM_DEBUG > 0)
1605                 clib_warning ("[%d] configured rx_fifo_size %ld (0x%lx)",
1606                               vcm->my_pid, vcl_cfg->rx_fifo_size,
1607                               vcl_cfg->rx_fifo_size);
1608             }
1609           else if (unformat (line_input, "tx-fifo-size 0x%lx",
1610                              &vcl_cfg->tx_fifo_size))
1611             {
1612               if (VPPCOM_DEBUG > 0)
1613                 clib_warning ("[%d] configured tx_fifo_size 0x%lx (%ld)",
1614                               vcm->my_pid, vcl_cfg->tx_fifo_size,
1615                               vcl_cfg->tx_fifo_size);
1616             }
1617           else if (unformat (line_input, "tx-fifo-size %ld",
1618                              &vcl_cfg->tx_fifo_size))
1619             {
1620               if (VPPCOM_DEBUG > 0)
1621                 clib_warning ("[%d] configured tx_fifo_size %ld (0x%lx)",
1622                               vcm->my_pid, vcl_cfg->tx_fifo_size,
1623                               vcl_cfg->tx_fifo_size);
1624             }
1625           else if (unformat (line_input, "event-queue-size 0x%lx",
1626                              &vcl_cfg->event_queue_size))
1627             {
1628               if (VPPCOM_DEBUG > 0)
1629                 clib_warning ("[%d] configured event_queue_size 0x%lx (%ld)",
1630                               vcm->my_pid, vcl_cfg->event_queue_size,
1631                               vcl_cfg->event_queue_size);
1632             }
1633           else if (unformat (line_input, "event-queue-size %ld",
1634                              &vcl_cfg->event_queue_size))
1635             {
1636               if (VPPCOM_DEBUG > 0)
1637                 clib_warning ("[%d] configured event_queue_size %ld (0x%lx)",
1638                               vcm->my_pid, vcl_cfg->event_queue_size,
1639                               vcl_cfg->event_queue_size);
1640             }
1641           else if (unformat (line_input, "listen-queue-size 0x%lx",
1642                              &vcl_cfg->listen_queue_size))
1643             {
1644               if (VPPCOM_DEBUG > 0)
1645                 clib_warning ("[%d] configured listen_queue_size 0x%lx (%ld)",
1646                               vcm->my_pid, vcl_cfg->listen_queue_size,
1647                               vcl_cfg->listen_queue_size);
1648             }
1649           else if (unformat (line_input, "listen-queue-size %ld",
1650                              &vcl_cfg->listen_queue_size))
1651             {
1652               if (VPPCOM_DEBUG > 0)
1653                 clib_warning ("[%d] configured listen_queue_size %ld (0x%lx)",
1654                               vcm->my_pid, vcl_cfg->listen_queue_size,
1655                               vcl_cfg->listen_queue_size);
1656             }
1657           else if (unformat (line_input, "app-timeout %f",
1658                              &vcl_cfg->app_timeout))
1659             {
1660               if (VPPCOM_DEBUG > 0)
1661                 clib_warning ("[%d] configured app_timeout %f",
1662                               vcm->my_pid, vcl_cfg->app_timeout);
1663             }
1664           else if (unformat (line_input, "session-timeout %f",
1665                              &vcl_cfg->session_timeout))
1666             {
1667               if (VPPCOM_DEBUG > 0)
1668                 clib_warning ("[%d] configured session_timeout %f",
1669                               vcm->my_pid, vcl_cfg->session_timeout);
1670             }
1671           else if (unformat (line_input, "accept-timeout %f",
1672                              &vcl_cfg->accept_timeout))
1673             {
1674               if (VPPCOM_DEBUG > 0)
1675                 clib_warning ("[%d] configured accept_timeout %f",
1676                               vcm->my_pid, vcl_cfg->accept_timeout);
1677             }
1678           else if (unformat (line_input, "}"))
1679             {
1680               vc_cfg_input = 0;
1681               if (VPPCOM_DEBUG > 0)
1682                 clib_warning ("[%d] completed parsing vppcom config!",
1683                               vcm->my_pid);
1684               goto input_done;
1685             }
1686           else
1687             {
1688               if (line_input->buffer[line_input->index] != '#')
1689                 {
1690                   clib_warning ("[%d] Unknown vppcom config option: '%s'",
1691                                 vcm->my_pid, (char *)
1692                                 &line_input->buffer[line_input->index]);
1693                 }
1694             }
1695         }
1696     }
1697
1698 input_done:
1699   unformat_free (input);
1700
1701 file_done:
1702   if (fd >= 0)
1703     close (fd);
1704 }
1705
1706 /*
1707  * VPPCOM Public API functions
1708  */
1709 int
1710 vppcom_app_create (char *app_name)
1711 {
1712   vppcom_main_t *vcm = &vppcom_main;
1713   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1714   u8 *heap;
1715   mheap_t *h;
1716   int rv;
1717
1718   if (!vcm->init)
1719     {
1720       char *conf_fname;
1721
1722       vcm->init = 1;
1723       vcm->my_pid = getpid ();
1724       clib_fifo_validate (vcm->client_session_index_fifo,
1725                           vcm->cfg.listen_queue_size);
1726       vppcom_cfg_init (vcl_cfg);
1727       conf_fname = getenv (VPPCOM_CONF_ENV);
1728       if (!conf_fname)
1729         {
1730           conf_fname = VPPCOM_CONF_DEFAULT;
1731           if (VPPCOM_DEBUG > 0)
1732             clib_warning ("[%d] getenv '%s' failed!", vcm->my_pid,
1733                           VPPCOM_CONF_ENV);
1734         }
1735       vppcom_cfg_heapsize (conf_fname);
1736       vppcom_cfg_read (conf_fname);
1737       vcm->bind_session_index = ~0;
1738       vcm->main_cpu = os_get_thread_index ();
1739       heap = clib_mem_get_per_cpu_heap ();
1740       h = mheap_header (heap);
1741
1742       /* make the main heap thread-safe */
1743       h->flags |= MHEAP_FLAG_THREAD_SAFE;
1744
1745       vcm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1746
1747       clib_time_init (&vcm->clib_time);
1748       vppcom_init_error_string_table ();
1749       svm_fifo_segment_init (vcl_cfg->segment_baseva,
1750                              20 /* timeout in secs */ );
1751       clib_spinlock_init (&vcm->sessions_lockp);
1752       vppcom_api_hookup ();
1753     }
1754
1755   if (vcm->my_client_index == ~0)
1756     {
1757       vcm->app_state = STATE_APP_START;
1758       rv = vppcom_connect_to_vpp (app_name);
1759       if (rv)
1760         {
1761           clib_warning ("[%s] couldn't connect to VPP.", vcm->my_pid);
1762           return rv;
1763         }
1764
1765       if (VPPCOM_DEBUG > 0)
1766         clib_warning ("[%d] sending session enable", vcm->my_pid);
1767
1768       rv = vppcom_app_session_enable ();
1769       if (rv)
1770         {
1771           clib_warning ("[%d] vppcom_app_session_enable() failed!",
1772                         vcm->my_pid);
1773           return rv;
1774         }
1775
1776       if (VPPCOM_DEBUG > 0)
1777         clib_warning ("[%d] sending app attach", vcm->my_pid);
1778
1779       rv = vppcom_app_attach ();
1780       if (rv)
1781         {
1782           clib_warning ("[%d] vppcom_app_attach() failed!", vcm->my_pid);
1783           return rv;
1784         }
1785     }
1786
1787   if (VPPCOM_DEBUG > 0)
1788     clib_warning ("[%d] app_name '%s', my_client_index %d (0x%x)",
1789                   vcm->my_pid, app_name, vcm->my_client_index,
1790                   vcm->my_client_index);
1791
1792   return VPPCOM_OK;
1793 }
1794
1795 void
1796 vppcom_app_destroy (void)
1797 {
1798   vppcom_main_t *vcm = &vppcom_main;
1799   int rv;
1800
1801   if (vcm->my_client_index == ~0)
1802     return;
1803
1804   if (VPPCOM_DEBUG > 0)
1805     clib_warning ("[%d] detaching from VPP, my_client_index %d (0x%x)",
1806                   vcm->my_pid, vcm->my_client_index, vcm->my_client_index);
1807
1808   vppcom_app_detach ();
1809   rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
1810   if (PREDICT_FALSE (rv))
1811     {
1812       if (VPPCOM_DEBUG > 0)
1813         clib_warning ("[%d] application detach timed out, rv = %s (%d)",
1814                       vcm->my_pid, vppcom_retval_str (rv), rv);
1815     }
1816   vl_client_disconnect_from_vlib ();
1817   vcm->my_client_index = ~0;
1818   vcm->app_state = STATE_APP_START;
1819 }
1820
1821 int
1822 vppcom_session_create (u32 vrf, u8 proto, u8 is_nonblocking)
1823 {
1824   vppcom_main_t *vcm = &vppcom_main;
1825   session_t *session;
1826   u32 session_index;
1827
1828   clib_spinlock_lock (&vcm->sessions_lockp);
1829   pool_get (vcm->sessions, session);
1830   memset (session, 0, sizeof (*session));
1831   session_index = session - vcm->sessions;
1832
1833   session->vrf = vrf;
1834   session->proto = proto;
1835   session->state = STATE_START;
1836   session->is_nonblocking = is_nonblocking;
1837   clib_spinlock_unlock (&vcm->sessions_lockp);
1838
1839   if (VPPCOM_DEBUG > 0)
1840     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1841
1842   return (int) session_index;
1843 }
1844
1845 int
1846 vppcom_session_close (uint32_t session_index)
1847 {
1848   vppcom_main_t *vcm = &vppcom_main;
1849   session_t *session = 0;
1850   int rv;
1851
1852   clib_spinlock_lock (&vcm->sessions_lockp);
1853   rv = vppcom_session_at_index (session_index, &session);
1854   if (PREDICT_FALSE (rv))
1855     {
1856       if (VPPCOM_DEBUG > 0)
1857         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1858                       vcm->my_pid, session_index);
1859       clib_spinlock_unlock (&vcm->sessions_lockp);
1860       goto done;
1861     }
1862   clib_spinlock_unlock (&vcm->sessions_lockp);
1863
1864   if (VPPCOM_DEBUG > 0)
1865     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1866
1867   if (session->is_vep)
1868     {
1869       u32 next_sid;
1870       for (next_sid = session->vep.next_sid; next_sid != ~0;
1871            next_sid = session->vep.next_sid)
1872         {
1873           rv = vppcom_epoll_ctl (session_index, EPOLL_CTL_DEL, next_sid, 0);
1874           if ((VPPCOM_DEBUG > 0) && (rv < 0))
1875             clib_warning ("[%d] EPOLL_CTL_DEL vep_idx %u, sid %u failed, "
1876                           "rv = %s (%d)", session_index, next_sid,
1877                           vcm->my_pid, session_index,
1878                           vppcom_retval_str (rv), rv);
1879
1880           clib_spinlock_lock (&vcm->sessions_lockp);
1881           rv = vppcom_session_at_index (session_index, &session);
1882           if (PREDICT_FALSE (rv))
1883             {
1884               if (VPPCOM_DEBUG > 0)
1885                 clib_warning
1886                   ("[%d] invalid session, sid (%u) has been closed!",
1887                    vcm->my_pid, session_index);
1888               clib_spinlock_unlock (&vcm->sessions_lockp);
1889               goto done;
1890             }
1891           clib_spinlock_unlock (&vcm->sessions_lockp);
1892         }
1893     }
1894   else
1895     {
1896       if (session->is_vep_session)
1897         {
1898           u32 vep_idx = session->vep.vep_idx;
1899           rv = vppcom_epoll_ctl (vep_idx, EPOLL_CTL_DEL, session_index, 0);
1900           if ((VPPCOM_DEBUG > 0) && (rv < 0))
1901             clib_warning ("[%d] EPOLL_CTL_DEL vep_idx %u, sid %u failed, "
1902                           "rv = %s (%d)", vep_idx, session_index,
1903                           vcm->my_pid, session_index,
1904                           vppcom_retval_str (rv), rv);
1905
1906           clib_spinlock_lock (&vcm->sessions_lockp);
1907           rv = vppcom_session_at_index (session_index, &session);
1908           if (PREDICT_FALSE (rv))
1909             {
1910               if (VPPCOM_DEBUG > 0)
1911                 clib_warning
1912                   ("[%d] invalid session, sid (%u) has been closed!",
1913                    vcm->my_pid, session_index);
1914               clib_spinlock_unlock (&vcm->sessions_lockp);
1915               goto done;
1916             }
1917           clib_spinlock_unlock (&vcm->sessions_lockp);
1918         }
1919
1920       if (session->is_cut_thru)
1921         {
1922           if (session->is_server)
1923             {
1924               rv = vppcom_session_unbind_cut_thru (session);
1925               if ((VPPCOM_DEBUG > 0) && (rv < 0))
1926                 clib_warning ("[%d] unbind cut-thru (session %d) failed, "
1927                               "rv = %s (%d)",
1928                               vcm->my_pid, session_index,
1929                               vppcom_retval_str (rv), rv);
1930             }
1931         }
1932       else if (session->is_server)
1933         {
1934           rv = vppcom_session_unbind (session_index);
1935           if ((VPPCOM_DEBUG > 0) && (rv < 0))
1936             clib_warning ("[%d] unbind (session %d) failed, rv = %s (%d)",
1937                           vcm->my_pid, session_index,
1938                           vppcom_retval_str (rv), rv);
1939         }
1940       else
1941         {
1942           rv = vppcom_session_disconnect (session_index);
1943           if ((VPPCOM_DEBUG > 0) && (rv < 0))
1944             clib_warning ("[%d] disconnect (session %d) failed, rv = %s (%d)",
1945                           vcm->my_pid, session_index,
1946                           vppcom_retval_str (rv), rv);
1947         }
1948     }
1949   pool_put_index (vcm->sessions, session_index);
1950 done:
1951   return rv;
1952 }
1953
1954 int
1955 vppcom_session_bind (uint32_t session_index, vppcom_endpt_t * ep)
1956 {
1957   vppcom_main_t *vcm = &vppcom_main;
1958   session_t *session = 0;
1959   int rv;
1960   ip46_address_t *ip46;
1961
1962   if (!ep || !ep->ip)
1963     return VPPCOM_EINVAL;
1964
1965   clib_spinlock_lock (&vcm->sessions_lockp);
1966   rv = vppcom_session_at_index (session_index, &session);
1967   if (PREDICT_FALSE (rv))
1968     {
1969       clib_spinlock_unlock (&vcm->sessions_lockp);
1970       if (VPPCOM_DEBUG > 0)
1971         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1972                       vcm->my_pid, session_index);
1973       return rv;
1974     }
1975
1976   if (VPPCOM_DEBUG > 0)
1977     clib_warning ("[%d] sid %d", vcm->my_pid, session_index);
1978
1979   session->vrf = ep->vrf;
1980   session->is_ip4 = ep->is_ip4;
1981   memset (session->ip, 0, sizeof (session->ip));
1982   ip46 = (ip46_address_t *) session->ip;
1983   *ip46 = to_ip46 (!ep->is_ip4, ep->ip);
1984   session->port = ep->port;
1985
1986   clib_spinlock_unlock (&vcm->sessions_lockp);
1987   return VPPCOM_OK;
1988 }
1989
1990 int
1991 vppcom_session_listen (uint32_t listen_session_index, uint32_t q_len)
1992 {
1993   vppcom_main_t *vcm = &vppcom_main;
1994   session_t *listen_session = 0;
1995   int rv;
1996
1997   clib_spinlock_lock (&vcm->sessions_lockp);
1998   rv = vppcom_session_at_index (listen_session_index, &listen_session);
1999   if (PREDICT_FALSE (rv))
2000     {
2001       clib_spinlock_unlock (&vcm->sessions_lockp);
2002       if (VPPCOM_DEBUG > 0)
2003         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2004                       vcm->my_pid, listen_session_index);
2005       return rv;
2006     }
2007
2008   if (VPPCOM_DEBUG > 0)
2009     clib_warning ("[%d] sid %d", vcm->my_pid, listen_session_index);
2010
2011   ASSERT (vcm->bind_session_index == ~0);
2012   vcm->bind_session_index = listen_session_index;
2013   vppcom_send_bind_sock (listen_session);
2014   clib_spinlock_unlock (&vcm->sessions_lockp);
2015   rv =
2016     vppcom_wait_for_session_state_change (listen_session_index, STATE_LISTEN,
2017                                           vcm->cfg.session_timeout);
2018   if (PREDICT_FALSE (rv))
2019     {
2020       vcm->bind_session_index = ~0;
2021       if (VPPCOM_DEBUG > 0)
2022         clib_warning ("[%d] server listen timed out, rv = %d (%d)",
2023                       vcm->my_pid, vppcom_retval_str (rv), rv);
2024       return rv;
2025     }
2026
2027   clib_spinlock_lock (&vcm->sessions_lockp);
2028   rv = vppcom_session_at_index (listen_session_index, &listen_session);
2029   if (PREDICT_FALSE (rv))
2030     {
2031       clib_spinlock_unlock (&vcm->sessions_lockp);
2032       if (VPPCOM_DEBUG > 0)
2033         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2034                       vcm->my_pid, listen_session_index);
2035       return rv;
2036     }
2037   listen_session->is_listen = 1;
2038   clib_fifo_validate (vcm->client_session_index_fifo, q_len);
2039   clib_spinlock_unlock (&vcm->sessions_lockp);
2040
2041   return VPPCOM_OK;
2042 }
2043
2044 int
2045 vppcom_session_accept (uint32_t listen_session_index, vppcom_endpt_t * ep,
2046                        double wait_for_time)
2047 {
2048   vppcom_main_t *vcm = &vppcom_main;
2049   session_t *listen_session = 0;
2050   session_t *client_session = 0;
2051   u32 client_session_index;
2052   int rv;
2053   f64 wait_for;
2054
2055   clib_spinlock_lock (&vcm->sessions_lockp);
2056   rv = vppcom_session_at_index (listen_session_index, &listen_session);
2057   if (PREDICT_FALSE (rv))
2058     {
2059       clib_spinlock_unlock (&vcm->sessions_lockp);
2060       if (VPPCOM_DEBUG > 0)
2061         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2062                       vcm->my_pid, listen_session_index);
2063       return rv;
2064     }
2065
2066   if (listen_session->state != STATE_LISTEN)
2067     {
2068       clib_spinlock_unlock (&vcm->sessions_lockp);
2069       if (VPPCOM_DEBUG > 0)
2070         clib_warning ("[%d] session not in listen state, state = %s",
2071                       vcm->my_pid,
2072                       vppcom_session_state_str (listen_session->state));
2073       return VPPCOM_EBADFD;
2074     }
2075   wait_for = listen_session->is_nonblocking ? 0 :
2076     (wait_for_time < 0) ? vcm->cfg.accept_timeout : wait_for_time;
2077
2078   if (VPPCOM_DEBUG > 0)
2079     clib_warning ("[%d] sid %d: %s (%d)", vcm->my_pid,
2080                   listen_session_index,
2081                   vppcom_session_state_str (listen_session->state),
2082                   listen_session->state);
2083   clib_spinlock_unlock (&vcm->sessions_lockp);
2084
2085   while (1)
2086     {
2087       rv = vppcom_wait_for_client_session_index (wait_for);
2088       if (rv)
2089         {
2090           if ((VPPCOM_DEBUG > 0))
2091             clib_warning ("[%d] sid %d, accept timed out, rv = %s (%d)",
2092                           vcm->my_pid, listen_session_index,
2093                           vppcom_retval_str (rv), rv);
2094           if ((wait_for == 0) || (wait_for_time > 0))
2095             return rv;
2096         }
2097       else
2098         break;
2099     }
2100
2101   clib_spinlock_lock (&vcm->sessions_lockp);
2102   clib_fifo_sub1 (vcm->client_session_index_fifo, client_session_index);
2103   rv = vppcom_session_at_index (client_session_index, &client_session);
2104   ASSERT (rv == VPPCOM_OK);
2105   ASSERT (client_session->is_ip4 == listen_session->is_ip4);
2106
2107   if (VPPCOM_DEBUG > 0)
2108     clib_warning ("[%d] Got a request: client sid %d", vcm->my_pid,
2109                   client_session_index);
2110
2111   ep->vrf = client_session->vrf;
2112   ep->is_cut_thru = client_session->is_cut_thru;
2113   ep->is_ip4 = client_session->is_ip4;
2114   ep->port = client_session->port;
2115   if (client_session->is_ip4)
2116     clib_memcpy (ep->ip, client_session->ip, sizeof (ip4_address_t));
2117   else
2118     clib_memcpy (ep->ip, client_session->ip, sizeof (ip6_address_t));
2119   clib_spinlock_unlock (&vcm->sessions_lockp);
2120   return (int) client_session_index;
2121 }
2122
2123 int
2124 vppcom_session_connect (uint32_t session_index, vppcom_endpt_t * server_ep)
2125 {
2126   vppcom_main_t *vcm = &vppcom_main;
2127   session_t *session = 0;
2128   int rv;
2129   ip46_address_t *ip46;
2130
2131   clib_spinlock_lock (&vcm->sessions_lockp);
2132   rv = vppcom_session_at_index (session_index, &session);
2133   if (PREDICT_FALSE (rv))
2134     {
2135       clib_spinlock_unlock (&vcm->sessions_lockp);
2136       if (VPPCOM_DEBUG > 0)
2137         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2138                       vcm->my_pid, session_index);
2139       return rv;
2140     }
2141
2142   if (session->state == STATE_CONNECT)
2143     {
2144       clib_spinlock_unlock (&vcm->sessions_lockp);
2145       if (VPPCOM_DEBUG > 0)
2146         clib_warning ("[%d] session, sid (%u) already connected!",
2147                       vcm->my_pid, session_index);
2148       return VPPCOM_OK;
2149     }
2150
2151   session->vrf = server_ep->vrf;
2152   session->is_ip4 = server_ep->is_ip4;
2153   memset (session->ip, 0, sizeof (session->ip));
2154   ip46 = (ip46_address_t *) session->ip;
2155   *ip46 = to_ip46 (!server_ep->is_ip4, server_ep->ip);
2156   session->port = server_ep->port;
2157
2158   if (VPPCOM_DEBUG > 0)
2159     {
2160       u8 *ip_str = format (0, "%U", format_ip46_address,
2161                            &session->ip, session->is_ip4);
2162       clib_warning ("[%d] connect sid %d to %s server port %d",
2163                     vcm->my_pid, session_index, ip_str,
2164                     clib_net_to_host_u16 (session->port));
2165       vec_free (ip_str);
2166     }
2167
2168   vppcom_send_connect_sock (session, session_index);
2169   clib_spinlock_unlock (&vcm->sessions_lockp);
2170   rv = vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
2171                                              vcm->cfg.session_timeout);
2172   if (PREDICT_FALSE (rv))
2173     {
2174       if (VPPCOM_DEBUG > 0)
2175         clib_warning ("[%d] connect timed out, rv = %s (%d)",
2176                       vcm->my_pid, vppcom_retval_str (rv), rv);
2177       return rv;
2178     }
2179   return VPPCOM_OK;
2180 }
2181
2182 int
2183 vppcom_session_read (uint32_t session_index, void *buf, int n)
2184 {
2185   vppcom_main_t *vcm = &vppcom_main;
2186   session_t *session = 0;
2187   svm_fifo_t *rx_fifo;
2188   int n_read = 0;
2189   int rv;
2190   char *fifo_str;
2191
2192   ASSERT (buf);
2193
2194   clib_spinlock_lock (&vcm->sessions_lockp);
2195   rv = vppcom_session_at_index (session_index, &session);
2196   if (PREDICT_FALSE (rv))
2197     {
2198       clib_spinlock_unlock (&vcm->sessions_lockp);
2199       if (VPPCOM_DEBUG > 0)
2200         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2201                       vcm->my_pid, session_index);
2202       return rv;
2203     }
2204
2205   if (session->state == STATE_DISCONNECT)
2206     {
2207       clib_spinlock_unlock (&vcm->sessions_lockp);
2208       if (VPPCOM_DEBUG > 0)
2209         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2210                       vcm->my_pid, session_index);
2211       return VPPCOM_ECONNRESET;
2212     }
2213
2214   rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2215              session->server_rx_fifo : session->server_tx_fifo);
2216   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2217               "server_rx_fifo" : "server_tx_fifo");
2218
2219   do
2220     {
2221       n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2222     }
2223   while (!session->is_nonblocking && (n_read <= 0));
2224
2225   if (n_read <= 0)
2226     session->vep.et_mask |= EPOLLIN;
2227
2228   clib_spinlock_unlock (&vcm->sessions_lockp);
2229
2230   if ((VPPCOM_DEBUG > 2) && (n_read > 0))
2231     clib_warning ("[%d] sid %d, read %d bytes from %s (%p)", vcm->my_pid,
2232                   session_index, n_read, fifo_str, rx_fifo);
2233
2234   return (n_read <= 0) ? VPPCOM_EAGAIN : n_read;
2235 }
2236
2237 static inline int
2238 vppcom_session_read_ready (session_t * session, u32 session_index)
2239 {
2240   vppcom_main_t *vcm = &vppcom_main;
2241   svm_fifo_t *rx_fifo;
2242   int ready = 0;
2243
2244   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2245   if (session->state == STATE_DISCONNECT)
2246     {
2247       if (VPPCOM_DEBUG > 0)
2248         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2249                       vcm->my_pid, session_index);
2250       return VPPCOM_ECONNRESET;
2251     }
2252
2253   if (session->is_listen)
2254     ready = clib_fifo_elts (vcm->client_session_index_fifo);
2255   else
2256     {
2257       rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2258                  session->server_rx_fifo : session->server_tx_fifo);
2259
2260       ready = svm_fifo_max_dequeue (rx_fifo);
2261     }
2262
2263   if (VPPCOM_DEBUG > 3)
2264     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2265                   session_index,
2266                   session->is_server ? "server_rx_fifo" : "server_tx_fifo",
2267                   rx_fifo, ready);
2268   if (ready == 0)
2269     session->vep.et_mask |= EPOLLIN;
2270
2271   return ready;
2272 }
2273
2274 int
2275 vppcom_session_write (uint32_t session_index, void *buf, int n)
2276 {
2277   vppcom_main_t *vcm = &vppcom_main;
2278   session_t *session = 0;
2279   svm_fifo_t *tx_fifo;
2280   unix_shared_memory_queue_t *q;
2281   session_fifo_event_t evt;
2282   int rv, n_write;
2283   char *fifo_str;
2284
2285   ASSERT (buf);
2286
2287   clib_spinlock_lock (&vcm->sessions_lockp);
2288   rv = vppcom_session_at_index (session_index, &session);
2289   if (PREDICT_FALSE (rv))
2290     {
2291       clib_spinlock_unlock (&vcm->sessions_lockp);
2292       if (VPPCOM_DEBUG > 0)
2293         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2294                       vcm->my_pid, session_index);
2295       return rv;
2296     }
2297
2298   if (session->state == STATE_DISCONNECT)
2299     {
2300       clib_spinlock_unlock (&vcm->sessions_lockp);
2301       if (VPPCOM_DEBUG > 0)
2302         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2303                       vcm->my_pid, session_index);
2304       return VPPCOM_ECONNRESET;
2305     }
2306
2307   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2308              session->server_tx_fifo : session->server_rx_fifo);
2309   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2310               "server_tx_fifo" : "server_rx_fifo");
2311   do
2312     {
2313       n_write = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
2314     }
2315   while (!session->is_nonblocking && (n_write <= 0));
2316
2317   /* If event wasn't set, add one */
2318   if (!session->is_cut_thru && (n_write > 0) && svm_fifo_set_event (tx_fifo))
2319     {
2320       int rval;
2321
2322       /* Fabricate TX event, send to vpp */
2323       evt.fifo = tx_fifo;
2324       evt.event_type = FIFO_EVENT_APP_TX;
2325       evt.event_id = vcm->tx_event_id++;
2326
2327       rval = vppcom_session_at_index (session_index, &session);
2328       if (PREDICT_FALSE (rval))
2329         {
2330           clib_spinlock_unlock (&vcm->sessions_lockp);
2331           if (VPPCOM_DEBUG > 1)
2332             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2333                           vcm->my_pid, session_index);
2334           return rval;
2335         }
2336       q = session->vpp_event_queue;
2337       ASSERT (q);
2338       unix_shared_memory_queue_add (q, (u8 *) & evt,
2339                                     0 /* do wait for mutex */ );
2340     }
2341
2342   if (n_write <= 0)
2343     session->vep.et_mask |= EPOLLOUT;
2344
2345   clib_spinlock_unlock (&vcm->sessions_lockp);
2346
2347   if (VPPCOM_DEBUG > 2)
2348     clib_warning ("[%d] sid %d, wrote %d bytes to %s (%p)", vcm->my_pid,
2349                   session_index, n_write, fifo_str, tx_fifo);
2350   return n_write;
2351 }
2352
2353 static inline int
2354 vppcom_session_write_ready (session_t * session, u32 session_index)
2355 {
2356   vppcom_main_t *vcm = &vppcom_main;
2357   svm_fifo_t *tx_fifo;
2358   char *fifo_str;
2359   int ready;
2360
2361   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2362   if (session->state == STATE_DISCONNECT)
2363     {
2364       if (VPPCOM_DEBUG > 0)
2365         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2366                       vcm->my_pid, session_index);
2367       return VPPCOM_ECONNRESET;
2368     }
2369
2370   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2371              session->server_tx_fifo : session->server_rx_fifo);
2372   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2373               "server_tx_fifo" : "server_rx_fifo");
2374
2375   ready = svm_fifo_max_enqueue (tx_fifo);
2376
2377   if (VPPCOM_DEBUG > 3)
2378     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2379                   session_index, fifo_str, tx_fifo, ready);
2380   if (ready == 0)
2381     session->vep.et_mask |= EPOLLOUT;
2382
2383   return ready;
2384 }
2385
2386 int
2387 vppcom_select (unsigned long n_bits, unsigned long *read_map,
2388                unsigned long *write_map, unsigned long *except_map,
2389                double time_to_wait)
2390 {
2391   vppcom_main_t *vcm = &vppcom_main;
2392   u32 session_index;
2393   session_t *session = 0;
2394   int rv, bits_set = 0;
2395   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
2396   u32 minbits = clib_max (n_bits, BITS (uword));
2397
2398   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
2399
2400   if (read_map)
2401     {
2402       clib_bitmap_validate (vcm->rd_bitmap, minbits);
2403       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
2404       memset (read_map, 0, vec_len (vcm->rd_bitmap));
2405     }
2406   if (write_map)
2407     {
2408       clib_bitmap_validate (vcm->wr_bitmap, minbits);
2409       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
2410       memset (write_map, 0, vec_len (vcm->wr_bitmap));
2411     }
2412   if (except_map)
2413     {
2414       clib_bitmap_validate (vcm->ex_bitmap, minbits);
2415       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
2416       memset (except_map, 0, vec_len (vcm->ex_bitmap));
2417     }
2418
2419   do
2420     {
2421       /* *INDENT-OFF* */
2422       clib_bitmap_foreach (session_index, vcm->rd_bitmap,
2423         ({
2424           clib_spinlock_lock (&vcm->sessions_lockp);
2425           rv = vppcom_session_at_index (session_index, &session);
2426           if (rv < 0)
2427             {
2428               clib_spinlock_unlock (&vcm->sessions_lockp);
2429               if (VPPCOM_DEBUG > 1)
2430                 clib_warning ("[%d] session %d specified in "
2431                               "read_map is closed.", vcm->my_pid,
2432                               session_index);
2433               bits_set = VPPCOM_EBADFD;
2434               goto select_done;
2435             }
2436
2437           rv = vppcom_session_read_ready (session, session_index);
2438           clib_spinlock_unlock (&vcm->sessions_lockp);
2439           if (vcm->ex_bitmap &&
2440               clib_bitmap_get (vcm->ex_bitmap, session_index) && (rv < 0))
2441             {
2442               // TBD: clib_warning
2443               /* coverity[FORWARD_NULL] */
2444               clib_bitmap_set_no_check (except_map, session_index, 1);
2445               bits_set++;
2446             }
2447           else if (rv > 0)
2448             {
2449               // TBD: clib_warning
2450               /* coverity[FORWARD_NULL] */
2451               clib_bitmap_set_no_check (read_map, session_index, 1);
2452               bits_set++;
2453             }
2454         }));
2455
2456       clib_bitmap_foreach (session_index, vcm->wr_bitmap,
2457         ({
2458           clib_spinlock_lock (&vcm->sessions_lockp);
2459           rv = vppcom_session_at_index (session_index, &session);
2460           if (rv < 0)
2461             {
2462               clib_spinlock_unlock (&vcm->sessions_lockp);
2463               if (VPPCOM_DEBUG > 0)
2464                 clib_warning ("[%d] session %d specified in "
2465                               "write_map is closed.", vcm->my_pid,
2466                               session_index);
2467               bits_set = VPPCOM_EBADFD;
2468               goto select_done;
2469             }
2470
2471           rv = vppcom_session_write_ready (session, session_index);
2472           clib_spinlock_unlock (&vcm->sessions_lockp);
2473           if (rv > 0 )
2474             {
2475               // TBD: clib_warning
2476               /* coverity[FORWARD_NULL] */
2477               clib_bitmap_set_no_check (write_map, session_index, 1);
2478               bits_set++;
2479             }
2480         }));
2481
2482       clib_bitmap_foreach (session_index, vcm->ex_bitmap,
2483         ({
2484           clib_spinlock_lock (&vcm->sessions_lockp);
2485           rv = vppcom_session_at_index (session_index, &session);
2486           if (rv < 0)
2487             {
2488               clib_spinlock_unlock (&vcm->sessions_lockp);
2489               if (VPPCOM_DEBUG > 1)
2490                 clib_warning ("[%d] session %d specified in "
2491                               "except_map is closed.", vcm->my_pid,
2492                               session_index);
2493               bits_set = VPPCOM_EBADFD;
2494               goto select_done;
2495             }
2496
2497           rv = vppcom_session_read_ready (session, session_index);
2498           clib_spinlock_unlock (&vcm->sessions_lockp);
2499           if (rv < 0)
2500             {
2501               // TBD: clib_warning
2502               /* coverity[FORWARD_NULL] */
2503               clib_bitmap_set_no_check (except_map, session_index, 1);
2504               bits_set++;
2505             }
2506         }));
2507       /* *INDENT-ON* */
2508     }
2509   while (clib_time_now (&vcm->clib_time) < timeout);
2510
2511 select_done:
2512   return (bits_set);
2513 }
2514
2515 static inline void
2516 vep_verify_epoll_chain (u32 vep_idx)
2517 {
2518   session_t *session;
2519   vppcom_epoll_t *vep;
2520   int rv;
2521   u32 sid;
2522
2523   if (VPPCOM_DEBUG < 1)
2524     return;
2525
2526   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2527   rv = vppcom_session_at_index (vep_idx, &session);
2528   if (PREDICT_FALSE (rv))
2529     {
2530       clib_warning ("ERROR: Invalid vep_idx (%u)!", vep_idx);
2531       goto done;
2532     }
2533   if (PREDICT_FALSE (!session->is_vep))
2534     {
2535       clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2536       goto done;
2537     }
2538   if (VPPCOM_DEBUG > 1)
2539     clib_warning ("vep_idx (%u): Dumping epoll chain\n"
2540                   "{\n"
2541                   "   is_vep         = %u\n"
2542                   "   is_vep_session = %u\n"
2543                   "   wait_cont_idx  = 0x%x (%u)\n"
2544                   "}\n",
2545                   vep_idx, session->is_vep, session->is_vep_session,
2546                   session->wait_cont_idx, session->wait_cont_idx);
2547   do
2548     {
2549       vep = &session->vep;
2550       if (session->is_vep_session)
2551         {
2552           if (VPPCOM_DEBUG > 1)
2553             clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
2554                           "{\n"
2555                           "   next_sid       = 0x%x (%u)\n"
2556                           "   prev_sid       = 0x%x (%u)\n"
2557                           "   vep_idx        = 0x%x (%u)\n"
2558                           "   ev.events      = 0x%x\n"
2559                           "   ev.data.u64    = 0x%llx\n"
2560                           "   et_mask        = 0x%x\n"
2561                           "}\n",
2562                           vep_idx, sid, sid,
2563                           vep->next_sid, vep->next_sid,
2564                           vep->prev_sid, vep->prev_sid,
2565                           vep->vep_idx, vep->vep_idx,
2566                           vep->ev.events, vep->ev.data.u64, vep->et_mask);
2567         }
2568       sid = vep->next_sid;
2569       if (sid != ~0)
2570         {
2571           rv = vppcom_session_at_index (sid, &session);
2572           if (PREDICT_FALSE (rv))
2573             {
2574               clib_warning ("ERROR: Invalid sid (%u)!", sid);
2575               goto done;
2576             }
2577           if (PREDICT_FALSE (session->is_vep))
2578             clib_warning ("ERROR: sid (%u) is a vep!", vep_idx);
2579           else if (PREDICT_FALSE (!session->is_vep_session))
2580             {
2581               clib_warning ("ERROR: session (%u) is not a vep session!", sid);
2582               goto done;
2583             }
2584           if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
2585             clib_warning ("ERROR: session (%u) vep_idx (%u) != "
2586                           "vep_idx (%u)!",
2587                           sid, session->vep.vep_idx, vep_idx);
2588         }
2589     }
2590   while (sid != ~0);
2591
2592 done:
2593   if (VPPCOM_DEBUG > 1)
2594     clib_warning ("vep_idx (%u): Dump complete!", vep_idx);
2595 }
2596
2597 int
2598 vppcom_epoll_create (void)
2599 {
2600   vppcom_main_t *vcm = &vppcom_main;
2601   session_t *vep_session;
2602   u32 vep_idx;
2603
2604   clib_spinlock_lock (&vcm->sessions_lockp);
2605   pool_get (vcm->sessions, vep_session);
2606   memset (vep_session, 0, sizeof (*vep_session));
2607   vep_idx = vep_session - vcm->sessions;
2608
2609   vep_session->is_vep = 1;
2610   vep_session->vep.vep_idx = ~0;
2611   vep_session->vep.next_sid = ~0;
2612   vep_session->vep.prev_sid = ~0;
2613   vep_session->wait_cont_idx = ~0;
2614   clib_spinlock_unlock (&vcm->sessions_lockp);
2615
2616   if (VPPCOM_DEBUG > 0)
2617     clib_warning ("Created vep_idx %u!", vep_idx);
2618
2619   return (vep_idx);
2620 }
2621
2622 int
2623 vppcom_epoll_ctl (uint32_t vep_idx, int op, uint32_t session_index,
2624                   struct epoll_event *event)
2625 {
2626   vppcom_main_t *vcm = &vppcom_main;
2627   session_t *vep_session;
2628   session_t *session;
2629   int rv;
2630
2631   if (vep_idx == session_index)
2632     {
2633       if (VPPCOM_DEBUG > 0)
2634         clib_warning ("ERROR: vep_idx == session_index (%u)!", vep_idx);
2635       return VPPCOM_EINVAL;
2636     }
2637
2638   clib_spinlock_lock (&vcm->sessions_lockp);
2639   rv = vppcom_session_at_index (vep_idx, &vep_session);
2640   if (PREDICT_FALSE (rv))
2641     {
2642       if (VPPCOM_DEBUG > 0)
2643         clib_warning ("ERROR: Invalid vep_idx (%u)!", vep_idx);
2644       goto done;
2645     }
2646   if (PREDICT_FALSE (!vep_session->is_vep))
2647     {
2648       if (VPPCOM_DEBUG > 0)
2649         clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2650       rv = VPPCOM_EINVAL;
2651       goto done;
2652     }
2653
2654   ASSERT (vep_session->vep.vep_idx == ~0);
2655   ASSERT (vep_session->vep.prev_sid == ~0);
2656
2657   rv = vppcom_session_at_index (session_index, &session);
2658   if (PREDICT_FALSE (rv))
2659     {
2660       if (VPPCOM_DEBUG > 0)
2661         clib_warning ("ERROR: Invalid session_index (%u)!", session_index);
2662       goto done;
2663     }
2664   if (PREDICT_FALSE (session->is_vep))
2665     {
2666       if (VPPCOM_DEBUG > 0)
2667         clib_warning ("ERROR: session_index (%u) is a vep!", vep_idx);
2668       rv = VPPCOM_EINVAL;
2669       goto done;
2670     }
2671
2672   switch (op)
2673     {
2674     case EPOLL_CTL_ADD:
2675       if (PREDICT_FALSE (!event))
2676         {
2677           clib_warning ("NULL pointer to epoll_event structure!");
2678           rv = VPPCOM_EINVAL;
2679           goto done;
2680         }
2681       if (vep_session->vep.next_sid != ~0)
2682         {
2683           session_t *next_session;
2684           rv = vppcom_session_at_index (vep_session->vep.next_sid,
2685                                         &next_session);
2686           if (PREDICT_FALSE (rv))
2687             {
2688               if (VPPCOM_DEBUG > 0)
2689                 clib_warning ("EPOLL_CTL_ADD: Invalid vep.next_sid (%u) on"
2690                               " vep_idx (%u)!", vep_session->vep.next_sid,
2691                               vep_idx);
2692               goto done;
2693             }
2694           ASSERT (next_session->vep.prev_sid == vep_idx);
2695           next_session->vep.prev_sid = session_index;
2696         }
2697       session->vep.next_sid = vep_session->vep.next_sid;
2698       session->vep.prev_sid = vep_idx;
2699       session->vep.vep_idx = vep_idx;
2700       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2701       session->vep.ev = *event;
2702       session->is_vep_session = 1;
2703       vep_session->vep.next_sid = session_index;
2704       if (VPPCOM_DEBUG > 1)
2705         clib_warning ("EPOLL_CTL_ADD: vep_idx %u, sid %u, events 0x%x,"
2706                       " data 0x%llx!", vep_idx, session_index,
2707                       event->events, event->data.u64);
2708       break;
2709
2710     case EPOLL_CTL_MOD:
2711       if (PREDICT_FALSE (!event))
2712         {
2713           clib_warning ("NULL pointer to epoll_event structure!");
2714           rv = VPPCOM_EINVAL;
2715           goto done;
2716         }
2717       if (PREDICT_FALSE (!session->is_vep_session &&
2718                          (session->vep.vep_idx != vep_idx)))
2719         {
2720           if (VPPCOM_DEBUG > 0)
2721             {
2722               if (!session->is_vep_session)
2723                 clib_warning ("EPOLL_CTL_MOD: session (%u) is not "
2724                               "a vep session!", session_index);
2725               else
2726                 clib_warning ("EPOLL_CTL_MOD: session (%u) vep_idx (%u) != "
2727                               "vep_idx (%u)!", session_index,
2728                               session->vep.vep_idx, vep_idx);
2729             }
2730           rv = VPPCOM_EINVAL;
2731           goto done;
2732         }
2733       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2734       session->vep.ev = *event;
2735       if (VPPCOM_DEBUG > 1)
2736         clib_warning ("EPOLL_CTL_MOD: vep_idx %u, sid %u, events 0x%x,"
2737                       " data 0x%llx!", vep_idx, session_index,
2738                       event->events, event->data.u64);
2739       break;
2740
2741     case EPOLL_CTL_DEL:
2742       if (PREDICT_FALSE (!session->is_vep_session &&
2743                          (session->vep.vep_idx != vep_idx)))
2744         {
2745           if (VPPCOM_DEBUG > 0)
2746             {
2747               if (!session->is_vep_session)
2748                 clib_warning ("EPOLL_CTL_DEL: session (%u) is not "
2749                               "a vep session!", session_index);
2750               else
2751                 clib_warning ("EPOLL_CTL_DEL: session (%u) vep_idx (%u) != "
2752                               "vep_idx (%u)!", session_index,
2753                               session->vep.vep_idx, vep_idx);
2754             }
2755           rv = VPPCOM_EINVAL;
2756           goto done;
2757         }
2758
2759       vep_session->wait_cont_idx =
2760         (vep_session->wait_cont_idx == session_index) ?
2761         session->vep.next_sid : vep_session->wait_cont_idx;
2762
2763       if (session->vep.prev_sid == vep_idx)
2764         vep_session->vep.next_sid = session->vep.next_sid;
2765       else
2766         {
2767           session_t *prev_session;
2768           rv = vppcom_session_at_index (session->vep.prev_sid, &prev_session);
2769           if (PREDICT_FALSE (rv))
2770             {
2771               if (VPPCOM_DEBUG > 0)
2772                 clib_warning ("EPOLL_CTL_DEL: Invalid vep.prev_sid (%u) on"
2773                               " sid (%u)!", session->vep.prev_sid,
2774                               session_index);
2775               goto done;
2776             }
2777           ASSERT (prev_session->vep.next_sid == session_index);
2778           prev_session->vep.next_sid = session->vep.next_sid;
2779         }
2780       if (session->vep.next_sid != ~0)
2781         {
2782           session_t *next_session;
2783           rv = vppcom_session_at_index (session->vep.next_sid, &next_session);
2784           if (PREDICT_FALSE (rv))
2785             {
2786               if (VPPCOM_DEBUG > 0)
2787                 clib_warning ("EPOLL_CTL_DEL: Invalid vep.next_sid (%u) on"
2788                               " sid (%u)!", session->vep.next_sid,
2789                               session_index);
2790               goto done;
2791             }
2792           ASSERT (next_session->vep.prev_sid == session_index);
2793           next_session->vep.prev_sid = session->vep.prev_sid;
2794         }
2795
2796       memset (&session->vep, 0, sizeof (session->vep));
2797       session->vep.next_sid = ~0;
2798       session->vep.prev_sid = ~0;
2799       session->vep.vep_idx = ~0;
2800       session->is_vep_session = 0;
2801       if (VPPCOM_DEBUG > 1)
2802         clib_warning ("EPOLL_CTL_DEL: vep_idx %u, sid %u!", vep_idx,
2803                       session_index);
2804       break;
2805
2806     default:
2807       clib_warning ("Invalid operation (%d)!", op);
2808       rv = VPPCOM_EINVAL;
2809     }
2810
2811   vep_verify_epoll_chain (vep_idx);
2812
2813 done:
2814   clib_spinlock_unlock (&vcm->sessions_lockp);
2815   return rv;
2816 }
2817
2818 #define VCL_LOCK_AND_GET_SESSION(I, S)                  \
2819 do {                                                    \
2820   vppcom_main_t *vcm = &vppcom_main;                    \
2821                                                         \
2822   clib_spinlock_lock (&vcm->sessions_lockp);            \
2823   rv = vppcom_session_at_index (I, S);                  \
2824   if (PREDICT_FALSE (rv))                               \
2825     {                                                   \
2826       clib_spinlock_unlock (&vcm->sessions_lockp);      \
2827                                                         \
2828       if (VPPCOM_DEBUG > 0)                             \
2829         clib_warning ("ERROR: Invalid ##I (%u)!", I);   \
2830                                                         \
2831       goto done;                                        \
2832     }                                                   \
2833 } while (0)
2834
2835 int
2836 vppcom_epoll_wait (uint32_t vep_idx, struct epoll_event *events,
2837                    int maxevents, double wait_for_time)
2838 {
2839   vppcom_main_t *vcm = &vppcom_main;
2840   session_t *vep_session;
2841   int rv;
2842   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
2843   int num_ev = 0;
2844   u32 vep_next_sid, wait_cont_idx;
2845   u8 is_vep;
2846
2847   if (PREDICT_FALSE (maxevents <= 0))
2848     {
2849       if (VPPCOM_DEBUG > 0)
2850         clib_warning ("ERROR: Invalid maxevents (%d)!", maxevents);
2851       return VPPCOM_EINVAL;
2852     }
2853   if (PREDICT_FALSE (wait_for_time < 0))
2854     {
2855       if (VPPCOM_DEBUG > 0)
2856         clib_warning ("ERROR: Invalid wait_for_time (%f)!", wait_for_time);
2857       return VPPCOM_EINVAL;
2858     }
2859   memset (events, 0, sizeof (*events) * maxevents);
2860
2861   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
2862   vep_next_sid = vep_session->vep.next_sid;
2863   is_vep = vep_session->is_vep;
2864   wait_cont_idx = vep_session->wait_cont_idx;
2865   clib_spinlock_unlock (&vcm->sessions_lockp);
2866
2867   if (PREDICT_FALSE (!is_vep))
2868     {
2869       if (VPPCOM_DEBUG > 0)
2870         clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2871       rv = VPPCOM_EINVAL;
2872       goto done;
2873     }
2874   if ((VPPCOM_DEBUG > 0) && (PREDICT_FALSE (vep_next_sid == ~0)))
2875     {
2876       clib_warning ("WARNING: vep_idx (%u) is empty!", vep_idx);
2877       goto done;
2878     }
2879
2880   do
2881     {
2882       u32 sid;
2883       u32 next_sid = ~0;
2884       session_t *session;
2885
2886       for (sid = (wait_cont_idx == ~0) ? vep_next_sid : wait_cont_idx;
2887            sid != ~0; sid = next_sid)
2888         {
2889           u32 session_events, et_mask, clear_et_mask, session_vep_idx;
2890           u8 add_event, is_vep_session;
2891           int ready;
2892           u64 session_ev_data;
2893
2894           VCL_LOCK_AND_GET_SESSION (sid, &session);
2895           next_sid = session->vep.next_sid;
2896           session_events = session->vep.ev.events;
2897           et_mask = session->vep.et_mask;
2898           is_vep = session->is_vep;
2899           is_vep_session = session->is_vep_session;
2900           session_vep_idx = session->vep.vep_idx;
2901           session_ev_data = session->vep.ev.data.u64;
2902           clib_spinlock_unlock (&vcm->sessions_lockp);
2903
2904           if (PREDICT_FALSE (is_vep))
2905             {
2906               if (VPPCOM_DEBUG > 0)
2907                 clib_warning ("ERROR: sid (%u) is a vep!", vep_idx);
2908               rv = VPPCOM_EINVAL;
2909               goto done;
2910             }
2911           if (PREDICT_FALSE (!is_vep_session))
2912             {
2913               if (VPPCOM_DEBUG > 0)
2914                 clib_warning ("EPOLL_CTL_MOD: session (%u) is not "
2915                               "a vep session!", sid);
2916               rv = VPPCOM_EINVAL;
2917               goto done;
2918             }
2919           if (PREDICT_FALSE (session_vep_idx != vep_idx))
2920             {
2921               clib_warning ("EPOLL_CTL_MOD: session (%u) "
2922                             "vep_idx (%u) != vep_idx (%u)!",
2923                             sid, session->vep.vep_idx, vep_idx);
2924               rv = VPPCOM_EINVAL;
2925               goto done;
2926             }
2927
2928           add_event = clear_et_mask = 0;
2929
2930           if ((EPOLLIN & session_events) && (EPOLLIN & et_mask))
2931             {
2932               VCL_LOCK_AND_GET_SESSION (sid, &session);
2933               ready = vppcom_session_read_ready (session, sid);
2934               clib_spinlock_unlock (&vcm->sessions_lockp);
2935               if (ready > 0)
2936                 {
2937                   add_event = 1;
2938                   events[num_ev].events |= EPOLLIN;
2939                   if (EPOLLET & session_events)
2940                     clear_et_mask |= EPOLLIN;
2941                 }
2942               else if (ready < 0)
2943                 {
2944                   add_event = 1;
2945                   switch (ready)
2946                     {
2947                     case VPPCOM_ECONNRESET:
2948                       events[num_ev].events |= EPOLLHUP | EPOLLRDHUP;
2949                       break;
2950
2951                     default:
2952                       events[num_ev].events |= EPOLLERR;
2953                       break;
2954                     }
2955                 }
2956             }
2957
2958           if ((EPOLLOUT & session_events) && (EPOLLOUT & et_mask))
2959             {
2960               VCL_LOCK_AND_GET_SESSION (sid, &session);
2961               ready = vppcom_session_write_ready (session, sid);
2962               clib_spinlock_unlock (&vcm->sessions_lockp);
2963               if (ready > 0)
2964                 {
2965                   add_event = 1;
2966                   events[num_ev].events |= EPOLLOUT;
2967                   if (EPOLLET & session_events)
2968                     clear_et_mask |= EPOLLOUT;
2969                 }
2970               else if (ready < 0)
2971                 {
2972                   add_event = 1;
2973                   switch (ready)
2974                     {
2975                     case VPPCOM_ECONNRESET:
2976                       events[num_ev].events |= EPOLLHUP;
2977                       break;
2978
2979                     default:
2980                       events[num_ev].events |= EPOLLERR;
2981                       break;
2982                     }
2983                 }
2984             }
2985
2986           if (add_event)
2987             {
2988               events[num_ev].data.u64 = session_ev_data;
2989               if (EPOLLONESHOT & session_events)
2990                 {
2991                   VCL_LOCK_AND_GET_SESSION (sid, &session);
2992                   session->vep.ev.events = 0;
2993                   clib_spinlock_unlock (&vcm->sessions_lockp);
2994                 }
2995               num_ev++;
2996               if (num_ev == maxevents)
2997                 {
2998                   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
2999                   vep_session->wait_cont_idx = next_sid;
3000                   clib_spinlock_unlock (&vcm->sessions_lockp);
3001                   goto done;
3002                 }
3003             }
3004           if (wait_cont_idx != ~0)
3005             {
3006               if (next_sid == ~0)
3007                 next_sid = vep_next_sid;
3008               else if (next_sid == wait_cont_idx)
3009                 next_sid = ~0;
3010             }
3011         }
3012     }
3013   while ((num_ev == 0) && (clib_time_now (&vcm->clib_time) <= timeout));
3014
3015   if (wait_cont_idx != ~0)
3016     {
3017       VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3018       vep_session->wait_cont_idx = ~0;
3019       clib_spinlock_unlock (&vcm->sessions_lockp);
3020     }
3021 done:
3022   return (rv != VPPCOM_OK) ? rv : num_ev;
3023 }
3024
3025   /*
3026    * fd.io coding-style-patch-verification: ON
3027    *
3028    * Local Variables:
3029    * eval: (c-set-style "gnu")
3030    * End:
3031    */