6841a5b299607865b891e63d7fbe4851392a23b3
[vpp.git] / src / vlib / cli.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * cli.c: command line interface
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <vlib/vlib.h>
41 #include <vlib/unix/unix.h>
42 #include <vppinfra/callback.h>
43 #include <vppinfra/cpu.h>
44 #include <vppinfra/elog.h>
45 #include <unistd.h>
46 #include <ctype.h>
47
48 /** \file src/vlib/cli.c Debug CLI Implementation
49  */
50
51 int vl_api_set_elog_trace_api_messages (int enable);
52 int vl_api_get_elog_trace_api_messages (void);
53
54 static void *current_traced_heap;
55
56 /* Root of all show commands. */
57 /* *INDENT-OFF* */
58 VLIB_CLI_COMMAND (vlib_cli_show_command, static) = {
59   .path = "show",
60   .short_help = "Show commands",
61 };
62 /* *INDENT-ON* */
63
64 /* Root of all clear commands. */
65 /* *INDENT-OFF* */
66 VLIB_CLI_COMMAND (vlib_cli_clear_command, static) = {
67   .path = "clear",
68   .short_help = "Clear commands",
69 };
70 /* *INDENT-ON* */
71
72 /* Root of all set commands. */
73 /* *INDENT-OFF* */
74 VLIB_CLI_COMMAND (vlib_cli_set_command, static) = {
75   .path = "set",
76   .short_help = "Set commands",
77 };
78 /* *INDENT-ON* */
79
80 /* Root of all test commands. */
81 /* *INDENT-OFF* */
82 VLIB_CLI_COMMAND (vlib_cli_test_command, static) = {
83   .path = "test",
84   .short_help = "Test commands",
85 };
86 /* *INDENT-ON* */
87
88 /* Returns bitmap of commands which match key. */
89 static uword *
90 vlib_cli_sub_command_match (vlib_cli_command_t * c, unformat_input_t * input)
91 {
92   int i, n;
93   uword *match = 0;
94   vlib_cli_parse_position_t *p;
95
96   unformat_skip_white_space (input);
97
98   for (i = 0;; i++)
99     {
100       uword k;
101
102       k = unformat_get_input (input);
103       switch (k)
104         {
105         case 'a' ... 'z':
106         case 'A' ... 'Z':
107         case '0' ... '9':
108         case '-':
109         case '_':
110           break;
111
112         case ' ':
113         case '\t':
114         case '\r':
115         case '\n':
116         case UNFORMAT_END_OF_INPUT:
117           /* White space or end of input removes any non-white
118              matches that were before possible. */
119           if (i < vec_len (c->sub_command_positions)
120               && clib_bitmap_count_set_bits (match) > 1)
121             {
122               p = vec_elt_at_index (c->sub_command_positions, i);
123               for (n = 0; n < vec_len (p->bitmaps); n++)
124                 match = clib_bitmap_andnot (match, p->bitmaps[n]);
125             }
126           goto done;
127
128         default:
129           unformat_put_input (input);
130           goto done;
131         }
132
133       if (i >= vec_len (c->sub_command_positions))
134         {
135         no_match:
136           clib_bitmap_free (match);
137           return 0;
138         }
139
140       p = vec_elt_at_index (c->sub_command_positions, i);
141       if (vec_len (p->bitmaps) == 0)
142         goto no_match;
143
144       n = k - p->min_char;
145       if (n < 0 || n >= vec_len (p->bitmaps))
146         goto no_match;
147
148       if (i == 0)
149         match = clib_bitmap_dup (p->bitmaps[n]);
150       else
151         match = clib_bitmap_and (match, p->bitmaps[n]);
152
153       if (clib_bitmap_is_zero (match))
154         goto no_match;
155     }
156
157 done:
158   return match;
159 }
160
161 /* Looks for string based sub-input formatted { SUB-INPUT }. */
162 uword
163 unformat_vlib_cli_sub_input (unformat_input_t * i, va_list * args)
164 {
165   unformat_input_t *sub_input = va_arg (*args, unformat_input_t *);
166   u8 *s;
167   uword c;
168
169   while (1)
170     {
171       c = unformat_get_input (i);
172       switch (c)
173         {
174         case ' ':
175         case '\t':
176         case '\n':
177         case '\r':
178         case '\f':
179           break;
180
181         case '{':
182         default:
183           /* Put back paren. */
184           if (c != UNFORMAT_END_OF_INPUT)
185             unformat_put_input (i);
186
187           if (c == '{' && unformat (i, "%v", &s))
188             {
189               unformat_init_vector (sub_input, s);
190               return 1;
191             }
192           return 0;
193         }
194     }
195   return 0;
196 }
197
198 static vlib_cli_command_t *
199 get_sub_command (vlib_cli_main_t * cm, vlib_cli_command_t * parent, u32 si)
200 {
201   vlib_cli_sub_command_t *s = vec_elt_at_index (parent->sub_commands, si);
202   return vec_elt_at_index (cm->commands, s->index);
203 }
204
205 static uword
206 unformat_vlib_cli_sub_command (unformat_input_t * i, va_list * args)
207 {
208   vlib_main_t *vm = va_arg (*args, vlib_main_t *);
209   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
210   vlib_cli_command_t **result = va_arg (*args, vlib_cli_command_t **);
211   vlib_cli_main_t *cm = &vm->cli_main;
212   uword *match_bitmap, is_unique, index;
213
214   match_bitmap = vlib_cli_sub_command_match (c, i);
215   is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
216   index = ~0;
217   if (is_unique)
218     {
219       index = clib_bitmap_first_set (match_bitmap);
220       *result = get_sub_command (cm, c, index);
221     }
222   clib_bitmap_free (match_bitmap);
223
224   return is_unique;
225 }
226
227 static int
228 vlib_cli_cmp_strings (void *a1, void *a2)
229 {
230   u8 *c1 = *(u8 **) a1;
231   u8 *c2 = *(u8 **) a2;
232
233   return vec_cmp (c1, c2);
234 }
235
236 u8 **
237 vlib_cli_get_possible_completions (u8 * str)
238 {
239   vlib_cli_command_t *c;
240   vlib_cli_sub_command_t *sc;
241   vlib_main_t *vm = vlib_get_main ();
242   vlib_cli_main_t *vcm = &vm->cli_main;
243   uword *match_bitmap = 0;
244   uword index, is_unique, help_next_level;
245   u8 **result = 0;
246   unformat_input_t input;
247   unformat_init_vector (&input, vec_dup (str));
248   c = vec_elt_at_index (vcm->commands, 0);
249
250   /* remove trailing whitespace, except for one of them */
251   while (vec_len (input.buffer) >= 2 &&
252          isspace (input.buffer[vec_len (input.buffer) - 1]) &&
253          isspace (input.buffer[vec_len (input.buffer) - 2]))
254     {
255       vec_del1 (input.buffer, vec_len (input.buffer) - 1);
256     }
257
258   /* if input is empty, directly return list of root commands */
259   if (vec_len (input.buffer) == 0 ||
260       (vec_len (input.buffer) == 1 && isspace (input.buffer[0])))
261     {
262       vec_foreach (sc, c->sub_commands)
263       {
264         vec_add1 (result, (u8 *) sc->name);
265       }
266       goto done;
267     }
268
269   /* add a trailing '?' so that vlib_cli_sub_command_match can find
270    * all commands starting with the input string */
271   vec_add1 (input.buffer, '?');
272
273   while (1)
274     {
275       match_bitmap = vlib_cli_sub_command_match (c, &input);
276       /* no match: return no result */
277       if (match_bitmap == 0)
278         {
279           goto done;
280         }
281       is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
282       /* unique match: try to step one subcommand level further */
283       if (is_unique)
284         {
285           /* stop if no more input */
286           if (input.index >= vec_len (input.buffer) - 1)
287             {
288               break;
289             }
290
291           index = clib_bitmap_first_set (match_bitmap);
292           c = get_sub_command (vcm, c, index);
293           clib_bitmap_free (match_bitmap);
294           continue;
295         }
296       /* multiple matches: stop here, return all matches */
297       break;
298     }
299
300   /* remove trailing '?' */
301   vec_del1 (input.buffer, vec_len (input.buffer) - 1);
302
303   /* if we have a space at the end of input, and a unique match,
304    * autocomplete the next level of subcommands */
305   help_next_level = (vec_len (str) == 0) || isspace (str[vec_len (str) - 1]);
306   /* *INDENT-OFF* */
307   clib_bitmap_foreach(index, match_bitmap, {
308     if (help_next_level && is_unique) {
309         c = get_sub_command (vcm, c, index);
310         vec_foreach (sc, c->sub_commands) {
311           vec_add1 (result, (u8*) sc->name);
312         }
313         goto done; /* break doesn't work in this macro-loop */
314     }
315     sc = &c->sub_commands[index];
316     vec_add1(result, (u8*) sc->name);
317   });
318   /* *INDENT-ON* */
319
320 done:
321   clib_bitmap_free (match_bitmap);
322   unformat_free (&input);
323
324   if (result)
325     vec_sort_with_function (result, vlib_cli_cmp_strings);
326   return result;
327 }
328
329 static u8 *
330 format_vlib_cli_command_help (u8 * s, va_list * args)
331 {
332   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
333   int is_long = va_arg (*args, int);
334   if (is_long && c->long_help)
335     s = format (s, "%s", c->long_help);
336   else if (c->short_help)
337     s = format (s, "%s", c->short_help);
338   else
339     s = format (s, "%v commands", c->path);
340   return s;
341 }
342
343 static u8 *
344 format_vlib_cli_path (u8 * s, va_list * args)
345 {
346   u8 *path = va_arg (*args, u8 *);
347
348   s = format (s, "%v", path);
349
350   return s;
351 }
352
353 static vlib_cli_command_t *
354 all_subs (vlib_cli_main_t * cm, vlib_cli_command_t * subs, u32 command_index)
355 {
356   vlib_cli_command_t *c = vec_elt_at_index (cm->commands, command_index);
357   vlib_cli_sub_command_t *sc;
358
359   if (c->function)
360     vec_add1 (subs, c[0]);
361
362   vec_foreach (sc, c->sub_commands) subs = all_subs (cm, subs, sc->index);
363
364   return subs;
365 }
366
367 static int
368 vlib_cli_cmp_rule (void *a1, void *a2)
369 {
370   vlib_cli_sub_rule_t *r1 = a1;
371   vlib_cli_sub_rule_t *r2 = a2;
372
373   return vec_cmp (r1->name, r2->name);
374 }
375
376 static int
377 vlib_cli_cmp_command (void *a1, void *a2)
378 {
379   vlib_cli_command_t *c1 = a1;
380   vlib_cli_command_t *c2 = a2;
381
382   return vec_cmp (c1->path, c2->path);
383 }
384
385 static clib_error_t *
386 vlib_cli_dispatch_sub_commands (vlib_main_t * vm,
387                                 vlib_cli_main_t * cm,
388                                 unformat_input_t * input,
389                                 uword parent_command_index)
390 {
391   vlib_cli_command_t *parent, *c;
392   clib_error_t *error = 0;
393   unformat_input_t sub_input;
394   u8 *string;
395   uword is_main_dispatch = cm == &vm->cli_main;
396
397   parent = vec_elt_at_index (cm->commands, parent_command_index);
398   if (is_main_dispatch && unformat (input, "help"))
399     {
400       uword help_at_end_of_line, i;
401
402       help_at_end_of_line =
403         unformat_check_input (input) == UNFORMAT_END_OF_INPUT;
404       while (1)
405         {
406           c = parent;
407           if (unformat_user
408               (input, unformat_vlib_cli_sub_command, vm, c, &parent))
409             ;
410
411           else if (!(unformat_check_input (input) == UNFORMAT_END_OF_INPUT))
412             goto unknown;
413
414           else
415             break;
416         }
417
418       /* help SUB-COMMAND => long format help.
419          "help" at end of line: show all commands. */
420       if (!help_at_end_of_line)
421         vlib_cli_output (vm, "%U", format_vlib_cli_command_help, c,
422                          /* is_long */ 1);
423
424       else if (vec_len (c->sub_commands) == 0)
425         vlib_cli_output (vm, "%v: no sub-commands", c->path);
426
427       else
428         {
429           vlib_cli_sub_rule_t *sr, *subs = 0;
430           vlib_cli_sub_command_t *sc;
431
432           vec_foreach (sc, c->sub_commands)
433           {
434             vec_add2 (subs, sr, 1);
435             sr->name = sc->name;
436             sr->command_index = sc->index;
437             sr->rule_index = ~0;
438           }
439
440           vec_sort_with_function (subs, vlib_cli_cmp_rule);
441
442           for (i = 0; i < vec_len (subs); i++)
443             {
444               vlib_cli_command_t *d;
445
446               d = vec_elt_at_index (cm->commands, subs[i].command_index);
447               vlib_cli_output
448                 (vm, "  %-30v %U", subs[i].name,
449                  format_vlib_cli_command_help, d, /* is_long */ 0);
450             }
451
452           vec_free (subs);
453         }
454     }
455
456   else if (is_main_dispatch
457            && (unformat (input, "choices") || unformat (input, "?")))
458     {
459       vlib_cli_command_t *sub, *subs;
460
461       subs = all_subs (cm, 0, parent_command_index);
462       vec_sort_with_function (subs, vlib_cli_cmp_command);
463       vec_foreach (sub, subs)
464         vlib_cli_output (vm, "  %-40U %U",
465                          format_vlib_cli_path, sub->path,
466                          format_vlib_cli_command_help, sub, /* is_long */ 0);
467       vec_free (subs);
468     }
469
470   else if (unformat (input, "comment %v", &string))
471     {
472       vec_free (string);
473     }
474
475   else if (unformat (input, "uncomment %U",
476                      unformat_vlib_cli_sub_input, &sub_input))
477     {
478       error =
479         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
480                                         parent_command_index);
481       unformat_free (&sub_input);
482     }
483   else if (unformat (input, "leak-check %U",
484                      unformat_vlib_cli_sub_input, &sub_input))
485     {
486       u8 *leak_report;
487       if (current_traced_heap)
488         {
489           void *oldheap;
490           oldheap = clib_mem_set_heap (current_traced_heap);
491           clib_mem_trace (0);
492           clib_mem_set_heap (oldheap);
493           current_traced_heap = 0;
494         }
495       clib_mem_trace (1);
496       error =
497         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
498                                         parent_command_index);
499       unformat_free (&sub_input);
500
501       /* Otherwise, the clib_error_t shows up as a leak... */
502       if (error)
503         {
504           vlib_cli_output (vm, "%v", error->what);
505           clib_error_free (error);
506           error = 0;
507         }
508
509       (void) clib_mem_trace_enable_disable (0);
510       leak_report = format (0, "%U", format_mheap, clib_mem_get_heap (),
511                             1 /* verbose, i.e. print leaks */ );
512       clib_mem_trace (0);
513       vlib_cli_output (vm, "%v", leak_report);
514       vec_free (leak_report);
515     }
516
517   else
518     if (unformat_user (input, unformat_vlib_cli_sub_command, vm, parent, &c))
519     {
520       unformat_input_t *si;
521       uword has_sub_commands =
522         vec_len (c->sub_commands) + vec_len (c->sub_rules) > 0;
523
524       si = input;
525       if (unformat_user (input, unformat_vlib_cli_sub_input, &sub_input))
526         si = &sub_input;
527
528       if (has_sub_commands)
529         error = vlib_cli_dispatch_sub_commands (vm, cm, si, c - cm->commands);
530
531       if (has_sub_commands && !error)
532         /* Found valid sub-command. */ ;
533
534       else if (c->function)
535         {
536           clib_error_t *c_error;
537
538           /* Skip white space for benefit of called function. */
539           unformat_skip_white_space (si);
540
541           if (unformat (si, "?"))
542             {
543               vlib_cli_output (vm, "  %-40U %U", format_vlib_cli_path, c->path, format_vlib_cli_command_help, c,        /* is_long */
544                                0);
545             }
546           else
547             {
548               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
549                 {
550                   /* *INDENT-OFF* */
551                   ELOG_TYPE_DECLARE (e) =
552                     {
553                       .format = "cli-cmd: %s",
554                       .format_args = "T4",
555                     };
556                   /* *INDENT-ON* */
557                   struct
558                   {
559                     u32 c;
560                   } *ed;
561                   ed = ELOG_DATA (&vm->elog_main, e);
562                   ed->c = elog_string (&vm->elog_main, "%v", c->path);
563                 }
564
565               if (!c->is_mp_safe)
566                 vlib_worker_thread_barrier_sync (vm);
567               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
568                 clib_call_callbacks (cm->perf_counter_cbs, cm,
569                                      c - cm->commands, 0 /* before */ );
570
571               c->hit_counter++;
572               c_error = c->function (vm, si, c);
573
574               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
575                 clib_call_callbacks (cm->perf_counter_cbs, cm,
576                                      c - cm->commands, 1 /* after */ );
577               if (!c->is_mp_safe)
578                 vlib_worker_thread_barrier_release (vm);
579
580               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
581                 {
582                   /* *INDENT-OFF* */
583                   ELOG_TYPE_DECLARE (e) =
584                     {
585                       .format = "cli-cmd: %s %s",
586                       .format_args = "T4T4",
587                     };
588                   /* *INDENT-ON* */
589                   struct
590                   {
591                     u32 c, err;
592                   } *ed;
593                   ed = ELOG_DATA (&vm->elog_main, e);
594                   ed->c = elog_string (&vm->elog_main, "%v", c->path);
595                   if (c_error)
596                     {
597                       vec_add1 (c_error->what, 0);
598                       ed->err =
599                         elog_string (&vm->elog_main, (char *) c_error->what);
600                       _vec_len (c_error->what) -= 1;
601                     }
602                   else
603                     ed->err = elog_string (&vm->elog_main, "OK");
604                 }
605
606               if (c_error)
607                 {
608                   error =
609                     clib_error_return (0, "%v: %v", c->path, c_error->what);
610                   clib_error_free (c_error);
611                   /* Free sub input. */
612                   if (si != input)
613                     unformat_free (si);
614
615                   return error;
616                 }
617             }
618
619           /* Free any previous error. */
620           clib_error_free (error);
621         }
622
623       else if (!error)
624         error = clib_error_return (0, "%v: no sub-commands", c->path);
625
626       /* Free sub input. */
627       if (si != input)
628         unformat_free (si);
629     }
630
631   else
632     goto unknown;
633
634   return error;
635
636 unknown:
637   if (parent->path)
638     return clib_error_return (0, "%v: unknown input `%U'", parent->path,
639                               format_unformat_error, input);
640   else
641     return clib_error_return (0, "unknown input `%U'", format_unformat_error,
642                               input);
643 }
644
645
646 void vlib_unix_error_report (vlib_main_t *, clib_error_t *)
647   __attribute__ ((weak));
648
649 void
650 vlib_unix_error_report (vlib_main_t * vm, clib_error_t * error)
651 {
652 }
653
654 /* Process CLI input. */
655 int
656 vlib_cli_input (vlib_main_t * vm,
657                 unformat_input_t * input,
658                 vlib_cli_output_function_t * function, uword function_arg)
659 {
660   vlib_process_t *cp = vlib_get_current_process (vm);
661   clib_error_t *error;
662   vlib_cli_output_function_t *save_function;
663   uword save_function_arg;
664   int rv = 0;
665
666   save_function = cp->output_function;
667   save_function_arg = cp->output_function_arg;
668
669   cp->output_function = function;
670   cp->output_function_arg = function_arg;
671
672   do
673     {
674       error = vlib_cli_dispatch_sub_commands (vm, &vm->cli_main, input,
675                                               /* parent */ 0);
676     }
677   while (!error && !unformat (input, "%U", unformat_eof));
678
679   if (error)
680     {
681       vlib_cli_output (vm, "%v", error->what);
682       vlib_unix_error_report (vm, error);
683       /* clib_error_return is unfortunately often called with a '0'
684          return code */
685       rv = error->code != 0 ? error->code : -1;
686       clib_error_free (error);
687     }
688
689   cp->output_function = save_function;
690   cp->output_function_arg = save_function_arg;
691   return rv;
692 }
693
694 /* Output to current CLI connection. */
695 void
696 vlib_cli_output (vlib_main_t * vm, char *fmt, ...)
697 {
698   vlib_process_t *cp = vlib_get_current_process (vm);
699   va_list va;
700   u8 *s;
701
702   va_start (va, fmt);
703   s = va_format (0, fmt, &va);
704   va_end (va);
705
706   /* Terminate with \n if not present. */
707   if (vec_len (s) > 0 && s[vec_len (s) - 1] != '\n')
708     vec_add1 (s, '\n');
709
710   if ((!cp) || (!cp->output_function))
711     fformat (stdout, "%v", s);
712   else
713     cp->output_function (cp->output_function_arg, s, vec_len (s));
714
715   vec_free (s);
716 }
717
718 void *vl_msg_push_heap (void) __attribute__ ((weak));
719 void *
720 vl_msg_push_heap (void)
721 {
722   return 0;
723 }
724
725 void vl_msg_pop_heap (void *oldheap) __attribute__ ((weak));
726 void
727 vl_msg_pop_heap (void *oldheap)
728 {
729 }
730
731 void *vlib_stats_push_heap (void *) __attribute__ ((weak));
732 void *
733 vlib_stats_push_heap (void *notused)
734 {
735   return 0;
736 }
737
738 static clib_error_t *
739 show_memory_usage (vlib_main_t * vm,
740                    unformat_input_t * input, vlib_cli_command_t * cmd)
741 {
742   clib_mem_main_t *mm = &clib_mem_main;
743   int verbose __attribute__ ((unused)) = 0;
744   int api_segment = 0, stats_segment = 0, main_heap = 0, numa_heaps = 0;
745   int map = 0;
746   clib_error_t *error;
747   u32 index = 0;
748   int i;
749   uword clib_mem_trace_enable_disable (uword enable);
750   uword was_enabled;
751
752
753   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
754     {
755       if (unformat (input, "verbose"))
756         verbose = 1;
757       else if (unformat (input, "api-segment"))
758         api_segment = 1;
759       else if (unformat (input, "stats-segment"))
760         stats_segment = 1;
761       else if (unformat (input, "main-heap"))
762         main_heap = 1;
763       else if (unformat (input, "numa-heaps"))
764         numa_heaps = 1;
765       else if (unformat (input, "map"))
766         map = 1;
767       else
768         {
769           error = clib_error_return (0, "unknown input `%U'",
770                                      format_unformat_error, input);
771           return error;
772         }
773     }
774
775   if ((api_segment + stats_segment + main_heap + numa_heaps + map) == 0)
776     return clib_error_return
777       (0, "Need one of api-segment, stats-segment, main-heap, numa-heaps "
778        "or map");
779
780   if (api_segment)
781     {
782       void *oldheap = vl_msg_push_heap ();
783       was_enabled = clib_mem_trace_enable_disable (0);
784       u8 *s_in_svm =
785         format (0, "%U\n", format_mheap, clib_mem_get_heap (), 1);
786       vl_msg_pop_heap (oldheap);
787       u8 *s = vec_dup (s_in_svm);
788
789       oldheap = vl_msg_push_heap ();
790       vec_free (s_in_svm);
791       clib_mem_trace_enable_disable (was_enabled);
792       vl_msg_pop_heap (oldheap);
793       vlib_cli_output (vm, "API segment");
794       vlib_cli_output (vm, "%v", s);
795       vec_free (s);
796     }
797   if (stats_segment)
798     {
799       void *oldheap = vlib_stats_push_heap (0);
800       was_enabled = clib_mem_trace_enable_disable (0);
801       u8 *s_in_svm =
802         format (0, "%U\n", format_mheap, clib_mem_get_heap (), 1);
803       if (oldheap)
804         clib_mem_set_heap (oldheap);
805       u8 *s = vec_dup (s_in_svm);
806
807       oldheap = vlib_stats_push_heap (0);
808       vec_free (s_in_svm);
809       if (oldheap)
810         {
811           clib_mem_trace_enable_disable (was_enabled);
812           clib_mem_set_heap (oldheap);
813         }
814       vlib_cli_output (vm, "Stats segment");
815       vlib_cli_output (vm, "%v", s);
816       vec_free (s);
817     }
818
819
820   {
821     if (main_heap)
822       {
823         /*
824          * Note: the foreach_vlib_main causes allocator traffic,
825          * so shut off tracing before we go there...
826          */
827         was_enabled = clib_mem_trace_enable_disable (0);
828
829         /* *INDENT-OFF* */
830         foreach_vlib_main (
831         ({
832           struct dlmallinfo mi;
833           void *mspace;
834           mspace = mm->per_cpu_mheaps[index];
835
836           mi = mspace_mallinfo (mspace);
837           vlib_cli_output (vm, "%sThread %d %s\n", index ? "\n":"", index,
838                            vlib_worker_threads[index].name);
839           vlib_cli_output (vm, "  %U\n", format_page_map,
840                            pointer_to_uword (mspace_least_addr(mspace)),
841                            mi.arena);
842           vlib_cli_output (vm, "  %U\n", format_mheap,
843                            mm->per_cpu_mheaps[index],
844                            verbose);
845           index++;
846         }));
847         /* *INDENT-ON* */
848
849         /* Restore the trace flag */
850         clib_mem_trace_enable_disable (was_enabled);
851       }
852     if (numa_heaps)
853       {
854         struct dlmallinfo mi;
855         void *mspace;
856
857         for (i = 0; i < ARRAY_LEN (mm->per_numa_mheaps); i++)
858           {
859             if (mm->per_numa_mheaps[i] == 0)
860               continue;
861             if (mm->per_numa_mheaps[i] == mm->per_cpu_mheaps[i])
862               {
863                 vlib_cli_output (vm, "Numa %d uses the main heap...", i);
864                 continue;
865               }
866             was_enabled = clib_mem_trace_enable_disable (0);
867             mspace = mm->per_numa_mheaps[i];
868
869             mi = mspace_mallinfo (mspace);
870             vlib_cli_output (vm, "Numa %d:", i);
871             vlib_cli_output (vm, "  %U\n", format_page_map,
872                              pointer_to_uword (mspace_least_addr (mspace)),
873                              mi.arena);
874             vlib_cli_output (vm, "  %U\n", format_mheap,
875                              mm->per_numa_mheaps[index], verbose);
876           }
877       }
878     if (map)
879       {
880         clib_mem_page_stats_t stats = { };
881         clib_mem_vm_map_hdr_t *hdr = 0;
882         u8 *s = 0;
883         int numa = -1;
884
885         s = format (s, "\n%-16s%7s%5s%7s%7s",
886                     "StartAddr", "size", "FD", "PageSz", "Pages");
887         while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
888           s = format (s, " Numa%u", numa);
889         s = format (s, " NotMap");
890         s = format (s, " Name");
891         vlib_cli_output (vm, "%v", s);
892         vec_reset_length (s);
893
894         while ((hdr = clib_mem_vm_get_next_map_hdr (hdr)))
895           {
896             clib_mem_get_page_stats ((void *) hdr->base_addr,
897                                      hdr->log2_page_sz, hdr->num_pages,
898                                      &stats);
899             s = format (s, "%016lx%7U",
900                         hdr->base_addr, format_memory_size,
901                         hdr->num_pages << hdr->log2_page_sz);
902
903             if (hdr->fd != -1)
904               s = format (s, "%5d", hdr->fd);
905             else
906               s = format (s, "%5s", " ");
907
908             s = format (s, "%7U%7lu",
909                         format_log2_page_size, hdr->log2_page_sz,
910                         hdr->num_pages);
911             while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
912               s = format (s, "%6lu", stats.per_numa[numa]);
913             s = format (s, "%7lu", stats.not_mapped);
914             s = format (s, " %s", hdr->name);
915             vlib_cli_output (vm, "%v", s);
916             vec_reset_length (s);
917           }
918         vec_free (s);
919       }
920   }
921   return 0;
922 }
923
924 /* *INDENT-OFF* */
925 VLIB_CLI_COMMAND (show_memory_usage_command, static) = {
926   .path = "show memory",
927   .short_help = "show memory [api-segment][stats-segment][verbose]\n"
928   "            [numa-heaps][map]",
929   .function = show_memory_usage,
930 };
931 /* *INDENT-ON* */
932
933 static clib_error_t *
934 show_cpu (vlib_main_t * vm, unformat_input_t * input,
935           vlib_cli_command_t * cmd)
936 {
937 #define _(a,b,c) vlib_cli_output (vm, "%-25s " b, a ":", c);
938   _("Model name", "%U", format_cpu_model_name);
939   _("Microarch model (family)", "%U", format_cpu_uarch);
940   _("Flags", "%U", format_cpu_flags);
941   _("Base frequency", "%.2f GHz",
942     ((f64) vm->clib_time.clocks_per_second) * 1e-9);
943 #undef _
944   return 0;
945 }
946
947 /*?
948  * Displays various information about the CPU.
949  *
950  * @cliexpar
951  * @cliexstart{show cpu}
952  * Model name:               Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz
953  * Microarchitecture:        Broadwell (Broadwell-EP/EX)
954  * Flags:                    sse3 ssse3 sse41 sse42 avx avx2 aes
955  * Base Frequency:           3.20 GHz
956  * @cliexend
957 ?*/
958 /* *INDENT-OFF* */
959 VLIB_CLI_COMMAND (show_cpu_command, static) = {
960   .path = "show cpu",
961   .short_help = "Show cpu information",
962   .function = show_cpu,
963 };
964 /* *INDENT-ON* */
965
966 static clib_error_t *
967 enable_disable_memory_trace (vlib_main_t * vm,
968                              unformat_input_t * input,
969                              vlib_cli_command_t * cmd)
970 {
971   clib_mem_main_t *mm = &clib_mem_main;
972   unformat_input_t _line_input, *line_input = &_line_input;
973   int enable = 1;
974   int api_segment = 0;
975   int stats_segment = 0;
976   int main_heap = 0;
977   u32 numa_id = ~0;
978   void *oldheap;
979
980   if (!unformat_user (input, unformat_line_input, line_input))
981     return 0;
982
983   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
984     {
985       if (unformat (line_input, "%U", unformat_vlib_enable_disable, &enable))
986         ;
987       else if (unformat (line_input, "api-segment"))
988         api_segment = 1;
989       else if (unformat (line_input, "stats-segment"))
990         stats_segment = 1;
991       else if (unformat (line_input, "main-heap"))
992         main_heap = 1;
993       else if (unformat (line_input, "numa-heap %d", &numa_id))
994         ;
995       else
996         {
997           unformat_free (line_input);
998           return clib_error_return (0, "invalid input");
999         }
1000     }
1001   unformat_free (line_input);
1002
1003   if ((api_segment + stats_segment + main_heap + (enable == 0)
1004        + (numa_id != ~0)) == 0)
1005     {
1006       return clib_error_return
1007         (0, "Need one of main-heap, stats-segment, api-segment,\n"
1008          "numa-heap <nn> or disable");
1009     }
1010
1011   /* Turn off current trace, if any */
1012   if (current_traced_heap)
1013     {
1014       void *oldheap;
1015       oldheap = clib_mem_set_heap (current_traced_heap);
1016       clib_mem_trace (0);
1017       clib_mem_set_heap (oldheap);
1018       current_traced_heap = 0;
1019     }
1020
1021   if (enable == 0)
1022     return 0;
1023
1024   /* API segment */
1025   if (api_segment)
1026     {
1027       oldheap = vl_msg_push_heap ();
1028       current_traced_heap = clib_mem_get_heap ();
1029       clib_mem_trace (1);
1030       vl_msg_pop_heap (oldheap);
1031
1032     }
1033
1034   /* Stats segment */
1035   if (stats_segment)
1036     {
1037       oldheap = vlib_stats_push_heap (0);
1038       current_traced_heap = clib_mem_get_heap ();
1039       clib_mem_trace (stats_segment);
1040       /* We don't want to call vlib_stats_pop_heap... */
1041       if (oldheap)
1042         clib_mem_set_heap (oldheap);
1043     }
1044
1045   /* main_heap */
1046   if (main_heap)
1047     {
1048       current_traced_heap = clib_mem_get_heap ();
1049       clib_mem_trace (main_heap);
1050     }
1051
1052   if (numa_id != ~0)
1053     {
1054       if (numa_id >= ARRAY_LEN (mm->per_numa_mheaps))
1055         return clib_error_return (0, "Numa %d out of range", numa_id);
1056       if (mm->per_numa_mheaps[numa_id] == 0)
1057         return clib_error_return (0, "Numa %d heap not active", numa_id);
1058
1059       if (mm->per_numa_mheaps[numa_id] == clib_mem_get_heap ())
1060         return clib_error_return (0, "Numa %d uses the main heap...",
1061                                   numa_id);
1062       current_traced_heap = mm->per_numa_mheaps[numa_id];
1063       oldheap = clib_mem_set_heap (current_traced_heap);
1064       clib_mem_trace (1);
1065       clib_mem_set_heap (oldheap);
1066     }
1067
1068
1069   return 0;
1070 }
1071
1072 /* *INDENT-OFF* */
1073 VLIB_CLI_COMMAND (enable_disable_memory_trace_command, static) = {
1074   .path = "memory-trace",
1075   .short_help = "memory-trace on|off [api-segment][stats-segment][main-heap]\n"
1076   "                   [numa-heap <numa-id>]\n",
1077   .function = enable_disable_memory_trace,
1078 };
1079 /* *INDENT-ON* */
1080
1081 static clib_error_t *
1082 restart_cmd_fn (vlib_main_t * vm, unformat_input_t * input,
1083                 vlib_cli_command_t * cmd)
1084 {
1085   clib_file_main_t *fm = &file_main;
1086   clib_file_t *f;
1087
1088   /* environ(7) does not indicate a header for this */
1089   extern char **environ;
1090
1091   /* Close all known open files */
1092   /* *INDENT-OFF* */
1093   pool_foreach(f, fm->file_pool,
1094     ({
1095       if (f->file_descriptor > 2)
1096         close(f->file_descriptor);
1097     }));
1098   /* *INDENT-ON* */
1099
1100   /* Exec ourself */
1101   execve (vm->name, (char **) vm->argv, environ);
1102
1103   return 0;
1104 }
1105
1106 /* *INDENT-OFF* */
1107 VLIB_CLI_COMMAND (restart_cmd,static) = {
1108     .path = "restart",
1109     .short_help = "restart process",
1110     .function = restart_cmd_fn,
1111 };
1112 /* *INDENT-ON* */
1113
1114 #ifdef TEST_CODE
1115 /*
1116  * A trivial test harness to verify the per-process output_function
1117  * is working correcty.
1118  */
1119
1120 static clib_error_t *
1121 sleep_ten_seconds (vlib_main_t * vm,
1122                    unformat_input_t * input, vlib_cli_command_t * cmd)
1123 {
1124   u16 i;
1125   u16 my_id = rand ();
1126
1127   vlib_cli_output (vm, "Starting 10 seconds sleep with id %u\n", my_id);
1128
1129   for (i = 0; i < 10; i++)
1130     {
1131       vlib_process_wait_for_event_or_clock (vm, 1.0);
1132       vlib_cli_output (vm, "Iteration number %u, my id: %u\n", i, my_id);
1133     }
1134   vlib_cli_output (vm, "Done with sleep with id %u\n", my_id);
1135   return 0;
1136 }
1137
1138 /* *INDENT-OFF* */
1139 VLIB_CLI_COMMAND (ping_command, static) = {
1140   .path = "test sleep",
1141   .function = sleep_ten_seconds,
1142   .short_help = "Sleep for 10 seconds",
1143 };
1144 /* *INDENT-ON* */
1145 #endif /* ifdef TEST_CODE */
1146
1147 static uword
1148 vlib_cli_normalize_path (char *input, char **result)
1149 {
1150   char *i = input;
1151   char *s = 0;
1152   uword l = 0;
1153   uword index_of_last_space = ~0;
1154
1155   while (*i != 0)
1156     {
1157       u8 c = *i++;
1158       /* Multiple white space -> single space. */
1159       switch (c)
1160         {
1161         case ' ':
1162         case '\t':
1163         case '\n':
1164         case '\r':
1165           if (l > 0 && s[l - 1] != ' ')
1166             {
1167               vec_add1 (s, ' ');
1168               l++;
1169             }
1170           break;
1171
1172         default:
1173           if (l > 0 && s[l - 1] == ' ')
1174             index_of_last_space = vec_len (s);
1175           vec_add1 (s, c);
1176           l++;
1177           break;
1178         }
1179     }
1180
1181   /* Remove any extra space at end. */
1182   if (l > 0 && s[l - 1] == ' ')
1183     _vec_len (s) -= 1;
1184
1185   *result = s;
1186   return index_of_last_space;
1187 }
1188
1189 always_inline uword
1190 parent_path_len (char *path)
1191 {
1192   word i;
1193   for (i = vec_len (path) - 1; i >= 0; i--)
1194     {
1195       if (path[i] == ' ')
1196         return i;
1197     }
1198   return ~0;
1199 }
1200
1201 static void
1202 add_sub_command (vlib_cli_main_t * cm, uword parent_index, uword child_index)
1203 {
1204   vlib_cli_command_t *p, *c;
1205   vlib_cli_sub_command_t *sub_c;
1206   u8 *sub_name;
1207   word i, l;
1208
1209   p = vec_elt_at_index (cm->commands, parent_index);
1210   c = vec_elt_at_index (cm->commands, child_index);
1211
1212   l = parent_path_len (c->path);
1213   if (l == ~0)
1214     sub_name = vec_dup ((u8 *) c->path);
1215   else
1216     {
1217       ASSERT (l + 1 < vec_len (c->path));
1218       sub_name = 0;
1219       vec_add (sub_name, c->path + l + 1, vec_len (c->path) - (l + 1));
1220     }
1221
1222   if (sub_name[0] == '%')
1223     {
1224       uword *q;
1225       vlib_cli_sub_rule_t *sr;
1226
1227       /* Remove %. */
1228       vec_delete (sub_name, 1, 0);
1229
1230       if (!p->sub_rule_index_by_name)
1231         p->sub_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1232                                                      sizeof (sub_name[0]),
1233                                                      sizeof (uword));
1234       q = hash_get_mem (p->sub_rule_index_by_name, sub_name);
1235       if (q)
1236         {
1237           sr = vec_elt_at_index (p->sub_rules, q[0]);
1238           ASSERT (sr->command_index == child_index);
1239           return;
1240         }
1241
1242       hash_set_mem (p->sub_rule_index_by_name, sub_name,
1243                     vec_len (p->sub_rules));
1244       vec_add2 (p->sub_rules, sr, 1);
1245       sr->name = sub_name;
1246       sr->rule_index = sr - p->sub_rules;
1247       sr->command_index = child_index;
1248       return;
1249     }
1250
1251   if (!p->sub_command_index_by_name)
1252     p->sub_command_index_by_name = hash_create_vec ( /* initial length */ 32,
1253                                                     sizeof (c->path[0]),
1254                                                     sizeof (uword));
1255
1256   /* Check if sub-command has already been created. */
1257   if (hash_get_mem (p->sub_command_index_by_name, sub_name))
1258     {
1259       vec_free (sub_name);
1260       return;
1261     }
1262
1263   vec_add2 (p->sub_commands, sub_c, 1);
1264   sub_c->index = child_index;
1265   sub_c->name = sub_name;
1266   hash_set_mem (p->sub_command_index_by_name, sub_c->name,
1267                 sub_c - p->sub_commands);
1268
1269   vec_validate (p->sub_command_positions, vec_len (sub_c->name) - 1);
1270   for (i = 0; i < vec_len (sub_c->name); i++)
1271     {
1272       int n;
1273       vlib_cli_parse_position_t *pos;
1274
1275       pos = vec_elt_at_index (p->sub_command_positions, i);
1276
1277       if (!pos->bitmaps)
1278         pos->min_char = sub_c->name[i];
1279
1280       n = sub_c->name[i] - pos->min_char;
1281       if (n < 0)
1282         {
1283           pos->min_char = sub_c->name[i];
1284           vec_insert (pos->bitmaps, -n, 0);
1285           n = 0;
1286         }
1287
1288       vec_validate (pos->bitmaps, n);
1289       pos->bitmaps[n] =
1290         clib_bitmap_ori (pos->bitmaps[n], sub_c - p->sub_commands);
1291     }
1292 }
1293
1294 static void
1295 vlib_cli_make_parent (vlib_cli_main_t * cm, uword ci)
1296 {
1297   uword p_len, pi, *p;
1298   char *p_path;
1299   vlib_cli_command_t *c, *parent;
1300
1301   /* Root command (index 0) should have already been added. */
1302   ASSERT (vec_len (cm->commands) > 0);
1303
1304   c = vec_elt_at_index (cm->commands, ci);
1305   p_len = parent_path_len (c->path);
1306
1307   /* No space?  Parent is root command. */
1308   if (p_len == ~0)
1309     {
1310       add_sub_command (cm, 0, ci);
1311       return;
1312     }
1313
1314   p_path = 0;
1315   vec_add (p_path, c->path, p_len);
1316
1317   p = hash_get_mem (cm->command_index_by_path, p_path);
1318
1319   /* Parent exists? */
1320   if (!p)
1321     {
1322       /* Parent does not exist; create it. */
1323       vec_add2 (cm->commands, parent, 1);
1324       parent->path = p_path;
1325       hash_set_mem (cm->command_index_by_path, parent->path,
1326                     parent - cm->commands);
1327       pi = parent - cm->commands;
1328     }
1329   else
1330     {
1331       pi = p[0];
1332       vec_free (p_path);
1333     }
1334
1335   add_sub_command (cm, pi, ci);
1336
1337   /* Create parent's parent. */
1338   if (!p)
1339     vlib_cli_make_parent (cm, pi);
1340 }
1341
1342 always_inline uword
1343 vlib_cli_command_is_empty (vlib_cli_command_t * c)
1344 {
1345   return (c->long_help == 0 && c->short_help == 0 && c->function == 0);
1346 }
1347
1348 clib_error_t *
1349 vlib_cli_register (vlib_main_t * vm, vlib_cli_command_t * c)
1350 {
1351   vlib_cli_main_t *cm = &vm->cli_main;
1352   clib_error_t *error = 0;
1353   uword ci, *p;
1354   char *normalized_path;
1355
1356   if ((error = vlib_call_init_function (vm, vlib_cli_init)))
1357     return error;
1358
1359   (void) vlib_cli_normalize_path (c->path, &normalized_path);
1360
1361   if (!cm->command_index_by_path)
1362     cm->command_index_by_path = hash_create_vec ( /* initial length */ 32,
1363                                                  sizeof (c->path[0]),
1364                                                  sizeof (uword));
1365
1366   /* See if command already exists with given path. */
1367   p = hash_get_mem (cm->command_index_by_path, normalized_path);
1368   if (p)
1369     {
1370       vlib_cli_command_t *d;
1371
1372       ci = p[0];
1373       d = vec_elt_at_index (cm->commands, ci);
1374
1375       /* If existing command was created via vlib_cli_make_parent
1376          replaced it with callers data. */
1377       if (vlib_cli_command_is_empty (d))
1378         {
1379           vlib_cli_command_t save = d[0];
1380
1381           ASSERT (!vlib_cli_command_is_empty (c));
1382
1383           /* Copy callers fields. */
1384           d[0] = c[0];
1385
1386           /* Save internal fields. */
1387           d->path = save.path;
1388           d->sub_commands = save.sub_commands;
1389           d->sub_command_index_by_name = save.sub_command_index_by_name;
1390           d->sub_command_positions = save.sub_command_positions;
1391           d->sub_rules = save.sub_rules;
1392         }
1393       else
1394         error =
1395           clib_error_return (0, "duplicate command name with path %v",
1396                              normalized_path);
1397
1398       vec_free (normalized_path);
1399       if (error)
1400         return error;
1401     }
1402   else
1403     {
1404       /* Command does not exist: create it. */
1405
1406       /* Add root command (index 0). */
1407       if (vec_len (cm->commands) == 0)
1408         {
1409           /* Create command with index 0; path is empty string. */
1410           vec_resize (cm->commands, 1);
1411         }
1412
1413       ci = vec_len (cm->commands);
1414       hash_set_mem (cm->command_index_by_path, normalized_path, ci);
1415       vec_add1 (cm->commands, c[0]);
1416
1417       c = vec_elt_at_index (cm->commands, ci);
1418       c->path = normalized_path;
1419
1420       /* Don't inherit from registration. */
1421       c->sub_commands = 0;
1422       c->sub_command_index_by_name = 0;
1423       c->sub_command_positions = 0;
1424     }
1425
1426   vlib_cli_make_parent (cm, ci);
1427   return 0;
1428 }
1429
1430 #if 0
1431 /* $$$ turn back on again someday, maybe */
1432 clib_error_t *
1433 vlib_cli_register_parse_rule (vlib_main_t * vm, vlib_cli_parse_rule_t * r_reg)
1434 {
1435   vlib_cli_main_t *cm = &vm->cli_main;
1436   vlib_cli_parse_rule_t *r;
1437   clib_error_t *error = 0;
1438   u8 *r_name;
1439   uword *p;
1440
1441   if (!cm->parse_rule_index_by_name)
1442     cm->parse_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1443                                                     sizeof (r->name[0]),
1444                                                     sizeof (uword));
1445
1446   /* Make vector copy of name. */
1447   r_name = format (0, "%s", r_reg->name);
1448
1449   if ((p = hash_get_mem (cm->parse_rule_index_by_name, r_name)))
1450     {
1451       vec_free (r_name);
1452       return clib_error_return (0, "duplicate parse rule name `%s'",
1453                                 r_reg->name);
1454     }
1455
1456   vec_add2 (cm->parse_rules, r, 1);
1457   r[0] = r_reg[0];
1458   r->name = (char *) r_name;
1459   hash_set_mem (cm->parse_rule_index_by_name, r->name, r - cm->parse_rules);
1460
1461   return error;
1462 }
1463
1464 static clib_error_t *vlib_cli_register_parse_rules (vlib_main_t * vm,
1465                                                     vlib_cli_parse_rule_t *
1466                                                     lo,
1467                                                     vlib_cli_parse_rule_t *
1468                                                     hi)
1469   __attribute__ ((unused))
1470 {
1471   clib_error_t *error = 0;
1472   vlib_cli_parse_rule_t *r;
1473
1474   for (r = lo; r < hi; r = clib_elf_section_data_next (r, 0))
1475     {
1476       if (!r->name || strlen (r->name) == 0)
1477         {
1478           error = clib_error_return (0, "parse rule with no name");
1479           goto done;
1480         }
1481
1482       error = vlib_cli_register_parse_rule (vm, r);
1483       if (error)
1484         goto done;
1485     }
1486
1487 done:
1488   return error;
1489 }
1490 #endif
1491
1492 static clib_error_t *
1493 elog_trace_command_fn (vlib_main_t * vm,
1494                        unformat_input_t * input, vlib_cli_command_t * cmd)
1495 {
1496   unformat_input_t _line_input, *line_input = &_line_input;
1497   int enable = 1;
1498   int api = 0, cli = 0, barrier = 0, dispatch = 0, circuit = 0;
1499   u32 circuit_node_index;
1500
1501   if (!unformat_user (input, unformat_line_input, line_input))
1502     goto print_status;
1503
1504   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1505     {
1506       if (unformat (line_input, "api"))
1507         api = 1;
1508       else if (unformat (line_input, "dispatch"))
1509         dispatch = 1;
1510       else if (unformat (line_input, "circuit-node %U",
1511                          unformat_vlib_node, vm, &circuit_node_index))
1512         circuit = 1;
1513       else if (unformat (line_input, "cli"))
1514         cli = 1;
1515       else if (unformat (line_input, "barrier"))
1516         barrier = 1;
1517       else if (unformat (line_input, "disable"))
1518         enable = 0;
1519       else if (unformat (line_input, "enable"))
1520         enable = 1;
1521       else
1522         break;
1523     }
1524   unformat_free (line_input);
1525
1526   vl_api_set_elog_trace_api_messages
1527     (api ? enable : vl_api_get_elog_trace_api_messages ());
1528   vm->elog_trace_cli_commands = cli ? enable : vm->elog_trace_cli_commands;
1529   vm->elog_trace_graph_dispatch = dispatch ?
1530     enable : vm->elog_trace_graph_dispatch;
1531   vm->elog_trace_graph_circuit = circuit ?
1532     enable : vm->elog_trace_graph_circuit;
1533   vlib_worker_threads->barrier_elog_enabled =
1534     barrier ? enable : vlib_worker_threads->barrier_elog_enabled;
1535   vm->elog_trace_graph_circuit_node_index = circuit_node_index;
1536
1537   /*
1538    * Set up start-of-buffer logic-analyzer trigger
1539    * for main loop event logs, which are fairly heavyweight.
1540    * See src/vlib/main/vlib_elog_main_loop_event(...), which
1541    * will fully disable the scheme when the elog buffer fills.
1542    */
1543   if (dispatch || circuit)
1544     {
1545       elog_main_t *em = &vm->elog_main;
1546
1547       em->n_total_events_disable_limit =
1548         em->n_total_events + vec_len (em->event_ring);
1549     }
1550
1551
1552 print_status:
1553   vlib_cli_output (vm, "Current status:");
1554
1555   vlib_cli_output
1556     (vm, "    Event log API message trace: %s\n    CLI command trace: %s",
1557      vl_api_get_elog_trace_api_messages ()? "on" : "off",
1558      vm->elog_trace_cli_commands ? "on" : "off");
1559   vlib_cli_output
1560     (vm, "    Barrier sync trace: %s",
1561      vlib_worker_threads->barrier_elog_enabled ? "on" : "off");
1562   vlib_cli_output
1563     (vm, "    Graph Dispatch: %s",
1564      vm->elog_trace_graph_dispatch ? "on" : "off");
1565   vlib_cli_output
1566     (vm, "    Graph Circuit: %s",
1567      vm->elog_trace_graph_circuit ? "on" : "off");
1568   if (vm->elog_trace_graph_circuit)
1569     vlib_cli_output
1570       (vm, "                   node %U",
1571        format_vlib_node_name, vm, vm->elog_trace_graph_circuit_node_index);
1572
1573   return 0;
1574 }
1575
1576 /*?
1577  * Control event logging of api, cli, and thread barrier events
1578  * With no arguments, displays the current trace status.
1579  * Name the event groups you wish to trace or stop tracing.
1580  *
1581  * @cliexpar
1582  * @clistart
1583  * elog trace api cli barrier
1584  * elog trace api cli barrier disable
1585  * elog trace dispatch
1586  * elog trace circuit-node ethernet-input
1587  * elog trace
1588  * @cliend
1589  * @cliexcmd{elog trace [api][cli][barrier][disable]}
1590 ?*/
1591 /* *INDENT-OFF* */
1592 VLIB_CLI_COMMAND (elog_trace_command, static) =
1593 {
1594   .path = "elog trace",
1595   .short_help = "elog trace [api][cli][barrier][dispatch]\n"
1596   "[circuit-node <name> e.g. ethernet-input][disable]",
1597   .function = elog_trace_command_fn,
1598 };
1599 /* *INDENT-ON* */
1600
1601 static clib_error_t *
1602 suspend_command_fn (vlib_main_t * vm,
1603                     unformat_input_t * input, vlib_cli_command_t * cmd)
1604 {
1605   vlib_process_suspend (vm, 30e-3);
1606   return 0;
1607 }
1608
1609 /* *INDENT-OFF* */
1610 VLIB_CLI_COMMAND (suspend_command, static) =
1611 {
1612   .path = "suspend",
1613   .short_help = "suspend debug CLI for 30ms",
1614   .function = suspend_command_fn,
1615   .is_mp_safe = 1,
1616 };
1617 /* *INDENT-ON* */
1618
1619
1620 static int
1621 sort_cmds_by_path (void *a1, void *a2)
1622 {
1623   u32 *index1 = a1;
1624   u32 *index2 = a2;
1625   vlib_main_t *vm = vlib_get_main ();
1626   vlib_cli_main_t *cm = &vm->cli_main;
1627   vlib_cli_command_t *c1, *c2;
1628   int i, lmin;
1629
1630   c1 = vec_elt_at_index (cm->commands, *index1);
1631   c2 = vec_elt_at_index (cm->commands, *index2);
1632
1633   lmin = vec_len (c1->path);
1634   lmin = (vec_len (c2->path) >= lmin) ? lmin : vec_len (c2->path);
1635
1636   for (i = 0; i < lmin; i++)
1637     {
1638       if (c1->path[i] < c2->path[i])
1639         return -1;
1640       else if (c1->path[i] > c2->path[i])
1641         return 1;
1642     }
1643
1644   return 0;
1645 }
1646
1647 typedef struct
1648 {
1649   vlib_cli_main_t *cm;
1650   u32 parent_command_index;
1651   int show_mp_safe;
1652   int show_not_mp_safe;
1653   int show_hit;
1654   int clear_hit;
1655 } vlib_cli_walk_args_t;
1656
1657 static void
1658 cli_recursive_walk (vlib_cli_walk_args_t * aa)
1659 {
1660   vlib_cli_command_t *parent;
1661   vlib_cli_sub_command_t *sub;
1662   vlib_cli_walk_args_t _a, *a = &_a;
1663   vlib_cli_main_t *cm;
1664   int i;
1665
1666   /* Copy args into this stack frame */
1667   *a = *aa;
1668   cm = a->cm;
1669
1670   parent = vec_elt_at_index (cm->commands, a->parent_command_index);
1671
1672   if (parent->function)
1673     {
1674       if (((a->show_mp_safe && parent->is_mp_safe)
1675            || (a->show_not_mp_safe && !parent->is_mp_safe))
1676           && (a->show_hit == 0 || parent->hit_counter))
1677         {
1678           vec_add1 (cm->sort_vector, a->parent_command_index);
1679         }
1680
1681       if (a->clear_hit)
1682         parent->hit_counter = 0;
1683     }
1684
1685   for (i = 0; i < vec_len (parent->sub_commands); i++)
1686     {
1687       sub = vec_elt_at_index (parent->sub_commands, i);
1688       a->parent_command_index = sub->index;
1689       cli_recursive_walk (a);
1690     }
1691 }
1692
1693 static u8 *
1694 format_mp_safe (u8 * s, va_list * args)
1695 {
1696   vlib_cli_main_t *cm = va_arg (*args, vlib_cli_main_t *);
1697   int show_mp_safe = va_arg (*args, int);
1698   int show_not_mp_safe = va_arg (*args, int);
1699   int show_hit = va_arg (*args, int);
1700   int clear_hit = va_arg (*args, int);
1701   vlib_cli_command_t *c;
1702   vlib_cli_walk_args_t _a, *a = &_a;
1703   int i;
1704   char *format_string = "\n%v";
1705
1706   if (show_hit)
1707     format_string = "\n%v: %u";
1708
1709   vec_reset_length (cm->sort_vector);
1710
1711   a->cm = cm;
1712   a->parent_command_index = 0;
1713   a->show_mp_safe = show_mp_safe;
1714   a->show_not_mp_safe = show_not_mp_safe;
1715   a->show_hit = show_hit;
1716   a->clear_hit = clear_hit;
1717
1718   cli_recursive_walk (a);
1719
1720   vec_sort_with_function (cm->sort_vector, sort_cmds_by_path);
1721
1722   for (i = 0; i < vec_len (cm->sort_vector); i++)
1723     {
1724       c = vec_elt_at_index (cm->commands, cm->sort_vector[i]);
1725       s = format (s, format_string, c->path, c->hit_counter);
1726     }
1727
1728   return s;
1729 }
1730
1731
1732 static clib_error_t *
1733 show_cli_command_fn (vlib_main_t * vm,
1734                      unformat_input_t * input, vlib_cli_command_t * cmd)
1735 {
1736   int show_mp_safe = 0;
1737   int show_not_mp_safe = 0;
1738   int show_hit = 0;
1739   int clear_hit = 0;
1740
1741   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1742     {
1743       if (unformat (input, "mp-safe"))
1744         show_mp_safe = 1;
1745       if (unformat (input, "not-mp-safe"))
1746         show_not_mp_safe = 1;
1747       else if (unformat (input, "hit"))
1748         show_hit = 1;
1749       else if (unformat (input, "clear-hit"))
1750         clear_hit = 1;
1751       else
1752         break;
1753     }
1754
1755   /* default set: all cli commands */
1756   if (clear_hit == 0 && (show_mp_safe + show_not_mp_safe) == 0)
1757     show_mp_safe = show_not_mp_safe = 1;
1758
1759   vlib_cli_output (vm, "%U", format_mp_safe, &vm->cli_main,
1760                    show_mp_safe, show_not_mp_safe, show_hit, clear_hit);
1761   if (clear_hit)
1762     vlib_cli_output (vm, "hit counters cleared...");
1763
1764   return 0;
1765 }
1766
1767 /*?
1768  * Displays debug cli command information
1769  *
1770  * @cliexpar
1771  * @cliexstart{show cli [mp-safe][not-mp-safe][hit][clear-hit]}
1772  *
1773  * "show cli" displays the entire debug cli:
1774  *
1775  * abf attach
1776  * abf policy
1777  * adjacency counters
1778  * api trace
1779  * app ns
1780  * bfd key del
1781  * ... and so on ...
1782  *
1783  * "show cli mp-safe" displays mp-safe debug CLI commands:
1784  *
1785  * abf policy
1786  * binary-api
1787  * create vhost-user
1788  * exec
1789  * ip container
1790  * ip mroute
1791  * ip probe-neighbor
1792  * ip route
1793  * ip scan-neighbor
1794  * ip table
1795  * ip6 table
1796  *
1797  * "show cli not-mp-safe" displays debug CLI commands
1798  * which cause worker thread barrier synchronization
1799  *
1800  * "show cli hit" displays commands which have been executed. Qualify
1801  * as desired with "mp-safe" or "not-mp-safe".
1802  *
1803  * "show cli clear-hit" clears the per-command hit counters.
1804  * @cliexend
1805 ?*/
1806
1807 /* *INDENT-OFF* */
1808 VLIB_CLI_COMMAND (show_cli_command, static) =
1809 {
1810   .path = "show cli",
1811   .short_help = "show cli [mp-safe][not-mp-safe][hit][clear-hit]",
1812   .function = show_cli_command_fn,
1813   .is_mp_safe = 1,
1814 };
1815 /* *INDENT-ON* */
1816
1817 static clib_error_t *
1818 vlib_cli_init (vlib_main_t * vm)
1819 {
1820   vlib_cli_main_t *cm = &vm->cli_main;
1821   clib_error_t *error = 0;
1822   vlib_cli_command_t *cmd;
1823
1824   cmd = cm->cli_command_registrations;
1825
1826   while (cmd)
1827     {
1828       error = vlib_cli_register (vm, cmd);
1829       if (error)
1830         return error;
1831       cmd = cmd->next_cli_command;
1832     }
1833   return error;
1834 }
1835
1836 VLIB_INIT_FUNCTION (vlib_cli_init);
1837
1838 /*
1839  * fd.io coding-style-patch-verification: ON
1840  *
1841  * Local Variables:
1842  * eval: (c-set-style "gnu")
1843  * End:
1844  */