api: multiple connections per process
[vpp.git] / src / vpp-api / vapi / vapi.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2017 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <arpa/inet.h>
22 #include <stddef.h>
23 #include <assert.h>
24
25 #include <vpp-api/vapi/vapi_dbg.h>
26 #include <vpp-api/vapi/vapi.h>
27 #include <vpp-api/vapi/vapi_internal.h>
28 #include <vppinfra/types.h>
29 #include <vppinfra/pool.h>
30 #include <vlib/vlib.h>
31 #include <vlibapi/api_common.h>
32 #include <vlibmemory/memory_client.h>
33
34 #include <vapi/memclnt.api.vapi.h>
35
36 /* we need to use control pings for some stuff and because we're forced to put
37  * the code in headers, we need a way to be able to grab the ids of these
38  * messages - so declare them here as extern */
39 vapi_msg_id_t vapi_msg_id_control_ping = 0;
40 vapi_msg_id_t vapi_msg_id_control_ping_reply = 0;
41
42 DEFINE_VAPI_MSG_IDS_MEMCLNT_API_JSON;
43 DEFINE_VAPI_MSG_IDS_VPE_API_JSON;
44
45 struct
46 {
47   size_t count;
48   vapi_message_desc_t **msgs;
49   size_t max_len_name_with_crc;
50 } __vapi_metadata;
51
52 typedef struct
53 {
54   u32 context;
55   vapi_cb_t callback;
56   void *callback_ctx;
57   bool is_dump;
58 } vapi_req_t;
59
60 static const u32 context_counter_mask = (1 << 31);
61
62 typedef struct
63 {
64   vapi_error_e (*cb) (vapi_ctx_t ctx, void *callback_ctx, vapi_msg_id_t id,
65                       void *payload);
66   void *ctx;
67 } vapi_generic_cb_with_ctx;
68
69 typedef struct
70 {
71   vapi_error_e (*cb) (vapi_ctx_t ctx, void *callback_ctx, void *payload);
72   void *ctx;
73 } vapi_event_cb_with_ctx;
74
75 struct vapi_ctx_s
76 {
77   vapi_mode_e mode;
78   int requests_size;            /* size of the requests array (circular queue) */
79   int requests_start;           /* index of first request */
80   int requests_count;           /* number of used slots */
81   vapi_req_t *requests;
82   u32 context_counter;
83   vapi_generic_cb_with_ctx generic_cb;
84   vapi_event_cb_with_ctx *event_cbs;
85   u16 *vapi_msg_id_t_to_vl_msg_id;
86   u16 vl_msg_id_max;
87   vapi_msg_id_t *vl_msg_id_to_vapi_msg_t;
88   bool connected;
89   bool handle_keepalives;
90   pthread_mutex_t requests_mutex;
91 };
92
93 u32
94 vapi_gen_req_context (vapi_ctx_t ctx)
95 {
96   ++ctx->context_counter;
97   ctx->context_counter %= context_counter_mask;
98   return ctx->context_counter | context_counter_mask;
99 }
100
101 size_t
102 vapi_get_request_count (vapi_ctx_t ctx)
103 {
104   return ctx->requests_count;
105 }
106
107 bool
108 vapi_requests_full (vapi_ctx_t ctx)
109 {
110   return (ctx->requests_count == ctx->requests_size);
111 }
112
113 bool
114 vapi_requests_empty (vapi_ctx_t ctx)
115 {
116   return (0 == ctx->requests_count);
117 }
118
119 static int
120 vapi_requests_end (vapi_ctx_t ctx)
121 {
122   return (ctx->requests_start + ctx->requests_count) % ctx->requests_size;
123 }
124
125 void
126 vapi_store_request (vapi_ctx_t ctx, u32 context, bool is_dump,
127                     vapi_cb_t callback, void *callback_ctx)
128 {
129   assert (!vapi_requests_full (ctx));
130   /* if the mutex is not held, bad things will happen */
131   assert (0 != pthread_mutex_trylock (&ctx->requests_mutex));
132   const int requests_end = vapi_requests_end (ctx);
133   vapi_req_t *slot = &ctx->requests[requests_end];
134   slot->is_dump = is_dump;
135   slot->context = context;
136   slot->callback = callback;
137   slot->callback_ctx = callback_ctx;
138   VAPI_DBG ("stored@%d: context:%x (start is @%d)", requests_end, context,
139             ctx->requests_start);
140   ++ctx->requests_count;
141   assert (!vapi_requests_empty (ctx));
142 }
143
144 #if VAPI_DEBUG_ALLOC
145 struct to_be_freed_s;
146 struct to_be_freed_s
147 {
148   void *v;
149   struct to_be_freed_s *next;
150 };
151
152 static struct to_be_freed_s *to_be_freed = NULL;
153
154 void
155 vapi_add_to_be_freed (void *v)
156 {
157   struct to_be_freed_s *prev = NULL;
158   struct to_be_freed_s *tmp;
159   tmp = to_be_freed;
160   while (tmp && tmp->v)
161     {
162       prev = tmp;
163       tmp = tmp->next;
164     }
165   if (!tmp)
166     {
167       if (!prev)
168         {
169           tmp = to_be_freed = calloc (1, sizeof (*to_be_freed));
170         }
171       else
172         {
173           tmp = prev->next = calloc (1, sizeof (*to_be_freed));
174         }
175     }
176   VAPI_DBG ("To be freed %p", v);
177   tmp->v = v;
178 }
179
180 void
181 vapi_trace_free (void *v)
182 {
183   struct to_be_freed_s *tmp = to_be_freed;
184   while (tmp && tmp->v != v)
185     {
186       tmp = tmp->next;
187     }
188   if (tmp && tmp->v == v)
189     {
190       VAPI_DBG ("Freed %p", v);
191       tmp->v = NULL;
192     }
193   else
194     {
195       VAPI_ERR ("Trying to free untracked pointer %p", v);
196       abort ();
197     }
198 }
199
200 void
201 vapi_to_be_freed_validate ()
202 {
203   struct to_be_freed_s *tmp = to_be_freed;
204   while (tmp)
205     {
206       if (tmp->v)
207         {
208           VAPI_ERR ("Unfreed msg %p!", tmp->v);
209         }
210       tmp = tmp->next;
211     }
212 }
213
214 #endif
215
216 void *
217 vapi_msg_alloc (vapi_ctx_t ctx, size_t size)
218 {
219   if (!ctx->connected)
220     {
221       return NULL;
222     }
223   void *rv = vl_msg_api_alloc_or_null (size);
224   return rv;
225 }
226
227 void
228 vapi_msg_free (vapi_ctx_t ctx, void *msg)
229 {
230   if (!ctx->connected)
231     {
232       return;
233     }
234 #if VAPI_DEBUG_ALLOC
235   vapi_trace_free (msg);
236 #endif
237   vl_msg_api_free (msg);
238 }
239
240 vapi_msg_id_t
241 vapi_lookup_vapi_msg_id_t (vapi_ctx_t ctx, u16 vl_msg_id)
242 {
243   if (vl_msg_id <= ctx->vl_msg_id_max)
244     {
245       return ctx->vl_msg_id_to_vapi_msg_t[vl_msg_id];
246     }
247   return VAPI_INVALID_MSG_ID;
248 }
249
250 vapi_error_e
251 vapi_ctx_alloc (vapi_ctx_t * result)
252 {
253   vapi_ctx_t ctx = calloc (1, sizeof (struct vapi_ctx_s));
254   if (!ctx)
255     {
256       return VAPI_ENOMEM;
257     }
258   ctx->context_counter = 0;
259   ctx->vapi_msg_id_t_to_vl_msg_id =
260     malloc (__vapi_metadata.count *
261             sizeof (*ctx->vapi_msg_id_t_to_vl_msg_id));
262   if (!ctx->vapi_msg_id_t_to_vl_msg_id)
263     {
264       goto fail;
265     }
266   clib_memset (ctx->vapi_msg_id_t_to_vl_msg_id, ~0,
267                __vapi_metadata.count *
268                sizeof (*ctx->vapi_msg_id_t_to_vl_msg_id));
269   ctx->event_cbs = calloc (__vapi_metadata.count, sizeof (*ctx->event_cbs));
270   if (!ctx->event_cbs)
271     {
272       goto fail;
273     }
274   pthread_mutex_init (&ctx->requests_mutex, NULL);
275   *result = ctx;
276   return VAPI_OK;
277 fail:
278   vapi_ctx_free (ctx);
279   return VAPI_ENOMEM;
280 }
281
282 void
283 vapi_ctx_free (vapi_ctx_t ctx)
284 {
285   assert (!ctx->connected);
286   free (ctx->requests);
287   free (ctx->vapi_msg_id_t_to_vl_msg_id);
288   free (ctx->event_cbs);
289   free (ctx->vl_msg_id_to_vapi_msg_t);
290   pthread_mutex_destroy (&ctx->requests_mutex);
291   free (ctx);
292 }
293
294 bool
295 vapi_is_msg_available (vapi_ctx_t ctx, vapi_msg_id_t id)
296 {
297   return vapi_lookup_vl_msg_id (ctx, id) != UINT16_MAX;
298 }
299
300 vapi_error_e
301 vapi_connect (vapi_ctx_t ctx, const char *name,
302               const char *chroot_prefix,
303               int max_outstanding_requests,
304               int response_queue_size, vapi_mode_e mode,
305               bool handle_keepalives)
306 {
307   if (response_queue_size <= 0 || max_outstanding_requests <= 0)
308     {
309       return VAPI_EINVAL;
310     }
311   if (!clib_mem_get_per_cpu_heap () && !clib_mem_init (0, 1024 * 1024 * 32))
312     {
313       return VAPI_ENOMEM;
314     }
315   ctx->requests_size = max_outstanding_requests;
316   const size_t size = ctx->requests_size * sizeof (*ctx->requests);
317   void *tmp = realloc (ctx->requests, size);
318   if (!tmp)
319     {
320       return VAPI_ENOMEM;
321     }
322   ctx->requests = tmp;
323   clib_memset (ctx->requests, 0, size);
324   /* coverity[MISSING_LOCK] - 177211 requests_mutex is not needed here */
325   ctx->requests_start = ctx->requests_count = 0;
326   if (chroot_prefix)
327     {
328       VAPI_DBG ("set memory root path `%s'", chroot_prefix);
329       vl_set_memory_root_path ((char *) chroot_prefix);
330     }
331   static char api_map[] = "/vpe-api";
332   VAPI_DBG ("client api map `%s'", api_map);
333   if ((vl_client_api_map (api_map)) < 0)
334     {
335       return VAPI_EMAP_FAIL;
336     }
337   VAPI_DBG ("connect client `%s'", name);
338   if (vl_client_connect ((char *) name, 0, response_queue_size) < 0)
339     {
340       vl_client_api_unmap ();
341       return VAPI_ECON_FAIL;
342     }
343 #if VAPI_DEBUG_CONNECT
344   VAPI_DBG ("start probing messages");
345 #endif
346   int rv;
347   int i;
348   for (i = 0; i < __vapi_metadata.count; ++i)
349     {
350       vapi_message_desc_t *m = __vapi_metadata.msgs[i];
351       u8 scratch[m->name_with_crc_len + 1];
352       memcpy (scratch, m->name_with_crc, m->name_with_crc_len + 1);
353       u32 id = vl_msg_api_get_msg_index (scratch);
354       if (VAPI_INVALID_MSG_ID != id)
355         {
356           if (id > UINT16_MAX)
357             {
358               VAPI_ERR ("Returned vl_msg_id `%u' > UINT16MAX `%u'!", id,
359                         UINT16_MAX);
360               rv = VAPI_EINVAL;
361               goto fail;
362             }
363           if (id > ctx->vl_msg_id_max)
364             {
365               vapi_msg_id_t *tmp = realloc (ctx->vl_msg_id_to_vapi_msg_t,
366                                             sizeof
367                                             (*ctx->vl_msg_id_to_vapi_msg_t) *
368                                             (id + 1));
369               if (!tmp)
370                 {
371                   rv = VAPI_ENOMEM;
372                   goto fail;
373                 }
374               ctx->vl_msg_id_to_vapi_msg_t = tmp;
375               ctx->vl_msg_id_max = id;
376             }
377           ctx->vl_msg_id_to_vapi_msg_t[id] = m->id;
378           ctx->vapi_msg_id_t_to_vl_msg_id[m->id] = id;
379 #if VAPI_DEBUG_CONNECT
380           VAPI_DBG ("Message `%s' has vl_msg_id `%u'", m->name_with_crc,
381                     (unsigned) id);
382 #endif
383         }
384       else
385         {
386           ctx->vapi_msg_id_t_to_vl_msg_id[m->id] = UINT16_MAX;
387           VAPI_DBG ("Message `%s' not available", m->name_with_crc);
388         }
389     }
390 #if VAPI_DEBUG_CONNECT
391   VAPI_DBG ("finished probing messages");
392 #endif
393   if (!vapi_is_msg_available (ctx, vapi_msg_id_control_ping) ||
394       !vapi_is_msg_available (ctx, vapi_msg_id_control_ping_reply))
395     {
396       VAPI_ERR
397         ("control ping or control ping reply not available, cannot connect");
398       rv = VAPI_EINCOMPATIBLE;
399       goto fail;
400     }
401   ctx->mode = mode;
402   ctx->connected = true;
403   if (vapi_is_msg_available (ctx, vapi_msg_id_memclnt_keepalive))
404     {
405       ctx->handle_keepalives = handle_keepalives;
406     }
407   else
408     {
409       ctx->handle_keepalives = false;
410     }
411   return VAPI_OK;
412 fail:
413   vl_client_disconnect ();
414   vl_client_api_unmap ();
415   return rv;
416 }
417
418 vapi_error_e
419 vapi_disconnect (vapi_ctx_t ctx)
420 {
421   if (!ctx->connected)
422     {
423       return VAPI_EINVAL;
424     }
425   vl_client_disconnect ();
426   vl_client_api_unmap ();
427 #if VAPI_DEBUG_ALLOC
428   vapi_to_be_freed_validate ();
429 #endif
430   ctx->connected = false;
431   return VAPI_OK;
432 }
433
434 vapi_error_e
435 vapi_get_fd (vapi_ctx_t ctx, int *fd)
436 {
437   return VAPI_ENOTSUP;
438 }
439
440 vapi_error_e
441 vapi_send (vapi_ctx_t ctx, void *msg)
442 {
443   vapi_error_e rv = VAPI_OK;
444   if (!ctx || !msg || !ctx->connected)
445     {
446       rv = VAPI_EINVAL;
447       goto out;
448     }
449   int tmp;
450   svm_queue_t *q = vlibapi_get_main ()->shmem_hdr->vl_input_queue;
451 #if VAPI_DEBUG
452   unsigned msgid = be16toh (*(u16 *) msg);
453   if (msgid <= ctx->vl_msg_id_max)
454     {
455       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid];
456       if (id < __vapi_metadata.count)
457         {
458           VAPI_DBG ("send msg@%p:%u[%s]", msg, msgid,
459                     __vapi_metadata.msgs[id]->name);
460         }
461       else
462         {
463           VAPI_DBG ("send msg@%p:%u[UNKNOWN]", msg, msgid);
464         }
465     }
466   else
467     {
468       VAPI_DBG ("send msg@%p:%u[UNKNOWN]", msg, msgid);
469     }
470 #endif
471   tmp = svm_queue_add (q, (u8 *) & msg,
472                        VAPI_MODE_BLOCKING == ctx->mode ? 0 : 1);
473   if (tmp < 0)
474     {
475       rv = VAPI_EAGAIN;
476     }
477   else
478     VL_MSG_API_POISON (msg);
479 out:
480   VAPI_DBG ("vapi_send() rv = %d", rv);
481   return rv;
482 }
483
484 vapi_error_e
485 vapi_send2 (vapi_ctx_t ctx, void *msg1, void *msg2)
486 {
487   vapi_error_e rv = VAPI_OK;
488   if (!ctx || !msg1 || !msg2 || !ctx->connected)
489     {
490       rv = VAPI_EINVAL;
491       goto out;
492     }
493   svm_queue_t *q = vlibapi_get_main ()->shmem_hdr->vl_input_queue;
494 #if VAPI_DEBUG
495   unsigned msgid1 = be16toh (*(u16 *) msg1);
496   unsigned msgid2 = be16toh (*(u16 *) msg2);
497   const char *name1 = "UNKNOWN";
498   const char *name2 = "UNKNOWN";
499   if (msgid1 <= ctx->vl_msg_id_max)
500     {
501       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid1];
502       if (id < __vapi_metadata.count)
503         {
504           name1 = __vapi_metadata.msgs[id]->name;
505         }
506     }
507   if (msgid2 <= ctx->vl_msg_id_max)
508     {
509       vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid2];
510       if (id < __vapi_metadata.count)
511         {
512           name2 = __vapi_metadata.msgs[id]->name;
513         }
514     }
515   VAPI_DBG ("send two: %u[%s], %u[%s]", msgid1, name1, msgid2, name2);
516 #endif
517   int tmp = svm_queue_add2 (q, (u8 *) & msg1, (u8 *) & msg2,
518                             VAPI_MODE_BLOCKING == ctx->mode ? 0 : 1);
519   if (tmp < 0)
520     {
521       rv = VAPI_EAGAIN;
522     }
523   else
524     VL_MSG_API_POISON (msg1);
525 out:
526   VAPI_DBG ("vapi_send() rv = %d", rv);
527   return rv;
528 }
529
530 vapi_error_e
531 vapi_recv (vapi_ctx_t ctx, void **msg, size_t * msg_size,
532            svm_q_conditional_wait_t cond, u32 time)
533 {
534   if (!ctx || !ctx->connected || !msg || !msg_size)
535     {
536       return VAPI_EINVAL;
537     }
538   vapi_error_e rv = VAPI_OK;
539   api_main_t *am = vlibapi_get_main ();
540   uword data;
541
542   if (am->our_pid == 0)
543     {
544       return VAPI_EINVAL;
545     }
546
547   svm_queue_t *q = am->vl_input_queue;
548 again:
549   VAPI_DBG ("doing shm queue sub");
550
551   int tmp = svm_queue_sub (q, (u8 *) & data, cond, time);
552
553   if (tmp == 0)
554     {
555       VL_MSG_API_UNPOISON ((void *) data);
556 #if VAPI_DEBUG_ALLOC
557       vapi_add_to_be_freed ((void *) data);
558 #endif
559       msgbuf_t *msgbuf =
560         (msgbuf_t *) ((u8 *) data - offsetof (msgbuf_t, data));
561       if (!msgbuf->data_len)
562         {
563           vapi_msg_free (ctx, (u8 *) data);
564           return VAPI_EAGAIN;
565         }
566       *msg = (u8 *) data;
567       *msg_size = ntohl (msgbuf->data_len);
568 #if VAPI_DEBUG
569       unsigned msgid = be16toh (*(u16 *) * msg);
570       if (msgid <= ctx->vl_msg_id_max)
571         {
572           vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[msgid];
573           if (id < __vapi_metadata.count)
574             {
575               VAPI_DBG ("recv msg@%p:%u[%s]", *msg, msgid,
576                         __vapi_metadata.msgs[id]->name);
577             }
578           else
579             {
580               VAPI_DBG ("recv msg@%p:%u[UNKNOWN]", *msg, msgid);
581             }
582         }
583       else
584         {
585           VAPI_DBG ("recv msg@%p:%u[UNKNOWN]", *msg, msgid);
586         }
587 #endif
588       if (ctx->handle_keepalives)
589         {
590           unsigned msgid = be16toh (*(u16 *) * msg);
591           if (msgid ==
592               vapi_lookup_vl_msg_id (ctx, vapi_msg_id_memclnt_keepalive))
593             {
594               vapi_msg_memclnt_keepalive_reply *reply = NULL;
595               do
596                 {
597                   reply = vapi_msg_alloc (ctx, sizeof (*reply));
598                 }
599               while (!reply);
600               reply->header.context = vapi_get_client_index (ctx);
601               reply->header._vl_msg_id =
602                 vapi_lookup_vl_msg_id (ctx,
603                                        vapi_msg_id_memclnt_keepalive_reply);
604               reply->payload.retval = 0;
605               vapi_msg_memclnt_keepalive_reply_hton (reply);
606               while (VAPI_EAGAIN == vapi_send (ctx, reply));
607               vapi_msg_free (ctx, *msg);
608               VAPI_DBG ("autohandled memclnt_keepalive");
609               goto again;
610             }
611         }
612     }
613   else
614     {
615       rv = VAPI_EAGAIN;
616     }
617   return rv;
618 }
619
620 vapi_error_e
621 vapi_wait (vapi_ctx_t ctx, vapi_wait_mode_e mode)
622 {
623   return VAPI_ENOTSUP;
624 }
625
626 static vapi_error_e
627 vapi_dispatch_response (vapi_ctx_t ctx, vapi_msg_id_t id,
628                         u32 context, void *msg)
629 {
630   int mrv;
631   if (0 != (mrv = pthread_mutex_lock (&ctx->requests_mutex)))
632     {
633       VAPI_DBG ("pthread_mutex_lock() failed, rv=%d:%s", mrv, strerror (mrv));
634       return VAPI_MUTEX_FAILURE;
635     }
636   int tmp = ctx->requests_start;
637   const int requests_end = vapi_requests_end (ctx);
638   while (ctx->requests[tmp].context != context && tmp != requests_end)
639     {
640       ++tmp;
641       if (tmp == ctx->requests_size)
642         {
643           tmp = 0;
644         }
645     }
646   VAPI_DBG ("dispatch, search from %d, %s at %d", ctx->requests_start,
647             ctx->requests[tmp].context == context ? "matched" : "stopped",
648             tmp);
649   vapi_error_e rv = VAPI_OK;
650   if (ctx->requests[tmp].context == context)
651     {
652       while (ctx->requests_start != tmp)
653         {
654           VAPI_ERR ("No response to req with context=%u",
655                     (unsigned) ctx->requests[tmp].context);
656           ctx->requests[ctx->requests_start].callback (ctx, ctx->requests
657                                                        [ctx->
658                                                         requests_start].callback_ctx,
659                                                        VAPI_ENORESP, true,
660                                                        NULL);
661           clib_memset (&ctx->requests[ctx->requests_start], 0,
662                        sizeof (ctx->requests[ctx->requests_start]));
663           ++ctx->requests_start;
664           --ctx->requests_count;
665           if (ctx->requests_start == ctx->requests_size)
666             {
667               ctx->requests_start = 0;
668             }
669         }
670       // now ctx->requests_start == tmp
671       int payload_offset = vapi_get_payload_offset (id);
672       void *payload = ((u8 *) msg) + payload_offset;
673       bool is_last = true;
674       if (ctx->requests[tmp].is_dump)
675         {
676           if (vapi_msg_id_control_ping_reply == id)
677             {
678               payload = NULL;
679             }
680           else
681             {
682               is_last = false;
683             }
684         }
685       if (payload_offset != -1)
686         {
687           rv =
688             ctx->requests[tmp].callback (ctx, ctx->requests[tmp].callback_ctx,
689                                          VAPI_OK, is_last, payload);
690         }
691       else
692         {
693           /* this is a message without payload, so bend the callback a little
694            */
695           rv =
696             ((vapi_error_e (*)(vapi_ctx_t, void *, vapi_error_e, bool))
697              ctx->requests[tmp].callback) (ctx,
698                                            ctx->requests[tmp].callback_ctx,
699                                            VAPI_OK, is_last);
700         }
701       if (is_last)
702         {
703           clib_memset (&ctx->requests[ctx->requests_start], 0,
704                        sizeof (ctx->requests[ctx->requests_start]));
705           ++ctx->requests_start;
706           --ctx->requests_count;
707           if (ctx->requests_start == ctx->requests_size)
708             {
709               ctx->requests_start = 0;
710             }
711         }
712       VAPI_DBG ("after dispatch, req start = %d, end = %d, count = %d",
713                 ctx->requests_start, requests_end, ctx->requests_count);
714     }
715   if (0 != (mrv = pthread_mutex_unlock (&ctx->requests_mutex)))
716     {
717       VAPI_DBG ("pthread_mutex_unlock() failed, rv=%d:%s", mrv,
718                 strerror (mrv));
719       abort ();                 /* this really shouldn't happen */
720     }
721   return rv;
722 }
723
724 static vapi_error_e
725 vapi_dispatch_event (vapi_ctx_t ctx, vapi_msg_id_t id, void *msg)
726 {
727   if (ctx->event_cbs[id].cb)
728     {
729       return ctx->event_cbs[id].cb (ctx, ctx->event_cbs[id].ctx, msg);
730     }
731   else if (ctx->generic_cb.cb)
732     {
733       return ctx->generic_cb.cb (ctx, ctx->generic_cb.ctx, id, msg);
734     }
735   else
736     {
737       VAPI_DBG
738         ("No handler/generic handler for msg id %u[%s], message ignored",
739          (unsigned) id, __vapi_metadata.msgs[id]->name);
740     }
741   return VAPI_OK;
742 }
743
744 bool
745 vapi_msg_is_with_context (vapi_msg_id_t id)
746 {
747   assert (id <= __vapi_metadata.count);
748   return __vapi_metadata.msgs[id]->has_context;
749 }
750
751 vapi_error_e
752 vapi_dispatch_one (vapi_ctx_t ctx)
753 {
754   VAPI_DBG ("vapi_dispatch_one()");
755   void *msg;
756   size_t size;
757   vapi_error_e rv = vapi_recv (ctx, &msg, &size, SVM_Q_WAIT, 0);
758   if (VAPI_OK != rv)
759     {
760       VAPI_DBG ("vapi_recv failed with rv=%d", rv);
761       return rv;
762     }
763   u16 vpp_id = be16toh (*(u16 *) msg);
764   if (vpp_id > ctx->vl_msg_id_max)
765     {
766       VAPI_ERR ("Unknown msg ID received, id `%u', out of range <0,%u>",
767                 (unsigned) vpp_id, (unsigned) ctx->vl_msg_id_max);
768       vapi_msg_free (ctx, msg);
769       return VAPI_EINVAL;
770     }
771   if (VAPI_INVALID_MSG_ID == (unsigned) ctx->vl_msg_id_to_vapi_msg_t[vpp_id])
772     {
773       VAPI_ERR ("Unknown msg ID received, id `%u' marked as not supported",
774                 (unsigned) vpp_id);
775       vapi_msg_free (ctx, msg);
776       return VAPI_EINVAL;
777     }
778   const vapi_msg_id_t id = ctx->vl_msg_id_to_vapi_msg_t[vpp_id];
779   const size_t expect_size = vapi_get_message_size (id);
780   if (size < expect_size)
781     {
782       VAPI_ERR
783         ("Invalid msg received, unexpected size `%zu' < expected min `%zu'",
784          size, expect_size);
785       vapi_msg_free (ctx, msg);
786       return VAPI_EINVAL;
787     }
788   u32 context;
789   vapi_get_swap_to_host_func (id) (msg);
790   if (vapi_msg_is_with_context (id))
791     {
792       context = *(u32 *) (((u8 *) msg) + vapi_get_context_offset (id));
793       /* is this a message originating from VAPI? */
794       VAPI_DBG ("dispatch, context is %x", context);
795       if (context & context_counter_mask)
796         {
797           rv = vapi_dispatch_response (ctx, id, context, msg);
798           goto done;
799         }
800     }
801   rv = vapi_dispatch_event (ctx, id, msg);
802
803 done:
804   vapi_msg_free (ctx, msg);
805   return rv;
806 }
807
808 vapi_error_e
809 vapi_dispatch (vapi_ctx_t ctx)
810 {
811   vapi_error_e rv = VAPI_OK;
812   while (!vapi_requests_empty (ctx))
813     {
814       rv = vapi_dispatch_one (ctx);
815       if (VAPI_OK != rv)
816         {
817           return rv;
818         }
819     }
820   return rv;
821 }
822
823 void
824 vapi_set_event_cb (vapi_ctx_t ctx, vapi_msg_id_t id,
825                    vapi_event_cb callback, void *callback_ctx)
826 {
827   vapi_event_cb_with_ctx *c = &ctx->event_cbs[id];
828   c->cb = callback;
829   c->ctx = callback_ctx;
830 }
831
832 void
833 vapi_clear_event_cb (vapi_ctx_t ctx, vapi_msg_id_t id)
834 {
835   vapi_set_event_cb (ctx, id, NULL, NULL);
836 }
837
838 void
839 vapi_set_generic_event_cb (vapi_ctx_t ctx, vapi_generic_event_cb callback,
840                            void *callback_ctx)
841 {
842   ctx->generic_cb.cb = callback;
843   ctx->generic_cb.ctx = callback_ctx;
844 }
845
846 void
847 vapi_clear_generic_event_cb (vapi_ctx_t ctx)
848 {
849   ctx->generic_cb.cb = NULL;
850   ctx->generic_cb.ctx = NULL;
851 }
852
853 u16
854 vapi_lookup_vl_msg_id (vapi_ctx_t ctx, vapi_msg_id_t id)
855 {
856   assert (id < __vapi_metadata.count);
857   return ctx->vapi_msg_id_t_to_vl_msg_id[id];
858 }
859
860 int
861 vapi_get_client_index (vapi_ctx_t ctx)
862 {
863   return vlibapi_get_main ()->my_client_index;
864 }
865
866 bool
867 vapi_is_nonblocking (vapi_ctx_t ctx)
868 {
869   return (VAPI_MODE_NONBLOCKING == ctx->mode);
870 }
871
872 size_t
873 vapi_get_max_request_count (vapi_ctx_t ctx)
874 {
875   return ctx->requests_size - 1;
876 }
877
878 int
879 vapi_get_payload_offset (vapi_msg_id_t id)
880 {
881   assert (id < __vapi_metadata.count);
882   return __vapi_metadata.msgs[id]->payload_offset;
883 }
884
885 void (*vapi_get_swap_to_host_func (vapi_msg_id_t id)) (void *msg)
886 {
887   assert (id < __vapi_metadata.count);
888   return __vapi_metadata.msgs[id]->swap_to_host;
889 }
890
891 void (*vapi_get_swap_to_be_func (vapi_msg_id_t id)) (void *msg)
892 {
893   assert (id < __vapi_metadata.count);
894   return __vapi_metadata.msgs[id]->swap_to_be;
895 }
896
897 size_t
898 vapi_get_message_size (vapi_msg_id_t id)
899 {
900   assert (id < __vapi_metadata.count);
901   return __vapi_metadata.msgs[id]->size;
902 }
903
904 size_t
905 vapi_get_context_offset (vapi_msg_id_t id)
906 {
907   assert (id < __vapi_metadata.count);
908   return __vapi_metadata.msgs[id]->context_offset;
909 }
910
911 vapi_msg_id_t
912 vapi_register_msg (vapi_message_desc_t * msg)
913 {
914   int i = 0;
915   for (i = 0; i < __vapi_metadata.count; ++i)
916     {
917       if (!strcmp
918           (msg->name_with_crc, __vapi_metadata.msgs[i]->name_with_crc))
919         {
920           /* this happens if somebody is linking together several objects while
921            * using the static inline headers, just fill in the already
922            * assigned id here so that all the objects are in sync */
923           msg->id = __vapi_metadata.msgs[i]->id;
924           return msg->id;
925         }
926     }
927   vapi_msg_id_t id = __vapi_metadata.count;
928   ++__vapi_metadata.count;
929   __vapi_metadata.msgs =
930     realloc (__vapi_metadata.msgs,
931              sizeof (*__vapi_metadata.msgs) * __vapi_metadata.count);
932   __vapi_metadata.msgs[id] = msg;
933   size_t s = strlen (msg->name_with_crc);
934   if (s > __vapi_metadata.max_len_name_with_crc)
935     {
936       __vapi_metadata.max_len_name_with_crc = s;
937     }
938   msg->id = id;
939   return id;
940 }
941
942 vapi_error_e
943 vapi_producer_lock (vapi_ctx_t ctx)
944 {
945   int mrv;
946   if (0 != (mrv = pthread_mutex_lock (&ctx->requests_mutex)))
947     {
948       VAPI_DBG ("pthread_mutex_lock() failed, rv=%d:%s", mrv, strerror (mrv));
949       (void) mrv;               /* avoid warning if the above debug is not enabled */
950       return VAPI_MUTEX_FAILURE;
951     }
952   return VAPI_OK;
953 }
954
955 vapi_error_e
956 vapi_producer_unlock (vapi_ctx_t ctx)
957 {
958   int mrv;
959   if (0 != (mrv = pthread_mutex_unlock (&ctx->requests_mutex)))
960     {
961       VAPI_DBG ("pthread_mutex_unlock() failed, rv=%d:%s", mrv,
962                 strerror (mrv));
963       (void) mrv;               /* avoid warning if the above debug is not enabled */
964       return VAPI_MUTEX_FAILURE;
965     }
966   return VAPI_OK;
967 }
968
969 size_t
970 vapi_get_message_count ()
971 {
972   return __vapi_metadata.count;
973 }
974
975 const char *
976 vapi_get_msg_name (vapi_msg_id_t id)
977 {
978   return __vapi_metadata.msgs[id]->name;
979 }
980
981 /*
982  * fd.io coding-style-patch-verification: ON
983  *
984  * Local Variables:
985  * eval: (c-set-style "gnu")
986  * End:
987  */