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