api: vppapitrace JSON/API trace converter
[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   clib_warning ("Message table length %d", vec_len (m));
253   fh.msgtbl_size = clib_host_to_net_u32 (vec_len (m));
254
255   if (fwrite (&fh, sizeof (fh), 1, fp) != 1)
256     {
257       return (-10);
258     }
259
260   /* Write the message table */
261   if (fwrite (m, vec_len (m), 1, fp) != 1)
262     {
263       return (-14);
264     }
265   vec_free (m);
266
267   /* No-wrap case */
268   if (tp->wrapped == 0)
269     {
270       /*
271        * Note: vec_len return 0 when fed a NULL pointer.
272        * Unfortunately, the static analysis tool doesn't
273        * figure it out, hence the suppressed warnings.
274        * What a great use of my time.
275        */
276       for (i = 0; i < vec_len (tp->traces); i++)
277         {
278           u32 msg_length;
279           /*sa_ignore NO_NULL_CHK */
280           msg = tp->traces[i];
281           /*
282            * This retarded check required to pass
283            * [sic] SA-checking.
284            */
285           if (!msg)
286             continue;
287
288           msg_length = clib_host_to_net_u32 (vec_len (msg));
289           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
290               != sizeof (msg_length))
291             {
292               return (-14);
293             }
294           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
295             {
296               return (-11);
297             }
298         }
299     }
300   else
301     {
302       /* Wrap case: write oldest -> end of buffer */
303       for (i = tp->curindex; i < vec_len (tp->traces); i++)
304         {
305           u32 msg_length;
306           msg = tp->traces[i];
307           /*
308            * This retarded check required to pass
309            * [sic] SA-checking
310            */
311           if (!msg)
312             continue;
313
314           msg_length = clib_host_to_net_u32 (vec_len (msg));
315           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
316               != sizeof (msg_length))
317             {
318               return (-14);
319             }
320
321           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
322             {
323               return (-12);
324             }
325         }
326       /* write beginning of buffer -> oldest-1 */
327       for (i = 0; i < tp->curindex; i++)
328         {
329           u32 msg_length;
330           /*sa_ignore NO_NULL_CHK */
331           msg = tp->traces[i];
332           /*
333            * This retarded check required to pass
334            * [sic] SA-checking
335            */
336           if (!msg)
337             continue;
338
339           msg_length = clib_host_to_net_u32 (vec_len (msg));
340           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
341               != sizeof (msg_length))
342             {
343               return (-14);
344             }
345
346           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
347             {
348               return (-13);
349             }
350         }
351     }
352   return 0;
353 }
354
355 int
356 vl_msg_api_trace_configure (api_main_t * am, vl_api_trace_which_t which,
357                             u32 nitems)
358 {
359   vl_api_trace_t *tp;
360   int was_on = 0;
361
362   switch (which)
363     {
364     case VL_API_TRACE_TX:
365       tp = am->tx_trace;
366       if (tp == 0)
367         {
368           vec_validate (am->tx_trace, 0);
369           tp = am->tx_trace;
370         }
371       break;
372
373     case VL_API_TRACE_RX:
374       tp = am->rx_trace;
375       if (tp == 0)
376         {
377           vec_validate (am->rx_trace, 0);
378           tp = am->rx_trace;
379         }
380
381       break;
382
383     default:
384       return -1;
385
386     }
387
388   if (tp->enabled)
389     {
390       was_on = vl_msg_api_trace_onoff (am, which, 0);
391     }
392   if (tp->traces)
393     {
394       vl_msg_api_trace_free (am, which);
395     }
396
397   clib_memset (tp, 0, sizeof (*tp));
398
399   if (clib_arch_is_big_endian)
400     {
401       tp->endian = VL_API_BIG_ENDIAN;
402     }
403   else
404     {
405       tp->endian = VL_API_LITTLE_ENDIAN;
406     }
407
408   tp->nitems = nitems;
409   if (was_on)
410     {
411       (void) vl_msg_api_trace_onoff (am, which, was_on);
412     }
413   return 0;
414 }
415
416 void
417 vl_msg_api_barrier_sync (void)
418 {
419 }
420
421 void
422 vl_msg_api_barrier_release (void)
423 {
424 }
425
426 always_inline void
427 msg_handler_internal (api_main_t * am,
428                       void *the_msg, int trace_it, int do_it, int free_it)
429 {
430   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
431   u8 *(*print_fp) (void *, void *);
432
433   if (PREDICT_FALSE (am->elog_trace_api_messages))
434     {
435       /* *INDENT-OFF* */
436       ELOG_TYPE_DECLARE (e) =
437         {
438           .format = "api-msg: %s",
439           .format_args = "T4",
440         };
441       /* *INDENT-ON* */
442       struct
443       {
444         u32 c;
445       } *ed;
446       ed = ELOG_DATA (am->elog_main, e);
447       if (id < vec_len (am->msg_names))
448         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
449       else
450         ed->c = elog_string (am->elog_main, "BOGUS");
451     }
452
453   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
454     {
455       if (trace_it)
456         vl_msg_api_trace (am, am->rx_trace, the_msg);
457
458       if (am->msg_print_flag)
459         {
460           fformat (stdout, "[%d]: %s\n", id, am->msg_names[id]);
461           print_fp = (void *) am->msg_print_handlers[id];
462           if (print_fp == 0)
463             {
464               fformat (stdout, "  [no registered print fn]\n");
465             }
466           else
467             {
468               (*print_fp) (the_msg, stdout);
469             }
470         }
471
472       if (do_it)
473         {
474           if (!am->is_mp_safe[id])
475             {
476               vl_msg_api_barrier_trace_context (am->msg_names[id]);
477               vl_msg_api_barrier_sync ();
478             }
479           (*am->msg_handlers[id]) (the_msg);
480           if (!am->is_mp_safe[id])
481             vl_msg_api_barrier_release ();
482         }
483     }
484   else
485     {
486       clib_warning ("no handler for msg id %d", id);
487     }
488
489   if (free_it)
490     vl_msg_api_free (the_msg);
491
492   if (PREDICT_FALSE (am->elog_trace_api_messages))
493     {
494       /* *INDENT-OFF* */
495       ELOG_TYPE_DECLARE (e) =
496         {
497           .format = "api-msg-done(%s): %s",
498           .format_args = "t4T4",
499           .n_enum_strings = 2,
500           .enum_strings =
501           {
502             "barrier",
503             "mp-safe",
504           }
505         };
506       /* *INDENT-ON* */
507
508       struct
509       {
510         u32 barrier;
511         u32 c;
512       } *ed;
513       ed = ELOG_DATA (am->elog_main, e);
514       if (id < vec_len (am->msg_names))
515         {
516           ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
517           ed->barrier = !am->is_mp_safe[id];
518         }
519       else
520         {
521           ed->c = elog_string (am->elog_main, "BOGUS");
522           ed->barrier = 0;
523         }
524     }
525 }
526
527 /* This is only to be called from a vlib/vnet app */
528 void
529 vl_msg_api_handler_with_vm_node (api_main_t * am,
530                                  void *the_msg, vlib_main_t * vm,
531                                  vlib_node_runtime_t * node)
532 {
533   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
534   u8 *(*handler) (void *, void *, void *);
535   u8 *(*print_fp) (void *, void *);
536   int is_mp_safe = 1;
537
538   if (PREDICT_FALSE (am->elog_trace_api_messages))
539     {
540       /* *INDENT-OFF* */
541       ELOG_TYPE_DECLARE (e) =
542         {
543           .format = "api-msg: %s",
544           .format_args = "T4",
545         };
546       /* *INDENT-ON* */
547       struct
548       {
549         u32 c;
550       } *ed;
551       ed = ELOG_DATA (am->elog_main, e);
552       if (id < vec_len (am->msg_names))
553         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
554       else
555         ed->c = elog_string (am->elog_main, "BOGUS");
556     }
557
558   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
559     {
560       handler = (void *) am->msg_handlers[id];
561
562       if (PREDICT_FALSE (am->rx_trace && am->rx_trace->enabled))
563         vl_msg_api_trace (am, am->rx_trace, the_msg);
564
565       if (PREDICT_FALSE (am->msg_print_flag))
566         {
567           fformat (stdout, "[%d]: %s\n", id, am->msg_names[id]);
568           print_fp = (void *) am->msg_print_handlers[id];
569           if (print_fp == 0)
570             {
571               fformat (stdout, "  [no registered print fn for msg %d]\n", id);
572             }
573           else
574             {
575               (*print_fp) (the_msg, vm);
576             }
577         }
578       is_mp_safe = am->is_mp_safe[id];
579
580       if (!is_mp_safe)
581         {
582           vl_msg_api_barrier_trace_context (am->msg_names[id]);
583           vl_msg_api_barrier_sync ();
584         }
585       (*handler) (the_msg, vm, node);
586       if (!is_mp_safe)
587         vl_msg_api_barrier_release ();
588     }
589   else
590     {
591       clib_warning ("no handler for msg id %d", id);
592     }
593
594   /*
595    * Special-case, so we can e.g. bounce messages off the vnet
596    * main thread without copying them...
597    */
598   if (!(am->message_bounce[id]))
599     vl_msg_api_free (the_msg);
600
601   if (PREDICT_FALSE (am->elog_trace_api_messages))
602     {
603       /* *INDENT-OFF* */
604       ELOG_TYPE_DECLARE (e) =
605         {
606           .format = "api-msg-done(%s): %s",
607           .format_args = "t4T4",
608           .n_enum_strings = 2,
609           .enum_strings =
610           {
611             "barrier",
612             "mp-safe",
613           }
614         };
615       /* *INDENT-ON* */
616
617       struct
618       {
619         u32 barrier;
620         u32 c;
621       } *ed;
622       ed = ELOG_DATA (am->elog_main, e);
623       if (id < vec_len (am->msg_names))
624         ed->c = elog_string (am->elog_main, (char *) am->msg_names[id]);
625       else
626         ed->c = elog_string (am->elog_main, "BOGUS");
627       ed->barrier = is_mp_safe;
628     }
629 }
630
631 void
632 vl_msg_api_handler (void *the_msg)
633 {
634   api_main_t *am = &api_main;
635
636   msg_handler_internal (am, the_msg,
637                         (am->rx_trace
638                          && am->rx_trace->enabled) /* trace_it */ ,
639                         1 /* do_it */ , 1 /* free_it */ );
640 }
641
642 void
643 vl_msg_api_handler_no_free (void *the_msg)
644 {
645   api_main_t *am = &api_main;
646   msg_handler_internal (am, the_msg,
647                         (am->rx_trace
648                          && am->rx_trace->enabled) /* trace_it */ ,
649                         1 /* do_it */ , 0 /* free_it */ );
650 }
651
652 void
653 vl_msg_api_handler_no_trace_no_free (void *the_msg)
654 {
655   api_main_t *am = &api_main;
656   msg_handler_internal (am, the_msg, 0 /* trace_it */ , 1 /* do_it */ ,
657                         0 /* free_it */ );
658 }
659
660 /*
661  * Add a trace record to the API message trace buffer, if
662  * API message tracing is enabled. Handy for adding sufficient
663  * data to the trace to reproduce autonomous state, as opposed to
664  * state downloaded via control-plane API messages. Example: the NAT
665  * application creates database entries based on packet traffic, not
666  * control-plane messages.
667  *
668  */
669 void
670 vl_msg_api_trace_only (void *the_msg)
671 {
672   api_main_t *am = &api_main;
673
674   msg_handler_internal (am, the_msg,
675                         (am->rx_trace
676                          && am->rx_trace->enabled) /* trace_it */ ,
677                         0 /* do_it */ , 0 /* free_it */ );
678 }
679
680 void
681 vl_msg_api_cleanup_handler (void *the_msg)
682 {
683   api_main_t *am = &api_main;
684   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
685
686   if (PREDICT_FALSE (id >= vec_len (am->msg_cleanup_handlers)))
687     {
688       clib_warning ("_vl_msg_id too large: %d\n", id);
689       return;
690     }
691   if (am->msg_cleanup_handlers[id])
692     (*am->msg_cleanup_handlers[id]) (the_msg);
693
694   vl_msg_api_free (the_msg);
695 }
696
697 /*
698  * vl_msg_api_replay_handler
699  */
700 void
701 vl_msg_api_replay_handler (void *the_msg)
702 {
703   api_main_t *am = &api_main;
704
705   u16 id = clib_net_to_host_u16 (*((u16 *) the_msg));
706
707   if (PREDICT_FALSE (id >= vec_len (am->msg_handlers)))
708     {
709       clib_warning ("_vl_msg_id too large: %d\n", id);
710       return;
711     }
712   /* do NOT trace the message... */
713   if (am->msg_handlers[id])
714     (*am->msg_handlers[id]) (the_msg);
715   /* do NOT free the message buffer... */
716 }
717
718 u32
719 vl_msg_api_get_msg_length (void *msg_arg)
720 {
721   return vl_msg_api_get_msg_length_inline (msg_arg);
722 }
723
724 /*
725  * vl_msg_api_socket_handler
726  */
727 void
728 vl_msg_api_socket_handler (void *the_msg)
729 {
730   api_main_t *am = &api_main;
731
732   msg_handler_internal (am, the_msg,
733                         (am->rx_trace
734                          && am->rx_trace->enabled) /* trace_it */ ,
735                         1 /* do_it */ , 0 /* free_it */ );
736 }
737
738 #define foreach_msg_api_vector                  \
739 _(msg_names)                                    \
740 _(msg_handlers)                                 \
741 _(msg_cleanup_handlers)                         \
742 _(msg_endian_handlers)                          \
743 _(msg_print_handlers)                           \
744 _(api_trace_cfg)                                \
745 _(message_bounce)                               \
746 _(is_mp_safe)
747
748 void
749 vl_msg_api_config (vl_msg_api_msg_config_t * c)
750 {
751   api_main_t *am = &api_main;
752
753   /*
754    * This happens during the java core tests if the message
755    * dictionary is missing newly added xxx_reply_t messages.
756    * Should never happen, but since I shot myself in the foot once
757    * this way, I thought I'd make it easy to debug if I ever do
758    * it again... (;-)...
759    */
760   if (c->id == 0)
761     {
762       if (c->name)
763         clib_warning ("Trying to register %s with a NULL msg id!", c->name);
764       else
765         clib_warning ("Trying to register a NULL msg with a NULL msg id!");
766       clib_warning ("Did you forget to call setup_message_id_table?");
767       return;
768     }
769
770 #define _(a) vec_validate (am->a, c->id);
771   foreach_msg_api_vector;
772 #undef _
773
774   if (am->msg_handlers[c->id] && am->msg_handlers[c->id] != c->handler)
775     clib_warning
776       ("BUG: re-registering 'vl_api_%s_t_handler'."
777        "Handler was %llx, replaced by %llx",
778        c->name, am->msg_handlers[c->id], c->handler);
779
780   am->msg_names[c->id] = c->name;
781   am->msg_handlers[c->id] = c->handler;
782   am->msg_cleanup_handlers[c->id] = c->cleanup;
783   am->msg_endian_handlers[c->id] = c->endian;
784   am->msg_print_handlers[c->id] = c->print;
785   am->message_bounce[c->id] = c->message_bounce;
786   am->is_mp_safe[c->id] = c->is_mp_safe;
787
788   am->api_trace_cfg[c->id].size = c->size;
789   am->api_trace_cfg[c->id].trace_enable = c->traced;
790   am->api_trace_cfg[c->id].replay_enable = c->replay;
791 }
792
793 /*
794  * vl_msg_api_set_handlers
795  * preserve the old API for a while
796  */
797 void
798 vl_msg_api_set_handlers (int id, char *name, void *handler, void *cleanup,
799                          void *endian, void *print, int size, int traced)
800 {
801   vl_msg_api_msg_config_t cfg;
802   vl_msg_api_msg_config_t *c = &cfg;
803
804   clib_memset (c, 0, sizeof (*c));
805
806   c->id = id;
807   c->name = name;
808   c->handler = handler;
809   c->cleanup = cleanup;
810   c->endian = endian;
811   c->print = print;
812   c->traced = traced;
813   c->replay = 1;
814   c->message_bounce = 0;
815   c->is_mp_safe = 0;
816   vl_msg_api_config (c);
817 }
818
819 void
820 vl_msg_api_clean_handlers (int msg_id)
821 {
822   vl_msg_api_msg_config_t cfg;
823   vl_msg_api_msg_config_t *c = &cfg;
824
825   clib_memset (c, 0, sizeof (*c));
826
827   c->id = msg_id;
828   vl_msg_api_config (c);
829 }
830
831 void
832 vl_msg_api_set_cleanup_handler (int msg_id, void *fp)
833 {
834   api_main_t *am = &api_main;
835   ASSERT (msg_id > 0);
836
837   vec_validate (am->msg_cleanup_handlers, msg_id);
838   am->msg_cleanup_handlers[msg_id] = fp;
839 }
840
841 void
842 vl_msg_api_queue_handler (svm_queue_t * q)
843 {
844   uword msg;
845
846   while (!svm_queue_sub (q, (u8 *) & msg, SVM_Q_WAIT, 0))
847     vl_msg_api_handler ((void *) msg);
848 }
849
850 vl_api_trace_t *
851 vl_msg_api_trace_get (api_main_t * am, vl_api_trace_which_t which)
852 {
853   switch (which)
854     {
855     case VL_API_TRACE_RX:
856       return am->rx_trace;
857     case VL_API_TRACE_TX:
858       return am->tx_trace;
859     default:
860       return 0;
861     }
862 }
863
864 void
865 vl_noop_handler (void *mp)
866 {
867 }
868
869
870 static u8 post_mortem_dump_enabled;
871
872 void
873 vl_msg_api_post_mortem_dump_enable_disable (int enable)
874 {
875   post_mortem_dump_enabled = enable;
876 }
877
878 void
879 vl_msg_api_post_mortem_dump (void)
880 {
881   api_main_t *am = &api_main;
882   FILE *fp;
883   char filename[64];
884   int rv;
885
886   if (post_mortem_dump_enabled == 0)
887     return;
888
889   snprintf (filename, sizeof (filename), "/tmp/api_post_mortem.%d",
890             getpid ());
891
892   fp = fopen (filename, "w");
893   if (fp == NULL)
894     {
895       rv = write (2, "Couldn't create ", 16);
896       rv = write (2, filename, strlen (filename));
897       rv = write (2, "\n", 1);
898       return;
899     }
900   rv = vl_msg_api_trace_save (am, VL_API_TRACE_RX, fp);
901   fclose (fp);
902   if (rv < 0)
903     {
904       rv = write (2, "Failed to save post-mortem API trace to ", 40);
905       rv = write (2, filename, strlen (filename));
906       rv = write (2, "\n", 1);
907     }
908
909 }
910
911 /* Layered message handling support */
912
913 void
914 vl_msg_api_register_pd_handler (void *fp, u16 msg_id_host_byte_order)
915 {
916   api_main_t *am = &api_main;
917
918   /* Mild idiot proofing */
919   if (msg_id_host_byte_order > 10000)
920     clib_warning ("msg_id_host_byte_order endian issue? %d arg vs %d",
921                   msg_id_host_byte_order,
922                   clib_net_to_host_u16 (msg_id_host_byte_order));
923   vec_validate (am->pd_msg_handlers, msg_id_host_byte_order);
924   am->pd_msg_handlers[msg_id_host_byte_order] = fp;
925 }
926
927 int
928 vl_msg_api_pd_handler (void *mp, int rv)
929 {
930   api_main_t *am = &api_main;
931   int (*fp) (void *, int);
932   u16 msg_id;
933
934   if (clib_arch_is_little_endian)
935     msg_id = clib_net_to_host_u16 (*((u16 *) mp));
936   else
937     msg_id = *((u16 *) mp);
938
939   if (msg_id >= vec_len (am->pd_msg_handlers)
940       || am->pd_msg_handlers[msg_id] == 0)
941     return rv;
942
943   fp = am->pd_msg_handlers[msg_id];
944   rv = (*fp) (mp, rv);
945   return rv;
946 }
947
948 void
949 vl_msg_api_set_first_available_msg_id (u16 first_avail)
950 {
951   api_main_t *am = &api_main;
952
953   am->first_available_msg_id = first_avail;
954 }
955
956 u16
957 vl_msg_api_get_msg_ids (const char *name, int n)
958 {
959   api_main_t *am = &api_main;
960   u8 *name_copy;
961   vl_api_msg_range_t *rp;
962   uword *p;
963   u16 rv;
964
965   if (am->msg_range_by_name == 0)
966     am->msg_range_by_name = hash_create_string (0, sizeof (uword));
967
968   name_copy = format (0, "%s%c", name, 0);
969
970   p = hash_get_mem (am->msg_range_by_name, name_copy);
971   if (p)
972     {
973       clib_warning ("WARNING: duplicate message range registration for '%s'",
974                     name_copy);
975       vec_free (name_copy);
976       return ((u16) ~ 0);
977     }
978
979   if (n < 0 || n > 1024)
980     {
981       clib_warning
982         ("WARNING: bad number of message-IDs (%d) requested by '%s'",
983          n, name_copy);
984       vec_free (name_copy);
985       return ((u16) ~ 0);
986     }
987
988   vec_add2 (am->msg_ranges, rp, 1);
989
990   rv = rp->first_msg_id = am->first_available_msg_id;
991   am->first_available_msg_id += n;
992   rp->last_msg_id = am->first_available_msg_id - 1;
993   rp->name = name_copy;
994
995   hash_set_mem (am->msg_range_by_name, name_copy, rp - am->msg_ranges);
996
997   return rv;
998 }
999
1000 void
1001 vl_msg_api_add_msg_name_crc (api_main_t * am, const char *string, u32 id)
1002 {
1003   uword *p;
1004
1005   if (am->msg_index_by_name_and_crc == 0)
1006     am->msg_index_by_name_and_crc = hash_create_string (0, sizeof (uword));
1007
1008   p = hash_get_mem (am->msg_index_by_name_and_crc, string);
1009   if (p)
1010     {
1011       clib_warning ("attempt to redefine '%s' ignored...", string);
1012       return;
1013     }
1014
1015   hash_set_mem (am->msg_index_by_name_and_crc, string, id);
1016 }
1017
1018 void
1019 vl_msg_api_add_version (api_main_t * am, const char *string,
1020                         u32 major, u32 minor, u32 patch)
1021 {
1022   api_version_t version = {.major = major,.minor = minor,.patch = patch };
1023   ASSERT (strlen (string) < 64);
1024   strncpy (version.name, string, 64 - 1);
1025   vec_add1 (am->api_version_list, version);
1026 }
1027
1028 u32
1029 vl_msg_api_get_msg_index (u8 * name_and_crc)
1030 {
1031   api_main_t *am = &api_main;
1032   uword *p;
1033
1034   if (am->msg_index_by_name_and_crc)
1035     {
1036       p = hash_get_mem (am->msg_index_by_name_and_crc, name_and_crc);
1037       if (p)
1038         return p[0];
1039     }
1040   return ~0;
1041 }
1042
1043 void *
1044 vl_msg_push_heap (void)
1045 {
1046   api_main_t *am = &api_main;
1047   pthread_mutex_lock (&am->vlib_rp->mutex);
1048   return svm_push_data_heap (am->vlib_rp);
1049 }
1050
1051 void
1052 vl_msg_pop_heap (void *oldheap)
1053 {
1054   api_main_t *am = &api_main;
1055   svm_pop_heap (oldheap);
1056   pthread_mutex_unlock (&am->vlib_rp->mutex);
1057 }
1058
1059 int
1060 vl_api_to_api_string (u32 len, const char *buf, vl_api_string_t * str)
1061 {
1062   clib_memcpy_fast (str->buf, buf, len);
1063   str->length = htonl (len);
1064   return len + sizeof (u32);
1065 }
1066
1067 int
1068 vl_api_vec_to_api_string (const u8 * vec, vl_api_string_t * str)
1069 {
1070   u32 len = vec_len (vec);
1071   clib_memcpy (str->buf, vec, len);
1072   str->length = htonl (len);
1073   return len + sizeof (u32);
1074 }
1075
1076 /* Return a pointer to the API string (not nul terminated */
1077 u8 *
1078 vl_api_from_api_string (vl_api_string_t * astr)
1079 {
1080   return astr->buf;
1081 }
1082
1083 u32
1084 vl_api_string_len (vl_api_string_t * astr)
1085 {
1086   return clib_net_to_host_u32 (astr->length);
1087 }
1088
1089 /*
1090  * Returns a new vector. Remember to free it after use.
1091  */
1092 u8 *
1093 vl_api_from_api_to_vec (vl_api_string_t * astr)
1094 {
1095   u8 *v = 0;
1096   vec_add (v, astr->buf, clib_net_to_host_u32 (astr->length));
1097   return v;
1098 }
1099
1100 void
1101 vl_api_set_elog_main (elog_main_t * m)
1102 {
1103   api_main_t *am = &api_main;
1104   am->elog_main = m;
1105 }
1106
1107 int
1108 vl_api_set_elog_trace_api_messages (int enable)
1109 {
1110   int rv;
1111   api_main_t *am = &api_main;
1112
1113   rv = am->elog_trace_api_messages;
1114   am->elog_trace_api_messages = enable;
1115   return rv;
1116 }
1117
1118 int
1119 vl_api_get_elog_trace_api_messages (void)
1120 {
1121   api_main_t *am = &api_main;
1122
1123   return am->elog_trace_api_messages;
1124 }
1125
1126 /*
1127  * fd.io coding-style-patch-verification: ON
1128  *
1129  * Local Variables:
1130  * eval: (c-set-style "gnu")
1131  * End:
1132  */