VCL/LDPRELOAD: Add support for getsockopt, sendto, and recvfrom
[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 int
2240 vppcom_session_read (uint32_t session_index, void *buf, int n)
2241 {
2242   vppcom_main_t *vcm = &vppcom_main;
2243   session_t *session = 0;
2244   svm_fifo_t *rx_fifo;
2245   int n_read = 0;
2246   int rv;
2247   char *fifo_str;
2248   u32 poll_et;
2249
2250   ASSERT (buf);
2251
2252   clib_spinlock_lock (&vcm->sessions_lockp);
2253   rv = vppcom_session_at_index (session_index, &session);
2254   if (PREDICT_FALSE (rv))
2255     {
2256       clib_spinlock_unlock (&vcm->sessions_lockp);
2257       if (VPPCOM_DEBUG > 0)
2258         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2259                       vcm->my_pid, session_index);
2260       return rv;
2261     }
2262
2263   if (session->is_vep)
2264     {
2265       clib_spinlock_unlock (&vcm->sessions_lockp);
2266       if (VPPCOM_DEBUG > 0)
2267         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2268                       vcm->my_pid, session_index);
2269       return VPPCOM_EBADFD;
2270     }
2271
2272   if (session->state == STATE_DISCONNECT)
2273     {
2274       clib_spinlock_unlock (&vcm->sessions_lockp);
2275       if (VPPCOM_DEBUG > 0)
2276         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2277                       vcm->my_pid, session_index);
2278       return VPPCOM_ECONNRESET;
2279     }
2280
2281   rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2282              session->server_rx_fifo : session->server_tx_fifo);
2283   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2284               "server_rx_fifo" : "server_tx_fifo");
2285   poll_et = EPOLLET & session->vep.ev.events;
2286   clib_spinlock_unlock (&vcm->sessions_lockp);
2287
2288   do
2289     {
2290       n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2291     }
2292   while (!session->is_nonblocking && (n_read <= 0));
2293
2294   if (poll_et && (n_read <= 0))
2295     {
2296       clib_spinlock_lock (&vcm->sessions_lockp);
2297       session->vep.et_mask |= EPOLLIN;
2298       clib_spinlock_unlock (&vcm->sessions_lockp);
2299     }
2300
2301   if ((VPPCOM_DEBUG > 2) && (n_read > 0))
2302     clib_warning ("[%d] sid %d, read %d bytes from %s (%p)", vcm->my_pid,
2303                   session_index, n_read, fifo_str, rx_fifo);
2304
2305   return (n_read <= 0) ? VPPCOM_EAGAIN : n_read;
2306 }
2307
2308 static inline int
2309 vppcom_session_read_ready (session_t * session, u32 session_index)
2310 {
2311   vppcom_main_t *vcm = &vppcom_main;
2312   svm_fifo_t *rx_fifo;
2313   int ready = 0;
2314
2315   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2316   if (session->is_vep)
2317     {
2318       clib_spinlock_unlock (&vcm->sessions_lockp);
2319       if (VPPCOM_DEBUG > 0)
2320         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2321                       vcm->my_pid, session_index);
2322       return VPPCOM_EBADFD;
2323     }
2324
2325   if (session->state == STATE_DISCONNECT)
2326     {
2327       if (VPPCOM_DEBUG > 0)
2328         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2329                       vcm->my_pid, session_index);
2330       return VPPCOM_ECONNRESET;
2331     }
2332
2333   if (session->is_listen)
2334     ready = clib_fifo_elts (vcm->client_session_index_fifo);
2335   else
2336     {
2337       rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2338                  session->server_rx_fifo : session->server_tx_fifo);
2339
2340       ready = svm_fifo_max_dequeue (rx_fifo);
2341     }
2342
2343   if (VPPCOM_DEBUG > 3)
2344     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2345                   session_index,
2346                   session->is_server ? "server_rx_fifo" : "server_tx_fifo",
2347                   rx_fifo, ready);
2348   if ((session->vep.ev.events & EPOLLET) && (ready == 0))
2349     session->vep.et_mask |= EPOLLIN;
2350
2351   return ready;
2352 }
2353
2354 int
2355 vppcom_session_write (uint32_t session_index, void *buf, int n)
2356 {
2357   vppcom_main_t *vcm = &vppcom_main;
2358   session_t *session = 0;
2359   svm_fifo_t *tx_fifo;
2360   unix_shared_memory_queue_t *q;
2361   session_fifo_event_t evt;
2362   int rv, n_write;
2363   char *fifo_str;
2364   u32 poll_et;
2365
2366   ASSERT (buf);
2367
2368   clib_spinlock_lock (&vcm->sessions_lockp);
2369   rv = vppcom_session_at_index (session_index, &session);
2370   if (PREDICT_FALSE (rv))
2371     {
2372       clib_spinlock_unlock (&vcm->sessions_lockp);
2373       if (VPPCOM_DEBUG > 0)
2374         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2375                       vcm->my_pid, session_index);
2376       return rv;
2377     }
2378
2379   if (session->is_vep)
2380     {
2381       clib_spinlock_unlock (&vcm->sessions_lockp);
2382       if (VPPCOM_DEBUG > 0)
2383         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2384                       vcm->my_pid, session_index);
2385       return VPPCOM_EBADFD;
2386     }
2387
2388   if (session->state == STATE_DISCONNECT)
2389     {
2390       clib_spinlock_unlock (&vcm->sessions_lockp);
2391       if (VPPCOM_DEBUG > 0)
2392         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2393                       vcm->my_pid, session_index);
2394       return VPPCOM_ECONNRESET;
2395     }
2396
2397   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2398              session->server_tx_fifo : session->server_rx_fifo);
2399   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2400               "server_tx_fifo" : "server_rx_fifo");
2401   q = session->vpp_event_queue;
2402   poll_et = EPOLLET & session->vep.ev.events;
2403   clib_spinlock_unlock (&vcm->sessions_lockp);
2404
2405   do
2406     {
2407       n_write = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
2408     }
2409   while (!session->is_nonblocking && (n_write <= 0));
2410
2411   /* If event wasn't set, add one */
2412   if (!session->is_cut_thru && (n_write > 0) && svm_fifo_set_event (tx_fifo))
2413     {
2414       int rval;
2415
2416       /* Fabricate TX event, send to vpp */
2417       evt.fifo = tx_fifo;
2418       evt.event_type = FIFO_EVENT_APP_TX;
2419
2420       rval = vppcom_session_at_index (session_index, &session);
2421       if (PREDICT_FALSE (rval))
2422         {
2423           if (VPPCOM_DEBUG > 1)
2424             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2425                           vcm->my_pid, session_index);
2426           return rval;
2427         }
2428       ASSERT (q);
2429       unix_shared_memory_queue_add (q, (u8 *) & evt,
2430                                     0 /* do wait for mutex */ );
2431     }
2432
2433   if (poll_et && (n_write <= 0))
2434     {
2435       clib_spinlock_lock (&vcm->sessions_lockp);
2436       session->vep.et_mask |= EPOLLOUT;
2437       clib_spinlock_unlock (&vcm->sessions_lockp);
2438     }
2439
2440   if (VPPCOM_DEBUG > 2)
2441     {
2442       if (n_write == -2)
2443         clib_warning ("[%d] sid %d, FIFO-FULL %s (%p)", vcm->my_pid,
2444                       session_index, fifo_str, tx_fifo);
2445       else
2446         clib_warning ("[%d] sid %d, wrote %d bytes to %s (%p)", vcm->my_pid,
2447                       session_index, n_write, fifo_str, tx_fifo);
2448     }
2449   return (n_write < 0) ? VPPCOM_EAGAIN : n_write;
2450 }
2451
2452 static inline int
2453 vppcom_session_write_ready (session_t * session, u32 session_index)
2454 {
2455   vppcom_main_t *vcm = &vppcom_main;
2456   svm_fifo_t *tx_fifo;
2457   char *fifo_str;
2458   int ready;
2459
2460   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2461   if (session->is_vep)
2462     {
2463       clib_spinlock_unlock (&vcm->sessions_lockp);
2464       if (VPPCOM_DEBUG > 0)
2465         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2466                       vcm->my_pid, session_index);
2467       return VPPCOM_EBADFD;
2468     }
2469
2470   if (session->state == STATE_DISCONNECT)
2471     {
2472       if (VPPCOM_DEBUG > 0)
2473         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2474                       vcm->my_pid, session_index);
2475       return VPPCOM_ECONNRESET;
2476     }
2477
2478   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2479              session->server_tx_fifo : session->server_rx_fifo);
2480   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2481               "server_tx_fifo" : "server_rx_fifo");
2482
2483   ready = svm_fifo_max_enqueue (tx_fifo);
2484
2485   if (VPPCOM_DEBUG > 3)
2486     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", vcm->my_pid,
2487                   session_index, fifo_str, tx_fifo, ready);
2488   if ((session->vep.ev.events & EPOLLET) && (ready == 0))
2489     session->vep.et_mask |= EPOLLOUT;
2490
2491   return ready;
2492 }
2493
2494 int
2495 vppcom_select (unsigned long n_bits, unsigned long *read_map,
2496                unsigned long *write_map, unsigned long *except_map,
2497                double time_to_wait)
2498 {
2499   vppcom_main_t *vcm = &vppcom_main;
2500   u32 session_index;
2501   session_t *session = 0;
2502   int rv, bits_set = 0;
2503   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
2504   u32 minbits = clib_max (n_bits, BITS (uword));
2505
2506   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
2507
2508   if (n_bits && read_map)
2509     {
2510       clib_bitmap_validate (vcm->rd_bitmap, minbits);
2511       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
2512       memset (read_map, 0, vec_len (vcm->rd_bitmap));
2513     }
2514   if (n_bits && write_map)
2515     {
2516       clib_bitmap_validate (vcm->wr_bitmap, minbits);
2517       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
2518       memset (write_map, 0, vec_len (vcm->wr_bitmap));
2519     }
2520   if (n_bits && except_map)
2521     {
2522       clib_bitmap_validate (vcm->ex_bitmap, minbits);
2523       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
2524       memset (except_map, 0, vec_len (vcm->ex_bitmap));
2525     }
2526
2527   do
2528     {
2529       /* *INDENT-OFF* */
2530       if (n_bits)
2531         {
2532           if (read_map)
2533             {
2534               clib_bitmap_foreach (session_index, vcm->rd_bitmap,
2535                 ({
2536                   clib_spinlock_lock (&vcm->sessions_lockp);
2537                   rv = vppcom_session_at_index (session_index, &session);
2538                   if (rv < 0)
2539                     {
2540                       clib_spinlock_unlock (&vcm->sessions_lockp);
2541                       if (VPPCOM_DEBUG > 1)
2542                         clib_warning ("[%d] session %d specified in "
2543                                       "read_map is closed.", vcm->my_pid,
2544                                       session_index);
2545                       bits_set = VPPCOM_EBADFD;
2546                       goto select_done;
2547                     }
2548
2549                   rv = vppcom_session_read_ready (session, session_index);
2550                   clib_spinlock_unlock (&vcm->sessions_lockp);
2551                   if (except_map && vcm->ex_bitmap &&
2552                       clib_bitmap_get (vcm->ex_bitmap, session_index) &&
2553                       (rv < 0))
2554                     {
2555                       // TBD: clib_warning
2556                       clib_bitmap_set_no_check (except_map, session_index, 1);
2557                       bits_set++;
2558                     }
2559                   else if (rv > 0)
2560                     {
2561                       // TBD: clib_warning
2562                       clib_bitmap_set_no_check (read_map, session_index, 1);
2563                       bits_set++;
2564                     }
2565                 }));
2566             }
2567
2568           if (write_map)
2569             {
2570               clib_bitmap_foreach (session_index, vcm->wr_bitmap,
2571                 ({
2572                   clib_spinlock_lock (&vcm->sessions_lockp);
2573                   rv = vppcom_session_at_index (session_index, &session);
2574                   if (rv < 0)
2575                     {
2576                       clib_spinlock_unlock (&vcm->sessions_lockp);
2577                       if (VPPCOM_DEBUG > 0)
2578                         clib_warning ("[%d] session %d specified in "
2579                                       "write_map is closed.", vcm->my_pid,
2580                                       session_index);
2581                       bits_set = VPPCOM_EBADFD;
2582                       goto select_done;
2583                     }
2584
2585                   rv = vppcom_session_write_ready (session, session_index);
2586                   clib_spinlock_unlock (&vcm->sessions_lockp);
2587                   if (write_map && (rv > 0))
2588                     {
2589                       // TBD: clib_warning
2590                       clib_bitmap_set_no_check (write_map, session_index, 1);
2591                       bits_set++;
2592                     }
2593                 }));
2594             }
2595
2596           if (except_map)
2597             {
2598               clib_bitmap_foreach (session_index, vcm->ex_bitmap,
2599                 ({
2600                   clib_spinlock_lock (&vcm->sessions_lockp);
2601                   rv = vppcom_session_at_index (session_index, &session);
2602                   if (rv < 0)
2603                     {
2604                       clib_spinlock_unlock (&vcm->sessions_lockp);
2605                       if (VPPCOM_DEBUG > 1)
2606                         clib_warning ("[%d] session %d specified in "
2607                                       "except_map is closed.", vcm->my_pid,
2608                                       session_index);
2609                       bits_set = VPPCOM_EBADFD;
2610                       goto select_done;
2611                     }
2612
2613                   rv = vppcom_session_read_ready (session, session_index);
2614                   clib_spinlock_unlock (&vcm->sessions_lockp);
2615                   if (rv < 0)
2616                     {
2617                       // TBD: clib_warning
2618                       clib_bitmap_set_no_check (except_map, session_index, 1);
2619                       bits_set++;
2620                     }
2621                 }));
2622             }
2623         }
2624       /* *INDENT-ON* */
2625     }
2626   while (clib_time_now (&vcm->clib_time) < timeout);
2627
2628 select_done:
2629   return (bits_set);
2630 }
2631
2632 static inline void
2633 vep_verify_epoll_chain (u32 vep_idx)
2634 {
2635   session_t *session;
2636   vppcom_epoll_t *vep;
2637   int rv;
2638   u32 sid;
2639
2640   if (VPPCOM_DEBUG < 1)
2641     return;
2642
2643   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2644   rv = vppcom_session_at_index (vep_idx, &session);
2645   if (PREDICT_FALSE (rv))
2646     {
2647       clib_warning ("ERROR: Invalid vep_idx (%u)!", vep_idx);
2648       goto done;
2649     }
2650   if (PREDICT_FALSE (!session->is_vep))
2651     {
2652       clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2653       goto done;
2654     }
2655   if (VPPCOM_DEBUG > 1)
2656     clib_warning ("vep_idx (%u): Dumping epoll chain\n"
2657                   "{\n"
2658                   "   is_vep         = %u\n"
2659                   "   is_vep_session = %u\n"
2660                   "   wait_cont_idx  = 0x%x (%u)\n"
2661                   "}\n",
2662                   vep_idx, session->is_vep, session->is_vep_session,
2663                   session->wait_cont_idx, session->wait_cont_idx);
2664   do
2665     {
2666       vep = &session->vep;
2667       sid = vep->next_sid;
2668       if (session->is_vep_session)
2669         {
2670           if (VPPCOM_DEBUG > 1)
2671             clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
2672                           "{\n"
2673                           "   next_sid       = 0x%x (%u)\n"
2674                           "   prev_sid       = 0x%x (%u)\n"
2675                           "   vep_idx        = 0x%x (%u)\n"
2676                           "   ev.events      = 0x%x\n"
2677                           "   ev.data.u64    = 0x%llx\n"
2678                           "   et_mask        = 0x%x\n"
2679                           "}\n",
2680                           vep_idx, sid, sid,
2681                           vep->next_sid, vep->next_sid,
2682                           vep->prev_sid, vep->prev_sid,
2683                           vep->vep_idx, vep->vep_idx,
2684                           vep->ev.events, vep->ev.data.u64, vep->et_mask);
2685         }
2686       if (sid != ~0)
2687         {
2688           rv = vppcom_session_at_index (sid, &session);
2689           if (PREDICT_FALSE (rv))
2690             {
2691               clib_warning ("ERROR: Invalid sid (%u)!", sid);
2692               goto done;
2693             }
2694           if (PREDICT_FALSE (session->is_vep))
2695             clib_warning ("ERROR: sid (%u) is a vep!", vep_idx);
2696           else if (PREDICT_FALSE (!session->is_vep_session))
2697             {
2698               clib_warning ("ERROR: session (%u) is not a vep session!", sid);
2699               goto done;
2700             }
2701           if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
2702             clib_warning ("ERROR: session (%u) vep_idx (%u) != "
2703                           "vep_idx (%u)!",
2704                           sid, session->vep.vep_idx, vep_idx);
2705         }
2706     }
2707   while (sid != ~0);
2708
2709 done:
2710   if (VPPCOM_DEBUG > 1)
2711     clib_warning ("vep_idx (%u): Dump complete!", vep_idx);
2712 }
2713
2714 int
2715 vppcom_epoll_create (void)
2716 {
2717   vppcom_main_t *vcm = &vppcom_main;
2718   session_t *vep_session;
2719   u32 vep_idx;
2720
2721   clib_spinlock_lock (&vcm->sessions_lockp);
2722   pool_get (vcm->sessions, vep_session);
2723   memset (vep_session, 0, sizeof (*vep_session));
2724   vep_idx = vep_session - vcm->sessions;
2725
2726   vep_session->is_vep = 1;
2727   vep_session->vep.vep_idx = ~0;
2728   vep_session->vep.next_sid = ~0;
2729   vep_session->vep.prev_sid = ~0;
2730   vep_session->wait_cont_idx = ~0;
2731   clib_spinlock_unlock (&vcm->sessions_lockp);
2732
2733   if (VPPCOM_DEBUG > 0)
2734     clib_warning ("Created vep_idx %u!", vep_idx);
2735
2736   return (vep_idx);
2737 }
2738
2739 int
2740 vppcom_epoll_ctl (uint32_t vep_idx, int op, uint32_t session_index,
2741                   struct epoll_event *event)
2742 {
2743   vppcom_main_t *vcm = &vppcom_main;
2744   session_t *vep_session;
2745   session_t *session;
2746   int rv;
2747
2748   if (vep_idx == session_index)
2749     {
2750       if (VPPCOM_DEBUG > 0)
2751         clib_warning ("ERROR: vep_idx == session_index (%u)!", vep_idx);
2752       return VPPCOM_EINVAL;
2753     }
2754
2755   clib_spinlock_lock (&vcm->sessions_lockp);
2756   rv = vppcom_session_at_index (vep_idx, &vep_session);
2757   if (PREDICT_FALSE (rv))
2758     {
2759       if (VPPCOM_DEBUG > 0)
2760         clib_warning ("ERROR: Invalid vep_idx (%u)!", vep_idx);
2761       goto done;
2762     }
2763   if (PREDICT_FALSE (!vep_session->is_vep))
2764     {
2765       if (VPPCOM_DEBUG > 0)
2766         clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2767       rv = VPPCOM_EINVAL;
2768       goto done;
2769     }
2770
2771   ASSERT (vep_session->vep.vep_idx == ~0);
2772   ASSERT (vep_session->vep.prev_sid == ~0);
2773
2774   rv = vppcom_session_at_index (session_index, &session);
2775   if (PREDICT_FALSE (rv))
2776     {
2777       if (VPPCOM_DEBUG > 0)
2778         clib_warning ("ERROR: Invalid session_index (%u)!", session_index);
2779       goto done;
2780     }
2781   if (PREDICT_FALSE (session->is_vep))
2782     {
2783       if (VPPCOM_DEBUG > 0)
2784         clib_warning ("ERROR: session_index (%u) is a vep!", vep_idx);
2785       rv = VPPCOM_EINVAL;
2786       goto done;
2787     }
2788
2789   switch (op)
2790     {
2791     case EPOLL_CTL_ADD:
2792       if (PREDICT_FALSE (!event))
2793         {
2794           clib_warning ("NULL pointer to epoll_event structure!");
2795           rv = VPPCOM_EINVAL;
2796           goto done;
2797         }
2798       if (vep_session->vep.next_sid != ~0)
2799         {
2800           session_t *next_session;
2801           rv = vppcom_session_at_index (vep_session->vep.next_sid,
2802                                         &next_session);
2803           if (PREDICT_FALSE (rv))
2804             {
2805               if (VPPCOM_DEBUG > 0)
2806                 clib_warning ("EPOLL_CTL_ADD: Invalid vep.next_sid (%u) on"
2807                               " vep_idx (%u)!", vep_session->vep.next_sid,
2808                               vep_idx);
2809               goto done;
2810             }
2811           ASSERT (next_session->vep.prev_sid == vep_idx);
2812           next_session->vep.prev_sid = session_index;
2813         }
2814       session->vep.next_sid = vep_session->vep.next_sid;
2815       session->vep.prev_sid = vep_idx;
2816       session->vep.vep_idx = vep_idx;
2817       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2818       session->vep.ev = *event;
2819       session->is_vep_session = 1;
2820       vep_session->vep.next_sid = session_index;
2821       if (VPPCOM_DEBUG > 1)
2822         clib_warning ("EPOLL_CTL_ADD: vep_idx %u, sid %u, events 0x%x,"
2823                       " data 0x%llx!", vep_idx, session_index,
2824                       event->events, event->data.u64);
2825       break;
2826
2827     case EPOLL_CTL_MOD:
2828       if (PREDICT_FALSE (!event))
2829         {
2830           clib_warning ("NULL pointer to epoll_event structure!");
2831           rv = VPPCOM_EINVAL;
2832           goto done;
2833         }
2834       if (PREDICT_FALSE (!session->is_vep_session &&
2835                          (session->vep.vep_idx != vep_idx)))
2836         {
2837           if (VPPCOM_DEBUG > 0)
2838             {
2839               if (!session->is_vep_session)
2840                 clib_warning ("EPOLL_CTL_MOD: session (%u) is not "
2841                               "a vep session!", session_index);
2842               else
2843                 clib_warning ("EPOLL_CTL_MOD: session (%u) vep_idx (%u) != "
2844                               "vep_idx (%u)!", session_index,
2845                               session->vep.vep_idx, vep_idx);
2846             }
2847           rv = VPPCOM_EINVAL;
2848           goto done;
2849         }
2850       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
2851       session->vep.ev = *event;
2852       if (VPPCOM_DEBUG > 1)
2853         clib_warning ("EPOLL_CTL_MOD: vep_idx %u, sid %u, events 0x%x,"
2854                       " data 0x%llx!", vep_idx, session_index,
2855                       event->events, event->data.u64);
2856       break;
2857
2858     case EPOLL_CTL_DEL:
2859       if (PREDICT_FALSE (!session->is_vep_session &&
2860                          (session->vep.vep_idx != vep_idx)))
2861         {
2862           if (VPPCOM_DEBUG > 0)
2863             {
2864               if (!session->is_vep_session)
2865                 clib_warning ("EPOLL_CTL_DEL: session (%u) is not "
2866                               "a vep session!", session_index);
2867               else
2868                 clib_warning ("EPOLL_CTL_DEL: session (%u) vep_idx (%u) != "
2869                               "vep_idx (%u)!", session_index,
2870                               session->vep.vep_idx, vep_idx);
2871             }
2872           rv = VPPCOM_EINVAL;
2873           goto done;
2874         }
2875
2876       vep_session->wait_cont_idx =
2877         (vep_session->wait_cont_idx == session_index) ?
2878         session->vep.next_sid : vep_session->wait_cont_idx;
2879
2880       if (session->vep.prev_sid == vep_idx)
2881         vep_session->vep.next_sid = session->vep.next_sid;
2882       else
2883         {
2884           session_t *prev_session;
2885           rv = vppcom_session_at_index (session->vep.prev_sid, &prev_session);
2886           if (PREDICT_FALSE (rv))
2887             {
2888               if (VPPCOM_DEBUG > 0)
2889                 clib_warning ("EPOLL_CTL_DEL: Invalid vep.prev_sid (%u) on"
2890                               " sid (%u)!", session->vep.prev_sid,
2891                               session_index);
2892               goto done;
2893             }
2894           ASSERT (prev_session->vep.next_sid == session_index);
2895           prev_session->vep.next_sid = session->vep.next_sid;
2896         }
2897       if (session->vep.next_sid != ~0)
2898         {
2899           session_t *next_session;
2900           rv = vppcom_session_at_index (session->vep.next_sid, &next_session);
2901           if (PREDICT_FALSE (rv))
2902             {
2903               if (VPPCOM_DEBUG > 0)
2904                 clib_warning ("EPOLL_CTL_DEL: Invalid vep.next_sid (%u) on"
2905                               " sid (%u)!", session->vep.next_sid,
2906                               session_index);
2907               goto done;
2908             }
2909           ASSERT (next_session->vep.prev_sid == session_index);
2910           next_session->vep.prev_sid = session->vep.prev_sid;
2911         }
2912
2913       memset (&session->vep, 0, sizeof (session->vep));
2914       session->vep.next_sid = ~0;
2915       session->vep.prev_sid = ~0;
2916       session->vep.vep_idx = ~0;
2917       session->is_vep_session = 0;
2918       if (VPPCOM_DEBUG > 1)
2919         clib_warning ("EPOLL_CTL_DEL: vep_idx %u, sid %u!", vep_idx,
2920                       session_index);
2921       break;
2922
2923     default:
2924       clib_warning ("Invalid operation (%d)!", op);
2925       rv = VPPCOM_EINVAL;
2926     }
2927
2928   vep_verify_epoll_chain (vep_idx);
2929
2930 done:
2931   clib_spinlock_unlock (&vcm->sessions_lockp);
2932   return rv;
2933 }
2934
2935 #define VCL_LOCK_AND_GET_SESSION(I, S)                  \
2936 do {                                                    \
2937   vppcom_main_t *vcm = &vppcom_main;                    \
2938                                                         \
2939   clib_spinlock_lock (&vcm->sessions_lockp);            \
2940   rv = vppcom_session_at_index (I, S);                  \
2941   if (PREDICT_FALSE (rv))                               \
2942     {                                                   \
2943       clib_spinlock_unlock (&vcm->sessions_lockp);      \
2944                                                         \
2945       if (VPPCOM_DEBUG > 0)                             \
2946         clib_warning ("ERROR: Invalid ##I (%u)!", I);   \
2947                                                         \
2948       goto done;                                        \
2949     }                                                   \
2950 } while (0)
2951
2952 int
2953 vppcom_epoll_wait (uint32_t vep_idx, struct epoll_event *events,
2954                    int maxevents, double wait_for_time)
2955 {
2956   vppcom_main_t *vcm = &vppcom_main;
2957   session_t *vep_session;
2958   int rv;
2959   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
2960   int num_ev = 0;
2961   u32 vep_next_sid, wait_cont_idx;
2962   u8 is_vep;
2963
2964   if (PREDICT_FALSE (maxevents <= 0))
2965     {
2966       if (VPPCOM_DEBUG > 0)
2967         clib_warning ("ERROR: Invalid maxevents (%d)!", maxevents);
2968       return VPPCOM_EINVAL;
2969     }
2970   if (PREDICT_FALSE (wait_for_time < 0))
2971     {
2972       if (VPPCOM_DEBUG > 0)
2973         clib_warning ("ERROR: Invalid wait_for_time (%f)!", wait_for_time);
2974       return VPPCOM_EINVAL;
2975     }
2976   memset (events, 0, sizeof (*events) * maxevents);
2977
2978   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
2979   vep_next_sid = vep_session->vep.next_sid;
2980   is_vep = vep_session->is_vep;
2981   wait_cont_idx = vep_session->wait_cont_idx;
2982   clib_spinlock_unlock (&vcm->sessions_lockp);
2983
2984   if (PREDICT_FALSE (!is_vep))
2985     {
2986       if (VPPCOM_DEBUG > 0)
2987         clib_warning ("ERROR: vep_idx (%u) is not a vep!", vep_idx);
2988       rv = VPPCOM_EINVAL;
2989       goto done;
2990     }
2991   if ((VPPCOM_DEBUG > 0) && (PREDICT_FALSE (vep_next_sid == ~0)))
2992     {
2993       clib_warning ("WARNING: vep_idx (%u) is empty!", vep_idx);
2994       goto done;
2995     }
2996
2997   do
2998     {
2999       u32 sid;
3000       u32 next_sid = ~0;
3001       session_t *session;
3002
3003       for (sid = (wait_cont_idx == ~0) ? vep_next_sid : wait_cont_idx;
3004            sid != ~0; sid = next_sid)
3005         {
3006           u32 session_events, et_mask, clear_et_mask, session_vep_idx;
3007           u8 add_event, is_vep_session;
3008           int ready;
3009           u64 session_ev_data;
3010
3011           VCL_LOCK_AND_GET_SESSION (sid, &session);
3012           next_sid = session->vep.next_sid;
3013           session_events = session->vep.ev.events;
3014           et_mask = session->vep.et_mask;
3015           is_vep = session->is_vep;
3016           is_vep_session = session->is_vep_session;
3017           session_vep_idx = session->vep.vep_idx;
3018           session_ev_data = session->vep.ev.data.u64;
3019           clib_spinlock_unlock (&vcm->sessions_lockp);
3020
3021           if (PREDICT_FALSE (is_vep))
3022             {
3023               if (VPPCOM_DEBUG > 0)
3024                 clib_warning ("ERROR: sid (%u) is a vep!", vep_idx);
3025               rv = VPPCOM_EINVAL;
3026               goto done;
3027             }
3028           if (PREDICT_FALSE (!is_vep_session))
3029             {
3030               if (VPPCOM_DEBUG > 0)
3031                 clib_warning ("EPOLL_CTL_MOD: session (%u) is not "
3032                               "a vep session!", sid);
3033               rv = VPPCOM_EINVAL;
3034               goto done;
3035             }
3036           if (PREDICT_FALSE (session_vep_idx != vep_idx))
3037             {
3038               clib_warning ("EPOLL_CTL_MOD: session (%u) "
3039                             "vep_idx (%u) != vep_idx (%u)!",
3040                             sid, session->vep.vep_idx, vep_idx);
3041               rv = VPPCOM_EINVAL;
3042               goto done;
3043             }
3044
3045           add_event = clear_et_mask = 0;
3046
3047           if ((EPOLLIN & session_events) && (EPOLLIN & et_mask))
3048             {
3049               VCL_LOCK_AND_GET_SESSION (sid, &session);
3050               ready = vppcom_session_read_ready (session, sid);
3051               clib_spinlock_unlock (&vcm->sessions_lockp);
3052               if (ready > 0)
3053                 {
3054                   add_event = 1;
3055                   events[num_ev].events |= EPOLLIN;
3056                   if (EPOLLET & session_events)
3057                     clear_et_mask |= EPOLLIN;
3058                 }
3059               else if (ready < 0)
3060                 {
3061                   add_event = 1;
3062                   switch (ready)
3063                     {
3064                     case VPPCOM_ECONNRESET:
3065                       events[num_ev].events |= EPOLLHUP | EPOLLRDHUP;
3066                       break;
3067
3068                     default:
3069                       events[num_ev].events |= EPOLLERR;
3070                       break;
3071                     }
3072                 }
3073             }
3074
3075           if ((EPOLLOUT & session_events) && (EPOLLOUT & et_mask))
3076             {
3077               VCL_LOCK_AND_GET_SESSION (sid, &session);
3078               ready = vppcom_session_write_ready (session, sid);
3079               clib_spinlock_unlock (&vcm->sessions_lockp);
3080               if (ready > 0)
3081                 {
3082                   add_event = 1;
3083                   events[num_ev].events |= EPOLLOUT;
3084                   if (EPOLLET & session_events)
3085                     clear_et_mask |= EPOLLOUT;
3086                 }
3087               else if (ready < 0)
3088                 {
3089                   add_event = 1;
3090                   switch (ready)
3091                     {
3092                     case VPPCOM_ECONNRESET:
3093                       events[num_ev].events |= EPOLLHUP;
3094                       break;
3095
3096                     default:
3097                       events[num_ev].events |= EPOLLERR;
3098                       break;
3099                     }
3100                 }
3101             }
3102
3103           if (add_event)
3104             {
3105               events[num_ev].data.u64 = session_ev_data;
3106               if (EPOLLONESHOT & session_events)
3107                 {
3108                   VCL_LOCK_AND_GET_SESSION (sid, &session);
3109                   session->vep.ev.events = 0;
3110                   clib_spinlock_unlock (&vcm->sessions_lockp);
3111                 }
3112               num_ev++;
3113               if (num_ev == maxevents)
3114                 {
3115                   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3116                   vep_session->wait_cont_idx = next_sid;
3117                   clib_spinlock_unlock (&vcm->sessions_lockp);
3118                   goto done;
3119                 }
3120             }
3121           if (wait_cont_idx != ~0)
3122             {
3123               if (next_sid == ~0)
3124                 next_sid = vep_next_sid;
3125               else if (next_sid == wait_cont_idx)
3126                 next_sid = ~0;
3127             }
3128         }
3129     }
3130   while ((num_ev == 0) && (clib_time_now (&vcm->clib_time) <= timeout));
3131
3132   if (wait_cont_idx != ~0)
3133     {
3134       VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3135       vep_session->wait_cont_idx = ~0;
3136       clib_spinlock_unlock (&vcm->sessions_lockp);
3137     }
3138 done:
3139   return (rv != VPPCOM_OK) ? rv : num_ev;
3140 }
3141
3142 int
3143 vppcom_session_attr (uint32_t session_index, uint32_t op,
3144                      void *buffer, uint32_t * buflen)
3145 {
3146   vppcom_main_t *vcm = &vppcom_main;
3147   session_t *session;
3148   int rv = VPPCOM_OK;
3149   u32 *flags = buffer;
3150   vppcom_endpt_t *ep = buffer;
3151
3152   VCL_LOCK_AND_GET_SESSION (session_index, &session);
3153   switch (op)
3154     {
3155     case VPPCOM_ATTR_GET_NREAD:
3156       rv = vppcom_session_read_ready (session, session_index);
3157       if (VPPCOM_DEBUG > 0)
3158         clib_warning ("VPPCOM_ATTR_GET_NREAD: nread = %d", rv);
3159
3160       break;
3161
3162     case VPPCOM_ATTR_PEEK_NREAD:
3163       /* TBD */
3164       break;
3165
3166     case VPPCOM_ATTR_GET_FLAGS:
3167       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3168         {
3169           *flags = O_RDWR | ((session->is_nonblocking) ? O_NONBLOCK : 0);
3170           *buflen = sizeof (*flags);
3171           if (VPPCOM_DEBUG > 0)
3172             clib_warning ("VPPCOM_ATTR_GET_FLAGS: flags = 0x%08x, "
3173                           "is_nonblocking = %u", *flags,
3174                           session->is_nonblocking);
3175         }
3176       else
3177         rv = VPPCOM_EINVAL;
3178       break;
3179
3180     case VPPCOM_ATTR_SET_FLAGS:
3181       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3182         {
3183           session->is_nonblocking = (*flags & O_NONBLOCK) ? 1 : 0;
3184           if (VPPCOM_DEBUG > 0)
3185             clib_warning ("VPPCOM_ATTR_SET_FLAGS: flags = 0x%08x, "
3186                           "is_nonblocking = %u", *flags,
3187                           session->is_nonblocking);
3188         }
3189       else
3190         rv = VPPCOM_EINVAL;
3191       break;
3192
3193     case VPPCOM_ATTR_GET_PEER_ADDR:
3194       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3195         {
3196           ep->vrf = session->vrf;
3197           ep->is_ip4 = session->peer_addr.is_ip4;
3198           ep->port = session->peer_port;
3199           if (session->peer_addr.is_ip4)
3200             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3201                          sizeof (ip4_address_t));
3202           else
3203             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3204                          sizeof (ip6_address_t));
3205           *buflen = sizeof (*ep);
3206           if (VPPCOM_DEBUG > 0)
3207             clib_warning ("VPPCOM_ATTR_GET_PEER_ADDR: sid %u is_ip4 = %u, "
3208                           "addr = %U, port %u", session_index,
3209                           ep->is_ip4, format_ip46_address,
3210                           &session->peer_addr.ip46, ep->is_ip4,
3211                           clib_net_to_host_u16 (ep->port));
3212         }
3213       else
3214         rv = VPPCOM_EINVAL;
3215       break;
3216
3217     case VPPCOM_ATTR_GET_LCL_ADDR:
3218       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3219         {
3220           ep->vrf = session->vrf;
3221           ep->is_ip4 = session->lcl_addr.is_ip4;
3222           ep->port = session->lcl_port;
3223           if (session->lcl_addr.is_ip4)
3224             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip4,
3225                          sizeof (ip4_address_t));
3226           else
3227             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip6,
3228                          sizeof (ip6_address_t));
3229           *buflen = sizeof (*ep);
3230           if (VPPCOM_DEBUG > 0)
3231             clib_warning ("VPPCOM_ATTR_GET_LCL_ADDR: sid %u is_ip4 = %u, "
3232                           "addr = %U port %d", session_index,
3233                           ep->is_ip4, format_ip46_address,
3234                           &session->lcl_addr.ip46, ep->is_ip4,
3235                           clib_net_to_host_u16 (ep->port));
3236         }
3237       else
3238         rv = VPPCOM_EINVAL;
3239       break;
3240
3241     case VPPCOM_ATTR_SET_REUSEADDR:
3242       break;
3243
3244     case VPPCOM_ATTR_SET_BROADCAST:
3245       break;
3246
3247     case VPPCOM_ATTR_SET_V6ONLY:
3248       break;
3249
3250     case VPPCOM_ATTR_SET_KEEPALIVE:
3251       break;
3252
3253     case VPPCOM_ATTR_SET_TCP_KEEPIDLE:
3254       break;
3255
3256     case VPPCOM_ATTR_SET_TCP_KEEPINTVL:
3257       break;
3258
3259     default:
3260       rv = VPPCOM_EINVAL;
3261       break;
3262     }
3263
3264 done:
3265   clib_spinlock_unlock (&vcm->sessions_lockp);
3266   return rv;
3267 }
3268
3269 int
3270 vppcom_session_recvfrom (uint32_t session_index, void *buffer,
3271                          uint32_t buflen, int flags, vppcom_endpt_t * ep)
3272 {
3273   vppcom_main_t *vcm = &vppcom_main;
3274   int rv = VPPCOM_OK;
3275   session_t *session = 0;
3276
3277   if (ep)
3278     {
3279       clib_spinlock_lock (&vcm->sessions_lockp);
3280       rv = vppcom_session_at_index (session_index, &session);
3281       if (PREDICT_FALSE (rv))
3282         {
3283           clib_spinlock_unlock (&vcm->sessions_lockp);
3284           if (VPPCOM_DEBUG > 0)
3285             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
3286                           vcm->my_pid, session_index);
3287           rv = VPPCOM_EINVAL;
3288         }
3289       ep->vrf = session->vrf;
3290       ep->is_ip4 = session->peer_addr.is_ip4;
3291       ep->port = session->peer_port;
3292       if (session->peer_addr.is_ip4)
3293         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3294                      sizeof (ip4_address_t));
3295       else
3296         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3297                      sizeof (ip6_address_t));
3298       clib_spinlock_unlock (&vcm->sessions_lockp);
3299       rv = vppcom_session_read (session_index, buffer, buflen);
3300     }
3301   else if (flags == 0)
3302     rv = vppcom_session_read (session_index, buffer, buflen);
3303   else if (flags & MSG_PEEK)
3304     {
3305       rv = vppcom_session_attr (session_index, VPPCOM_ATTR_GET_NREAD, 0, 0);
3306       if (rv > buflen)
3307         rv = buflen;
3308     }
3309   else
3310     {
3311       clib_warning ("Unsupport flags for recvfro %d", flags);
3312       rv = VPPCOM_EAFNOSUPPORT;
3313     }
3314
3315   return rv;
3316 }
3317
3318 int
3319 vppcom_session_sendto (uint32_t session_index, void *buffer,
3320                        uint32_t buflen, int flags, vppcom_endpt_t * ep)
3321 {
3322   if (ep)
3323     // TBD
3324     return -1;
3325   else if (flags == 0)
3326     return (vppcom_session_write (session_index, buffer, buflen));
3327   else if (flags)
3328     // TBD check the flags and do the right thing
3329     return (vppcom_session_write (session_index, buffer, buflen));
3330
3331   return -1;
3332 }
3333
3334 /*
3335  * fd.io coding-style-patch-verification: ON
3336  *
3337  * Local Variables:
3338  * eval: (c-set-style "gnu")
3339  * End:
3340  */