Clean up binary api message handler registration issues
[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 <sys/types.h>
27 #include <sys/mman.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <vppinfra/format.h>
32 #include <vppinfra/byte_order.h>
33 #include <vppinfra/error.h>
34 #include <vlib/vlib.h>
35 #include <vlib/unix/unix.h>
36 #include <vlibapi/api.h>
37 #include <vppinfra/elog.h>
38
39 api_main_t api_main;
40
41 void vl_msg_api_barrier_sync (void) __attribute__ ((weak));
42 void
43 vl_msg_api_barrier_sync (void)
44 {
45 }
46
47 void vl_msg_api_barrier_release (void) __attribute__ ((weak));
48 void
49 vl_msg_api_barrier_release (void)
50 {
51 }
52
53 void
54 vl_msg_api_increment_missing_client_counter (void)
55 {
56   api_main_t *am = &api_main;
57   am->missing_clients++;
58 }
59
60 typedef enum
61 {
62   DUMP,
63   CUSTOM_DUMP,
64   REPLAY,
65   INITIALIZERS,
66 } vl_api_replay_t;
67
68 int
69 vl_msg_api_rx_trace_enabled (api_main_t * am)
70 {
71   return (am->rx_trace && am->rx_trace->enabled);
72 }
73
74 int
75 vl_msg_api_tx_trace_enabled (api_main_t * am)
76 {
77   return (am->tx_trace && am->tx_trace->enabled);
78 }
79
80 /*
81  * vl_msg_api_trace
82  */
83 void
84 vl_msg_api_trace (api_main_t * am, vl_api_trace_t * tp, void *msg)
85 {
86   u8 **this_trace;
87   u8 **old_trace;
88   u8 *msg_copy;
89   u32 length;
90   trace_cfg_t *cfgp;
91   u16 msg_id = ntohs (*((u16 *) msg));
92   msgbuf_t *header = (msgbuf_t *) (((u8 *) msg) - offsetof (msgbuf_t, data));
93
94   cfgp = am->api_trace_cfg + msg_id;
95
96   if (!cfgp || !cfgp->trace_enable)
97     return;
98
99   msg_copy = 0;
100
101   if (tp->nitems == 0)
102     {
103       clib_warning ("tp->nitems is 0");
104       return;
105     }
106
107   if (vec_len (tp->traces) < tp->nitems)
108     {
109       vec_add1 (tp->traces, 0);
110       this_trace = tp->traces + vec_len (tp->traces) - 1;
111     }
112   else
113     {
114       tp->wrapped = 1;
115       old_trace = tp->traces + tp->curindex++;
116       if (tp->curindex == tp->nitems)
117         tp->curindex = 0;
118       vec_free (*old_trace);
119       this_trace = old_trace;
120     }
121
122   length = clib_net_to_host_u32 (header->data_len);
123
124   vec_validate (msg_copy, length - 1);
125   clib_memcpy (msg_copy, msg, length);
126   *this_trace = msg_copy;
127 }
128
129 int
130 vl_msg_api_trace_onoff (api_main_t * am, vl_api_trace_which_t which,
131                         int onoff)
132 {
133   vl_api_trace_t *tp;
134   int rv;
135
136   switch (which)
137     {
138     case VL_API_TRACE_TX:
139       tp = am->tx_trace;
140       if (tp == 0)
141         {
142           vl_msg_api_trace_configure (am, which, 1024);
143           tp = am->tx_trace;
144         }
145       break;
146
147     case VL_API_TRACE_RX:
148       tp = am->rx_trace;
149       if (tp == 0)
150         {
151           vl_msg_api_trace_configure (am, which, 1024);
152           tp = am->rx_trace;
153         }
154       break;
155
156     default:
157       /* duh? */
158       return -1;
159     }
160
161   /* Configured? */
162   if (tp == 0 || tp->nitems == 0)
163     return -1;
164
165   rv = tp->enabled;
166   tp->enabled = onoff;
167
168   return rv;
169 }
170
171 int
172 vl_msg_api_trace_free (api_main_t * am, vl_api_trace_which_t which)
173 {
174   vl_api_trace_t *tp;
175   int i;
176
177   switch (which)
178     {
179     case VL_API_TRACE_TX:
180       tp = am->tx_trace;
181       break;
182
183     case VL_API_TRACE_RX:
184       tp = am->rx_trace;
185       break;
186
187     default:
188       /* duh? */
189       return -1;
190     }
191
192   /* Configured? */
193   if (!tp || tp->nitems == 0)
194     return -1;
195
196   tp->curindex = 0;
197   tp->wrapped = 0;
198
199   for (i = 0; i < vec_len (tp->traces); i++)
200     {
201       vec_free (tp->traces[i]);
202     }
203   vec_free (tp->traces);
204
205   return 0;
206 }
207
208 int
209 vl_msg_api_trace_save (api_main_t * am, vl_api_trace_which_t which, FILE * fp)
210 {
211   vl_api_trace_t *tp;
212   vl_api_trace_file_header_t fh;
213   int i;
214   u8 *msg;
215
216   switch (which)
217     {
218     case VL_API_TRACE_TX:
219       tp = am->tx_trace;
220       break;
221
222     case VL_API_TRACE_RX:
223       tp = am->rx_trace;
224       break;
225
226     default:
227       /* duh? */
228       return -1;
229     }
230
231   /* Configured, data present? */
232   if (tp == 0 || tp->nitems == 0 || vec_len (tp->traces) == 0)
233     return -1;
234
235   /* "Dare to be stupid" check */
236   if (fp == 0)
237     {
238       return -2;
239     }
240
241   /* Write the file header */
242   fh.nitems = vec_len (tp->traces);
243   fh.endian = tp->endian;
244   fh.wrapped = tp->wrapped;
245
246   if (fwrite (&fh, sizeof (fh), 1, fp) != 1)
247     {
248       return (-10);
249     }
250
251   /* No-wrap case */
252   if (tp->wrapped == 0)
253     {
254       /*
255        * Note: vec_len return 0 when fed a NULL pointer.
256        * Unfortunately, the static analysis tool doesn't
257        * figure it out, hence the suppressed warnings.
258        * What a great use of my time.
259        */
260       for (i = 0; i < vec_len (tp->traces); i++)
261         {
262           u32 msg_length;
263           /*sa_ignore NO_NULL_CHK */
264           msg = tp->traces[i];
265           /*
266            * This retarded check required to pass
267            * [sic] SA-checking.
268            */
269           if (!msg)
270             continue;
271
272           msg_length = clib_host_to_net_u32 (vec_len (msg));
273           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
274               != sizeof (msg_length))
275             {
276               return (-14);
277             }
278           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
279             {
280               return (-11);
281             }
282         }
283     }
284   else
285     {
286       /* Wrap case: write oldest -> end of buffer */
287       for (i = tp->curindex; i < vec_len (tp->traces); i++)
288         {
289           u32 msg_length;
290           msg = tp->traces[i];
291           /*
292            * This retarded check required to pass
293            * [sic] SA-checking
294            */
295           if (!msg)
296             continue;
297
298           msg_length = clib_host_to_net_u32 (vec_len (msg));
299           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
300               != sizeof (msg_length))
301             {
302               return (-14);
303             }
304
305           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
306             {
307               return (-12);
308             }
309         }
310       /* write beginning of buffer -> oldest-1 */
311       for (i = 0; i < tp->curindex; i++)
312         {
313           u32 msg_length;
314           /*sa_ignore NO_NULL_CHK */
315           msg = tp->traces[i];
316           /*
317            * This retarded check required to pass
318            * [sic] SA-checking
319            */
320           if (!msg)
321             continue;
322
323           msg_length = clib_host_to_net_u32 (vec_len (msg));
324           if (fwrite (&msg_length, 1, sizeof (msg_length), fp)
325               != sizeof (msg_length))
326             {
327               return (-14);
328             }
329
330           if (fwrite (msg, 1, vec_len (msg), fp) != vec_len (msg))
331             {
332               return (-13);
333             }
334         }
335     }
336   return 0;
337 }
338
339 int
340 vl_msg_api_trace_configure (api_main_t * am, vl_api_trace_which_t which,
341                             u32 nitems)
342 {
343   vl_api_trace_t *tp;
344   int was_on = 0;
345
346   switch (which)
347     {
348     case VL_API_TRACE_TX:
349       tp = am->tx_trace;
350       if (tp == 0)
351         {
352           vec_validate (am->tx_trace, 0);
353           tp = am->tx_trace;
354         }
355       break;
356
357     case VL_API_TRACE_RX:
358       tp = am->rx_trace;
359       if (tp == 0)
360         {
361           vec_validate (am->rx_trace, 0);
362           tp = am->rx_trace;
363         }
364
365       break;
366
367     default:
368       return -1;
369
370     }
371
372   if (tp->enabled)
373     {
374       was_on = vl_msg_api_trace_onoff (am, which, 0);
375     }
376   if (tp->traces)
377     {
378       vl_msg_api_trace_free (am, which);
379     }
380
381   memset (tp, 0, sizeof (*tp));
382
383   if (clib_arch_is_big_endian)
384     {
385       tp->endian = VL_API_BIG_ENDIAN;
386     }
387   else
388     {
389       tp->endian = VL_API_LITTLE_ENDIAN;
390     }
391
392   tp->nitems = nitems;
393   if (was_on)
394     {
395       (void) vl_msg_api_trace_onoff (am, which, was_on);
396     }
397   return 0;
398 }
399
400 always_inline void
401 msg_handler_internal (api_main_t * am,
402                       void *the_msg, int trace_it, int do_it, int free_it)
403 {
404   u16 id = ntohs (*((u16 *) the_msg));
405   u8 *(*print_fp) (void *, void *);
406
407   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
408     {
409       if (trace_it)
410         vl_msg_api_trace (am, am->rx_trace, the_msg);
411
412       if (am->msg_print_flag)
413         {
414           fformat (stdout, "[%d]: %s\n", id, am->msg_names[id]);
415           print_fp = (void *) am->msg_print_handlers[id];
416           if (print_fp == 0)
417             {
418               fformat (stdout, "  [no registered print fn]\n");
419             }
420           else
421             {
422               (*print_fp) (the_msg, stdout);
423             }
424         }
425
426       if (do_it)
427         {
428           if (!am->is_mp_safe[id])
429             vl_msg_api_barrier_sync ();
430           (*am->msg_handlers[id]) (the_msg);
431           if (!am->is_mp_safe[id])
432             vl_msg_api_barrier_release ();
433         }
434     }
435   else
436     {
437       clib_warning ("no handler for msg id %d", id);
438     }
439
440   if (free_it)
441     vl_msg_api_free (the_msg);
442 }
443
444 /* set to 1 if you want before/after message handler event logging */
445 #define ELOG_API_MESSAGE_HANDLERS 0
446
447 #if ELOG_API_MESSAGE_HANDLERS > 0
448 static u32
449 elog_id_for_msg_name (vlib_main_t * vm, char *msg_name)
450 {
451   uword *p, r;
452   static uword *h;
453   u8 *name_copy;
454
455   if (!h)
456     h = hash_create_string (0, sizeof (uword));
457
458   p = hash_get_mem (h, msg_name);
459   if (p)
460     return p[0];
461   r = elog_string (&vm->elog_main, "%s", msg_name);
462
463   name_copy = format (0, "%s%c", msg_name, 0);
464
465   hash_set_mem (h, name_copy, r);
466
467   return r;
468 }
469 #endif
470
471 /* This is only to be called from a vlib/vnet app */
472 void
473 vl_msg_api_handler_with_vm_node (api_main_t * am,
474                                  void *the_msg, vlib_main_t * vm,
475                                  vlib_node_runtime_t * node)
476 {
477   u16 id = ntohs (*((u16 *) the_msg));
478   u8 *(*handler) (void *, void *, void *);
479
480 #if ELOG_API_MESSAGE_HANDLERS > 0
481   {
482     /* *INDENT-OFF* */
483     ELOG_TYPE_DECLARE (e) =
484       {
485         .format = "api-msg: %s",
486         .format_args = "T4",
487       };
488     /* *INDENT-ON* */
489     struct
490     {
491       u32 c;
492     } *ed;
493     ed = ELOG_DATA (&vm->elog_main, e);
494     if (id < vec_len (am->msg_names))
495       ed->c = elog_id_for_msg_name (vm, am->msg_names[id]);
496     else
497       ed->c = elog_id_for_msg_name (vm, "BOGUS");
498   }
499 #endif
500
501   if (id < vec_len (am->msg_handlers) && am->msg_handlers[id])
502     {
503       handler = (void *) am->msg_handlers[id];
504
505       if (am->rx_trace && am->rx_trace->enabled)
506         vl_msg_api_trace (am, am->rx_trace, the_msg);
507
508       if (!am->is_mp_safe[id])
509         vl_msg_api_barrier_sync ();
510       (*handler) (the_msg, vm, node);
511       if (!am->is_mp_safe[id])
512         vl_msg_api_barrier_release ();
513     }
514   else
515     {
516       clib_warning ("no handler for msg id %d", id);
517     }
518
519   /*
520    * Special-case, so we can e.g. bounce messages off the vnet
521    * main thread without copying them...
522    */
523   if (!(am->message_bounce[id]))
524     vl_msg_api_free (the_msg);
525
526 #if ELOG_API_MESSAGE_HANDLERS > 0
527   {
528   /* *INDENT-OFF* */
529   ELOG_TYPE_DECLARE (e) = {
530     .format = "api-msg-done: %s",
531     .format_args = "T4",
532   };
533   /* *INDENT-ON* */
534
535     struct
536     {
537       u32 c;
538     } *ed;
539     ed = ELOG_DATA (&vm->elog_main, e);
540     if (id < vec_len (am->msg_names))
541       ed->c = elog_id_for_msg_name (vm, am->msg_names[id]);
542     else
543       ed->c = elog_id_for_msg_name (vm, "BOGUS");
544   }
545 #endif
546 }
547
548 void
549 vl_msg_api_handler (void *the_msg)
550 {
551   api_main_t *am = &api_main;
552
553   msg_handler_internal (am, the_msg,
554                         (am->rx_trace
555                          && am->rx_trace->enabled) /* trace_it */ ,
556                         1 /* do_it */ , 1 /* free_it */ );
557 }
558
559 void
560 vl_msg_api_handler_no_free (void *the_msg)
561 {
562   api_main_t *am = &api_main;
563   msg_handler_internal (am, the_msg,
564                         (am->rx_trace
565                          && am->rx_trace->enabled) /* trace_it */ ,
566                         1 /* do_it */ , 0 /* free_it */ );
567 }
568
569 void
570 vl_msg_api_handler_no_trace_no_free (void *the_msg)
571 {
572   api_main_t *am = &api_main;
573   msg_handler_internal (am, the_msg, 0 /* trace_it */ , 1 /* do_it */ ,
574                         0 /* free_it */ );
575 }
576
577 /*
578  * Add a trace record to the API message trace buffer, if
579  * API message tracing is enabled. Handy for adding sufficient
580  * data to the trace to reproduce autonomous state, as opposed to
581  * state downloaded via control-plane API messages. Example: the NAT
582  * application creates database entries based on packet traffic, not
583  * control-plane messages.
584  *
585  */
586 void
587 vl_msg_api_trace_only (void *the_msg)
588 {
589   api_main_t *am = &api_main;
590
591   msg_handler_internal (am, the_msg,
592                         (am->rx_trace
593                          && am->rx_trace->enabled) /* trace_it */ ,
594                         0 /* do_it */ , 0 /* free_it */ );
595 }
596
597 void
598 vl_msg_api_cleanup_handler (void *the_msg)
599 {
600   api_main_t *am = &api_main;
601   u16 id = ntohs (*((u16 *) the_msg));
602
603   if (PREDICT_FALSE (id >= vec_len (am->msg_cleanup_handlers)))
604     {
605       clib_warning ("_vl_msg_id too large: %d\n", id);
606       return;
607     }
608   if (am->msg_cleanup_handlers[id])
609     (*am->msg_cleanup_handlers[id]) (the_msg);
610
611   vl_msg_api_free (the_msg);
612 }
613
614 /*
615  * vl_msg_api_replay_handler
616  */
617 void
618 vl_msg_api_replay_handler (void *the_msg)
619 {
620   api_main_t *am = &api_main;
621
622   u16 id = ntohs (*((u16 *) the_msg));
623
624   if (PREDICT_FALSE (id >= vec_len (am->msg_handlers)))
625     {
626       clib_warning ("_vl_msg_id too large: %d\n", id);
627       return;
628     }
629   /* do NOT trace the message... */
630   if (am->msg_handlers[id])
631     (*am->msg_handlers[id]) (the_msg);
632   /* do NOT free the message buffer... */
633 }
634
635 /*
636  * vl_msg_api_socket_handler
637  */
638 void
639 vl_msg_api_socket_handler (void *the_msg)
640 {
641   api_main_t *am = &api_main;
642
643   msg_handler_internal (am, the_msg,
644                         (am->rx_trace
645                          && am->rx_trace->enabled) /* trace_it */ ,
646                         1 /* do_it */ , 0 /* free_it */ );
647 }
648
649 #define foreach_msg_api_vector                  \
650 _(msg_names)                                    \
651 _(msg_handlers)                                 \
652 _(msg_cleanup_handlers)                         \
653 _(msg_endian_handlers)                          \
654 _(msg_print_handlers)                           \
655 _(api_trace_cfg)                                \
656 _(message_bounce)                               \
657 _(is_mp_safe)
658
659 void
660 vl_msg_api_config (vl_msg_api_msg_config_t * c)
661 {
662   api_main_t *am = &api_main;
663
664   ASSERT (c->id > 0);
665
666 #define _(a) vec_validate (am->a, c->id);
667   foreach_msg_api_vector;
668 #undef _
669
670   if (am->msg_names[c->id])
671     clib_warning ("BUG: multiple registrations of 'vl_api_%s_t_handler'",
672                   c->name);
673
674   am->msg_names[c->id] = c->name;
675   am->msg_handlers[c->id] = c->handler;
676   am->msg_cleanup_handlers[c->id] = c->cleanup;
677   am->msg_endian_handlers[c->id] = c->endian;
678   am->msg_print_handlers[c->id] = c->print;
679   am->message_bounce[c->id] = c->message_bounce;
680   am->is_mp_safe[c->id] = c->is_mp_safe;
681
682   am->api_trace_cfg[c->id].size = c->size;
683   am->api_trace_cfg[c->id].trace_enable = c->traced;
684   am->api_trace_cfg[c->id].replay_enable = c->replay;
685 }
686
687 /*
688  * vl_msg_api_set_handlers
689  * preserve the old API for a while
690  */
691 void
692 vl_msg_api_set_handlers (int id, char *name, void *handler, void *cleanup,
693                          void *endian, void *print, int size, int traced)
694 {
695   vl_msg_api_msg_config_t cfg;
696   vl_msg_api_msg_config_t *c = &cfg;
697
698   memset (c, 0, sizeof (*c));
699
700   c->id = id;
701   c->name = name;
702   c->handler = handler;
703   c->cleanup = cleanup;
704   c->endian = endian;
705   c->print = print;
706   c->traced = traced;
707   c->replay = 1;
708   c->message_bounce = 0;
709   c->is_mp_safe = 0;
710   vl_msg_api_config (c);
711 }
712
713 void
714 vl_msg_api_set_cleanup_handler (int msg_id, void *fp)
715 {
716   api_main_t *am = &api_main;
717   ASSERT (msg_id > 0);
718
719   vec_validate (am->msg_cleanup_handlers, msg_id);
720   am->msg_cleanup_handlers[msg_id] = fp;
721 }
722
723 void
724 vl_msg_api_queue_handler (unix_shared_memory_queue_t * q)
725 {
726   uword msg;
727
728   while (!unix_shared_memory_queue_sub (q, (u8 *) & msg, 0))
729     vl_msg_api_handler ((void *) msg);
730 }
731
732 vl_api_trace_t *
733 vl_msg_api_trace_get (api_main_t * am, vl_api_trace_which_t which)
734 {
735   switch (which)
736     {
737     case VL_API_TRACE_RX:
738       return am->rx_trace;
739     case VL_API_TRACE_TX:
740       return am->tx_trace;
741     default:
742       return 0;
743     }
744 }
745
746 void
747 vl_noop_handler (void *mp)
748 {
749 }
750
751 clib_error_t *
752 vl_api_init (vlib_main_t * vm)
753 {
754   static u8 once;
755   api_main_t *am = &api_main;
756
757   if (once)
758     return 0;
759
760   once = 1;
761
762   am->region_name = "/unset";
763   /*
764    * Eventually passed to fchown, -1 => "current user"
765    * instead of 0 => "root". A very fine disctinction at best.
766    */
767   if (am->api_uid == 0)
768     am->api_uid = -1;
769   if (am->api_gid == 0)
770     am->api_gid = -1;
771
772   return (0);
773 }
774
775 void vl_msg_api_custom_dump_configure (api_main_t * am)
776   __attribute__ ((weak));
777 void
778 vl_msg_api_custom_dump_configure (api_main_t * am)
779 {
780 }
781
782 VLIB_INIT_FUNCTION (vl_api_init);
783
784 static void
785 vl_msg_api_process_file (vlib_main_t * vm, u8 * filename,
786                          u32 first_index, u32 last_index,
787                          vl_api_replay_t which)
788 {
789   vl_api_trace_file_header_t *hp;
790   int i, fd;
791   struct stat statb;
792   size_t file_size;
793   u8 *msg;
794   u8 endian_swap_needed = 0;
795   api_main_t *am = &api_main;
796   u8 *tmpbuf = 0;
797   u32 nitems;
798   void **saved_print_handlers = 0;
799
800   fd = open ((char *) filename, O_RDONLY);
801
802   if (fd < 0)
803     {
804       vlib_cli_output (vm, "Couldn't open %s\n", filename);
805       return;
806     }
807
808   if (fstat (fd, &statb) < 0)
809     {
810       vlib_cli_output (vm, "Couldn't stat %s\n", filename);
811       close (fd);
812       return;
813     }
814
815   if (!(statb.st_mode & S_IFREG) || (statb.st_size < sizeof (*hp)))
816     {
817       vlib_cli_output (vm, "File not plausible: %s\n", filename);
818       close (fd);
819       return;
820     }
821
822   file_size = statb.st_size;
823   file_size = (file_size + 4095) & ~(4096);
824
825   hp = mmap (0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
826
827   if (hp == (vl_api_trace_file_header_t *) MAP_FAILED)
828     {
829       vlib_cli_output (vm, "mmap failed: %s\n", filename);
830       close (fd);
831       return;
832     }
833   close (fd);
834
835   if ((clib_arch_is_little_endian && hp->endian == VL_API_BIG_ENDIAN)
836       || (clib_arch_is_big_endian && hp->endian == VL_API_LITTLE_ENDIAN))
837     endian_swap_needed = 1;
838
839   if (endian_swap_needed)
840     nitems = ntohl (hp->nitems);
841   else
842     nitems = hp->nitems;
843
844   if (last_index == (u32) ~ 0)
845     {
846       last_index = nitems - 1;
847     }
848
849   if (first_index >= nitems || last_index >= nitems)
850     {
851       vlib_cli_output (vm, "Range (%d, %d) outside file range (0, %d)\n",
852                        first_index, last_index, nitems - 1);
853       munmap (hp, file_size);
854       return;
855     }
856   if (hp->wrapped)
857     vlib_cli_output (vm,
858                      "Note: wrapped/incomplete trace, results may vary\n");
859
860   if (which == CUSTOM_DUMP)
861     {
862       saved_print_handlers = (void **) vec_dup (am->msg_print_handlers);
863       vl_msg_api_custom_dump_configure (am);
864     }
865
866
867   msg = (u8 *) (hp + 1);
868
869   for (i = 0; i < first_index; i++)
870     {
871       trace_cfg_t *cfgp;
872       int size;
873       u16 msg_id;
874
875       size = clib_host_to_net_u32 (*(u32 *) msg);
876       msg += sizeof (u32);
877
878       if (clib_arch_is_little_endian)
879         msg_id = ntohs (*((u16 *) msg));
880       else
881         msg_id = *((u16 *) msg);
882
883       cfgp = am->api_trace_cfg + msg_id;
884       if (!cfgp)
885         {
886           vlib_cli_output (vm, "Ugh: msg id %d no trace config\n", msg_id);
887           munmap (hp, file_size);
888           return;
889         }
890       msg += size;
891     }
892
893   for (; i <= last_index; i++)
894     {
895       trace_cfg_t *cfgp;
896       u16 *msg_idp;
897       u16 msg_id;
898       int size;
899
900       if (which == DUMP)
901         vlib_cli_output (vm, "---------- trace %d -----------\n", i);
902
903       size = clib_host_to_net_u32 (*(u32 *) msg);
904       msg += sizeof (u32);
905
906       if (clib_arch_is_little_endian)
907         msg_id = ntohs (*((u16 *) msg));
908       else
909         msg_id = *((u16 *) msg);
910
911       cfgp = am->api_trace_cfg + msg_id;
912       if (!cfgp)
913         {
914           vlib_cli_output (vm, "Ugh: msg id %d no trace config\n", msg_id);
915           munmap (hp, file_size);
916           vec_free (tmpbuf);
917           return;
918         }
919
920       /* Copy the buffer (from the read-only mmap'ed file) */
921       vec_validate (tmpbuf, size - 1 + sizeof (uword));
922       clib_memcpy (tmpbuf + sizeof (uword), msg, size);
923       memset (tmpbuf, 0xf, sizeof (uword));
924
925       /*
926        * Endian swap if needed. All msg data is supposed to be
927        * in network byte order. All msg handlers are supposed to
928        * know that. The generic message dumpers don't know that.
929        * One could fix apigen, I suppose.
930        */
931       if ((which == DUMP && clib_arch_is_little_endian) || endian_swap_needed)
932         {
933           void (*endian_fp) (void *);
934           if (msg_id >= vec_len (am->msg_endian_handlers)
935               || (am->msg_endian_handlers[msg_id] == 0))
936             {
937               vlib_cli_output (vm, "Ugh: msg id %d no endian swap\n", msg_id);
938               munmap (hp, file_size);
939               vec_free (tmpbuf);
940               return;
941             }
942           endian_fp = am->msg_endian_handlers[msg_id];
943           (*endian_fp) (tmpbuf + sizeof (uword));
944         }
945
946       /* msg_id always in network byte order */
947       if (clib_arch_is_little_endian)
948         {
949           msg_idp = (u16 *) (tmpbuf + sizeof (uword));
950           *msg_idp = msg_id;
951         }
952
953       switch (which)
954         {
955         case CUSTOM_DUMP:
956         case DUMP:
957           if (msg_id < vec_len (am->msg_print_handlers) &&
958               am->msg_print_handlers[msg_id])
959             {
960               u8 *(*print_fp) (void *, void *);
961
962               print_fp = (void *) am->msg_print_handlers[msg_id];
963               (*print_fp) (tmpbuf + sizeof (uword), vm);
964             }
965           else
966             {
967               vlib_cli_output (vm, "Skipping msg id %d: no print fcn\n",
968                                msg_id);
969               break;
970             }
971           break;
972
973         case INITIALIZERS:
974           if (msg_id < vec_len (am->msg_print_handlers) &&
975               am->msg_print_handlers[msg_id])
976             {
977               u8 *s;
978               int j;
979               u8 *(*print_fp) (void *, void *);
980
981               print_fp = (void *) am->msg_print_handlers[msg_id];
982
983               vlib_cli_output (vm, "/*");
984
985               (*print_fp) (tmpbuf + sizeof (uword), vm);
986               vlib_cli_output (vm, "*/\n");
987
988               s = format (0, "static u8 * vl_api_%s_%d[%d] = {",
989                           am->msg_names[msg_id], i,
990                           am->api_trace_cfg[msg_id].size);
991
992               for (j = 0; j < am->api_trace_cfg[msg_id].size; j++)
993                 {
994                   if ((j & 7) == 0)
995                     s = format (s, "\n    ");
996                   s = format (s, "0x%02x,", tmpbuf[sizeof (uword) + j]);
997                 }
998               s = format (s, "\n};\n%c", 0);
999               vlib_cli_output (vm, (char *) s);
1000               vec_free (s);
1001             }
1002           break;
1003
1004         case REPLAY:
1005           if (msg_id < vec_len (am->msg_print_handlers) &&
1006               am->msg_print_handlers[msg_id] && cfgp->replay_enable)
1007             {
1008               void (*handler) (void *);
1009
1010               handler = (void *) am->msg_handlers[msg_id];
1011
1012               if (!am->is_mp_safe[msg_id])
1013                 vl_msg_api_barrier_sync ();
1014               (*handler) (tmpbuf + sizeof (uword));
1015               if (!am->is_mp_safe[msg_id])
1016                 vl_msg_api_barrier_release ();
1017             }
1018           else
1019             {
1020               if (cfgp->replay_enable)
1021                 vlib_cli_output (vm, "Skipping msg id %d: no handler\n",
1022                                  msg_id);
1023               break;
1024             }
1025           break;
1026         }
1027
1028       _vec_len (tmpbuf) = 0;
1029       msg += size;
1030     }
1031
1032   if (saved_print_handlers)
1033     {
1034       clib_memcpy (am->msg_print_handlers, saved_print_handlers,
1035                    vec_len (am->msg_print_handlers) * sizeof (void *));
1036       vec_free (saved_print_handlers);
1037     }
1038
1039   munmap (hp, file_size);
1040   vec_free (tmpbuf);
1041 }
1042
1043 u8 *
1044 format_vl_msg_api_trace_status (u8 * s, va_list * args)
1045 {
1046   api_main_t *am = va_arg (*args, api_main_t *);
1047   vl_api_trace_which_t which = va_arg (*args, vl_api_trace_which_t);
1048   vl_api_trace_t *tp;
1049   char *trace_name;
1050
1051   switch (which)
1052     {
1053     case VL_API_TRACE_TX:
1054       tp = am->tx_trace;
1055       trace_name = "TX trace";
1056       break;
1057
1058     case VL_API_TRACE_RX:
1059       tp = am->rx_trace;
1060       trace_name = "RX trace";
1061       break;
1062
1063     default:
1064       abort ();
1065     }
1066
1067   if (tp == 0)
1068     {
1069       s = format (s, "%s: not yet configured.\n", trace_name);
1070       return s;
1071     }
1072
1073   s = format (s, "%s: used %d of %d items, %s enabled, %s wrapped\n",
1074               trace_name, vec_len (tp->traces), tp->nitems,
1075               tp->enabled ? "is" : "is not", tp->wrapped ? "has" : "has not");
1076   return s;
1077 }
1078
1079 static u8 post_mortem_dump_enabled;
1080
1081 static clib_error_t *
1082 api_trace_command_fn (vlib_main_t * vm,
1083                       unformat_input_t * input, vlib_cli_command_t * cmd)
1084 {
1085   u32 nitems = 256 << 10;
1086   api_main_t *am = &api_main;
1087   vl_api_trace_which_t which = VL_API_TRACE_RX;
1088   u8 *filename;
1089   u32 first = 0;
1090   u32 last = (u32) ~ 0;
1091   FILE *fp;
1092   int rv;
1093
1094   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1095     {
1096       if (unformat (input, "on") || unformat (input, "enable"))
1097         {
1098           if (unformat (input, "nitems %d", &nitems))
1099             ;
1100           vl_msg_api_trace_configure (am, which, nitems);
1101           vl_msg_api_trace_onoff (am, which, 1 /* on */ );
1102         }
1103       else if (unformat (input, "off"))
1104         {
1105           vl_msg_api_trace_onoff (am, which, 0);
1106         }
1107       else if (unformat (input, "save %s", &filename))
1108         {
1109           u8 *chroot_filename;
1110           if (strstr ((char *) filename, "..")
1111               || index ((char *) filename, '/'))
1112             {
1113               vlib_cli_output (vm, "illegal characters in filename '%s'",
1114                                filename);
1115               return 0;
1116             }
1117
1118           chroot_filename = format (0, "/tmp/%s%c", filename, 0);
1119
1120           vec_free (filename);
1121
1122           fp = fopen ((char *) chroot_filename, "w");
1123           if (fp == NULL)
1124             {
1125               vlib_cli_output (vm, "Couldn't create %s\n", chroot_filename);
1126               return 0;
1127             }
1128           rv = vl_msg_api_trace_save (am, which, fp);
1129           fclose (fp);
1130           if (rv == -1)
1131             vlib_cli_output (vm, "API Trace data not present\n");
1132           else if (rv == -2)
1133             vlib_cli_output (vm, "File for writing is closed\n");
1134           else if (rv == -10)
1135             vlib_cli_output (vm, "Error while writing header to file\n");
1136           else if (rv == -11)
1137             vlib_cli_output (vm, "Error while writing trace to file\n");
1138           else if (rv == -12)
1139             vlib_cli_output (vm,
1140                              "Error while writing end of buffer trace to file\n");
1141           else if (rv == -13)
1142             vlib_cli_output (vm,
1143                              "Error while writing start of buffer trace to file\n");
1144           else if (rv < 0)
1145             vlib_cli_output (vm, "Unkown error while saving: %d", rv);
1146           else
1147             vlib_cli_output (vm, "API trace saved to %s\n", chroot_filename);
1148           vec_free (chroot_filename);
1149         }
1150       else if (unformat (input, "dump %s", &filename))
1151         {
1152           vl_msg_api_process_file (vm, filename, first, last, DUMP);
1153         }
1154       else if (unformat (input, "custom-dump %s", &filename))
1155         {
1156           vl_msg_api_process_file (vm, filename, first, last, CUSTOM_DUMP);
1157         }
1158       else if (unformat (input, "replay %s", &filename))
1159         {
1160           vl_msg_api_process_file (vm, filename, first, last, REPLAY);
1161         }
1162       else if (unformat (input, "initializers %s", &filename))
1163         {
1164           vl_msg_api_process_file (vm, filename, first, last, INITIALIZERS);
1165         }
1166       else if (unformat (input, "tx"))
1167         {
1168           which = VL_API_TRACE_TX;
1169         }
1170       else if (unformat (input, "first %d", &first))
1171         {
1172           ;
1173         }
1174       else if (unformat (input, "last %d", &last))
1175         {
1176           ;
1177         }
1178       else if (unformat (input, "status"))
1179         {
1180           vlib_cli_output (vm, "%U", format_vl_msg_api_trace_status,
1181                            am, which);
1182         }
1183       else if (unformat (input, "free"))
1184         {
1185           vl_msg_api_trace_onoff (am, which, 0);
1186           vl_msg_api_trace_free (am, which);
1187         }
1188       else if (unformat (input, "post-mortem-on"))
1189         post_mortem_dump_enabled = 1;
1190       else if (unformat (input, "post-mortem-off"))
1191         post_mortem_dump_enabled = 0;
1192       else
1193         return clib_error_return (0, "unknown input `%U'",
1194                                   format_unformat_error, input);
1195     }
1196   return 0;
1197 }
1198
1199 /* *INDENT-OFF* */
1200 VLIB_CLI_COMMAND (api_trace_command, static) = {
1201     .path = "api trace",
1202     .short_help =
1203     "api trace [on|off][dump|save|replay <file>][status][free][post-mortem-on]",
1204     .function = api_trace_command_fn,
1205 };
1206 /* *INDENT-ON* */
1207
1208 static clib_error_t *
1209 api_config_fn (vlib_main_t * vm, unformat_input_t * input)
1210 {
1211   u32 nitems = 256 << 10;
1212   vl_api_trace_which_t which = VL_API_TRACE_RX;
1213   api_main_t *am = &api_main;
1214
1215   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1216     {
1217       if (unformat (input, "on") || unformat (input, "enable"))
1218         {
1219           if (unformat (input, "nitems %d", &nitems))
1220             ;
1221           vl_msg_api_trace_configure (am, which, nitems);
1222           vl_msg_api_trace_onoff (am, which, 1 /* on */ );
1223           post_mortem_dump_enabled = 1;
1224         }
1225       else
1226         return clib_error_return (0, "unknown input `%U'",
1227                                   format_unformat_error, input);
1228     }
1229   return 0;
1230 }
1231
1232 VLIB_CONFIG_FUNCTION (api_config_fn, "api-trace");
1233
1234 void
1235 vl_msg_api_post_mortem_dump (void)
1236 {
1237   api_main_t *am = &api_main;
1238   FILE *fp;
1239   char filename[64];
1240   int rv;
1241
1242   if (post_mortem_dump_enabled == 0)
1243     return;
1244
1245   snprintf (filename, sizeof (filename), "/tmp/api_post_mortem.%d",
1246             getpid ());
1247
1248   fp = fopen (filename, "w");
1249   if (fp == NULL)
1250     {
1251       rv = write (2, "Couldn't create ", 16);
1252       rv = write (2, filename, strlen (filename));
1253       rv = write (2, "\n", 1);
1254       return;
1255     }
1256   rv = vl_msg_api_trace_save (am, VL_API_TRACE_RX, fp);
1257   fclose (fp);
1258   if (rv < 0)
1259     {
1260       rv = write (2, "Failed to save post-mortem API trace to ", 40);
1261       rv = write (2, filename, strlen (filename));
1262       rv = write (2, "\n", 1);
1263     }
1264
1265 }
1266
1267 /* Layered message handling support */
1268
1269 void
1270 vl_msg_api_register_pd_handler (void *fp, u16 msg_id_host_byte_order)
1271 {
1272   api_main_t *am = &api_main;
1273
1274   /* Mild idiot proofing */
1275   if (msg_id_host_byte_order > 10000)
1276     clib_warning ("msg_id_host_byte_order endian issue? %d arg vs %d",
1277                   msg_id_host_byte_order,
1278                   clib_net_to_host_u16 (msg_id_host_byte_order));
1279   vec_validate (am->pd_msg_handlers, msg_id_host_byte_order);
1280   am->pd_msg_handlers[msg_id_host_byte_order] = fp;
1281 }
1282
1283 int
1284 vl_msg_api_pd_handler (void *mp, int rv)
1285 {
1286   api_main_t *am = &api_main;
1287   int (*fp) (void *, int);
1288   u16 msg_id;
1289
1290   if (clib_arch_is_little_endian)
1291     msg_id = clib_net_to_host_u16 (*((u16 *) mp));
1292   else
1293     msg_id = *((u16 *) mp);
1294
1295   if (msg_id >= vec_len (am->pd_msg_handlers)
1296       || am->pd_msg_handlers[msg_id] == 0)
1297     return rv;
1298
1299   fp = am->pd_msg_handlers[msg_id];
1300   rv = (*fp) (mp, rv);
1301   return rv;
1302 }
1303
1304 void
1305 vl_msg_api_set_first_available_msg_id (u16 first_avail)
1306 {
1307   api_main_t *am = &api_main;
1308
1309   am->first_available_msg_id = first_avail;
1310 }
1311
1312 u16
1313 vl_msg_api_get_msg_ids (char *name, int n)
1314 {
1315   api_main_t *am = &api_main;
1316   u8 *name_copy;
1317   vl_api_msg_range_t *rp;
1318   uword *p;
1319   u16 rv;
1320
1321   if (am->msg_range_by_name == 0)
1322     am->msg_range_by_name = hash_create_string (0, sizeof (uword));
1323
1324   name_copy = format (0, "%s%c", name, 0);
1325
1326   p = hash_get_mem (am->msg_range_by_name, name_copy);
1327   if (p)
1328     {
1329       clib_warning ("WARNING: duplicate message range registration for '%s'",
1330                     name_copy);
1331       vec_free (name_copy);
1332       return ((u16) ~ 0);
1333     }
1334
1335   if (n < 0 || n > 1024)
1336     {
1337       clib_warning
1338         ("WARNING: bad number of message-IDs (%d) requested by '%s'",
1339          n, name_copy);
1340       vec_free (name_copy);
1341       return ((u16) ~ 0);
1342     }
1343
1344   vec_add2 (am->msg_ranges, rp, 1);
1345
1346   rv = rp->first_msg_id = am->first_available_msg_id;
1347   am->first_available_msg_id += n;
1348   rp->last_msg_id = am->first_available_msg_id - 1;
1349   rp->name = name_copy;
1350
1351   hash_set_mem (am->msg_range_by_name, name_copy, rp - am->msg_ranges);
1352
1353   return rv;
1354 }
1355
1356 void
1357 vl_msg_api_add_msg_name_crc (api_main_t * am, char *string, u32 id)
1358 {
1359   uword *p;
1360
1361   if (am->msg_index_by_name_and_crc == 0)
1362     am->msg_index_by_name_and_crc = hash_create_string (0, sizeof (uword));
1363
1364   p = hash_get_mem (am->msg_index_by_name_and_crc, string);
1365   if (p)
1366     {
1367       clib_warning ("attempt to redefine '%s' ignored...", string);
1368       return;
1369     }
1370
1371   hash_set_mem (am->msg_index_by_name_and_crc, string, id);
1372 }
1373
1374
1375 /*
1376  * fd.io coding-style-patch-verification: ON
1377  *
1378  * Local Variables:
1379  * eval: (c-set-style "gnu")
1380  * End:
1381  */