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