7a4d2d4689a579d6b0a6edb6928c158ffa6aaec7
[linux-2.6-block.git] / kernel / debug / kdb / kdb_main.c
1 /*
2  * Kernel Debugger Architecture Independent Main Code
3  *
4  * This file is subject to the terms and conditions of the GNU General Public
5  * License.  See the file "COPYING" in the main directory of this archive
6  * for more details.
7  *
8  * Copyright (C) 1999-2004 Silicon Graphics, Inc.  All Rights Reserved.
9  * Copyright (C) 2000 Stephane Eranian <eranian@hpl.hp.com>
10  * Xscale (R) modifications copyright (C) 2003 Intel Corporation.
11  * Copyright (c) 2009 Wind River Systems, Inc.  All Rights Reserved.
12  */
13
14 #include <linux/ctype.h>
15 #include <linux/types.h>
16 #include <linux/string.h>
17 #include <linux/kernel.h>
18 #include <linux/kmsg_dump.h>
19 #include <linux/reboot.h>
20 #include <linux/sched.h>
21 #include <linux/sched/loadavg.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/debug.h>
24 #include <linux/sysrq.h>
25 #include <linux/smp.h>
26 #include <linux/utsname.h>
27 #include <linux/vmalloc.h>
28 #include <linux/moduleparam.h>
29 #include <linux/mm.h>
30 #include <linux/init.h>
31 #include <linux/kallsyms.h>
32 #include <linux/kgdb.h>
33 #include <linux/kdb.h>
34 #include <linux/notifier.h>
35 #include <linux/interrupt.h>
36 #include <linux/delay.h>
37 #include <linux/nmi.h>
38 #include <linux/time.h>
39 #include <linux/ptrace.h>
40 #include <linux/sysctl.h>
41 #include <linux/cpu.h>
42 #include <linux/kdebug.h>
43 #include <linux/proc_fs.h>
44 #include <linux/uaccess.h>
45 #include <linux/slab.h>
46 #include <linux/security.h>
47 #include "kdb_private.h"
48
49 #undef  MODULE_PARAM_PREFIX
50 #define MODULE_PARAM_PREFIX "kdb."
51
52 static int kdb_cmd_enabled = CONFIG_KDB_DEFAULT_ENABLE;
53 module_param_named(cmd_enable, kdb_cmd_enabled, int, 0600);
54
55 char kdb_grep_string[KDB_GREP_STRLEN];
56 int kdb_grepping_flag;
57 EXPORT_SYMBOL(kdb_grepping_flag);
58 int kdb_grep_leading;
59 int kdb_grep_trailing;
60
61 /*
62  * Kernel debugger state flags
63  */
64 unsigned int kdb_flags;
65
66 /*
67  * kdb_lock protects updates to kdb_initial_cpu.  Used to
68  * single thread processors through the kernel debugger.
69  */
70 int kdb_initial_cpu = -1;       /* cpu number that owns kdb */
71 int kdb_nextline = 1;
72 int kdb_state;                  /* General KDB state */
73
74 struct task_struct *kdb_current_task;
75 struct pt_regs *kdb_current_regs;
76
77 const char *kdb_diemsg;
78 static int kdb_go_count;
79 #ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
80 static unsigned int kdb_continue_catastrophic =
81         CONFIG_KDB_CONTINUE_CATASTROPHIC;
82 #else
83 static unsigned int kdb_continue_catastrophic;
84 #endif
85
86 /* kdb_cmds_head describes the available commands. */
87 static LIST_HEAD(kdb_cmds_head);
88
89 typedef struct _kdbmsg {
90         int     km_diag;        /* kdb diagnostic */
91         char    *km_msg;        /* Corresponding message text */
92 } kdbmsg_t;
93
94 #define KDBMSG(msgnum, text) \
95         { KDB_##msgnum, text }
96
97 static kdbmsg_t kdbmsgs[] = {
98         KDBMSG(NOTFOUND, "Command Not Found"),
99         KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
100         KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, "
101                "8 is only allowed on 64 bit systems"),
102         KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
103         KDBMSG(NOTENV, "Cannot find environment variable"),
104         KDBMSG(NOENVVALUE, "Environment variable should have value"),
105         KDBMSG(NOTIMP, "Command not implemented"),
106         KDBMSG(ENVFULL, "Environment full"),
107         KDBMSG(KMALLOCFAILED, "Failed to allocate memory"),
108         KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
109 #ifdef CONFIG_CPU_XSCALE
110         KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
111 #else
112         KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
113 #endif
114         KDBMSG(DUPBPT, "Duplicate breakpoint address"),
115         KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
116         KDBMSG(BADMODE, "Invalid IDMODE"),
117         KDBMSG(BADINT, "Illegal numeric value"),
118         KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
119         KDBMSG(BADREG, "Invalid register name"),
120         KDBMSG(BADCPUNUM, "Invalid cpu number"),
121         KDBMSG(BADLENGTH, "Invalid length field"),
122         KDBMSG(NOBP, "No Breakpoint exists"),
123         KDBMSG(BADADDR, "Invalid address"),
124         KDBMSG(NOPERM, "Permission denied"),
125 };
126 #undef KDBMSG
127
128 static const int __nkdb_err = ARRAY_SIZE(kdbmsgs);
129
130
131 /*
132  * Initial environment. This is all kept static and local to this file.
133  * The entire environment is limited to a fixed number of entries
134  * (add more to __env[] if required)
135  */
136
137 static char *__env[31] = {
138 #if defined(CONFIG_SMP)
139         "PROMPT=[%d]kdb> ",
140 #else
141         "PROMPT=kdb> ",
142 #endif
143         "MOREPROMPT=more> ",
144         "RADIX=16",
145         "MDCOUNT=8",            /* lines of md output */
146         KDB_PLATFORM_ENV,
147         "DTABCOUNT=30",
148         "NOSECT=1",
149 };
150
151 static const int __nenv = ARRAY_SIZE(__env);
152
153 /*
154  * Update the permissions flags (kdb_cmd_enabled) to match the
155  * current lockdown state.
156  *
157  * Within this function the calls to security_locked_down() are "lazy". We
158  * avoid calling them if the current value of kdb_cmd_enabled already excludes
159  * flags that might be subject to lockdown. Additionally we deliberately check
160  * the lockdown flags independently (even though read lockdown implies write
161  * lockdown) since that results in both simpler code and clearer messages to
162  * the user on first-time debugger entry.
163  *
164  * The permission masks during a read+write lockdown permits the following
165  * flags: INSPECT, SIGNAL, REBOOT (and ALWAYS_SAFE).
166  *
167  * The INSPECT commands are not blocked during lockdown because they are
168  * not arbitrary memory reads. INSPECT covers the backtrace family (sometimes
169  * forcing them to have no arguments) and lsmod. These commands do expose
170  * some kernel state but do not allow the developer seated at the console to
171  * choose what state is reported. SIGNAL and REBOOT should not be controversial,
172  * given these are allowed for root during lockdown already.
173  */
174 static void kdb_check_for_lockdown(void)
175 {
176         const int write_flags = KDB_ENABLE_MEM_WRITE |
177                                 KDB_ENABLE_REG_WRITE |
178                                 KDB_ENABLE_FLOW_CTRL;
179         const int read_flags = KDB_ENABLE_MEM_READ |
180                                KDB_ENABLE_REG_READ;
181
182         bool need_to_lockdown_write = false;
183         bool need_to_lockdown_read = false;
184
185         if (kdb_cmd_enabled & (KDB_ENABLE_ALL | write_flags))
186                 need_to_lockdown_write =
187                         security_locked_down(LOCKDOWN_DBG_WRITE_KERNEL);
188
189         if (kdb_cmd_enabled & (KDB_ENABLE_ALL | read_flags))
190                 need_to_lockdown_read =
191                         security_locked_down(LOCKDOWN_DBG_READ_KERNEL);
192
193         /* De-compose KDB_ENABLE_ALL if required */
194         if (need_to_lockdown_write || need_to_lockdown_read)
195                 if (kdb_cmd_enabled & KDB_ENABLE_ALL)
196                         kdb_cmd_enabled = KDB_ENABLE_MASK & ~KDB_ENABLE_ALL;
197
198         if (need_to_lockdown_write)
199                 kdb_cmd_enabled &= ~write_flags;
200
201         if (need_to_lockdown_read)
202                 kdb_cmd_enabled &= ~read_flags;
203 }
204
205 /*
206  * Check whether the flags of the current command, the permissions of the kdb
207  * console and the lockdown state allow a command to be run.
208  */
209 static bool kdb_check_flags(kdb_cmdflags_t flags, int permissions,
210                                    bool no_args)
211 {
212         /* permissions comes from userspace so needs massaging slightly */
213         permissions &= KDB_ENABLE_MASK;
214         permissions |= KDB_ENABLE_ALWAYS_SAFE;
215
216         /* some commands change group when launched with no arguments */
217         if (no_args)
218                 permissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT;
219
220         flags |= KDB_ENABLE_ALL;
221
222         return permissions & flags;
223 }
224
225 /*
226  * kdbgetenv - This function will return the character string value of
227  *      an environment variable.
228  * Parameters:
229  *      match   A character string representing an environment variable.
230  * Returns:
231  *      NULL    No environment variable matches 'match'
232  *      char*   Pointer to string value of environment variable.
233  */
234 char *kdbgetenv(const char *match)
235 {
236         char **ep = __env;
237         int matchlen = strlen(match);
238         int i;
239
240         for (i = 0; i < __nenv; i++) {
241                 char *e = *ep++;
242
243                 if (!e)
244                         continue;
245
246                 if ((strncmp(match, e, matchlen) == 0)
247                  && ((e[matchlen] == '\0')
248                    || (e[matchlen] == '='))) {
249                         char *cp = strchr(e, '=');
250                         return cp ? ++cp : "";
251                 }
252         }
253         return NULL;
254 }
255
256 /*
257  * kdbgetulenv - This function will return the value of an unsigned
258  *      long-valued environment variable.
259  * Parameters:
260  *      match   A character string representing a numeric value
261  * Outputs:
262  *      *value  the unsigned long representation of the env variable 'match'
263  * Returns:
264  *      Zero on success, a kdb diagnostic on failure.
265  */
266 static int kdbgetulenv(const char *match, unsigned long *value)
267 {
268         char *ep;
269
270         ep = kdbgetenv(match);
271         if (!ep)
272                 return KDB_NOTENV;
273         if (strlen(ep) == 0)
274                 return KDB_NOENVVALUE;
275         if (kstrtoul(ep, 0, value))
276                 return KDB_BADINT;
277
278         return 0;
279 }
280
281 /*
282  * kdbgetintenv - This function will return the value of an
283  *      integer-valued environment variable.
284  * Parameters:
285  *      match   A character string representing an integer-valued env variable
286  * Outputs:
287  *      *value  the integer representation of the environment variable 'match'
288  * Returns:
289  *      Zero on success, a kdb diagnostic on failure.
290  */
291 int kdbgetintenv(const char *match, int *value)
292 {
293         unsigned long val;
294         int diag;
295
296         diag = kdbgetulenv(match, &val);
297         if (!diag)
298                 *value = (int) val;
299         return diag;
300 }
301
302 /*
303  * kdb_setenv() - Alter an existing environment variable or create a new one.
304  * @var: Name of the variable
305  * @val: Value of the variable
306  *
307  * Return: Zero on success, a kdb diagnostic on failure.
308  */
309 static int kdb_setenv(const char *var, const char *val)
310 {
311         int i;
312         char *ep;
313         size_t varlen, vallen;
314
315         varlen = strlen(var);
316         vallen = strlen(val);
317         ep = kmalloc(varlen + vallen + 2, GFP_KDB);
318         if (!ep)
319                 return KDB_KMALLOCFAILED;
320
321         sprintf(ep, "%s=%s", var, val);
322
323         for (i = 0; i < __nenv; i++) {
324                 if (__env[i]
325                  && ((strncmp(__env[i], var, varlen) == 0)
326                    && ((__env[i][varlen] == '\0')
327                     || (__env[i][varlen] == '=')))) {
328                         kfree_const(__env[i]);
329                         __env[i] = ep;
330                         return 0;
331                 }
332         }
333
334         /*
335          * Wasn't existing variable.  Fit into slot.
336          */
337         for (i = 0; i < __nenv-1; i++) {
338                 if (__env[i] == (char *)0) {
339                         __env[i] = ep;
340                         return 0;
341                 }
342         }
343
344         return KDB_ENVFULL;
345 }
346
347 /*
348  * kdb_printenv() - Display the current environment variables.
349  */
350 static void kdb_printenv(void)
351 {
352         int i;
353
354         for (i = 0; i < __nenv; i++) {
355                 if (__env[i])
356                         kdb_printf("%s\n", __env[i]);
357         }
358 }
359
360 /*
361  * kdbgetularg - This function will convert a numeric string into an
362  *      unsigned long value.
363  * Parameters:
364  *      arg     A character string representing a numeric value
365  * Outputs:
366  *      *value  the unsigned long representation of arg.
367  * Returns:
368  *      Zero on success, a kdb diagnostic on failure.
369  */
370 int kdbgetularg(const char *arg, unsigned long *value)
371 {
372         if (kstrtoul(arg, 0, value))
373                 return KDB_BADINT;
374         return 0;
375 }
376
377 int kdbgetu64arg(const char *arg, u64 *value)
378 {
379         if (kstrtou64(arg, 0, value))
380                 return KDB_BADINT;
381         return 0;
382 }
383
384 /*
385  * kdb_set - This function implements the 'set' command.  Alter an
386  *      existing environment variable or create a new one.
387  */
388 int kdb_set(int argc, const char **argv)
389 {
390         /*
391          * we can be invoked two ways:
392          *   set var=value    argv[1]="var", argv[2]="value"
393          *   set var = value  argv[1]="var", argv[2]="=", argv[3]="value"
394          * - if the latter, shift 'em down.
395          */
396         if (argc == 3) {
397                 argv[2] = argv[3];
398                 argc--;
399         }
400
401         if (argc != 2)
402                 return KDB_ARGCOUNT;
403
404         /*
405          * Censor sensitive variables
406          */
407         if (strcmp(argv[1], "PROMPT") == 0 &&
408             !kdb_check_flags(KDB_ENABLE_MEM_READ, kdb_cmd_enabled, false))
409                 return KDB_NOPERM;
410
411         /*
412          * Check for internal variables
413          */
414         if (strcmp(argv[1], "KDBDEBUG") == 0) {
415                 unsigned int debugflags;
416                 int ret;
417
418                 ret = kstrtouint(argv[2], 0, &debugflags);
419                 if (ret || debugflags & ~KDB_DEBUG_FLAG_MASK) {
420                         kdb_printf("kdb: illegal debug flags '%s'\n",
421                                     argv[2]);
422                         return 0;
423                 }
424                 kdb_flags = (kdb_flags & ~KDB_DEBUG(MASK))
425                         | (debugflags << KDB_DEBUG_FLAG_SHIFT);
426
427                 return 0;
428         }
429
430         /*
431          * Tokenizer squashed the '=' sign.  argv[1] is variable
432          * name, argv[2] = value.
433          */
434         return kdb_setenv(argv[1], argv[2]);
435 }
436
437 static int kdb_check_regs(void)
438 {
439         if (!kdb_current_regs) {
440                 kdb_printf("No current kdb registers."
441                            "  You may need to select another task\n");
442                 return KDB_BADREG;
443         }
444         return 0;
445 }
446
447 /*
448  * kdbgetaddrarg - This function is responsible for parsing an
449  *      address-expression and returning the value of the expression,
450  *      symbol name, and offset to the caller.
451  *
452  *      The argument may consist of a numeric value (decimal or
453  *      hexadecimal), a symbol name, a register name (preceded by the
454  *      percent sign), an environment variable with a numeric value
455  *      (preceded by a dollar sign) or a simple arithmetic expression
456  *      consisting of a symbol name, +/-, and a numeric constant value
457  *      (offset).
458  * Parameters:
459  *      argc    - count of arguments in argv
460  *      argv    - argument vector
461  *      *nextarg - index to next unparsed argument in argv[]
462  *      regs    - Register state at time of KDB entry
463  * Outputs:
464  *      *value  - receives the value of the address-expression
465  *      *offset - receives the offset specified, if any
466  *      *name   - receives the symbol name, if any
467  *      *nextarg - index to next unparsed argument in argv[]
468  * Returns:
469  *      zero is returned on success, a kdb diagnostic code is
470  *      returned on error.
471  */
472 int kdbgetaddrarg(int argc, const char **argv, int *nextarg,
473                   unsigned long *value,  long *offset,
474                   char **name)
475 {
476         unsigned long addr;
477         unsigned long off = 0;
478         int positive;
479         int diag;
480         int found = 0;
481         char *symname;
482         char symbol = '\0';
483         char *cp;
484         kdb_symtab_t symtab;
485
486         /*
487          * If the enable flags prohibit both arbitrary memory access
488          * and flow control then there are no reasonable grounds to
489          * provide symbol lookup.
490          */
491         if (!kdb_check_flags(KDB_ENABLE_MEM_READ | KDB_ENABLE_FLOW_CTRL,
492                              kdb_cmd_enabled, false))
493                 return KDB_NOPERM;
494
495         /*
496          * Process arguments which follow the following syntax:
497          *
498          *  symbol | numeric-address [+/- numeric-offset]
499          *  %register
500          *  $environment-variable
501          */
502
503         if (*nextarg > argc)
504                 return KDB_ARGCOUNT;
505
506         symname = (char *)argv[*nextarg];
507
508         /*
509          * If there is no whitespace between the symbol
510          * or address and the '+' or '-' symbols, we
511          * remember the character and replace it with a
512          * null so the symbol/value can be properly parsed
513          */
514         cp = strpbrk(symname, "+-");
515         if (cp != NULL) {
516                 symbol = *cp;
517                 *cp++ = '\0';
518         }
519
520         if (symname[0] == '$') {
521                 diag = kdbgetulenv(&symname[1], &addr);
522                 if (diag)
523                         return diag;
524         } else if (symname[0] == '%') {
525                 diag = kdb_check_regs();
526                 if (diag)
527                         return diag;
528                 /* Implement register values with % at a later time as it is
529                  * arch optional.
530                  */
531                 return KDB_NOTIMP;
532         } else {
533                 found = kdbgetsymval(symname, &symtab);
534                 if (found) {
535                         addr = symtab.sym_start;
536                 } else {
537                         diag = kdbgetularg(argv[*nextarg], &addr);
538                         if (diag)
539                                 return diag;
540                 }
541         }
542
543         if (!found)
544                 found = kdbnearsym(addr, &symtab);
545
546         (*nextarg)++;
547
548         if (name)
549                 *name = symname;
550         if (value)
551                 *value = addr;
552         if (offset && name && *name)
553                 *offset = addr - symtab.sym_start;
554
555         if ((*nextarg > argc)
556          && (symbol == '\0'))
557                 return 0;
558
559         /*
560          * check for +/- and offset
561          */
562
563         if (symbol == '\0') {
564                 if ((argv[*nextarg][0] != '+')
565                  && (argv[*nextarg][0] != '-')) {
566                         /*
567                          * Not our argument.  Return.
568                          */
569                         return 0;
570                 } else {
571                         positive = (argv[*nextarg][0] == '+');
572                         (*nextarg)++;
573                 }
574         } else
575                 positive = (symbol == '+');
576
577         /*
578          * Now there must be an offset!
579          */
580         if ((*nextarg > argc)
581          && (symbol == '\0')) {
582                 return KDB_INVADDRFMT;
583         }
584
585         if (!symbol) {
586                 cp = (char *)argv[*nextarg];
587                 (*nextarg)++;
588         }
589
590         diag = kdbgetularg(cp, &off);
591         if (diag)
592                 return diag;
593
594         if (!positive)
595                 off = -off;
596
597         if (offset)
598                 *offset += off;
599
600         if (value)
601                 *value += off;
602
603         return 0;
604 }
605
606 static void kdb_cmderror(int diag)
607 {
608         int i;
609
610         if (diag >= 0) {
611                 kdb_printf("no error detected (diagnostic is %d)\n", diag);
612                 return;
613         }
614
615         for (i = 0; i < __nkdb_err; i++) {
616                 if (kdbmsgs[i].km_diag == diag) {
617                         kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
618                         return;
619                 }
620         }
621
622         kdb_printf("Unknown diag %d\n", -diag);
623 }
624
625 /*
626  * kdb_defcmd, kdb_defcmd2 - This function implements the 'defcmd'
627  *      command which defines one command as a set of other commands,
628  *      terminated by endefcmd.  kdb_defcmd processes the initial
629  *      'defcmd' command, kdb_defcmd2 is invoked from kdb_parse for
630  *      the following commands until 'endefcmd'.
631  * Inputs:
632  *      argc    argument count
633  *      argv    argument vector
634  * Returns:
635  *      zero for success, a kdb diagnostic if error
636  */
637 struct kdb_macro {
638         kdbtab_t cmd;                   /* Macro command */
639         struct list_head statements;    /* Associated statement list */
640 };
641
642 struct kdb_macro_statement {
643         char *statement;                /* Statement text */
644         struct list_head list_node;     /* Statement list node */
645 };
646
647 static struct kdb_macro *kdb_macro;
648 static bool defcmd_in_progress;
649
650 /* Forward references */
651 static int kdb_exec_defcmd(int argc, const char **argv);
652
653 static int kdb_defcmd2(const char *cmdstr, const char *argv0)
654 {
655         struct kdb_macro_statement *kms;
656
657         if (!kdb_macro)
658                 return KDB_NOTIMP;
659
660         if (strcmp(argv0, "endefcmd") == 0) {
661                 defcmd_in_progress = false;
662                 if (!list_empty(&kdb_macro->statements))
663                         kdb_register(&kdb_macro->cmd);
664                 return 0;
665         }
666
667         kms = kmalloc(sizeof(*kms), GFP_KDB);
668         if (!kms) {
669                 kdb_printf("Could not allocate new kdb macro command: %s\n",
670                            cmdstr);
671                 return KDB_NOTIMP;
672         }
673
674         kms->statement = kdb_strdup(cmdstr, GFP_KDB);
675         list_add_tail(&kms->list_node, &kdb_macro->statements);
676
677         return 0;
678 }
679
680 static int kdb_defcmd(int argc, const char **argv)
681 {
682         kdbtab_t *mp;
683
684         if (defcmd_in_progress) {
685                 kdb_printf("kdb: nested defcmd detected, assuming missing "
686                            "endefcmd\n");
687                 kdb_defcmd2("endefcmd", "endefcmd");
688         }
689         if (argc == 0) {
690                 kdbtab_t *kp;
691                 struct kdb_macro *kmp;
692                 struct kdb_macro_statement *kms;
693
694                 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
695                         if (kp->func == kdb_exec_defcmd) {
696                                 kdb_printf("defcmd %s \"%s\" \"%s\"\n",
697                                            kp->name, kp->usage, kp->help);
698                                 kmp = container_of(kp, struct kdb_macro, cmd);
699                                 list_for_each_entry(kms, &kmp->statements,
700                                                     list_node)
701                                         kdb_printf("%s", kms->statement);
702                                 kdb_printf("endefcmd\n");
703                         }
704                 }
705                 return 0;
706         }
707         if (argc != 3)
708                 return KDB_ARGCOUNT;
709         if (in_dbg_master()) {
710                 kdb_printf("Command only available during kdb_init()\n");
711                 return KDB_NOTIMP;
712         }
713         kdb_macro = kzalloc(sizeof(*kdb_macro), GFP_KDB);
714         if (!kdb_macro)
715                 goto fail_defcmd;
716
717         mp = &kdb_macro->cmd;
718         mp->func = kdb_exec_defcmd;
719         mp->minlen = 0;
720         mp->flags = KDB_ENABLE_ALWAYS_SAFE;
721         mp->name = kdb_strdup(argv[1], GFP_KDB);
722         if (!mp->name)
723                 goto fail_name;
724         mp->usage = kdb_strdup(argv[2], GFP_KDB);
725         if (!mp->usage)
726                 goto fail_usage;
727         mp->help = kdb_strdup(argv[3], GFP_KDB);
728         if (!mp->help)
729                 goto fail_help;
730         if (mp->usage[0] == '"') {
731                 strcpy(mp->usage, argv[2]+1);
732                 mp->usage[strlen(mp->usage)-1] = '\0';
733         }
734         if (mp->help[0] == '"') {
735                 strcpy(mp->help, argv[3]+1);
736                 mp->help[strlen(mp->help)-1] = '\0';
737         }
738
739         INIT_LIST_HEAD(&kdb_macro->statements);
740         defcmd_in_progress = true;
741         return 0;
742 fail_help:
743         kfree(mp->usage);
744 fail_usage:
745         kfree(mp->name);
746 fail_name:
747         kfree(kdb_macro);
748 fail_defcmd:
749         kdb_printf("Could not allocate new kdb_macro entry for %s\n", argv[1]);
750         return KDB_NOTIMP;
751 }
752
753 /*
754  * kdb_exec_defcmd - Execute the set of commands associated with this
755  *      defcmd name.
756  * Inputs:
757  *      argc    argument count
758  *      argv    argument vector
759  * Returns:
760  *      zero for success, a kdb diagnostic if error
761  */
762 static int kdb_exec_defcmd(int argc, const char **argv)
763 {
764         int ret;
765         kdbtab_t *kp;
766         struct kdb_macro *kmp;
767         struct kdb_macro_statement *kms;
768
769         if (argc != 0)
770                 return KDB_ARGCOUNT;
771
772         list_for_each_entry(kp, &kdb_cmds_head, list_node) {
773                 if (strcmp(kp->name, argv[0]) == 0)
774                         break;
775         }
776         if (list_entry_is_head(kp, &kdb_cmds_head, list_node)) {
777                 kdb_printf("kdb_exec_defcmd: could not find commands for %s\n",
778                            argv[0]);
779                 return KDB_NOTIMP;
780         }
781         kmp = container_of(kp, struct kdb_macro, cmd);
782         list_for_each_entry(kms, &kmp->statements, list_node) {
783                 /*
784                  * Recursive use of kdb_parse, do not use argv after this point.
785                  */
786                 argv = NULL;
787                 kdb_printf("[%s]kdb> %s\n", kmp->cmd.name, kms->statement);
788                 ret = kdb_parse(kms->statement);
789                 if (ret)
790                         return ret;
791         }
792         return 0;
793 }
794
795 /* Command history */
796 #define KDB_CMD_HISTORY_COUNT   32
797 #define CMD_BUFLEN              200     /* kdb_printf: max printline
798                                          * size == 256 */
799 static unsigned int cmd_head, cmd_tail;
800 static unsigned int cmdptr;
801 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
802 static char cmd_cur[CMD_BUFLEN];
803
804 /*
805  * The "str" argument may point to something like  | grep xyz
806  */
807 static void parse_grep(const char *str)
808 {
809         int     len;
810         char    *cp = (char *)str, *cp2;
811
812         /* sanity check: we should have been called with the \ first */
813         if (*cp != '|')
814                 return;
815         cp++;
816         while (isspace(*cp))
817                 cp++;
818         if (!str_has_prefix(cp, "grep ")) {
819                 kdb_printf("invalid 'pipe', see grephelp\n");
820                 return;
821         }
822         cp += 5;
823         while (isspace(*cp))
824                 cp++;
825         cp2 = strchr(cp, '\n');
826         if (cp2)
827                 *cp2 = '\0'; /* remove the trailing newline */
828         len = strlen(cp);
829         if (len == 0) {
830                 kdb_printf("invalid 'pipe', see grephelp\n");
831                 return;
832         }
833         /* now cp points to a nonzero length search string */
834         if (*cp == '"') {
835                 /* allow it be "x y z" by removing the "'s - there must
836                    be two of them */
837                 cp++;
838                 cp2 = strchr(cp, '"');
839                 if (!cp2) {
840                         kdb_printf("invalid quoted string, see grephelp\n");
841                         return;
842                 }
843                 *cp2 = '\0'; /* end the string where the 2nd " was */
844         }
845         kdb_grep_leading = 0;
846         if (*cp == '^') {
847                 kdb_grep_leading = 1;
848                 cp++;
849         }
850         len = strlen(cp);
851         kdb_grep_trailing = 0;
852         if (*(cp+len-1) == '$') {
853                 kdb_grep_trailing = 1;
854                 *(cp+len-1) = '\0';
855         }
856         len = strlen(cp);
857         if (!len)
858                 return;
859         if (len >= KDB_GREP_STRLEN) {
860                 kdb_printf("search string too long\n");
861                 return;
862         }
863         strcpy(kdb_grep_string, cp);
864         kdb_grepping_flag++;
865         return;
866 }
867
868 /*
869  * kdb_parse - Parse the command line, search the command table for a
870  *      matching command and invoke the command function.  This
871  *      function may be called recursively, if it is, the second call
872  *      will overwrite argv and cbuf.  It is the caller's
873  *      responsibility to save their argv if they recursively call
874  *      kdb_parse().
875  * Parameters:
876  *      cmdstr  The input command line to be parsed.
877  *      regs    The registers at the time kdb was entered.
878  * Returns:
879  *      Zero for success, a kdb diagnostic if failure.
880  * Remarks:
881  *      Limited to 20 tokens.
882  *
883  *      Real rudimentary tokenization. Basically only whitespace
884  *      is considered a token delimiter (but special consideration
885  *      is taken of the '=' sign as used by the 'set' command).
886  *
887  *      The algorithm used to tokenize the input string relies on
888  *      there being at least one whitespace (or otherwise useless)
889  *      character between tokens as the character immediately following
890  *      the token is altered in-place to a null-byte to terminate the
891  *      token string.
892  */
893
894 #define MAXARGC 20
895
896 int kdb_parse(const char *cmdstr)
897 {
898         static char *argv[MAXARGC];
899         static int argc;
900         static char cbuf[CMD_BUFLEN+2];
901         char *cp;
902         char *cpp, quoted;
903         kdbtab_t *tp;
904         int escaped, ignore_errors = 0, check_grep = 0;
905
906         /*
907          * First tokenize the command string.
908          */
909         cp = (char *)cmdstr;
910
911         if (KDB_FLAG(CMD_INTERRUPT)) {
912                 /* Previous command was interrupted, newline must not
913                  * repeat the command */
914                 KDB_FLAG_CLEAR(CMD_INTERRUPT);
915                 KDB_STATE_SET(PAGER);
916                 argc = 0;       /* no repeat */
917         }
918
919         if (*cp != '\n' && *cp != '\0') {
920                 argc = 0;
921                 cpp = cbuf;
922                 while (*cp) {
923                         /* skip whitespace */
924                         while (isspace(*cp))
925                                 cp++;
926                         if ((*cp == '\0') || (*cp == '\n') ||
927                             (*cp == '#' && !defcmd_in_progress))
928                                 break;
929                         /* special case: check for | grep pattern */
930                         if (*cp == '|') {
931                                 check_grep++;
932                                 break;
933                         }
934                         if (cpp >= cbuf + CMD_BUFLEN) {
935                                 kdb_printf("kdb_parse: command buffer "
936                                            "overflow, command ignored\n%s\n",
937                                            cmdstr);
938                                 return KDB_NOTFOUND;
939                         }
940                         if (argc >= MAXARGC - 1) {
941                                 kdb_printf("kdb_parse: too many arguments, "
942                                            "command ignored\n%s\n", cmdstr);
943                                 return KDB_NOTFOUND;
944                         }
945                         argv[argc++] = cpp;
946                         escaped = 0;
947                         quoted = '\0';
948                         /* Copy to next unquoted and unescaped
949                          * whitespace or '=' */
950                         while (*cp && *cp != '\n' &&
951                                (escaped || quoted || !isspace(*cp))) {
952                                 if (cpp >= cbuf + CMD_BUFLEN)
953                                         break;
954                                 if (escaped) {
955                                         escaped = 0;
956                                         *cpp++ = *cp++;
957                                         continue;
958                                 }
959                                 if (*cp == '\\') {
960                                         escaped = 1;
961                                         ++cp;
962                                         continue;
963                                 }
964                                 if (*cp == quoted)
965                                         quoted = '\0';
966                                 else if (*cp == '\'' || *cp == '"')
967                                         quoted = *cp;
968                                 *cpp = *cp++;
969                                 if (*cpp == '=' && !quoted)
970                                         break;
971                                 ++cpp;
972                         }
973                         *cpp++ = '\0';  /* Squash a ws or '=' character */
974                 }
975         }
976         if (!argc)
977                 return 0;
978         if (check_grep)
979                 parse_grep(cp);
980         if (defcmd_in_progress) {
981                 int result = kdb_defcmd2(cmdstr, argv[0]);
982                 if (!defcmd_in_progress) {
983                         argc = 0;       /* avoid repeat on endefcmd */
984                         *(argv[0]) = '\0';
985                 }
986                 return result;
987         }
988         if (argv[0][0] == '-' && argv[0][1] &&
989             (argv[0][1] < '0' || argv[0][1] > '9')) {
990                 ignore_errors = 1;
991                 ++argv[0];
992         }
993
994         list_for_each_entry(tp, &kdb_cmds_head, list_node) {
995                 /*
996                  * If this command is allowed to be abbreviated,
997                  * check to see if this is it.
998                  */
999                 if (tp->minlen && (strlen(argv[0]) <= tp->minlen) &&
1000                     (strncmp(argv[0], tp->name, tp->minlen) == 0))
1001                         break;
1002
1003                 if (strcmp(argv[0], tp->name) == 0)
1004                         break;
1005         }
1006
1007         /*
1008          * If we don't find a command by this name, see if the first
1009          * few characters of this match any of the known commands.
1010          * e.g., md1c20 should match md.
1011          */
1012         if (list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1013                 list_for_each_entry(tp, &kdb_cmds_head, list_node) {
1014                         if (strncmp(argv[0], tp->name, strlen(tp->name)) == 0)
1015                                 break;
1016                 }
1017         }
1018
1019         if (!list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1020                 int result;
1021
1022                 if (!kdb_check_flags(tp->flags, kdb_cmd_enabled, argc <= 1))
1023                         return KDB_NOPERM;
1024
1025                 KDB_STATE_SET(CMD);
1026                 result = (*tp->func)(argc-1, (const char **)argv);
1027                 if (result && ignore_errors && result > KDB_CMD_GO)
1028                         result = 0;
1029                 KDB_STATE_CLEAR(CMD);
1030
1031                 if (tp->flags & KDB_REPEAT_WITH_ARGS)
1032                         return result;
1033
1034                 argc = tp->flags & KDB_REPEAT_NO_ARGS ? 1 : 0;
1035                 if (argv[argc])
1036                         *(argv[argc]) = '\0';
1037                 return result;
1038         }
1039
1040         /*
1041          * If the input with which we were presented does not
1042          * map to an existing command, attempt to parse it as an
1043          * address argument and display the result.   Useful for
1044          * obtaining the address of a variable, or the nearest symbol
1045          * to an address contained in a register.
1046          */
1047         {
1048                 unsigned long value;
1049                 char *name = NULL;
1050                 long offset;
1051                 int nextarg = 0;
1052
1053                 if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
1054                                   &value, &offset, &name)) {
1055                         return KDB_NOTFOUND;
1056                 }
1057
1058                 kdb_printf("%s = ", argv[0]);
1059                 kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
1060                 kdb_printf("\n");
1061                 return 0;
1062         }
1063 }
1064
1065
1066 static int handle_ctrl_cmd(char *cmd)
1067 {
1068 #define CTRL_P  16
1069 #define CTRL_N  14
1070
1071         /* initial situation */
1072         if (cmd_head == cmd_tail)
1073                 return 0;
1074         switch (*cmd) {
1075         case CTRL_P:
1076                 if (cmdptr != cmd_tail)
1077                         cmdptr = (cmdptr + KDB_CMD_HISTORY_COUNT - 1) %
1078                                  KDB_CMD_HISTORY_COUNT;
1079                 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1080                 return 1;
1081         case CTRL_N:
1082                 if (cmdptr != cmd_head)
1083                         cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
1084                 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1085                 return 1;
1086         }
1087         return 0;
1088 }
1089
1090 /*
1091  * kdb_reboot - This function implements the 'reboot' command.  Reboot
1092  *      the system immediately, or loop for ever on failure.
1093  */
1094 static int kdb_reboot(int argc, const char **argv)
1095 {
1096         emergency_restart();
1097         kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
1098         while (1)
1099                 cpu_relax();
1100         /* NOTREACHED */
1101         return 0;
1102 }
1103
1104 static void kdb_dumpregs(struct pt_regs *regs)
1105 {
1106         int old_lvl = console_loglevel;
1107         console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
1108         kdb_trap_printk++;
1109         show_regs(regs);
1110         kdb_trap_printk--;
1111         kdb_printf("\n");
1112         console_loglevel = old_lvl;
1113 }
1114
1115 static void kdb_set_current_task(struct task_struct *p)
1116 {
1117         kdb_current_task = p;
1118
1119         if (kdb_task_has_cpu(p)) {
1120                 kdb_current_regs = KDB_TSKREGS(kdb_process_cpu(p));
1121                 return;
1122         }
1123         kdb_current_regs = NULL;
1124 }
1125
1126 static void drop_newline(char *buf)
1127 {
1128         size_t len = strlen(buf);
1129
1130         if (len == 0)
1131                 return;
1132         if (*(buf + len - 1) == '\n')
1133                 *(buf + len - 1) = '\0';
1134 }
1135
1136 /*
1137  * kdb_local - The main code for kdb.  This routine is invoked on a
1138  *      specific processor, it is not global.  The main kdb() routine
1139  *      ensures that only one processor at a time is in this routine.
1140  *      This code is called with the real reason code on the first
1141  *      entry to a kdb session, thereafter it is called with reason
1142  *      SWITCH, even if the user goes back to the original cpu.
1143  * Inputs:
1144  *      reason          The reason KDB was invoked
1145  *      error           The hardware-defined error code
1146  *      regs            The exception frame at time of fault/breakpoint.
1147  *      db_result       Result code from the break or debug point.
1148  * Returns:
1149  *      0       KDB was invoked for an event which it wasn't responsible
1150  *      1       KDB handled the event for which it was invoked.
1151  *      KDB_CMD_GO      User typed 'go'.
1152  *      KDB_CMD_CPU     User switched to another cpu.
1153  *      KDB_CMD_SS      Single step.
1154  */
1155 static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
1156                      kdb_dbtrap_t db_result)
1157 {
1158         char *cmdbuf;
1159         int diag;
1160         struct task_struct *kdb_current =
1161                 curr_task(raw_smp_processor_id());
1162
1163         KDB_DEBUG_STATE("kdb_local 1", reason);
1164
1165         kdb_check_for_lockdown();
1166
1167         kdb_go_count = 0;
1168         if (reason == KDB_REASON_DEBUG) {
1169                 /* special case below */
1170         } else {
1171                 kdb_printf("\nEntering kdb (current=0x%px, pid %d) ",
1172                            kdb_current, kdb_current ? kdb_current->pid : 0);
1173 #if defined(CONFIG_SMP)
1174                 kdb_printf("on processor %d ", raw_smp_processor_id());
1175 #endif
1176         }
1177
1178         switch (reason) {
1179         case KDB_REASON_DEBUG:
1180         {
1181                 /*
1182                  * If re-entering kdb after a single step
1183                  * command, don't print the message.
1184                  */
1185                 switch (db_result) {
1186                 case KDB_DB_BPT:
1187                         kdb_printf("\nEntering kdb (0x%px, pid %d) ",
1188                                    kdb_current, kdb_current->pid);
1189 #if defined(CONFIG_SMP)
1190                         kdb_printf("on processor %d ", raw_smp_processor_id());
1191 #endif
1192                         kdb_printf("due to Debug @ " kdb_machreg_fmt "\n",
1193                                    instruction_pointer(regs));
1194                         break;
1195                 case KDB_DB_SS:
1196                         break;
1197                 case KDB_DB_SSBPT:
1198                         KDB_DEBUG_STATE("kdb_local 4", reason);
1199                         return 1;       /* kdba_db_trap did the work */
1200                 default:
1201                         kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
1202                                    db_result);
1203                         break;
1204                 }
1205
1206         }
1207                 break;
1208         case KDB_REASON_ENTER:
1209                 if (KDB_STATE(KEYBOARD))
1210                         kdb_printf("due to Keyboard Entry\n");
1211                 else
1212                         kdb_printf("due to KDB_ENTER()\n");
1213                 break;
1214         case KDB_REASON_KEYBOARD:
1215                 KDB_STATE_SET(KEYBOARD);
1216                 kdb_printf("due to Keyboard Entry\n");
1217                 break;
1218         case KDB_REASON_ENTER_SLAVE:
1219                 /* drop through, slaves only get released via cpu switch */
1220         case KDB_REASON_SWITCH:
1221                 kdb_printf("due to cpu switch\n");
1222                 break;
1223         case KDB_REASON_OOPS:
1224                 kdb_printf("Oops: %s\n", kdb_diemsg);
1225                 kdb_printf("due to oops @ " kdb_machreg_fmt "\n",
1226                            instruction_pointer(regs));
1227                 kdb_dumpregs(regs);
1228                 break;
1229         case KDB_REASON_SYSTEM_NMI:
1230                 kdb_printf("due to System NonMaskable Interrupt\n");
1231                 break;
1232         case KDB_REASON_NMI:
1233                 kdb_printf("due to NonMaskable Interrupt @ "
1234                            kdb_machreg_fmt "\n",
1235                            instruction_pointer(regs));
1236                 break;
1237         case KDB_REASON_SSTEP:
1238         case KDB_REASON_BREAK:
1239                 kdb_printf("due to %s @ " kdb_machreg_fmt "\n",
1240                            reason == KDB_REASON_BREAK ?
1241                            "Breakpoint" : "SS trap", instruction_pointer(regs));
1242                 /*
1243                  * Determine if this breakpoint is one that we
1244                  * are interested in.
1245                  */
1246                 if (db_result != KDB_DB_BPT) {
1247                         kdb_printf("kdb: error return from kdba_bp_trap: %d\n",
1248                                    db_result);
1249                         KDB_DEBUG_STATE("kdb_local 6", reason);
1250                         return 0;       /* Not for us, dismiss it */
1251                 }
1252                 break;
1253         case KDB_REASON_RECURSE:
1254                 kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n",
1255                            instruction_pointer(regs));
1256                 break;
1257         default:
1258                 kdb_printf("kdb: unexpected reason code: %d\n", reason);
1259                 KDB_DEBUG_STATE("kdb_local 8", reason);
1260                 return 0;       /* Not for us, dismiss it */
1261         }
1262
1263         while (1) {
1264                 /*
1265                  * Initialize pager context.
1266                  */
1267                 kdb_nextline = 1;
1268                 KDB_STATE_CLEAR(SUPPRESS);
1269                 kdb_grepping_flag = 0;
1270                 /* ensure the old search does not leak into '/' commands */
1271                 kdb_grep_string[0] = '\0';
1272
1273                 cmdbuf = cmd_cur;
1274                 *cmdbuf = '\0';
1275                 *(cmd_hist[cmd_head]) = '\0';
1276
1277 do_full_getstr:
1278                 /* PROMPT can only be set if we have MEM_READ permission. */
1279                 snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
1280                          raw_smp_processor_id());
1281
1282                 /*
1283                  * Fetch command from keyboard
1284                  */
1285                 cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
1286                 if (*cmdbuf != '\n') {
1287                         if (*cmdbuf < 32) {
1288                                 if (cmdptr == cmd_head) {
1289                                         strscpy(cmd_hist[cmd_head], cmd_cur,
1290                                                 CMD_BUFLEN);
1291                                         *(cmd_hist[cmd_head] +
1292                                           strlen(cmd_hist[cmd_head])-1) = '\0';
1293                                 }
1294                                 if (!handle_ctrl_cmd(cmdbuf))
1295                                         *(cmd_cur+strlen(cmd_cur)-1) = '\0';
1296                                 cmdbuf = cmd_cur;
1297                                 goto do_full_getstr;
1298                         } else {
1299                                 strscpy(cmd_hist[cmd_head], cmd_cur,
1300                                         CMD_BUFLEN);
1301                         }
1302
1303                         cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
1304                         if (cmd_head == cmd_tail)
1305                                 cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
1306                 }
1307
1308                 cmdptr = cmd_head;
1309                 diag = kdb_parse(cmdbuf);
1310                 if (diag == KDB_NOTFOUND) {
1311                         drop_newline(cmdbuf);
1312                         kdb_printf("Unknown kdb command: '%s'\n", cmdbuf);
1313                         diag = 0;
1314                 }
1315                 if (diag == KDB_CMD_GO
1316                  || diag == KDB_CMD_CPU
1317                  || diag == KDB_CMD_SS
1318                  || diag == KDB_CMD_KGDB)
1319                         break;
1320
1321                 if (diag)
1322                         kdb_cmderror(diag);
1323         }
1324         KDB_DEBUG_STATE("kdb_local 9", diag);
1325         return diag;
1326 }
1327
1328
1329 /*
1330  * kdb_print_state - Print the state data for the current processor
1331  *      for debugging.
1332  * Inputs:
1333  *      text            Identifies the debug point
1334  *      value           Any integer value to be printed, e.g. reason code.
1335  */
1336 void kdb_print_state(const char *text, int value)
1337 {
1338         kdb_printf("state: %s cpu %d value %d initial %d state %x\n",
1339                    text, raw_smp_processor_id(), value, kdb_initial_cpu,
1340                    kdb_state);
1341 }
1342
1343 /*
1344  * kdb_main_loop - After initial setup and assignment of the
1345  *      controlling cpu, all cpus are in this loop.  One cpu is in
1346  *      control and will issue the kdb prompt, the others will spin
1347  *      until 'go' or cpu switch.
1348  *
1349  *      To get a consistent view of the kernel stacks for all
1350  *      processes, this routine is invoked from the main kdb code via
1351  *      an architecture specific routine.  kdba_main_loop is
1352  *      responsible for making the kernel stacks consistent for all
1353  *      processes, there should be no difference between a blocked
1354  *      process and a running process as far as kdb is concerned.
1355  * Inputs:
1356  *      reason          The reason KDB was invoked
1357  *      error           The hardware-defined error code
1358  *      reason2         kdb's current reason code.
1359  *                      Initially error but can change
1360  *                      according to kdb state.
1361  *      db_result       Result code from break or debug point.
1362  *      regs            The exception frame at time of fault/breakpoint.
1363  *                      should always be valid.
1364  * Returns:
1365  *      0       KDB was invoked for an event which it wasn't responsible
1366  *      1       KDB handled the event for which it was invoked.
1367  */
1368 int kdb_main_loop(kdb_reason_t reason, kdb_reason_t reason2, int error,
1369               kdb_dbtrap_t db_result, struct pt_regs *regs)
1370 {
1371         int result = 1;
1372         /* Stay in kdb() until 'go', 'ss[b]' or an error */
1373         while (1) {
1374                 /*
1375                  * All processors except the one that is in control
1376                  * will spin here.
1377                  */
1378                 KDB_DEBUG_STATE("kdb_main_loop 1", reason);
1379                 while (KDB_STATE(HOLD_CPU)) {
1380                         /* state KDB is turned off by kdb_cpu to see if the
1381                          * other cpus are still live, each cpu in this loop
1382                          * turns it back on.
1383                          */
1384                         if (!KDB_STATE(KDB))
1385                                 KDB_STATE_SET(KDB);
1386                 }
1387
1388                 KDB_STATE_CLEAR(SUPPRESS);
1389                 KDB_DEBUG_STATE("kdb_main_loop 2", reason);
1390                 if (KDB_STATE(LEAVING))
1391                         break;  /* Another cpu said 'go' */
1392                 /* Still using kdb, this processor is in control */
1393                 result = kdb_local(reason2, error, regs, db_result);
1394                 KDB_DEBUG_STATE("kdb_main_loop 3", result);
1395
1396                 if (result == KDB_CMD_CPU)
1397                         break;
1398
1399                 if (result == KDB_CMD_SS) {
1400                         KDB_STATE_SET(DOING_SS);
1401                         break;
1402                 }
1403
1404                 if (result == KDB_CMD_KGDB) {
1405                         if (!KDB_STATE(DOING_KGDB))
1406                                 kdb_printf("Entering please attach debugger "
1407                                            "or use $D#44+ or $3#33\n");
1408                         break;
1409                 }
1410                 if (result && result != 1 && result != KDB_CMD_GO)
1411                         kdb_printf("\nUnexpected kdb_local return code %d\n",
1412                                    result);
1413                 KDB_DEBUG_STATE("kdb_main_loop 4", reason);
1414                 break;
1415         }
1416         if (KDB_STATE(DOING_SS))
1417                 KDB_STATE_CLEAR(SSBPT);
1418
1419         /* Clean up any keyboard devices before leaving */
1420         kdb_kbd_cleanup_state();
1421
1422         return result;
1423 }
1424
1425 /*
1426  * kdb_mdr - This function implements the guts of the 'mdr', memory
1427  * read command.
1428  *      mdr  <addr arg>,<byte count>
1429  * Inputs:
1430  *      addr    Start address
1431  *      count   Number of bytes
1432  * Returns:
1433  *      Always 0.  Any errors are detected and printed by kdb_getarea.
1434  */
1435 static int kdb_mdr(unsigned long addr, unsigned int count)
1436 {
1437         unsigned char c;
1438         while (count--) {
1439                 if (kdb_getarea(c, addr))
1440                         return 0;
1441                 kdb_printf("%02x", c);
1442                 addr++;
1443         }
1444         kdb_printf("\n");
1445         return 0;
1446 }
1447
1448 /*
1449  * kdb_md - This function implements the 'md', 'md1', 'md2', 'md4',
1450  *      'md8' 'mdr' and 'mds' commands.
1451  *
1452  *      md|mds  [<addr arg> [<line count> [<radix>]]]
1453  *      mdWcN   [<addr arg> [<line count> [<radix>]]]
1454  *              where W = is the width (1, 2, 4 or 8) and N is the count.
1455  *              for eg., md1c20 reads 20 bytes, 1 at a time.
1456  *      mdr  <addr arg>,<byte count>
1457  */
1458 static void kdb_md_line(const char *fmtstr, unsigned long addr,
1459                         int symbolic, int nosect, int bytesperword,
1460                         int num, int repeat, int phys)
1461 {
1462         /* print just one line of data */
1463         kdb_symtab_t symtab;
1464         char cbuf[32];
1465         char *c = cbuf;
1466         int i;
1467         int j;
1468         unsigned long word;
1469
1470         memset(cbuf, '\0', sizeof(cbuf));
1471         if (phys)
1472                 kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
1473         else
1474                 kdb_printf(kdb_machreg_fmt0 " ", addr);
1475
1476         for (i = 0; i < num && repeat--; i++) {
1477                 if (phys) {
1478                         if (kdb_getphysword(&word, addr, bytesperword))
1479                                 break;
1480                 } else if (kdb_getword(&word, addr, bytesperword))
1481                         break;
1482                 kdb_printf(fmtstr, word);
1483                 if (symbolic)
1484                         kdbnearsym(word, &symtab);
1485                 else
1486                         memset(&symtab, 0, sizeof(symtab));
1487                 if (symtab.sym_name) {
1488                         kdb_symbol_print(word, &symtab, 0);
1489                         if (!nosect) {
1490                                 kdb_printf("\n");
1491                                 kdb_printf("                       %s %s "
1492                                            kdb_machreg_fmt " "
1493                                            kdb_machreg_fmt " "
1494                                            kdb_machreg_fmt, symtab.mod_name,
1495                                            symtab.sec_name, symtab.sec_start,
1496                                            symtab.sym_start, symtab.sym_end);
1497                         }
1498                         addr += bytesperword;
1499                 } else {
1500                         union {
1501                                 u64 word;
1502                                 unsigned char c[8];
1503                         } wc;
1504                         unsigned char *cp;
1505 #ifdef  __BIG_ENDIAN
1506                         cp = wc.c + 8 - bytesperword;
1507 #else
1508                         cp = wc.c;
1509 #endif
1510                         wc.word = word;
1511 #define printable_char(c) \
1512         ({unsigned char __c = c; isascii(__c) && isprint(__c) ? __c : '.'; })
1513                         for (j = 0; j < bytesperword; j++)
1514                                 *c++ = printable_char(*cp++);
1515                         addr += bytesperword;
1516 #undef printable_char
1517                 }
1518         }
1519         kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1),
1520                    " ", cbuf);
1521 }
1522
1523 static int kdb_md(int argc, const char **argv)
1524 {
1525         static unsigned long last_addr;
1526         static int last_radix, last_bytesperword, last_repeat;
1527         int radix = 16, mdcount = 8, bytesperword = KDB_WORD_SIZE, repeat;
1528         int nosect = 0;
1529         char fmtchar, fmtstr[64];
1530         unsigned long addr;
1531         unsigned long word;
1532         long offset = 0;
1533         int symbolic = 0;
1534         int valid = 0;
1535         int phys = 0;
1536         int raw = 0;
1537
1538         kdbgetintenv("MDCOUNT", &mdcount);
1539         kdbgetintenv("RADIX", &radix);
1540         kdbgetintenv("BYTESPERWORD", &bytesperword);
1541
1542         /* Assume 'md <addr>' and start with environment values */
1543         repeat = mdcount * 16 / bytesperword;
1544
1545         if (strcmp(argv[0], "mdr") == 0) {
1546                 if (argc == 2 || (argc == 0 && last_addr != 0))
1547                         valid = raw = 1;
1548                 else
1549                         return KDB_ARGCOUNT;
1550         } else if (isdigit(argv[0][2])) {
1551                 bytesperword = (int)(argv[0][2] - '0');
1552                 if (bytesperword == 0) {
1553                         bytesperword = last_bytesperword;
1554                         if (bytesperword == 0)
1555                                 bytesperword = 4;
1556                 }
1557                 last_bytesperword = bytesperword;
1558                 repeat = mdcount * 16 / bytesperword;
1559                 if (!argv[0][3])
1560                         valid = 1;
1561                 else if (argv[0][3] == 'c' && argv[0][4]) {
1562                         if (kstrtouint(argv[0] + 4, 10, &repeat))
1563                                 return KDB_BADINT;
1564                         mdcount = ((repeat * bytesperword) + 15) / 16;
1565                         valid = 1;
1566                 }
1567                 last_repeat = repeat;
1568         } else if (strcmp(argv[0], "md") == 0)
1569                 valid = 1;
1570         else if (strcmp(argv[0], "mds") == 0)
1571                 valid = 1;
1572         else if (strcmp(argv[0], "mdp") == 0) {
1573                 phys = valid = 1;
1574         }
1575         if (!valid)
1576                 return KDB_NOTFOUND;
1577
1578         if (argc == 0) {
1579                 if (last_addr == 0)
1580                         return KDB_ARGCOUNT;
1581                 addr = last_addr;
1582                 radix = last_radix;
1583                 bytesperword = last_bytesperword;
1584                 repeat = last_repeat;
1585                 if (raw)
1586                         mdcount = repeat;
1587                 else
1588                         mdcount = ((repeat * bytesperword) + 15) / 16;
1589         }
1590
1591         if (argc) {
1592                 unsigned long val;
1593                 int diag, nextarg = 1;
1594                 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr,
1595                                      &offset, NULL);
1596                 if (diag)
1597                         return diag;
1598                 if (argc > nextarg+2)
1599                         return KDB_ARGCOUNT;
1600
1601                 if (argc >= nextarg) {
1602                         diag = kdbgetularg(argv[nextarg], &val);
1603                         if (!diag) {
1604                                 mdcount = (int) val;
1605                                 if (raw)
1606                                         repeat = mdcount;
1607                                 else
1608                                         repeat = mdcount * 16 / bytesperword;
1609                         }
1610                 }
1611                 if (argc >= nextarg+1) {
1612                         diag = kdbgetularg(argv[nextarg+1], &val);
1613                         if (!diag)
1614                                 radix = (int) val;
1615                 }
1616         }
1617
1618         if (strcmp(argv[0], "mdr") == 0) {
1619                 int ret;
1620                 last_addr = addr;
1621                 ret = kdb_mdr(addr, mdcount);
1622                 last_addr += mdcount;
1623                 last_repeat = mdcount;
1624                 last_bytesperword = bytesperword; // to make REPEAT happy
1625                 return ret;
1626         }
1627
1628         switch (radix) {
1629         case 10:
1630                 fmtchar = 'd';
1631                 break;
1632         case 16:
1633                 fmtchar = 'x';
1634                 break;
1635         case 8:
1636                 fmtchar = 'o';
1637                 break;
1638         default:
1639                 return KDB_BADRADIX;
1640         }
1641
1642         last_radix = radix;
1643
1644         if (bytesperword > KDB_WORD_SIZE)
1645                 return KDB_BADWIDTH;
1646
1647         switch (bytesperword) {
1648         case 8:
1649                 sprintf(fmtstr, "%%16.16l%c ", fmtchar);
1650                 break;
1651         case 4:
1652                 sprintf(fmtstr, "%%8.8l%c ", fmtchar);
1653                 break;
1654         case 2:
1655                 sprintf(fmtstr, "%%4.4l%c ", fmtchar);
1656                 break;
1657         case 1:
1658                 sprintf(fmtstr, "%%2.2l%c ", fmtchar);
1659                 break;
1660         default:
1661                 return KDB_BADWIDTH;
1662         }
1663
1664         last_repeat = repeat;
1665         last_bytesperword = bytesperword;
1666
1667         if (strcmp(argv[0], "mds") == 0) {
1668                 symbolic = 1;
1669                 /* Do not save these changes as last_*, they are temporary mds
1670                  * overrides.
1671                  */
1672                 bytesperword = KDB_WORD_SIZE;
1673                 repeat = mdcount;
1674                 kdbgetintenv("NOSECT", &nosect);
1675         }
1676
1677         /* Round address down modulo BYTESPERWORD */
1678
1679         addr &= ~(bytesperword-1);
1680
1681         while (repeat > 0) {
1682                 unsigned long a;
1683                 int n, z, num = (symbolic ? 1 : (16 / bytesperword));
1684
1685                 if (KDB_FLAG(CMD_INTERRUPT))
1686                         return 0;
1687                 for (a = addr, z = 0; z < repeat; a += bytesperword, ++z) {
1688                         if (phys) {
1689                                 if (kdb_getphysword(&word, a, bytesperword)
1690                                                 || word)
1691                                         break;
1692                         } else if (kdb_getword(&word, a, bytesperword) || word)
1693                                 break;
1694                 }
1695                 n = min(num, repeat);
1696                 kdb_md_line(fmtstr, addr, symbolic, nosect, bytesperword,
1697                             num, repeat, phys);
1698                 addr += bytesperword * n;
1699                 repeat -= n;
1700                 z = (z + num - 1) / num;
1701                 if (z > 2) {
1702                         int s = num * (z-2);
1703                         kdb_printf(kdb_machreg_fmt0 "-" kdb_machreg_fmt0
1704                                    " zero suppressed\n",
1705                                 addr, addr + bytesperword * s - 1);
1706                         addr += bytesperword * s;
1707                         repeat -= s;
1708                 }
1709         }
1710         last_addr = addr;
1711
1712         return 0;
1713 }
1714
1715 /*
1716  * kdb_mm - This function implements the 'mm' command.
1717  *      mm address-expression new-value
1718  * Remarks:
1719  *      mm works on machine words, mmW works on bytes.
1720  */
1721 static int kdb_mm(int argc, const char **argv)
1722 {
1723         int diag;
1724         unsigned long addr;
1725         long offset = 0;
1726         unsigned long contents;
1727         int nextarg;
1728         int width;
1729
1730         if (argv[0][2] && !isdigit(argv[0][2]))
1731                 return KDB_NOTFOUND;
1732
1733         if (argc < 2)
1734                 return KDB_ARGCOUNT;
1735
1736         nextarg = 1;
1737         diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
1738         if (diag)
1739                 return diag;
1740
1741         if (nextarg > argc)
1742                 return KDB_ARGCOUNT;
1743         diag = kdbgetaddrarg(argc, argv, &nextarg, &contents, NULL, NULL);
1744         if (diag)
1745                 return diag;
1746
1747         if (nextarg != argc + 1)
1748                 return KDB_ARGCOUNT;
1749
1750         width = argv[0][2] ? (argv[0][2] - '0') : (KDB_WORD_SIZE);
1751         diag = kdb_putword(addr, contents, width);
1752         if (diag)
1753                 return diag;
1754
1755         kdb_printf(kdb_machreg_fmt " = " kdb_machreg_fmt "\n", addr, contents);
1756
1757         return 0;
1758 }
1759
1760 /*
1761  * kdb_go - This function implements the 'go' command.
1762  *      go [address-expression]
1763  */
1764 static int kdb_go(int argc, const char **argv)
1765 {
1766         unsigned long addr;
1767         int diag;
1768         int nextarg;
1769         long offset;
1770
1771         if (raw_smp_processor_id() != kdb_initial_cpu) {
1772                 kdb_printf("go must execute on the entry cpu, "
1773                            "please use \"cpu %d\" and then execute go\n",
1774                            kdb_initial_cpu);
1775                 return KDB_BADCPUNUM;
1776         }
1777         if (argc == 1) {
1778                 nextarg = 1;
1779                 diag = kdbgetaddrarg(argc, argv, &nextarg,
1780                                      &addr, &offset, NULL);
1781                 if (diag)
1782                         return diag;
1783         } else if (argc) {
1784                 return KDB_ARGCOUNT;
1785         }
1786
1787         diag = KDB_CMD_GO;
1788         if (KDB_FLAG(CATASTROPHIC)) {
1789                 kdb_printf("Catastrophic error detected\n");
1790                 kdb_printf("kdb_continue_catastrophic=%d, ",
1791                         kdb_continue_catastrophic);
1792                 if (kdb_continue_catastrophic == 0 && kdb_go_count++ == 0) {
1793                         kdb_printf("type go a second time if you really want "
1794                                    "to continue\n");
1795                         return 0;
1796                 }
1797                 if (kdb_continue_catastrophic == 2) {
1798                         kdb_printf("forcing reboot\n");
1799                         kdb_reboot(0, NULL);
1800                 }
1801                 kdb_printf("attempting to continue\n");
1802         }
1803         return diag;
1804 }
1805
1806 /*
1807  * kdb_rd - This function implements the 'rd' command.
1808  */
1809 static int kdb_rd(int argc, const char **argv)
1810 {
1811         int len = kdb_check_regs();
1812 #if DBG_MAX_REG_NUM > 0
1813         int i;
1814         char *rname;
1815         int rsize;
1816         u64 reg64;
1817         u32 reg32;
1818         u16 reg16;
1819         u8 reg8;
1820
1821         if (len)
1822                 return len;
1823
1824         for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1825                 rsize = dbg_reg_def[i].size * 2;
1826                 if (rsize > 16)
1827                         rsize = 2;
1828                 if (len + strlen(dbg_reg_def[i].name) + 4 + rsize > 80) {
1829                         len = 0;
1830                         kdb_printf("\n");
1831                 }
1832                 if (len)
1833                         len += kdb_printf("  ");
1834                 switch(dbg_reg_def[i].size * 8) {
1835                 case 8:
1836                         rname = dbg_get_reg(i, &reg8, kdb_current_regs);
1837                         if (!rname)
1838                                 break;
1839                         len += kdb_printf("%s: %02x", rname, reg8);
1840                         break;
1841                 case 16:
1842                         rname = dbg_get_reg(i, &reg16, kdb_current_regs);
1843                         if (!rname)
1844                                 break;
1845                         len += kdb_printf("%s: %04x", rname, reg16);
1846                         break;
1847                 case 32:
1848                         rname = dbg_get_reg(i, &reg32, kdb_current_regs);
1849                         if (!rname)
1850                                 break;
1851                         len += kdb_printf("%s: %08x", rname, reg32);
1852                         break;
1853                 case 64:
1854                         rname = dbg_get_reg(i, &reg64, kdb_current_regs);
1855                         if (!rname)
1856                                 break;
1857                         len += kdb_printf("%s: %016llx", rname, reg64);
1858                         break;
1859                 default:
1860                         len += kdb_printf("%s: ??", dbg_reg_def[i].name);
1861                 }
1862         }
1863         kdb_printf("\n");
1864 #else
1865         if (len)
1866                 return len;
1867
1868         kdb_dumpregs(kdb_current_regs);
1869 #endif
1870         return 0;
1871 }
1872
1873 /*
1874  * kdb_rm - This function implements the 'rm' (register modify)  command.
1875  *      rm register-name new-contents
1876  * Remarks:
1877  *      Allows register modification with the same restrictions as gdb
1878  */
1879 static int kdb_rm(int argc, const char **argv)
1880 {
1881 #if DBG_MAX_REG_NUM > 0
1882         int diag;
1883         const char *rname;
1884         int i;
1885         u64 reg64;
1886         u32 reg32;
1887         u16 reg16;
1888         u8 reg8;
1889
1890         if (argc != 2)
1891                 return KDB_ARGCOUNT;
1892         /*
1893          * Allow presence or absence of leading '%' symbol.
1894          */
1895         rname = argv[1];
1896         if (*rname == '%')
1897                 rname++;
1898
1899         diag = kdbgetu64arg(argv[2], &reg64);
1900         if (diag)
1901                 return diag;
1902
1903         diag = kdb_check_regs();
1904         if (diag)
1905                 return diag;
1906
1907         diag = KDB_BADREG;
1908         for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1909                 if (strcmp(rname, dbg_reg_def[i].name) == 0) {
1910                         diag = 0;
1911                         break;
1912                 }
1913         }
1914         if (!diag) {
1915                 switch(dbg_reg_def[i].size * 8) {
1916                 case 8:
1917                         reg8 = reg64;
1918                         dbg_set_reg(i, &reg8, kdb_current_regs);
1919                         break;
1920                 case 16:
1921                         reg16 = reg64;
1922                         dbg_set_reg(i, &reg16, kdb_current_regs);
1923                         break;
1924                 case 32:
1925                         reg32 = reg64;
1926                         dbg_set_reg(i, &reg32, kdb_current_regs);
1927                         break;
1928                 case 64:
1929                         dbg_set_reg(i, &reg64, kdb_current_regs);
1930                         break;
1931                 }
1932         }
1933         return diag;
1934 #else
1935         kdb_printf("ERROR: Register set currently not implemented\n");
1936     return 0;
1937 #endif
1938 }
1939
1940 #if defined(CONFIG_MAGIC_SYSRQ)
1941 /*
1942  * kdb_sr - This function implements the 'sr' (SYSRQ key) command
1943  *      which interfaces to the soi-disant MAGIC SYSRQ functionality.
1944  *              sr <magic-sysrq-code>
1945  */
1946 static int kdb_sr(int argc, const char **argv)
1947 {
1948         bool check_mask =
1949             !kdb_check_flags(KDB_ENABLE_ALL, kdb_cmd_enabled, false);
1950
1951         if (argc != 1)
1952                 return KDB_ARGCOUNT;
1953
1954         kdb_trap_printk++;
1955         __handle_sysrq(*argv[1], check_mask);
1956         kdb_trap_printk--;
1957
1958         return 0;
1959 }
1960 #endif  /* CONFIG_MAGIC_SYSRQ */
1961
1962 /*
1963  * kdb_ef - This function implements the 'regs' (display exception
1964  *      frame) command.  This command takes an address and expects to
1965  *      find an exception frame at that address, formats and prints
1966  *      it.
1967  *              regs address-expression
1968  * Remarks:
1969  *      Not done yet.
1970  */
1971 static int kdb_ef(int argc, const char **argv)
1972 {
1973         int diag;
1974         unsigned long addr;
1975         long offset;
1976         int nextarg;
1977
1978         if (argc != 1)
1979                 return KDB_ARGCOUNT;
1980
1981         nextarg = 1;
1982         diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
1983         if (diag)
1984                 return diag;
1985         show_regs((struct pt_regs *)addr);
1986         return 0;
1987 }
1988
1989 /*
1990  * kdb_env - This function implements the 'env' command.  Display the
1991  *      current environment variables.
1992  */
1993
1994 static int kdb_env(int argc, const char **argv)
1995 {
1996         kdb_printenv();
1997
1998         if (KDB_DEBUG(MASK))
1999                 kdb_printf("KDBDEBUG=0x%x\n",
2000                         (kdb_flags & KDB_DEBUG(MASK)) >> KDB_DEBUG_FLAG_SHIFT);
2001
2002         return 0;
2003 }
2004
2005 #ifdef CONFIG_PRINTK
2006 /*
2007  * kdb_dmesg - This function implements the 'dmesg' command to display
2008  *      the contents of the syslog buffer.
2009  *              dmesg [lines] [adjust]
2010  */
2011 static int kdb_dmesg(int argc, const char **argv)
2012 {
2013         int diag;
2014         int logging;
2015         int lines = 0;
2016         int adjust = 0;
2017         int n = 0;
2018         int skip = 0;
2019         struct kmsg_dump_iter iter;
2020         size_t len;
2021         char buf[201];
2022
2023         if (argc > 2)
2024                 return KDB_ARGCOUNT;
2025         if (argc) {
2026                 if (kstrtoint(argv[1], 0, &lines))
2027                         lines = 0;
2028                 if (argc > 1 && (kstrtoint(argv[2], 0, &adjust) || adjust < 0))
2029                         adjust = 0;
2030         }
2031
2032         /* disable LOGGING if set */
2033         diag = kdbgetintenv("LOGGING", &logging);
2034         if (!diag && logging) {
2035                 const char *setargs[] = { "set", "LOGGING", "0" };
2036                 kdb_set(2, setargs);
2037         }
2038
2039         kmsg_dump_rewind(&iter);
2040         while (kmsg_dump_get_line(&iter, 1, NULL, 0, NULL))
2041                 n++;
2042
2043         if (lines < 0) {
2044                 if (adjust >= n)
2045                         kdb_printf("buffer only contains %d lines, nothing "
2046                                    "printed\n", n);
2047                 else if (adjust - lines >= n)
2048                         kdb_printf("buffer only contains %d lines, last %d "
2049                                    "lines printed\n", n, n - adjust);
2050                 skip = adjust;
2051                 lines = abs(lines);
2052         } else if (lines > 0) {
2053                 skip = n - lines - adjust;
2054                 lines = abs(lines);
2055                 if (adjust >= n) {
2056                         kdb_printf("buffer only contains %d lines, "
2057                                    "nothing printed\n", n);
2058                         skip = n;
2059                 } else if (skip < 0) {
2060                         lines += skip;
2061                         skip = 0;
2062                         kdb_printf("buffer only contains %d lines, first "
2063                                    "%d lines printed\n", n, lines);
2064                 }
2065         } else {
2066                 lines = n;
2067         }
2068
2069         if (skip >= n || skip < 0)
2070                 return 0;
2071
2072         kmsg_dump_rewind(&iter);
2073         while (kmsg_dump_get_line(&iter, 1, buf, sizeof(buf), &len)) {
2074                 if (skip) {
2075                         skip--;
2076                         continue;
2077                 }
2078                 if (!lines--)
2079                         break;
2080                 if (KDB_FLAG(CMD_INTERRUPT))
2081                         return 0;
2082
2083                 kdb_printf("%.*s\n", (int)len - 1, buf);
2084         }
2085
2086         return 0;
2087 }
2088 #endif /* CONFIG_PRINTK */
2089 /*
2090  * kdb_cpu - This function implements the 'cpu' command.
2091  *      cpu     [<cpunum>]
2092  * Returns:
2093  *      KDB_CMD_CPU for success, a kdb diagnostic if error
2094  */
2095 static void kdb_cpu_status(void)
2096 {
2097         int i, start_cpu, first_print = 1;
2098         char state, prev_state = '?';
2099
2100         kdb_printf("Currently on cpu %d\n", raw_smp_processor_id());
2101         kdb_printf("Available cpus: ");
2102         for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
2103                 if (!cpu_online(i)) {
2104                         state = 'F';    /* cpu is offline */
2105                 } else if (!kgdb_info[i].enter_kgdb) {
2106                         state = 'D';    /* cpu is online but unresponsive */
2107                 } else {
2108                         state = ' ';    /* cpu is responding to kdb */
2109                         if (kdb_task_state_char(KDB_TSK(i)) == '-')
2110                                 state = '-';    /* idle task */
2111                 }
2112                 if (state != prev_state) {
2113                         if (prev_state != '?') {
2114                                 if (!first_print)
2115                                         kdb_printf(", ");
2116                                 first_print = 0;
2117                                 kdb_printf("%d", start_cpu);
2118                                 if (start_cpu < i-1)
2119                                         kdb_printf("-%d", i-1);
2120                                 if (prev_state != ' ')
2121                                         kdb_printf("(%c)", prev_state);
2122                         }
2123                         prev_state = state;
2124                         start_cpu = i;
2125                 }
2126         }
2127         /* print the trailing cpus, ignoring them if they are all offline */
2128         if (prev_state != 'F') {
2129                 if (!first_print)
2130                         kdb_printf(", ");
2131                 kdb_printf("%d", start_cpu);
2132                 if (start_cpu < i-1)
2133                         kdb_printf("-%d", i-1);
2134                 if (prev_state != ' ')
2135                         kdb_printf("(%c)", prev_state);
2136         }
2137         kdb_printf("\n");
2138 }
2139
2140 static int kdb_cpu(int argc, const char **argv)
2141 {
2142         unsigned long cpunum;
2143         int diag;
2144
2145         if (argc == 0) {
2146                 kdb_cpu_status();
2147                 return 0;
2148         }
2149
2150         if (argc != 1)
2151                 return KDB_ARGCOUNT;
2152
2153         diag = kdbgetularg(argv[1], &cpunum);
2154         if (diag)
2155                 return diag;
2156
2157         /*
2158          * Validate cpunum
2159          */
2160         if ((cpunum >= CONFIG_NR_CPUS) || !kgdb_info[cpunum].enter_kgdb)
2161                 return KDB_BADCPUNUM;
2162
2163         dbg_switch_cpu = cpunum;
2164
2165         /*
2166          * Switch to other cpu
2167          */
2168         return KDB_CMD_CPU;
2169 }
2170
2171 /* The user may not realize that ps/bta with no parameters does not print idle
2172  * or sleeping system daemon processes, so tell them how many were suppressed.
2173  */
2174 void kdb_ps_suppressed(void)
2175 {
2176         int idle = 0, daemon = 0;
2177         unsigned long cpu;
2178         const struct task_struct *p, *g;
2179         for_each_online_cpu(cpu) {
2180                 p = curr_task(cpu);
2181                 if (kdb_task_state(p, "-"))
2182                         ++idle;
2183         }
2184         for_each_process_thread(g, p) {
2185                 if (kdb_task_state(p, "ims"))
2186                         ++daemon;
2187         }
2188         if (idle || daemon) {
2189                 if (idle)
2190                         kdb_printf("%d idle process%s (state -)%s\n",
2191                                    idle, idle == 1 ? "" : "es",
2192                                    daemon ? " and " : "");
2193                 if (daemon)
2194                         kdb_printf("%d sleeping system daemon (state [ims]) "
2195                                    "process%s", daemon,
2196                                    daemon == 1 ? "" : "es");
2197                 kdb_printf(" suppressed,\nuse 'ps A' to see all.\n");
2198         }
2199 }
2200
2201 void kdb_ps1(const struct task_struct *p)
2202 {
2203         int cpu;
2204         unsigned long tmp;
2205
2206         if (!p ||
2207             copy_from_kernel_nofault(&tmp, (char *)p, sizeof(unsigned long)))
2208                 return;
2209
2210         cpu = kdb_process_cpu(p);
2211         kdb_printf("0x%px %8d %8d  %d %4d   %c  0x%px %c%s\n",
2212                    (void *)p, p->pid, p->parent->pid,
2213                    kdb_task_has_cpu(p), kdb_process_cpu(p),
2214                    kdb_task_state_char(p),
2215                    (void *)(&p->thread),
2216                    p == curr_task(raw_smp_processor_id()) ? '*' : ' ',
2217                    p->comm);
2218         if (kdb_task_has_cpu(p)) {
2219                 if (!KDB_TSK(cpu)) {
2220                         kdb_printf("  Error: no saved data for this cpu\n");
2221                 } else {
2222                         if (KDB_TSK(cpu) != p)
2223                                 kdb_printf("  Error: does not match running "
2224                                    "process table (0x%px)\n", KDB_TSK(cpu));
2225                 }
2226         }
2227 }
2228
2229 /*
2230  * kdb_ps - This function implements the 'ps' command which shows a
2231  *          list of the active processes.
2232  *
2233  * ps [<state_chars>]   Show processes, optionally selecting only those whose
2234  *                      state character is found in <state_chars>.
2235  */
2236 static int kdb_ps(int argc, const char **argv)
2237 {
2238         struct task_struct *g, *p;
2239         const char *mask;
2240         unsigned long cpu;
2241
2242         if (argc == 0)
2243                 kdb_ps_suppressed();
2244         kdb_printf("%-*s      Pid   Parent [*] cpu State %-*s Command\n",
2245                 (int)(2*sizeof(void *))+2, "Task Addr",
2246                 (int)(2*sizeof(void *))+2, "Thread");
2247         mask = argc ? argv[1] : kdbgetenv("PS");
2248         /* Run the active tasks first */
2249         for_each_online_cpu(cpu) {
2250                 if (KDB_FLAG(CMD_INTERRUPT))
2251                         return 0;
2252                 p = curr_task(cpu);
2253                 if (kdb_task_state(p, mask))
2254                         kdb_ps1(p);
2255         }
2256         kdb_printf("\n");
2257         /* Now the real tasks */
2258         for_each_process_thread(g, p) {
2259                 if (KDB_FLAG(CMD_INTERRUPT))
2260                         return 0;
2261                 if (kdb_task_state(p, mask))
2262                         kdb_ps1(p);
2263         }
2264
2265         return 0;
2266 }
2267
2268 /*
2269  * kdb_pid - This function implements the 'pid' command which switches
2270  *      the currently active process.
2271  *              pid [<pid> | R]
2272  */
2273 static int kdb_pid(int argc, const char **argv)
2274 {
2275         struct task_struct *p;
2276         unsigned long val;
2277         int diag;
2278
2279         if (argc > 1)
2280                 return KDB_ARGCOUNT;
2281
2282         if (argc) {
2283                 if (strcmp(argv[1], "R") == 0) {
2284                         p = KDB_TSK(kdb_initial_cpu);
2285                 } else {
2286                         diag = kdbgetularg(argv[1], &val);
2287                         if (diag)
2288                                 return KDB_BADINT;
2289
2290                         p = find_task_by_pid_ns((pid_t)val,     &init_pid_ns);
2291                         if (!p) {
2292                                 kdb_printf("No task with pid=%d\n", (pid_t)val);
2293                                 return 0;
2294                         }
2295                 }
2296                 kdb_set_current_task(p);
2297         }
2298         kdb_printf("KDB current process is %s(pid=%d)\n",
2299                    kdb_current_task->comm,
2300                    kdb_current_task->pid);
2301
2302         return 0;
2303 }
2304
2305 static int kdb_kgdb(int argc, const char **argv)
2306 {
2307         return KDB_CMD_KGDB;
2308 }
2309
2310 /*
2311  * kdb_help - This function implements the 'help' and '?' commands.
2312  */
2313 static int kdb_help(int argc, const char **argv)
2314 {
2315         kdbtab_t *kt;
2316
2317         kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
2318         kdb_printf("-----------------------------"
2319                    "-----------------------------\n");
2320         list_for_each_entry(kt, &kdb_cmds_head, list_node) {
2321                 char *space = "";
2322                 if (KDB_FLAG(CMD_INTERRUPT))
2323                         return 0;
2324                 if (!kdb_check_flags(kt->flags, kdb_cmd_enabled, true))
2325                         continue;
2326                 if (strlen(kt->usage) > 20)
2327                         space = "\n                                    ";
2328                 kdb_printf("%-15.15s %-20s%s%s\n", kt->name,
2329                            kt->usage, space, kt->help);
2330         }
2331         return 0;
2332 }
2333
2334 /*
2335  * kdb_kill - This function implements the 'kill' commands.
2336  */
2337 static int kdb_kill(int argc, const char **argv)
2338 {
2339         long sig, pid;
2340         struct task_struct *p;
2341
2342         if (argc != 2)
2343                 return KDB_ARGCOUNT;
2344
2345         if (kstrtol(argv[1], 0, &sig))
2346                 return KDB_BADINT;
2347         if ((sig >= 0) || !valid_signal(-sig)) {
2348                 kdb_printf("Invalid signal parameter.<-signal>\n");
2349                 return 0;
2350         }
2351         sig = -sig;
2352
2353         if (kstrtol(argv[2], 0, &pid))
2354                 return KDB_BADINT;
2355         if (pid <= 0) {
2356                 kdb_printf("Process ID must be large than 0.\n");
2357                 return 0;
2358         }
2359
2360         /* Find the process. */
2361         p = find_task_by_pid_ns(pid, &init_pid_ns);
2362         if (!p) {
2363                 kdb_printf("The specified process isn't found.\n");
2364                 return 0;
2365         }
2366         p = p->group_leader;
2367         kdb_send_sig(p, sig);
2368         return 0;
2369 }
2370
2371 /*
2372  * Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
2373  * I cannot call that code directly from kdb, it has an unconditional
2374  * cli()/sti() and calls routines that take locks which can stop the debugger.
2375  */
2376 static void kdb_sysinfo(struct sysinfo *val)
2377 {
2378         u64 uptime = ktime_get_mono_fast_ns();
2379
2380         memset(val, 0, sizeof(*val));
2381         val->uptime = div_u64(uptime, NSEC_PER_SEC);
2382         val->loads[0] = avenrun[0];
2383         val->loads[1] = avenrun[1];
2384         val->loads[2] = avenrun[2];
2385         val->procs = nr_threads-1;
2386         si_meminfo(val);
2387
2388         return;
2389 }
2390
2391 /*
2392  * kdb_summary - This function implements the 'summary' command.
2393  */
2394 static int kdb_summary(int argc, const char **argv)
2395 {
2396         time64_t now;
2397         struct sysinfo val;
2398
2399         if (argc)
2400                 return KDB_ARGCOUNT;
2401
2402         kdb_printf("sysname    %s\n", init_uts_ns.name.sysname);
2403         kdb_printf("release    %s\n", init_uts_ns.name.release);
2404         kdb_printf("version    %s\n", init_uts_ns.name.version);
2405         kdb_printf("machine    %s\n", init_uts_ns.name.machine);
2406         kdb_printf("nodename   %s\n", init_uts_ns.name.nodename);
2407         kdb_printf("domainname %s\n", init_uts_ns.name.domainname);
2408
2409         now = __ktime_get_real_seconds();
2410         kdb_printf("date       %ptTs tz_minuteswest %d\n", &now, sys_tz.tz_minuteswest);
2411         kdb_sysinfo(&val);
2412         kdb_printf("uptime     ");
2413         if (val.uptime > (24*60*60)) {
2414                 int days = val.uptime / (24*60*60);
2415                 val.uptime %= (24*60*60);
2416                 kdb_printf("%d day%s ", days, str_plural(days));
2417         }
2418         kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
2419
2420         kdb_printf("load avg   %ld.%02ld %ld.%02ld %ld.%02ld\n",
2421                 LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
2422                 LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
2423                 LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
2424
2425         /* Display in kilobytes */
2426 #define K(x) ((x) << (PAGE_SHIFT - 10))
2427         kdb_printf("\nMemTotal:       %8lu kB\nMemFree:        %8lu kB\n"
2428                    "Buffers:        %8lu kB\n",
2429                    K(val.totalram), K(val.freeram), K(val.bufferram));
2430         return 0;
2431 }
2432
2433 /*
2434  * kdb_per_cpu - This function implements the 'per_cpu' command.
2435  */
2436 static int kdb_per_cpu(int argc, const char **argv)
2437 {
2438         char fmtstr[64];
2439         int cpu, diag, nextarg = 1;
2440         unsigned long addr, symaddr, val, bytesperword = 0, whichcpu = ~0UL;
2441
2442         if (argc < 1 || argc > 3)
2443                 return KDB_ARGCOUNT;
2444
2445         diag = kdbgetaddrarg(argc, argv, &nextarg, &symaddr, NULL, NULL);
2446         if (diag)
2447                 return diag;
2448
2449         if (argc >= 2) {
2450                 diag = kdbgetularg(argv[2], &bytesperword);
2451                 if (diag)
2452                         return diag;
2453         }
2454         if (!bytesperword)
2455                 bytesperword = KDB_WORD_SIZE;
2456         else if (bytesperword > KDB_WORD_SIZE)
2457                 return KDB_BADWIDTH;
2458         sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
2459         if (argc >= 3) {
2460                 diag = kdbgetularg(argv[3], &whichcpu);
2461                 if (diag)
2462                         return diag;
2463                 if (whichcpu >= nr_cpu_ids || !cpu_online(whichcpu)) {
2464                         kdb_printf("cpu %ld is not online\n", whichcpu);
2465                         return KDB_BADCPUNUM;
2466                 }
2467         }
2468
2469         /* Most architectures use __per_cpu_offset[cpu], some use
2470          * __per_cpu_offset(cpu), smp has no __per_cpu_offset.
2471          */
2472 #ifdef  __per_cpu_offset
2473 #define KDB_PCU(cpu) __per_cpu_offset(cpu)
2474 #else
2475 #ifdef  CONFIG_SMP
2476 #define KDB_PCU(cpu) __per_cpu_offset[cpu]
2477 #else
2478 #define KDB_PCU(cpu) 0
2479 #endif
2480 #endif
2481         for_each_online_cpu(cpu) {
2482                 if (KDB_FLAG(CMD_INTERRUPT))
2483                         return 0;
2484
2485                 if (whichcpu != ~0UL && whichcpu != cpu)
2486                         continue;
2487                 addr = symaddr + KDB_PCU(cpu);
2488                 diag = kdb_getword(&val, addr, bytesperword);
2489                 if (diag) {
2490                         kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to "
2491                                    "read, diag=%d\n", cpu, addr, diag);
2492                         continue;
2493                 }
2494                 kdb_printf("%5d ", cpu);
2495                 kdb_md_line(fmtstr, addr,
2496                         bytesperword == KDB_WORD_SIZE,
2497                         1, bytesperword, 1, 1, 0);
2498         }
2499 #undef KDB_PCU
2500         return 0;
2501 }
2502
2503 /*
2504  * display help for the use of cmd | grep pattern
2505  */
2506 static int kdb_grep_help(int argc, const char **argv)
2507 {
2508         kdb_printf("Usage of  cmd args | grep pattern:\n");
2509         kdb_printf("  Any command's output may be filtered through an ");
2510         kdb_printf("emulated 'pipe'.\n");
2511         kdb_printf("  'grep' is just a key word.\n");
2512         kdb_printf("  The pattern may include a very limited set of "
2513                    "metacharacters:\n");
2514         kdb_printf("   pattern or ^pattern or pattern$ or ^pattern$\n");
2515         kdb_printf("  And if there are spaces in the pattern, you may "
2516                    "quote it:\n");
2517         kdb_printf("   \"pat tern\" or \"^pat tern\" or \"pat tern$\""
2518                    " or \"^pat tern$\"\n");
2519         return 0;
2520 }
2521
2522 /**
2523  * kdb_register() - This function is used to register a kernel debugger
2524  *                  command.
2525  * @cmd: pointer to kdb command
2526  *
2527  * Note that it's the job of the caller to keep the memory for the cmd
2528  * allocated until unregister is called.
2529  */
2530 int kdb_register(kdbtab_t *cmd)
2531 {
2532         kdbtab_t *kp;
2533
2534         list_for_each_entry(kp, &kdb_cmds_head, list_node) {
2535                 if (strcmp(kp->name, cmd->name) == 0) {
2536                         kdb_printf("Duplicate kdb cmd: %s, func %p help %s\n",
2537                                    cmd->name, cmd->func, cmd->help);
2538                         return 1;
2539                 }
2540         }
2541
2542         list_add_tail(&cmd->list_node, &kdb_cmds_head);
2543         return 0;
2544 }
2545 EXPORT_SYMBOL_GPL(kdb_register);
2546
2547 /**
2548  * kdb_register_table() - This function is used to register a kdb command
2549  *                        table.
2550  * @kp: pointer to kdb command table
2551  * @len: length of kdb command table
2552  */
2553 void kdb_register_table(kdbtab_t *kp, size_t len)
2554 {
2555         while (len--) {
2556                 list_add_tail(&kp->list_node, &kdb_cmds_head);
2557                 kp++;
2558         }
2559 }
2560
2561 /**
2562  * kdb_unregister() - This function is used to unregister a kernel debugger
2563  *                    command. It is generally called when a module which
2564  *                    implements kdb command is unloaded.
2565  * @cmd: pointer to kdb command
2566  */
2567 void kdb_unregister(kdbtab_t *cmd)
2568 {
2569         list_del(&cmd->list_node);
2570 }
2571 EXPORT_SYMBOL_GPL(kdb_unregister);
2572
2573 static kdbtab_t maintab[] = {
2574         {       .name = "md",
2575                 .func = kdb_md,
2576                 .usage = "<vaddr>",
2577                 .help = "Display Memory Contents, also mdWcN, e.g. md8c1",
2578                 .minlen = 1,
2579                 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2580         },
2581         {       .name = "mdr",
2582                 .func = kdb_md,
2583                 .usage = "<vaddr> <bytes>",
2584                 .help = "Display Raw Memory",
2585                 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2586         },
2587         {       .name = "mdp",
2588                 .func = kdb_md,
2589                 .usage = "<paddr> <bytes>",
2590                 .help = "Display Physical Memory",
2591                 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2592         },
2593         {       .name = "mds",
2594                 .func = kdb_md,
2595                 .usage = "<vaddr>",
2596                 .help = "Display Memory Symbolically",
2597                 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2598         },
2599         {       .name = "mm",
2600                 .func = kdb_mm,
2601                 .usage = "<vaddr> <contents>",
2602                 .help = "Modify Memory Contents",
2603                 .flags = KDB_ENABLE_MEM_WRITE | KDB_REPEAT_NO_ARGS,
2604         },
2605         {       .name = "go",
2606                 .func = kdb_go,
2607                 .usage = "[<vaddr>]",
2608                 .help = "Continue Execution",
2609                 .minlen = 1,
2610                 .flags = KDB_ENABLE_REG_WRITE |
2611                              KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2612         },
2613         {       .name = "rd",
2614                 .func = kdb_rd,
2615                 .usage = "",
2616                 .help = "Display Registers",
2617                 .flags = KDB_ENABLE_REG_READ,
2618         },
2619         {       .name = "rm",
2620                 .func = kdb_rm,
2621                 .usage = "<reg> <contents>",
2622                 .help = "Modify Registers",
2623                 .flags = KDB_ENABLE_REG_WRITE,
2624         },
2625         {       .name = "ef",
2626                 .func = kdb_ef,
2627                 .usage = "<vaddr>",
2628                 .help = "Display exception frame",
2629                 .flags = KDB_ENABLE_MEM_READ,
2630         },
2631         {       .name = "bt",
2632                 .func = kdb_bt,
2633                 .usage = "[<vaddr>]",
2634                 .help = "Stack traceback",
2635                 .minlen = 1,
2636                 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2637         },
2638         {       .name = "btp",
2639                 .func = kdb_bt,
2640                 .usage = "<pid>",
2641                 .help = "Display stack for process <pid>",
2642                 .flags = KDB_ENABLE_INSPECT,
2643         },
2644         {       .name = "bta",
2645                 .func = kdb_bt,
2646                 .usage = "[<state_chars>|A]",
2647                 .help = "Backtrace all processes whose state matches",
2648                 .flags = KDB_ENABLE_INSPECT,
2649         },
2650         {       .name = "btc",
2651                 .func = kdb_bt,
2652                 .usage = "",
2653                 .help = "Backtrace current process on each cpu",
2654                 .flags = KDB_ENABLE_INSPECT,
2655         },
2656         {       .name = "btt",
2657                 .func = kdb_bt,
2658                 .usage = "<vaddr>",
2659                 .help = "Backtrace process given its struct task address",
2660                 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2661         },
2662         {       .name = "env",
2663                 .func = kdb_env,
2664                 .usage = "",
2665                 .help = "Show environment variables",
2666                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2667         },
2668         {       .name = "set",
2669                 .func = kdb_set,
2670                 .usage = "",
2671                 .help = "Set environment variables",
2672                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2673         },
2674         {       .name = "help",
2675                 .func = kdb_help,
2676                 .usage = "",
2677                 .help = "Display Help Message",
2678                 .minlen = 1,
2679                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2680         },
2681         {       .name = "?",
2682                 .func = kdb_help,
2683                 .usage = "",
2684                 .help = "Display Help Message",
2685                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2686         },
2687         {       .name = "cpu",
2688                 .func = kdb_cpu,
2689                 .usage = "<cpunum>",
2690                 .help = "Switch to new cpu",
2691                 .flags = KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2692         },
2693         {       .name = "kgdb",
2694                 .func = kdb_kgdb,
2695                 .usage = "",
2696                 .help = "Enter kgdb mode",
2697                 .flags = 0,
2698         },
2699         {       .name = "ps",
2700                 .func = kdb_ps,
2701                 .usage = "[<state_chars>|A]",
2702                 .help = "Display active task list",
2703                 .flags = KDB_ENABLE_INSPECT,
2704         },
2705         {       .name = "pid",
2706                 .func = kdb_pid,
2707                 .usage = "<pidnum>",
2708                 .help = "Switch to another task",
2709                 .flags = KDB_ENABLE_INSPECT,
2710         },
2711         {       .name = "reboot",
2712                 .func = kdb_reboot,
2713                 .usage = "",
2714                 .help = "Reboot the machine immediately",
2715                 .flags = KDB_ENABLE_REBOOT,
2716         },
2717 #if defined(CONFIG_MODULES)
2718         {       .name = "lsmod",
2719                 .func = kdb_lsmod,
2720                 .usage = "",
2721                 .help = "List loaded kernel modules",
2722                 .flags = KDB_ENABLE_INSPECT,
2723         },
2724 #endif
2725 #if defined(CONFIG_MAGIC_SYSRQ)
2726         {       .name = "sr",
2727                 .func = kdb_sr,
2728                 .usage = "<key>",
2729                 .help = "Magic SysRq key",
2730                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2731         },
2732 #endif
2733 #if defined(CONFIG_PRINTK)
2734         {       .name = "dmesg",
2735                 .func = kdb_dmesg,
2736                 .usage = "[lines]",
2737                 .help = "Display syslog buffer",
2738                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2739         },
2740 #endif
2741         {       .name = "defcmd",
2742                 .func = kdb_defcmd,
2743                 .usage = "name \"usage\" \"help\"",
2744                 .help = "Define a set of commands, down to endefcmd",
2745                 /*
2746                  * Macros are always safe because when executed each
2747                  * internal command re-enters kdb_parse() and is safety
2748                  * checked individually.
2749                  */
2750                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2751         },
2752         {       .name = "kill",
2753                 .func = kdb_kill,
2754                 .usage = "<-signal> <pid>",
2755                 .help = "Send a signal to a process",
2756                 .flags = KDB_ENABLE_SIGNAL,
2757         },
2758         {       .name = "summary",
2759                 .func = kdb_summary,
2760                 .usage = "",
2761                 .help = "Summarize the system",
2762                 .minlen = 4,
2763                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2764         },
2765         {       .name = "per_cpu",
2766                 .func = kdb_per_cpu,
2767                 .usage = "<sym> [<bytes>] [<cpu>]",
2768                 .help = "Display per_cpu variables",
2769                 .minlen = 3,
2770                 .flags = KDB_ENABLE_MEM_READ,
2771         },
2772         {       .name = "grephelp",
2773                 .func = kdb_grep_help,
2774                 .usage = "",
2775                 .help = "Display help on | grep",
2776                 .flags = KDB_ENABLE_ALWAYS_SAFE,
2777         },
2778 };
2779
2780 /* Initialize the kdb command table. */
2781 static void __init kdb_inittab(void)
2782 {
2783         kdb_register_table(maintab, ARRAY_SIZE(maintab));
2784 }
2785
2786 /* Execute any commands defined in kdb_cmds.  */
2787 static void __init kdb_cmd_init(void)
2788 {
2789         int i, diag;
2790         for (i = 0; kdb_cmds[i]; ++i) {
2791                 diag = kdb_parse(kdb_cmds[i]);
2792                 if (diag)
2793                         kdb_printf("kdb command %s failed, kdb diag %d\n",
2794                                 kdb_cmds[i], diag);
2795         }
2796         if (defcmd_in_progress) {
2797                 kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
2798                 kdb_parse("endefcmd");
2799         }
2800 }
2801
2802 /* Initialize kdb_printf, breakpoint tables and kdb state */
2803 void __init kdb_init(int lvl)
2804 {
2805         static int kdb_init_lvl = KDB_NOT_INITIALIZED;
2806         int i;
2807
2808         if (kdb_init_lvl == KDB_INIT_FULL || lvl <= kdb_init_lvl)
2809                 return;
2810         for (i = kdb_init_lvl; i < lvl; i++) {
2811                 switch (i) {
2812                 case KDB_NOT_INITIALIZED:
2813                         kdb_inittab();          /* Initialize Command Table */
2814                         kdb_initbptab();        /* Initialize Breakpoints */
2815                         break;
2816                 case KDB_INIT_EARLY:
2817                         kdb_cmd_init();         /* Build kdb_cmds tables */
2818                         break;
2819                 }
2820         }
2821         kdb_init_lvl = lvl;
2822 }