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