api: avoid swapping vlib_rp before barrier sync
[vpp.git] / src / vlibapi / api_shared.c
1 /*
2  *------------------------------------------------------------------
3  * api_shared.c - API message handling, common code for both clients
4  * and the vlib process itself.
5  *
6  *
7  * Copyright (c) 2009 Cisco and/or its affiliates.
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at:
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *------------------------------------------------------------------
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <string.h>
26 #include <vppinfra/format.h>
27 #include <vppinfra/byte_order.h>
28 #include <vppinfra/error.h>
29 #include <vlib/vlib.h>
30 #include <vlib/unix/unix.h>
31 #include <vlibapi/api.h>
32 #include <vppinfra/elog.h>
33
34 /* *INDENT-OFF* */
35 api_main_t api_main =
36   {
37     .region_name = "/unset",
38     .api_uid = -1,
39     .api_gid = -1,
40   };
41 /* *INDENT-ON* */
42
43 void
44 vl_msg_api_increment_missing_client_counter (void)
45 {
46   api_main_t *am = &api_main;
47   am->missing_clients++;
48 }
49
50 int
51 vl_msg_api_rx_trace_enabled (api_main_t * am)
52 {
53   return (am->rx_trace && am->rx_trace->enabled);
54 }
55
56 int
57 vl_msg_api_tx_trace_enabled (api_main_t * am)
58 {
59   return (am->tx_trace && am->tx_trace->enabled);
60 }
61
62 /*
63  * vl_msg_api_trace
64  */
65 void
66 vl_msg_api_trace (api_main_t * am, vl_api_trace_t * tp, void *msg)
67 {
68   u8 **this_trace;
69   u8 **old_trace;
70   u8 *msg_copy;
71   u32 length;
72   trace_cfg_t *cfgp;
73   u16 msg_id = clib_net_to_host_u16 (*((u16 *) msg));
74   msgbuf_t *header = (msgbuf_t *) (((u8 *) msg) - offsetof (msgbuf_t, data));
75
76   cfgp = am->api_trace_cfg + msg_id;
77
78   if (!cfgp || !cfgp->trace_enable)
79     return;
80
81   msg_copy = 0;
82
83   if (tp->nitems == 0)
84     {
85       clib_warning ("tp->nitems is 0");
86       return;
87     }
88
89   if (vec_len (tp->traces) < tp->nitems)
90     {
91       vec_add1 (tp->traces, 0);
92       this_trace = tp->traces + vec_len (tp->traces) - 1;
93     }
94   else
95     {
96       tp->wrapped = 1;
97       old_trace = tp->traces + tp->curindex++;
98       if (tp->curindex == tp->nitems)
99         tp->curindex = 0;
100       /* Reuse the trace record, may save some memory allocator traffic */
101       msg_copy = *old_trace;
102       vec_reset_length (msg_copy);
103       this_trace = old_trace;
104     }
105
106   length = clib_net_to_host_u32 (header->data_len);
107
108   vec_validate (msg_copy, length - 1);
109   clib_memcpy_fast (msg_copy, msg, length);
110   *this_trace = msg_copy;
111 }
112
113 int
114 vl_msg_api_trace_onoff (api_main_t * am, vl_api_trace_which_t which,
115                         int onoff)
116 {
117   vl_api_trace_t *tp;
118   int rv;
119
120   switch (which)
121     {
122     case VL_API_TRACE_TX:
123       tp = am->tx_trace;
124       if (tp == 0)
125         {
126           vl_msg_api_trace_configure (am, which, 1024);
127           tp = am->tx_trace;
128         }
129       break;
130
131     case VL_API_TRACE_RX:
132       tp = am->rx_trace;
133       if (tp == 0)
134         {
135           vl_msg_api_trace_configure (am, which, 1024);
136           tp = am->rx_trace;
137         }
138       break;
139
140     default:
141       /* duh? */
142       return -1;
143     }
144
145   /* Configured? */
146   if (tp == 0 || tp->nitems == 0)
147     return -1;
148
149   rv = tp->enabled;
150   tp->enabled = onoff;
151
152   return rv;
153 }
154
155 int
156 vl_msg_api_trace_free (api_main_t * am, vl_api_trace_which_t which)
157 {
158   vl_api_trace_t *tp;
159   int i;
160
161   switch (which)
162     {
163     case VL_API_TRACE_TX:
164       tp = am->tx_trace;
165       break;
166
167     case VL_API_TRACE_RX:
168       tp = am->rx_trace;
169       break;
170
171     default:
172       /* duh? */
173       return -1;
174     }
175
176   /* Configured? */
177   if (!tp || tp->nitems == 0)
178     return -1;
179
180   tp->curindex = 0;
181   tp->wrapped = 0;
182
183   for (i = 0; i < vec_len (tp->traces); i++)
184     {
185       vec_free (tp->traces[i]);
186     }
187   vec_free (tp->traces);
188
189   return 0;
190 }
191
192 u8 *
193 vl_api_serialize_message_table (api_main_t * am, u8 * vector)
194 {
195   serialize_main_t _sm, *sm = &_sm;
196   hash_pair_t *hp;
197   u32 nmsg = hash_elts (am->msg_index_by_name_and_crc);
198
199   serialize_open_vector (sm, vector);
200
201   /* serialize the count */
202   serialize_integer (sm, nmsg, sizeof (u32));
203
204   /* *INDENT-OFF* */
205   hash_foreach_pair (hp, am->msg_index_by_name_and_crc,
206   ({
207     serialize_likely_small_unsigned_integer (sm, hp->value[0]);
208     serialize_cstring (sm, (char *) hp->key);
209   }));
210   /* *INDENT-ON* */
211
212   return serialize_close_vector (sm);
213 }
214
215 int
216 vl_msg_api_trace_save (api_main_t * am, vl_api_trace_which_t which, FILE * fp)
217 {
218   vl_api_trace_t *tp;
219   vl_api_trace_file_header_t fh;
220   int i;
221   u8 *msg;
222
223   switch (which)
224     {
225     case VL_API_TRACE_TX:
226       tp = am->tx_trace;
227       break;
228
229     case VL_API_TRACE_RX:
230       tp = am->rx_trace;
231       break;
232
233     default:
234       /* duh? */
235       return -1;
236     }
237
238   /* Configured, data present? */
239   if (tp == 0 || tp->nitems == 0 || vec_len (tp->traces) == 0)
240     return -1;
241
242   /* "Dare to be stupid" check */
243   if (fp == 0)
244     {
245       return -2;
246     }
247
248   /* Write the file header */
249   fh.wrapped = tp->wrapped;
250   fh.nitems = clib_host_to_net_u32 (vec_len (tp->traces));
251   u8 *m = vl_api_serialize_message_table (am, 0);
252   fh.msgtbl_size = clib_host_to_net_u32 (vec_len (m));
253
254   if (fwrite (&fh, sizeof (fh), 1, fp) != 1)
255     {
256       return (-10);
257     }
258
259   /* Write the message table */
260   if (fwrite (m, vec_len (m), 1, fp) != 1)
261     {
262       return (-14);
263     }
264   vec_free (m);
265
266   /* No-wrap case */
267   if (tp->wrapped == 0)
268     {
269       /*
270        * Note: vec_len return 0 when fed a NULL pointer.
271        * Unfortunately, the static analysis tool doesn't
272        * figure it out, hence the suppressed warnings.
273        * What a great use of my time.
274        */
275       for (i = 0; i < vec_len (tp->traces); i++)
276         {
277           u32 msg_length;
278           /*sa_ignore NO_NULL_CHK */
279           msg = tp->traces[i];
280           /*
281            * This retarded check required to pass
282            * [sic] SA-checking.
283            */
284           if (!msg)
285             continue;
286
287           msg_length = clib_host_to_net_u32 (vec_len (msg));
288           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
289               != sizeof (msg_length))
290             {
291               return (-14);
292             }
293           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
294             {
295               return (-11);
296             }
297         }
298     }
299   else
300     {
301       /* Wrap case: write oldest -> end of buffer */
302       for (i = tp->curindex; i < vec_len (tp->traces); i++)
303         {
304           u32 msg_length;
305           msg = tp->traces[i];
306           /*
307            * This retarded check required to pass
308            * [sic] SA-checking
309            */
310           if (!msg)
311             continue;
312
313           msg_length = clib_host_to_net_u32 (vec_len (msg));
314           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
315               != sizeof (msg_length))
316             {
317               return (-14);
318             }
319
320           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
321             {
322               return (-12);
323             }
324         }
325       /* write beginning of buffer -> oldest-1 */
326       for (i = 0; i < tp->curindex; i++)
327         {
328           u32 msg_length;
329           /*sa_ignore NO_NULL_CHK */
330           msg = tp->traces[i];
331           /*
332            * This retarded check required to pass
333            * [sic] SA-checking
334            */
335           if (!msg)
336             continue;
337
338           msg_length = clib_host_to_net_u32 (vec_len (msg));
339           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
340               != sizeof (msg_length))
341             {
342               return (-14);
343             }
344
345           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
346             {
347               return (-13);
348             }
349         }
350     }
351   return 0;
352 }
353
354 int
355 vl_msg_api_trace_configure (api_main_t * am, vl_api_trace_which_t which,
356                             u32 nitems)
357 {
358   vl_api_trace_t *tp;
359   int was_on = 0;
360
361   switch (which)
362     {
363     case VL_API_TRACE_TX:
364       tp = am->tx_trace;
365       if (tp == 0)
366         {
367           vec_validate (am->tx_trace, 0);
368           tp = am->tx_trace;
369         }
370       break;
371
372     case VL_API_TRACE_RX:
373       tp = am->rx_trace;
374       if (tp == 0)
375         {
376           vec_validate (am->rx_trace, 0);
377           tp = am->rx_trace;
378         }
379
380       break;
381
382     default:
383       return -1;
384
385     }
386
387   if (tp->enabled)
388     {
389       was_on = vl_msg_api_trace_onoff (am, which, 0);
390     }
391   if (tp->traces)
392     {
393       vl_msg_api_trace_free (am, which);
394     }
395
396   clib_memset (tp, 0, sizeof (*tp));
397
398   if (clib_arch_is_big_endian)
399     {
400       tp->endian = VL_API_BIG_ENDIAN;
401     }
402   else
403     {
404       tp->endian = VL_API_LITTLE_ENDIAN;
405     }
406
407   tp->nitems = nitems;
408   if (was_on)
409     {
410       (void) vl_msg_api_trace_onoff (am, which, was_on);
411     }
412   return 0;
413 }
414
415 void
416 vl_msg_api_barrier_sync (void)
417 {
418 }
419
420 void
421 vl_msg_api_barrier_release (void)
422 {
423 }
424
425 always_inline void
426 msg_handler_internal (api_main_t * am,
427                       void *the_msg, int trace_it, int do_it, int free_it)
428 {
429   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
430   u8 *(*print_fp) (void *, void *);
431
432   if (PREDICT_FALSE (am->elog_trace_api_messages))
433     {
434       /* *INDENT-OFF* */
435       ELOG_TYPE_DECLARE (e) =
436         {
437           .format = "api-msg: %s",
438           .format_args = "T4",
439         };
440       /* *INDENT-ON* */
441       struct
442       {
443         u32 c;
444       } *ed;
445       ed = ELOG_DATA (am->elog_main, e);
446       if (id < vec_len (am->msg_names))
447         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
448       else
449         ed->c = elog_string (am->elog_main, "BOGUS");
450     }
451
452   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
453     {
454       if (trace_it)
455         vl_msg_api_trace (am, am->rx_trace, the_msg);
456
457       if (am->msg_print_flag)
458         {
459           fformat (stdout, "[%d]: %s\n", id, am->msg_names[id]);
460           print_fp = (void *) am->msg_print_handlers[id];
461           if (print_fp == 0)
462             {
463               fformat (stdout, "  [no registered print fn]\n");
464             }
465           else
466             {
467               (*print_fp) (the_msg, stdout);
468             }
469         }
470
471       if (do_it)
472         {
473           if (!am->is_mp_safe[id])
474             {
475               vl_msg_api_barrier_trace_context (am->msg_names[id]);
476               vl_msg_api_barrier_sync ();
477             }
478           (*am->msg_handlers[id]) (the_msg);
479           if (!am->is_mp_safe[id])
480             vl_msg_api_barrier_release ();
481         }
482     }
483   else
484     {
485       clib_warning ("no handler for msg id %d", id);
486     }
487
488   if (free_it)
489     vl_msg_api_free (the_msg);
490
491   if (PREDICT_FALSE (am->elog_trace_api_messages))
492     {
493       /* *INDENT-OFF* */
494       ELOG_TYPE_DECLARE (e) =
495         {
496           .format = "api-msg-done(%s): %s",
497           .format_args = "t4T4",
498           .n_enum_strings = 2,
499           .enum_strings =
500           {
501             "barrier",
502             "mp-safe",
503           }
504         };
505       /* *INDENT-ON* */
506
507       struct
508       {
509         u32 barrier;
510         u32 c;
511       } *ed;
512       ed = ELOG_DATA (am->elog_main, e);
513       if (id < vec_len (am->msg_names))
514         {
515           ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
516           ed->barrier = !am->is_mp_safe[id];
517         }
518       else
519         {
520           ed->c = elog_string (am->elog_main, "BOGUS");
521           ed->barrier = 0;
522         }
523     }
524 }
525
526 /* This is only to be called from a vlib/vnet app */
527 void
528 vl_msg_api_handler_with_vm_node (api_main_t * am, svm_region_t * vlib_rp,
529                                  void *the_msg, vlib_main_t * vm,
530                                  vlib_node_runtime_t * node, u8 is_private)
531 {
532   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
533   u8 *(*handler) (void *, void *, void *);
534   u8 *(*print_fp) (void *, void *);
535   svm_region_t *old_vlib_rp;
536   void *save_shmem_hdr;
537   int is_mp_safe = 1;
538
539   if (PREDICT_FALSE (am->elog_trace_api_messages))
540     {
541       /* *INDENT-OFF* */
542       ELOG_TYPE_DECLARE (e) =
543         {
544           .format = "api-msg: %s",
545           .format_args = "T4",
546         };
547       /* *INDENT-ON* */
548       struct
549       {
550         u32 c;
551       } *ed;
552       ed = ELOG_DATA (am->elog_main, e);
553       if (id < vec_len (am->msg_names))
554         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
555       else
556         ed->c = elog_string (am->elog_main, "BOGUS");
557     }
558
559   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
560     {
561       handler = (void *) am->msg_handlers[id];
562
563       if (PREDICT_FALSE (am->rx_trace && am->rx_trace->enabled))
564         vl_msg_api_trace (am, am->rx_trace, the_msg);
565
566       if (PREDICT_FALSE (am->msg_print_flag))
567         {
568           fformat (stdout, "[%d]: %s\n", id, am->msg_names[id]);
569           print_fp = (void *) am->msg_print_handlers[id];
570           if (print_fp == 0)
571             {
572               fformat (stdout, "  [no registered print fn for msg %d]\n", id);
573             }
574           else
575             {
576               (*print_fp) (the_msg, vm);
577             }
578         }
579       is_mp_safe = am->is_mp_safe[id];
580
581       if (!is_mp_safe)
582         {
583           vl_msg_api_barrier_trace_context (am->msg_names[id]);
584           vl_msg_api_barrier_sync ();
585         }
586       if (is_private)
587         {
588           old_vlib_rp = am->vlib_rp;
589           save_shmem_hdr = am->shmem_hdr;
590           am->vlib_rp = vlib_rp;
591           am->shmem_hdr = (void *) vlib_rp->user_ctx;
592         }
593       (*handler) (the_msg, vm, node);
594       if (is_private)
595         {
596           am->vlib_rp = old_vlib_rp;
597           am->shmem_hdr = save_shmem_hdr;
598         }
599       if (!is_mp_safe)
600         vl_msg_api_barrier_release ();
601     }
602   else
603     {
604       clib_warning ("no handler for msg id %d", id);
605     }
606
607   /*
608    * Special-case, so we can e.g. bounce messages off the vnet
609    * main thread without copying them...
610    */
611   if (!(am->message_bounce[id]))
612     vl_msg_api_free (the_msg);
613
614   if (PREDICT_FALSE (am->elog_trace_api_messages))
615     {
616       /* *INDENT-OFF* */
617       ELOG_TYPE_DECLARE (e) =
618         {
619           .format = "api-msg-done(%s): %s",
620           .format_args = "t4T4",
621           .n_enum_strings = 2,
622           .enum_strings =
623           {
624             "barrier",
625             "mp-safe",
626           }
627         };
628       /* *INDENT-ON* */
629
630       struct
631       {
632         u32 barrier;
633         u32 c;
634       } *ed;
635       ed = ELOG_DATA (am->elog_main, e);
636       if (id < vec_len (am->msg_names))
637         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
638       else
639         ed->c = elog_string (am->elog_main, "BOGUS");
640       ed->barrier = is_mp_safe;
641     }
642 }
643
644 void
645 vl_msg_api_handler (void *the_msg)
646 {
647   api_main_t *am = &api_main;
648
649   msg_handler_internal (am, the_msg,
650                         (am->rx_trace
651                          && am->rx_trace->enabled) /* trace_it */ ,
652                         1 /* do_it */ , 1 /* free_it */ );
653 }
654
655 void
656 vl_msg_api_handler_no_free (void *the_msg)
657 {
658   api_main_t *am = &api_main;
659   msg_handler_internal (am, the_msg,
660                         (am->rx_trace
661                          && am->rx_trace->enabled) /* trace_it */ ,
662                         1 /* do_it */ , 0 /* free_it */ );
663 }
664
665 void
666 vl_msg_api_handler_no_trace_no_free (void *the_msg)
667 {
668   api_main_t *am = &api_main;
669   msg_handler_internal (am, the_msg, 0 /* trace_it */ , 1 /* do_it */ ,
670                         0 /* free_it */ );
671 }
672
673 /*
674  * Add a trace record to the API message trace buffer, if
675  * API message tracing is enabled. Handy for adding sufficient
676  * data to the trace to reproduce autonomous state, as opposed to
677  * state downloaded via control-plane API messages. Example: the NAT
678  * application creates database entries based on packet traffic, not
679  * control-plane messages.
680  *
681  */
682 void
683 vl_msg_api_trace_only (void *the_msg)
684 {
685   api_main_t *am = &api_main;
686
687   msg_handler_internal (am, the_msg,
688                         (am->rx_trace
689                          && am->rx_trace->enabled) /* trace_it */ ,
690                         0 /* do_it */ , 0 /* free_it */ );
691 }
692
693 void
694 vl_msg_api_cleanup_handler (void *the_msg)
695 {
696   api_main_t *am = &api_main;
697   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
698
699   if (PREDICT_FALSE (id >= vec_len (am->msg_cleanup_handlers)))
700     {
701       clib_warning ("_vl_msg_id too large: %d\n", id);
702       return;
703     }
704   if (am->msg_cleanup_handlers[id])
705     (*am->msg_cleanup_handlers[id]) (the_msg);
706
707   vl_msg_api_free (the_msg);
708 }
709
710 /*
711  * vl_msg_api_replay_handler
712  */
713 void
714 vl_msg_api_replay_handler (void *the_msg)
715 {
716   api_main_t *am = &api_main;
717
718   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
719
720   if (PREDICT_FALSE (id >= vec_len (am->msg_handlers)))
721     {
722       clib_warning ("_vl_msg_id too large: %d\n", id);
723       return;
724     }
725   /* do NOT trace the message... */
726   if (am->msg_handlers[id])
727     (*am->msg_handlers[id]) (the_msg);
728   /* do NOT free the message buffer... */
729 }
730
731 u32
732 vl_msg_api_get_msg_length (void *msg_arg)
733 {
734   return vl_msg_api_get_msg_length_inline (msg_arg);
735 }
736
737 /*
738  * vl_msg_api_socket_handler
739  */
740 void
741 vl_msg_api_socket_handler (void *the_msg)
742 {
743   api_main_t *am = &api_main;
744
745   msg_handler_internal (am, the_msg,
746                         (am->rx_trace
747                          && am->rx_trace->enabled) /* trace_it */ ,
748                         1 /* do_it */ , 0 /* free_it */ );
749 }
750
751 #define foreach_msg_api_vector                  \
752 _(msg_names)                                    \
753 _(msg_handlers)                                 \
754 _(msg_cleanup_handlers)                         \
755 _(msg_endian_handlers)                          \
756 _(msg_print_handlers)                           \
757 _(api_trace_cfg)                                \
758 _(message_bounce)                               \
759 _(is_mp_safe)
760
761 void
762 vl_msg_api_config (vl_msg_api_msg_config_t * c)
763 {
764   api_main_t *am = &api_main;
765
766   /*
767    * This happens during the java core tests if the message
768    * dictionary is missing newly added xxx_reply_t messages.
769    * Should never happen, but since I shot myself in the foot once
770    * this way, I thought I'd make it easy to debug if I ever do
771    * it again... (;-)...
772    */
773   if (c->id == 0)
774     {
775       if (c->name)
776         clib_warning ("Trying to register %s with a NULL msg id!", c->name);
777       else
778         clib_warning ("Trying to register a NULL msg with a NULL msg id!");
779       clib_warning ("Did you forget to call setup_message_id_table?");
780       return;
781     }
782
783 #define _(a) vec_validate (am->a, c->id);
784   foreach_msg_api_vector;
785 #undef _
786
787   if (am->msg_handlers[c->id] && am->msg_handlers[c->id] != c->handler)
788     clib_warning
789       ("BUG: re-registering 'vl_api_%s_t_handler'."
790        "Handler was %llx, replaced by %llx",
791        c->name, am->msg_handlers[c->id], c->handler);
792
793   am->msg_names[c->id] = c->name;
794   am->msg_handlers[c->id] = c->handler;
795   am->msg_cleanup_handlers[c->id] = c->cleanup;
796   am->msg_endian_handlers[c->id] = c->endian;
797   am->msg_print_handlers[c->id] = c->print;
798   am->message_bounce[c->id] = c->message_bounce;
799   am->is_mp_safe[c->id] = c->is_mp_safe;
800
801   am->api_trace_cfg[c->id].size = c->size;
802   am->api_trace_cfg[c->id].trace_enable = c->traced;
803   am->api_trace_cfg[c->id].replay_enable = c->replay;
804 }
805
806 /*
807  * vl_msg_api_set_handlers
808  * preserve the old API for a while
809  */
810 void
811 vl_msg_api_set_handlers (int id, char *name, void *handler, void *cleanup,
812                          void *endian, void *print, int size, int traced)
813 {
814   vl_msg_api_msg_config_t cfg;
815   vl_msg_api_msg_config_t *c = &cfg;
816
817   clib_memset (c, 0, sizeof (*c));
818
819   c->id = id;
820   c->name = name;
821   c->handler = handler;
822   c->cleanup = cleanup;
823   c->endian = endian;
824   c->print = print;
825   c->traced = traced;
826   c->replay = 1;
827   c->message_bounce = 0;
828   c->is_mp_safe = 0;
829   vl_msg_api_config (c);
830 }
831
832 void
833 vl_msg_api_clean_handlers (int msg_id)
834 {
835   vl_msg_api_msg_config_t cfg;
836   vl_msg_api_msg_config_t *c = &cfg;
837
838   clib_memset (c, 0, sizeof (*c));
839
840   c->id = msg_id;
841   vl_msg_api_config (c);
842 }
843
844 void
845 vl_msg_api_set_cleanup_handler (int msg_id, void *fp)
846 {
847   api_main_t *am = &api_main;
848   ASSERT (msg_id > 0);
849
850   vec_validate (am->msg_cleanup_handlers, msg_id);
851   am->msg_cleanup_handlers[msg_id] = fp;
852 }
853
854 void
855 vl_msg_api_queue_handler (svm_queue_t * q)
856 {
857   uword msg;
858
859   while (!svm_queue_sub (q, (u8 *) & msg, SVM_Q_WAIT, 0))
860     vl_msg_api_handler ((void *) msg);
861 }
862
863 vl_api_trace_t *
864 vl_msg_api_trace_get (api_main_t * am, vl_api_trace_which_t which)
865 {
866   switch (which)
867     {
868     case VL_API_TRACE_RX:
869       return am->rx_trace;
870     case VL_API_TRACE_TX:
871       return am->tx_trace;
872     default:
873       return 0;
874     }
875 }
876
877 void
878 vl_noop_handler (void *mp)
879 {
880 }
881
882
883 static u8 post_mortem_dump_enabled;
884
885 void
886 vl_msg_api_post_mortem_dump_enable_disable (int enable)
887 {
888   post_mortem_dump_enabled = enable;
889 }
890
891 void
892 vl_msg_api_post_mortem_dump (void)
893 {
894   api_main_t *am = &api_main;
895   FILE *fp;
896   char filename[64];
897   int rv;
898
899   if (post_mortem_dump_enabled == 0)
900     return;
901
902   snprintf (filename, sizeof (filename), "/tmp/api_post_mortem.%d",
903             getpid ());
904
905   fp = fopen (filename, "w");
906   if (fp == NULL)
907     {
908       rv = write (2, "Couldn't create ", 16);
909       rv = write (2, filename, strlen (filename));
910       rv = write (2, "\n", 1);
911       return;
912     }
913   rv = vl_msg_api_trace_save (am, VL_API_TRACE_RX, fp);
914   fclose (fp);
915   if (rv < 0)
916     {
917       rv = write (2, "Failed to save post-mortem API trace to ", 40);
918       rv = write (2, filename, strlen (filename));
919       rv = write (2, "\n", 1);
920     }
921
922 }
923
924 /* Layered message handling support */
925
926 void
927 vl_msg_api_register_pd_handler (void *fp, u16 msg_id_host_byte_order)
928 {
929   api_main_t *am = &api_main;
930
931   /* Mild idiot proofing */
932   if (msg_id_host_byte_order > 10000)
933     clib_warning ("msg_id_host_byte_order endian issue? %d arg vs %d",
934                   msg_id_host_byte_order,
935                   clib_net_to_host_u16 (msg_id_host_byte_order));
936   vec_validate (am->pd_msg_handlers, msg_id_host_byte_order);
937   am->pd_msg_handlers[msg_id_host_byte_order] = fp;
938 }
939
940 int
941 vl_msg_api_pd_handler (void *mp, int rv)
942 {
943   api_main_t *am = &api_main;
944   int (*fp) (void *, int);
945   u16 msg_id;
946
947   if (clib_arch_is_little_endian)
948     msg_id = clib_net_to_host_u16 (*((u16 *) mp));
949   else
950     msg_id = *((u16 *) mp);
951
952   if (msg_id >= vec_len (am->pd_msg_handlers)
953       || am->pd_msg_handlers[msg_id] == 0)
954     return rv;
955
956   fp = am->pd_msg_handlers[msg_id];
957   rv = (*fp) (mp, rv);
958   return rv;
959 }
960
961 void
962 vl_msg_api_set_first_available_msg_id (u16 first_avail)
963 {
964   api_main_t *am = &api_main;
965
966   am->first_available_msg_id = first_avail;
967 }
968
969 u16
970 vl_msg_api_get_msg_ids (const char *name, int n)
971 {
972   api_main_t *am = &api_main;
973   u8 *name_copy;
974   vl_api_msg_range_t *rp;
975   uword *p;
976   u16 rv;
977
978   if (am->msg_range_by_name == 0)
979     am->msg_range_by_name = hash_create_string (0, sizeof (uword));
980
981   name_copy = format (0, "%s%c", name, 0);
982
983   p = hash_get_mem (am->msg_range_by_name, name_copy);
984   if (p)
985     {
986       clib_warning ("WARNING: duplicate message range registration for '%s'",
987                     name_copy);
988       vec_free (name_copy);
989       return ((u16) ~ 0);
990     }
991
992   if (n < 0 || n > 1024)
993     {
994       clib_warning
995         ("WARNING: bad number of message-IDs (%d) requested by '%s'",
996          n, name_copy);
997       vec_free (name_copy);
998       return ((u16) ~ 0);
999     }
1000
1001   vec_add2 (am->msg_ranges, rp, 1);
1002
1003   rv = rp->first_msg_id = am->first_available_msg_id;
1004   am->first_available_msg_id += n;
1005   rp->last_msg_id = am->first_available_msg_id - 1;
1006   rp->name = name_copy;
1007
1008   hash_set_mem (am->msg_range_by_name, name_copy, rp - am->msg_ranges);
1009
1010   return rv;
1011 }
1012
1013 void
1014 vl_msg_api_add_msg_name_crc (api_main_t * am, const char *string, u32 id)
1015 {
1016   uword *p;
1017
1018   if (am->msg_index_by_name_and_crc == 0)
1019     am->msg_index_by_name_and_crc = hash_create_string (0, sizeof (uword));
1020
1021   p = hash_get_mem (am->msg_index_by_name_and_crc, string);
1022   if (p)
1023     {
1024       clib_warning ("attempt to redefine '%s' ignored...", string);
1025       return;
1026     }
1027
1028   hash_set_mem (am->msg_index_by_name_and_crc, string, id);
1029 }
1030
1031 void
1032 vl_msg_api_add_version (api_main_t * am, const char *string,
1033                         u32 major, u32 minor, u32 patch)
1034 {
1035   api_version_t version = {.major = major,.minor = minor,.patch = patch };
1036   ASSERT (strlen (string) < 64);
1037   strncpy (version.name, string, 64 - 1);
1038   vec_add1 (am->api_version_list, version);
1039 }
1040
1041 u32
1042 vl_msg_api_get_msg_index (u8 * name_and_crc)
1043 {
1044   api_main_t *am = &api_main;
1045   uword *p;
1046
1047   if (am->msg_index_by_name_and_crc)
1048     {
1049       p = hash_get_mem (am->msg_index_by_name_and_crc, name_and_crc);
1050       if (p)
1051         return p[0];
1052     }
1053   return ~0;
1054 }
1055
1056 void *
1057 vl_msg_push_heap (void)
1058 {
1059   api_main_t *am = &api_main;
1060   pthread_mutex_lock (&am->vlib_rp->mutex);
1061   return svm_push_data_heap (am->vlib_rp);
1062 }
1063
1064 void
1065 vl_msg_pop_heap (void *oldheap)
1066 {
1067   api_main_t *am = &api_main;
1068   svm_pop_heap (oldheap);
1069   pthread_mutex_unlock (&am->vlib_rp->mutex);
1070 }
1071
1072 int
1073 vl_api_to_api_string (u32 len, const char *buf, vl_api_string_t * str)
1074 {
1075   if (len)
1076     clib_memcpy_fast (str->buf, buf, len);
1077   str->length = htonl (len);
1078   return len + sizeof (u32);
1079 }
1080
1081 int
1082 vl_api_vec_to_api_string (const u8 * vec, vl_api_string_t * str)
1083 {
1084   u32 len = vec_len (vec);
1085   clib_memcpy (str->buf, vec, len);
1086   str->length = htonl (len);
1087   return len + sizeof (u32);
1088 }
1089
1090 /* Return a pointer to the API string (not nul terminated */
1091 u8 *
1092 vl_api_from_api_string (vl_api_string_t * astr)
1093 {
1094   return astr->buf;
1095 }
1096
1097 u32
1098 vl_api_string_len (vl_api_string_t * astr)
1099 {
1100   return clib_net_to_host_u32 (astr->length);
1101 }
1102
1103 u8 *
1104 vl_api_format_string (u8 * s, va_list * args)
1105 {
1106   vl_api_string_t *a = va_arg (*args, vl_api_string_t *);
1107   vec_add (s, a->buf, clib_net_to_host_u32 (a->length));
1108   return s;
1109 }
1110
1111 /*
1112  * Returns a new vector. Remember to free it after use.
1113  */
1114 u8 *
1115 vl_api_from_api_to_vec (vl_api_string_t * astr)
1116 {
1117   u8 *v = 0;
1118   vec_add (v, astr->buf, clib_net_to_host_u32 (astr->length));
1119   return v;
1120 }
1121
1122 void
1123 vl_api_set_elog_main (elog_main_t * m)
1124 {
1125   api_main_t *am = &api_main;
1126   am->elog_main = m;
1127 }
1128
1129 int
1130 vl_api_set_elog_trace_api_messages (int enable)
1131 {
1132   int rv;
1133   api_main_t *am = &api_main;
1134
1135   rv = am->elog_trace_api_messages;
1136   am->elog_trace_api_messages = enable;
1137   return rv;
1138 }
1139
1140 int
1141 vl_api_get_elog_trace_api_messages (void)
1142 {
1143   api_main_t *am = &api_main;
1144
1145   return am->elog_trace_api_messages;
1146 }
1147
1148 /*
1149  * fd.io coding-style-patch-verification: ON
1150  *
1151  * Local Variables:
1152  * eval: (c-set-style "gnu")
1153  * End:
1154  */