2 * Kernel Debugger Architecture Independent Main Code
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
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.
14 #include <linux/ctype.h>
15 #include <linux/types.h>
16 #include <linux/string.h>
17 #include <linux/kernel.h>
18 #include <linux/kmsg_dump.h>
19 #include <linux/reboot.h>
20 #include <linux/sched.h>
21 #include <linux/sched/loadavg.h>
22 #include <linux/sched/stat.h>
23 #include <linux/sched/debug.h>
24 #include <linux/sysrq.h>
25 #include <linux/smp.h>
26 #include <linux/utsname.h>
27 #include <linux/vmalloc.h>
28 #include <linux/moduleparam.h>
30 #include <linux/init.h>
31 #include <linux/kallsyms.h>
32 #include <linux/kgdb.h>
33 #include <linux/kdb.h>
34 #include <linux/notifier.h>
35 #include <linux/interrupt.h>
36 #include <linux/delay.h>
37 #include <linux/nmi.h>
38 #include <linux/time.h>
39 #include <linux/ptrace.h>
40 #include <linux/sysctl.h>
41 #include <linux/cpu.h>
42 #include <linux/kdebug.h>
43 #include <linux/proc_fs.h>
44 #include <linux/uaccess.h>
45 #include <linux/slab.h>
46 #include <linux/security.h>
47 #include "kdb_private.h"
49 #undef MODULE_PARAM_PREFIX
50 #define MODULE_PARAM_PREFIX "kdb."
52 static int kdb_cmd_enabled = CONFIG_KDB_DEFAULT_ENABLE;
53 module_param_named(cmd_enable, kdb_cmd_enabled, int, 0600);
55 char kdb_grep_string[KDB_GREP_STRLEN];
56 int kdb_grepping_flag;
57 EXPORT_SYMBOL(kdb_grepping_flag);
59 int kdb_grep_trailing;
62 * Kernel debugger state flags
64 unsigned int kdb_flags;
67 * kdb_lock protects updates to kdb_initial_cpu. Used to
68 * single thread processors through the kernel debugger.
70 int kdb_initial_cpu = -1; /* cpu number that owns kdb */
72 int kdb_state; /* General KDB state */
74 struct task_struct *kdb_current_task;
75 struct pt_regs *kdb_current_regs;
77 const char *kdb_diemsg;
78 static int kdb_go_count;
79 #ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
80 static unsigned int kdb_continue_catastrophic =
81 CONFIG_KDB_CONTINUE_CATASTROPHIC;
83 static unsigned int kdb_continue_catastrophic;
86 /* kdb_cmds_head describes the available commands. */
87 static LIST_HEAD(kdb_cmds_head);
89 typedef struct _kdbmsg {
90 int km_diag; /* kdb diagnostic */
91 char *km_msg; /* Corresponding message text */
94 #define KDBMSG(msgnum, text) \
95 { KDB_##msgnum, text }
97 static kdbmsg_t kdbmsgs[] = {
98 KDBMSG(NOTFOUND, "Command Not Found"),
99 KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
100 KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, "
101 "8 is only allowed on 64 bit systems"),
102 KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
103 KDBMSG(NOTENV, "Cannot find environment variable"),
104 KDBMSG(NOENVVALUE, "Environment variable should have value"),
105 KDBMSG(NOTIMP, "Command not implemented"),
106 KDBMSG(ENVFULL, "Environment full"),
107 KDBMSG(KMALLOCFAILED, "Failed to allocate memory"),
108 KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
109 #ifdef CONFIG_CPU_XSCALE
110 KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
112 KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
114 KDBMSG(DUPBPT, "Duplicate breakpoint address"),
115 KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
116 KDBMSG(BADMODE, "Invalid IDMODE"),
117 KDBMSG(BADINT, "Illegal numeric value"),
118 KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
119 KDBMSG(BADREG, "Invalid register name"),
120 KDBMSG(BADCPUNUM, "Invalid cpu number"),
121 KDBMSG(BADLENGTH, "Invalid length field"),
122 KDBMSG(NOBP, "No Breakpoint exists"),
123 KDBMSG(BADADDR, "Invalid address"),
124 KDBMSG(NOPERM, "Permission denied"),
128 static const int __nkdb_err = ARRAY_SIZE(kdbmsgs);
132 * Initial environment. This is all kept static and local to this file.
133 * The entire environment is limited to a fixed number of entries
134 * (add more to __env[] if required)
137 static char *__env[31] = {
138 #if defined(CONFIG_SMP)
145 "MDCOUNT=8", /* lines of md output */
151 static const int __nenv = ARRAY_SIZE(__env);
154 * Update the permissions flags (kdb_cmd_enabled) to match the
155 * current lockdown state.
157 * Within this function the calls to security_locked_down() are "lazy". We
158 * avoid calling them if the current value of kdb_cmd_enabled already excludes
159 * flags that might be subject to lockdown. Additionally we deliberately check
160 * the lockdown flags independently (even though read lockdown implies write
161 * lockdown) since that results in both simpler code and clearer messages to
162 * the user on first-time debugger entry.
164 * The permission masks during a read+write lockdown permits the following
165 * flags: INSPECT, SIGNAL, REBOOT (and ALWAYS_SAFE).
167 * The INSPECT commands are not blocked during lockdown because they are
168 * not arbitrary memory reads. INSPECT covers the backtrace family (sometimes
169 * forcing them to have no arguments) and lsmod. These commands do expose
170 * some kernel state but do not allow the developer seated at the console to
171 * choose what state is reported. SIGNAL and REBOOT should not be controversial,
172 * given these are allowed for root during lockdown already.
174 static void kdb_check_for_lockdown(void)
176 const int write_flags = KDB_ENABLE_MEM_WRITE |
177 KDB_ENABLE_REG_WRITE |
178 KDB_ENABLE_FLOW_CTRL;
179 const int read_flags = KDB_ENABLE_MEM_READ |
182 bool need_to_lockdown_write = false;
183 bool need_to_lockdown_read = false;
185 if (kdb_cmd_enabled & (KDB_ENABLE_ALL | write_flags))
186 need_to_lockdown_write =
187 security_locked_down(LOCKDOWN_DBG_WRITE_KERNEL);
189 if (kdb_cmd_enabled & (KDB_ENABLE_ALL | read_flags))
190 need_to_lockdown_read =
191 security_locked_down(LOCKDOWN_DBG_READ_KERNEL);
193 /* De-compose KDB_ENABLE_ALL if required */
194 if (need_to_lockdown_write || need_to_lockdown_read)
195 if (kdb_cmd_enabled & KDB_ENABLE_ALL)
196 kdb_cmd_enabled = KDB_ENABLE_MASK & ~KDB_ENABLE_ALL;
198 if (need_to_lockdown_write)
199 kdb_cmd_enabled &= ~write_flags;
201 if (need_to_lockdown_read)
202 kdb_cmd_enabled &= ~read_flags;
206 * Check whether the flags of the current command, the permissions of the kdb
207 * console and the lockdown state allow a command to be run.
209 static bool kdb_check_flags(kdb_cmdflags_t flags, int permissions,
212 /* permissions comes from userspace so needs massaging slightly */
213 permissions &= KDB_ENABLE_MASK;
214 permissions |= KDB_ENABLE_ALWAYS_SAFE;
216 /* some commands change group when launched with no arguments */
218 permissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT;
220 flags |= KDB_ENABLE_ALL;
222 return permissions & flags;
226 * kdbgetenv - This function will return the character string value of
227 * an environment variable.
229 * match A character string representing an environment variable.
231 * NULL No environment variable matches 'match'
232 * char* Pointer to string value of environment variable.
234 char *kdbgetenv(const char *match)
237 int matchlen = strlen(match);
240 for (i = 0; i < __nenv; i++) {
246 if ((strncmp(match, e, matchlen) == 0)
247 && ((e[matchlen] == '\0')
248 || (e[matchlen] == '='))) {
249 char *cp = strchr(e, '=');
250 return cp ? ++cp : "";
257 * kdbgetulenv - This function will return the value of an unsigned
258 * long-valued environment variable.
260 * match A character string representing a numeric value
262 * *value the unsigned long representation of the env variable 'match'
264 * Zero on success, a kdb diagnostic on failure.
266 static int kdbgetulenv(const char *match, unsigned long *value)
270 ep = kdbgetenv(match);
274 return KDB_NOENVVALUE;
275 if (kstrtoul(ep, 0, value))
282 * kdbgetintenv - This function will return the value of an
283 * integer-valued environment variable.
285 * match A character string representing an integer-valued env variable
287 * *value the integer representation of the environment variable 'match'
289 * Zero on success, a kdb diagnostic on failure.
291 int kdbgetintenv(const char *match, int *value)
296 diag = kdbgetulenv(match, &val);
303 * kdb_setenv() - Alter an existing environment variable or create a new one.
304 * @var: Name of the variable
305 * @val: Value of the variable
307 * Return: Zero on success, a kdb diagnostic on failure.
309 static int kdb_setenv(const char *var, const char *val)
313 size_t varlen, vallen;
315 varlen = strlen(var);
316 vallen = strlen(val);
317 ep = kmalloc(varlen + vallen + 2, GFP_KDB);
319 return KDB_KMALLOCFAILED;
321 sprintf(ep, "%s=%s", var, val);
323 for (i = 0; i < __nenv; i++) {
325 && ((strncmp(__env[i], var, varlen) == 0)
326 && ((__env[i][varlen] == '\0')
327 || (__env[i][varlen] == '=')))) {
328 kfree_const(__env[i]);
335 * Wasn't existing variable. Fit into slot.
337 for (i = 0; i < __nenv-1; i++) {
338 if (__env[i] == (char *)0) {
348 * kdb_printenv() - Display the current environment variables.
350 static void kdb_printenv(void)
354 for (i = 0; i < __nenv; i++) {
356 kdb_printf("%s\n", __env[i]);
361 * kdbgetularg - This function will convert a numeric string into an
362 * unsigned long value.
364 * arg A character string representing a numeric value
366 * *value the unsigned long representation of arg.
368 * Zero on success, a kdb diagnostic on failure.
370 int kdbgetularg(const char *arg, unsigned long *value)
372 if (kstrtoul(arg, 0, value))
377 int kdbgetu64arg(const char *arg, u64 *value)
379 if (kstrtou64(arg, 0, value))
385 * kdb_set - This function implements the 'set' command. Alter an
386 * existing environment variable or create a new one.
388 int kdb_set(int argc, const char **argv)
391 * we can be invoked two ways:
392 * set var=value argv[1]="var", argv[2]="value"
393 * set var = value argv[1]="var", argv[2]="=", argv[3]="value"
394 * - if the latter, shift 'em down.
405 * Censor sensitive variables
407 if (strcmp(argv[1], "PROMPT") == 0 &&
408 !kdb_check_flags(KDB_ENABLE_MEM_READ, kdb_cmd_enabled, false))
412 * Check for internal variables
414 if (strcmp(argv[1], "KDBDEBUG") == 0) {
415 unsigned int debugflags;
418 ret = kstrtouint(argv[2], 0, &debugflags);
419 if (ret || debugflags & ~KDB_DEBUG_FLAG_MASK) {
420 kdb_printf("kdb: illegal debug flags '%s'\n",
424 kdb_flags = (kdb_flags & ~KDB_DEBUG(MASK))
425 | (debugflags << KDB_DEBUG_FLAG_SHIFT);
431 * Tokenizer squashed the '=' sign. argv[1] is variable
432 * name, argv[2] = value.
434 return kdb_setenv(argv[1], argv[2]);
437 static int kdb_check_regs(void)
439 if (!kdb_current_regs) {
440 kdb_printf("No current kdb registers."
441 " You may need to select another task\n");
448 * kdbgetaddrarg - This function is responsible for parsing an
449 * address-expression and returning the value of the expression,
450 * symbol name, and offset to the caller.
452 * The argument may consist of a numeric value (decimal or
453 * hexadecimal), a symbol name, a register name (preceded by the
454 * percent sign), an environment variable with a numeric value
455 * (preceded by a dollar sign) or a simple arithmetic expression
456 * consisting of a symbol name, +/-, and a numeric constant value
459 * argc - count of arguments in argv
460 * argv - argument vector
461 * *nextarg - index to next unparsed argument in argv[]
462 * regs - Register state at time of KDB entry
464 * *value - receives the value of the address-expression
465 * *offset - receives the offset specified, if any
466 * *name - receives the symbol name, if any
467 * *nextarg - index to next unparsed argument in argv[]
469 * zero is returned on success, a kdb diagnostic code is
472 int kdbgetaddrarg(int argc, const char **argv, int *nextarg,
473 unsigned long *value, long *offset,
477 unsigned long off = 0;
487 * If the enable flags prohibit both arbitrary memory access
488 * and flow control then there are no reasonable grounds to
489 * provide symbol lookup.
491 if (!kdb_check_flags(KDB_ENABLE_MEM_READ | KDB_ENABLE_FLOW_CTRL,
492 kdb_cmd_enabled, false))
496 * Process arguments which follow the following syntax:
498 * symbol | numeric-address [+/- numeric-offset]
500 * $environment-variable
506 symname = (char *)argv[*nextarg];
509 * If there is no whitespace between the symbol
510 * or address and the '+' or '-' symbols, we
511 * remember the character and replace it with a
512 * null so the symbol/value can be properly parsed
514 cp = strpbrk(symname, "+-");
520 if (symname[0] == '$') {
521 diag = kdbgetulenv(&symname[1], &addr);
524 } else if (symname[0] == '%') {
525 diag = kdb_check_regs();
528 /* Implement register values with % at a later time as it is
533 found = kdbgetsymval(symname, &symtab);
535 addr = symtab.sym_start;
537 diag = kdbgetularg(argv[*nextarg], &addr);
544 found = kdbnearsym(addr, &symtab);
552 if (offset && name && *name)
553 *offset = addr - symtab.sym_start;
555 if ((*nextarg > argc)
560 * check for +/- and offset
563 if (symbol == '\0') {
564 if ((argv[*nextarg][0] != '+')
565 && (argv[*nextarg][0] != '-')) {
567 * Not our argument. Return.
571 positive = (argv[*nextarg][0] == '+');
575 positive = (symbol == '+');
578 * Now there must be an offset!
580 if ((*nextarg > argc)
581 && (symbol == '\0')) {
582 return KDB_INVADDRFMT;
586 cp = (char *)argv[*nextarg];
590 diag = kdbgetularg(cp, &off);
606 static void kdb_cmderror(int diag)
611 kdb_printf("no error detected (diagnostic is %d)\n", diag);
615 for (i = 0; i < __nkdb_err; i++) {
616 if (kdbmsgs[i].km_diag == diag) {
617 kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
622 kdb_printf("Unknown diag %d\n", -diag);
626 * kdb_defcmd, kdb_defcmd2 - This function implements the 'defcmd'
627 * command which defines one command as a set of other commands,
628 * terminated by endefcmd. kdb_defcmd processes the initial
629 * 'defcmd' command, kdb_defcmd2 is invoked from kdb_parse for
630 * the following commands until 'endefcmd'.
632 * argc argument count
633 * argv argument vector
635 * zero for success, a kdb diagnostic if error
638 kdbtab_t cmd; /* Macro command */
639 struct list_head statements; /* Associated statement list */
642 struct kdb_macro_statement {
643 char *statement; /* Statement text */
644 struct list_head list_node; /* Statement list node */
647 static struct kdb_macro *kdb_macro;
648 static bool defcmd_in_progress;
650 /* Forward references */
651 static int kdb_exec_defcmd(int argc, const char **argv);
653 static int kdb_defcmd2(const char *cmdstr, const char *argv0)
655 struct kdb_macro_statement *kms;
660 if (strcmp(argv0, "endefcmd") == 0) {
661 defcmd_in_progress = false;
662 if (!list_empty(&kdb_macro->statements))
663 kdb_register(&kdb_macro->cmd);
667 kms = kmalloc(sizeof(*kms), GFP_KDB);
669 kdb_printf("Could not allocate new kdb macro command: %s\n",
674 kms->statement = kdb_strdup(cmdstr, GFP_KDB);
675 list_add_tail(&kms->list_node, &kdb_macro->statements);
680 static int kdb_defcmd(int argc, const char **argv)
684 if (defcmd_in_progress) {
685 kdb_printf("kdb: nested defcmd detected, assuming missing "
687 kdb_defcmd2("endefcmd", "endefcmd");
691 struct kdb_macro *kmp;
692 struct kdb_macro_statement *kms;
694 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
695 if (kp->func == kdb_exec_defcmd) {
696 kdb_printf("defcmd %s \"%s\" \"%s\"\n",
697 kp->name, kp->usage, kp->help);
698 kmp = container_of(kp, struct kdb_macro, cmd);
699 list_for_each_entry(kms, &kmp->statements,
701 kdb_printf("%s", kms->statement);
702 kdb_printf("endefcmd\n");
709 if (in_dbg_master()) {
710 kdb_printf("Command only available during kdb_init()\n");
713 kdb_macro = kzalloc(sizeof(*kdb_macro), GFP_KDB);
717 mp = &kdb_macro->cmd;
718 mp->func = kdb_exec_defcmd;
720 mp->flags = KDB_ENABLE_ALWAYS_SAFE;
721 mp->name = kdb_strdup(argv[1], GFP_KDB);
724 mp->usage = kdb_strdup(argv[2], GFP_KDB);
727 mp->help = kdb_strdup(argv[3], GFP_KDB);
730 if (mp->usage[0] == '"') {
731 strcpy(mp->usage, argv[2]+1);
732 mp->usage[strlen(mp->usage)-1] = '\0';
734 if (mp->help[0] == '"') {
735 strcpy(mp->help, argv[3]+1);
736 mp->help[strlen(mp->help)-1] = '\0';
739 INIT_LIST_HEAD(&kdb_macro->statements);
740 defcmd_in_progress = true;
749 kdb_printf("Could not allocate new kdb_macro entry for %s\n", argv[1]);
754 * kdb_exec_defcmd - Execute the set of commands associated with this
757 * argc argument count
758 * argv argument vector
760 * zero for success, a kdb diagnostic if error
762 static int kdb_exec_defcmd(int argc, const char **argv)
766 struct kdb_macro *kmp;
767 struct kdb_macro_statement *kms;
772 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
773 if (strcmp(kp->name, argv[0]) == 0)
776 if (list_entry_is_head(kp, &kdb_cmds_head, list_node)) {
777 kdb_printf("kdb_exec_defcmd: could not find commands for %s\n",
781 kmp = container_of(kp, struct kdb_macro, cmd);
782 list_for_each_entry(kms, &kmp->statements, list_node) {
784 * Recursive use of kdb_parse, do not use argv after this point.
787 kdb_printf("[%s]kdb> %s\n", kmp->cmd.name, kms->statement);
788 ret = kdb_parse(kms->statement);
795 /* Command history */
796 #define KDB_CMD_HISTORY_COUNT 32
797 #define CMD_BUFLEN 200 /* kdb_printf: max printline
799 static unsigned int cmd_head, cmd_tail;
800 static unsigned int cmdptr;
801 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
802 static char cmd_cur[CMD_BUFLEN];
805 * The "str" argument may point to something like | grep xyz
807 static void parse_grep(const char *str)
810 char *cp = (char *)str, *cp2;
812 /* sanity check: we should have been called with the \ first */
818 if (!str_has_prefix(cp, "grep ")) {
819 kdb_printf("invalid 'pipe', see grephelp\n");
825 cp2 = strchr(cp, '\n');
827 *cp2 = '\0'; /* remove the trailing newline */
830 kdb_printf("invalid 'pipe', see grephelp\n");
833 /* now cp points to a nonzero length search string */
835 /* allow it be "x y z" by removing the "'s - there must
838 cp2 = strchr(cp, '"');
840 kdb_printf("invalid quoted string, see grephelp\n");
843 *cp2 = '\0'; /* end the string where the 2nd " was */
845 kdb_grep_leading = 0;
847 kdb_grep_leading = 1;
851 kdb_grep_trailing = 0;
852 if (*(cp+len-1) == '$') {
853 kdb_grep_trailing = 1;
859 if (len >= KDB_GREP_STRLEN) {
860 kdb_printf("search string too long\n");
863 strcpy(kdb_grep_string, cp);
869 * kdb_parse - Parse the command line, search the command table for a
870 * matching command and invoke the command function. This
871 * function may be called recursively, if it is, the second call
872 * will overwrite argv and cbuf. It is the caller's
873 * responsibility to save their argv if they recursively call
876 * cmdstr The input command line to be parsed.
877 * regs The registers at the time kdb was entered.
879 * Zero for success, a kdb diagnostic if failure.
881 * Limited to 20 tokens.
883 * Real rudimentary tokenization. Basically only whitespace
884 * is considered a token delimiter (but special consideration
885 * is taken of the '=' sign as used by the 'set' command).
887 * The algorithm used to tokenize the input string relies on
888 * there being at least one whitespace (or otherwise useless)
889 * character between tokens as the character immediately following
890 * the token is altered in-place to a null-byte to terminate the
896 int kdb_parse(const char *cmdstr)
898 static char *argv[MAXARGC];
900 static char cbuf[CMD_BUFLEN+2];
904 int escaped, ignore_errors = 0, check_grep = 0;
907 * First tokenize the command string.
911 if (KDB_FLAG(CMD_INTERRUPT)) {
912 /* Previous command was interrupted, newline must not
913 * repeat the command */
914 KDB_FLAG_CLEAR(CMD_INTERRUPT);
915 KDB_STATE_SET(PAGER);
916 argc = 0; /* no repeat */
919 if (*cp != '\n' && *cp != '\0') {
923 /* skip whitespace */
926 if ((*cp == '\0') || (*cp == '\n') ||
927 (*cp == '#' && !defcmd_in_progress))
929 /* special case: check for | grep pattern */
934 if (cpp >= cbuf + CMD_BUFLEN) {
935 kdb_printf("kdb_parse: command buffer "
936 "overflow, command ignored\n%s\n",
940 if (argc >= MAXARGC - 1) {
941 kdb_printf("kdb_parse: too many arguments, "
942 "command ignored\n%s\n", cmdstr);
948 /* Copy to next unquoted and unescaped
949 * whitespace or '=' */
950 while (*cp && *cp != '\n' &&
951 (escaped || quoted || !isspace(*cp))) {
952 if (cpp >= cbuf + CMD_BUFLEN)
966 else if (*cp == '\'' || *cp == '"')
969 if (*cpp == '=' && !quoted)
973 *cpp++ = '\0'; /* Squash a ws or '=' character */
980 if (defcmd_in_progress) {
981 int result = kdb_defcmd2(cmdstr, argv[0]);
982 if (!defcmd_in_progress) {
983 argc = 0; /* avoid repeat on endefcmd */
988 if (argv[0][0] == '-' && argv[0][1] &&
989 (argv[0][1] < '0' || argv[0][1] > '9')) {
994 list_for_each_entry(tp, &kdb_cmds_head, list_node) {
996 * If this command is allowed to be abbreviated,
997 * check to see if this is it.
999 if (tp->minlen && (strlen(argv[0]) <= tp->minlen) &&
1000 (strncmp(argv[0], tp->name, tp->minlen) == 0))
1003 if (strcmp(argv[0], tp->name) == 0)
1008 * If we don't find a command by this name, see if the first
1009 * few characters of this match any of the known commands.
1010 * e.g., md1c20 should match md.
1012 if (list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1013 list_for_each_entry(tp, &kdb_cmds_head, list_node) {
1014 if (strncmp(argv[0], tp->name, strlen(tp->name)) == 0)
1019 if (!list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1022 if (!kdb_check_flags(tp->flags, kdb_cmd_enabled, argc <= 1))
1026 result = (*tp->func)(argc-1, (const char **)argv);
1027 if (result && ignore_errors && result > KDB_CMD_GO)
1029 KDB_STATE_CLEAR(CMD);
1031 if (tp->flags & KDB_REPEAT_WITH_ARGS)
1034 argc = tp->flags & KDB_REPEAT_NO_ARGS ? 1 : 0;
1036 *(argv[argc]) = '\0';
1041 * If the input with which we were presented does not
1042 * map to an existing command, attempt to parse it as an
1043 * address argument and display the result. Useful for
1044 * obtaining the address of a variable, or the nearest symbol
1045 * to an address contained in a register.
1048 unsigned long value;
1053 if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
1054 &value, &offset, &name)) {
1055 return KDB_NOTFOUND;
1058 kdb_printf("%s = ", argv[0]);
1059 kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
1066 static int handle_ctrl_cmd(char *cmd)
1071 /* initial situation */
1072 if (cmd_head == cmd_tail)
1076 if (cmdptr != cmd_tail)
1077 cmdptr = (cmdptr + KDB_CMD_HISTORY_COUNT - 1) %
1078 KDB_CMD_HISTORY_COUNT;
1079 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1082 if (cmdptr != cmd_head)
1083 cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
1084 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1091 * kdb_reboot - This function implements the 'reboot' command. Reboot
1092 * the system immediately, or loop for ever on failure.
1094 static int kdb_reboot(int argc, const char **argv)
1096 emergency_restart();
1097 kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
1104 static void kdb_dumpregs(struct pt_regs *regs)
1106 int old_lvl = console_loglevel;
1107 console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
1112 console_loglevel = old_lvl;
1115 static void kdb_set_current_task(struct task_struct *p)
1117 kdb_current_task = p;
1119 if (kdb_task_has_cpu(p)) {
1120 kdb_current_regs = KDB_TSKREGS(kdb_process_cpu(p));
1123 kdb_current_regs = NULL;
1126 static void drop_newline(char *buf)
1128 size_t len = strlen(buf);
1132 if (*(buf + len - 1) == '\n')
1133 *(buf + len - 1) = '\0';
1137 * kdb_local - The main code for kdb. This routine is invoked on a
1138 * specific processor, it is not global. The main kdb() routine
1139 * ensures that only one processor at a time is in this routine.
1140 * This code is called with the real reason code on the first
1141 * entry to a kdb session, thereafter it is called with reason
1142 * SWITCH, even if the user goes back to the original cpu.
1144 * reason The reason KDB was invoked
1145 * error The hardware-defined error code
1146 * regs The exception frame at time of fault/breakpoint.
1147 * db_result Result code from the break or debug point.
1149 * 0 KDB was invoked for an event which it wasn't responsible
1150 * 1 KDB handled the event for which it was invoked.
1151 * KDB_CMD_GO User typed 'go'.
1152 * KDB_CMD_CPU User switched to another cpu.
1153 * KDB_CMD_SS Single step.
1155 static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
1156 kdb_dbtrap_t db_result)
1160 struct task_struct *kdb_current =
1161 curr_task(raw_smp_processor_id());
1163 KDB_DEBUG_STATE("kdb_local 1", reason);
1165 kdb_check_for_lockdown();
1168 if (reason == KDB_REASON_DEBUG) {
1169 /* special case below */
1171 kdb_printf("\nEntering kdb (current=0x%px, pid %d) ",
1172 kdb_current, kdb_current ? kdb_current->pid : 0);
1173 #if defined(CONFIG_SMP)
1174 kdb_printf("on processor %d ", raw_smp_processor_id());
1179 case KDB_REASON_DEBUG:
1182 * If re-entering kdb after a single step
1183 * command, don't print the message.
1185 switch (db_result) {
1187 kdb_printf("\nEntering kdb (0x%px, pid %d) ",
1188 kdb_current, kdb_current->pid);
1189 #if defined(CONFIG_SMP)
1190 kdb_printf("on processor %d ", raw_smp_processor_id());
1192 kdb_printf("due to Debug @ " kdb_machreg_fmt "\n",
1193 instruction_pointer(regs));
1198 KDB_DEBUG_STATE("kdb_local 4", reason);
1199 return 1; /* kdba_db_trap did the work */
1201 kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
1208 case KDB_REASON_ENTER:
1209 if (KDB_STATE(KEYBOARD))
1210 kdb_printf("due to Keyboard Entry\n");
1212 kdb_printf("due to KDB_ENTER()\n");
1214 case KDB_REASON_KEYBOARD:
1215 KDB_STATE_SET(KEYBOARD);
1216 kdb_printf("due to Keyboard Entry\n");
1218 case KDB_REASON_ENTER_SLAVE:
1219 /* drop through, slaves only get released via cpu switch */
1220 case KDB_REASON_SWITCH:
1221 kdb_printf("due to cpu switch\n");
1223 case KDB_REASON_OOPS:
1224 kdb_printf("Oops: %s\n", kdb_diemsg);
1225 kdb_printf("due to oops @ " kdb_machreg_fmt "\n",
1226 instruction_pointer(regs));
1229 case KDB_REASON_SYSTEM_NMI:
1230 kdb_printf("due to System NonMaskable Interrupt\n");
1232 case KDB_REASON_NMI:
1233 kdb_printf("due to NonMaskable Interrupt @ "
1234 kdb_machreg_fmt "\n",
1235 instruction_pointer(regs));
1237 case KDB_REASON_SSTEP:
1238 case KDB_REASON_BREAK:
1239 kdb_printf("due to %s @ " kdb_machreg_fmt "\n",
1240 reason == KDB_REASON_BREAK ?
1241 "Breakpoint" : "SS trap", instruction_pointer(regs));
1243 * Determine if this breakpoint is one that we
1244 * are interested in.
1246 if (db_result != KDB_DB_BPT) {
1247 kdb_printf("kdb: error return from kdba_bp_trap: %d\n",
1249 KDB_DEBUG_STATE("kdb_local 6", reason);
1250 return 0; /* Not for us, dismiss it */
1253 case KDB_REASON_RECURSE:
1254 kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n",
1255 instruction_pointer(regs));
1258 kdb_printf("kdb: unexpected reason code: %d\n", reason);
1259 KDB_DEBUG_STATE("kdb_local 8", reason);
1260 return 0; /* Not for us, dismiss it */
1265 * Initialize pager context.
1268 KDB_STATE_CLEAR(SUPPRESS);
1269 kdb_grepping_flag = 0;
1270 /* ensure the old search does not leak into '/' commands */
1271 kdb_grep_string[0] = '\0';
1275 *(cmd_hist[cmd_head]) = '\0';
1278 /* PROMPT can only be set if we have MEM_READ permission. */
1279 snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
1280 raw_smp_processor_id());
1283 * Fetch command from keyboard
1285 cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
1286 if (*cmdbuf != '\n') {
1288 if (cmdptr == cmd_head) {
1289 strscpy(cmd_hist[cmd_head], cmd_cur,
1291 *(cmd_hist[cmd_head] +
1292 strlen(cmd_hist[cmd_head])-1) = '\0';
1294 if (!handle_ctrl_cmd(cmdbuf))
1295 *(cmd_cur+strlen(cmd_cur)-1) = '\0';
1297 goto do_full_getstr;
1299 strscpy(cmd_hist[cmd_head], cmd_cur,
1303 cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
1304 if (cmd_head == cmd_tail)
1305 cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
1309 diag = kdb_parse(cmdbuf);
1310 if (diag == KDB_NOTFOUND) {
1311 drop_newline(cmdbuf);
1312 kdb_printf("Unknown kdb command: '%s'\n", cmdbuf);
1315 if (diag == KDB_CMD_GO
1316 || diag == KDB_CMD_CPU
1317 || diag == KDB_CMD_SS
1318 || diag == KDB_CMD_KGDB)
1324 KDB_DEBUG_STATE("kdb_local 9", diag);
1330 * kdb_print_state - Print the state data for the current processor
1333 * text Identifies the debug point
1334 * value Any integer value to be printed, e.g. reason code.
1336 void kdb_print_state(const char *text, int value)
1338 kdb_printf("state: %s cpu %d value %d initial %d state %x\n",
1339 text, raw_smp_processor_id(), value, kdb_initial_cpu,
1344 * kdb_main_loop - After initial setup and assignment of the
1345 * controlling cpu, all cpus are in this loop. One cpu is in
1346 * control and will issue the kdb prompt, the others will spin
1347 * until 'go' or cpu switch.
1349 * To get a consistent view of the kernel stacks for all
1350 * processes, this routine is invoked from the main kdb code via
1351 * an architecture specific routine. kdba_main_loop is
1352 * responsible for making the kernel stacks consistent for all
1353 * processes, there should be no difference between a blocked
1354 * process and a running process as far as kdb is concerned.
1356 * reason The reason KDB was invoked
1357 * error The hardware-defined error code
1358 * reason2 kdb's current reason code.
1359 * Initially error but can change
1360 * according to kdb state.
1361 * db_result Result code from break or debug point.
1362 * regs The exception frame at time of fault/breakpoint.
1363 * should always be valid.
1365 * 0 KDB was invoked for an event which it wasn't responsible
1366 * 1 KDB handled the event for which it was invoked.
1368 int kdb_main_loop(kdb_reason_t reason, kdb_reason_t reason2, int error,
1369 kdb_dbtrap_t db_result, struct pt_regs *regs)
1372 /* Stay in kdb() until 'go', 'ss[b]' or an error */
1375 * All processors except the one that is in control
1378 KDB_DEBUG_STATE("kdb_main_loop 1", reason);
1379 while (KDB_STATE(HOLD_CPU)) {
1380 /* state KDB is turned off by kdb_cpu to see if the
1381 * other cpus are still live, each cpu in this loop
1384 if (!KDB_STATE(KDB))
1388 KDB_STATE_CLEAR(SUPPRESS);
1389 KDB_DEBUG_STATE("kdb_main_loop 2", reason);
1390 if (KDB_STATE(LEAVING))
1391 break; /* Another cpu said 'go' */
1392 /* Still using kdb, this processor is in control */
1393 result = kdb_local(reason2, error, regs, db_result);
1394 KDB_DEBUG_STATE("kdb_main_loop 3", result);
1396 if (result == KDB_CMD_CPU)
1399 if (result == KDB_CMD_SS) {
1400 KDB_STATE_SET(DOING_SS);
1404 if (result == KDB_CMD_KGDB) {
1405 if (!KDB_STATE(DOING_KGDB))
1406 kdb_printf("Entering please attach debugger "
1407 "or use $D#44+ or $3#33\n");
1410 if (result && result != 1 && result != KDB_CMD_GO)
1411 kdb_printf("\nUnexpected kdb_local return code %d\n",
1413 KDB_DEBUG_STATE("kdb_main_loop 4", reason);
1416 if (KDB_STATE(DOING_SS))
1417 KDB_STATE_CLEAR(SSBPT);
1419 /* Clean up any keyboard devices before leaving */
1420 kdb_kbd_cleanup_state();
1426 * kdb_mdr - This function implements the guts of the 'mdr', memory
1428 * mdr <addr arg>,<byte count>
1430 * addr Start address
1431 * count Number of bytes
1433 * Always 0. Any errors are detected and printed by kdb_getarea.
1435 static int kdb_mdr(unsigned long addr, unsigned int count)
1439 if (kdb_getarea(c, addr))
1441 kdb_printf("%02x", c);
1449 * kdb_md - This function implements the 'md', 'md1', 'md2', 'md4',
1450 * 'md8' 'mdr' and 'mds' commands.
1452 * md|mds [<addr arg> [<line count> [<radix>]]]
1453 * mdWcN [<addr arg> [<line count> [<radix>]]]
1454 * where W = is the width (1, 2, 4 or 8) and N is the count.
1455 * for eg., md1c20 reads 20 bytes, 1 at a time.
1456 * mdr <addr arg>,<byte count>
1458 static void kdb_md_line(const char *fmtstr, unsigned long addr,
1459 int symbolic, int nosect, int bytesperword,
1460 int num, int repeat, int phys)
1462 /* print just one line of data */
1463 kdb_symtab_t symtab;
1470 memset(cbuf, '\0', sizeof(cbuf));
1472 kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
1474 kdb_printf(kdb_machreg_fmt0 " ", addr);
1476 for (i = 0; i < num && repeat--; i++) {
1478 if (kdb_getphysword(&word, addr, bytesperword))
1480 } else if (kdb_getword(&word, addr, bytesperword))
1482 kdb_printf(fmtstr, word);
1484 kdbnearsym(word, &symtab);
1486 memset(&symtab, 0, sizeof(symtab));
1487 if (symtab.sym_name) {
1488 kdb_symbol_print(word, &symtab, 0);
1491 kdb_printf(" %s %s "
1494 kdb_machreg_fmt, symtab.mod_name,
1495 symtab.sec_name, symtab.sec_start,
1496 symtab.sym_start, symtab.sym_end);
1498 addr += bytesperword;
1506 cp = wc.c + 8 - bytesperword;
1511 #define printable_char(c) \
1512 ({unsigned char __c = c; isascii(__c) && isprint(__c) ? __c : '.'; })
1513 for (j = 0; j < bytesperword; j++)
1514 *c++ = printable_char(*cp++);
1515 addr += bytesperword;
1516 #undef printable_char
1519 kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1),
1523 static int kdb_md(int argc, const char **argv)
1525 static unsigned long last_addr;
1526 static int last_radix, last_bytesperword, last_repeat;
1527 int radix = 16, mdcount = 8, bytesperword = KDB_WORD_SIZE, repeat;
1529 char fmtchar, fmtstr[64];
1538 kdbgetintenv("MDCOUNT", &mdcount);
1539 kdbgetintenv("RADIX", &radix);
1540 kdbgetintenv("BYTESPERWORD", &bytesperword);
1542 /* Assume 'md <addr>' and start with environment values */
1543 repeat = mdcount * 16 / bytesperword;
1545 if (strcmp(argv[0], "mdr") == 0) {
1546 if (argc == 2 || (argc == 0 && last_addr != 0))
1549 return KDB_ARGCOUNT;
1550 } else if (isdigit(argv[0][2])) {
1551 bytesperword = (int)(argv[0][2] - '0');
1552 if (bytesperword == 0) {
1553 bytesperword = last_bytesperword;
1554 if (bytesperword == 0)
1557 last_bytesperword = bytesperword;
1558 repeat = mdcount * 16 / bytesperword;
1561 else if (argv[0][3] == 'c' && argv[0][4]) {
1562 if (kstrtouint(argv[0] + 4, 10, &repeat))
1564 mdcount = ((repeat * bytesperword) + 15) / 16;
1567 last_repeat = repeat;
1568 } else if (strcmp(argv[0], "md") == 0)
1570 else if (strcmp(argv[0], "mds") == 0)
1572 else if (strcmp(argv[0], "mdp") == 0) {
1576 return KDB_NOTFOUND;
1580 return KDB_ARGCOUNT;
1583 bytesperword = last_bytesperword;
1584 repeat = last_repeat;
1588 mdcount = ((repeat * bytesperword) + 15) / 16;
1593 int diag, nextarg = 1;
1594 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr,
1598 if (argc > nextarg+2)
1599 return KDB_ARGCOUNT;
1601 if (argc >= nextarg) {
1602 diag = kdbgetularg(argv[nextarg], &val);
1604 mdcount = (int) val;
1608 repeat = mdcount * 16 / bytesperword;
1611 if (argc >= nextarg+1) {
1612 diag = kdbgetularg(argv[nextarg+1], &val);
1618 if (strcmp(argv[0], "mdr") == 0) {
1621 ret = kdb_mdr(addr, mdcount);
1622 last_addr += mdcount;
1623 last_repeat = mdcount;
1624 last_bytesperword = bytesperword; // to make REPEAT happy
1639 return KDB_BADRADIX;
1644 if (bytesperword > KDB_WORD_SIZE)
1645 return KDB_BADWIDTH;
1647 switch (bytesperword) {
1649 sprintf(fmtstr, "%%16.16l%c ", fmtchar);
1652 sprintf(fmtstr, "%%8.8l%c ", fmtchar);
1655 sprintf(fmtstr, "%%4.4l%c ", fmtchar);
1658 sprintf(fmtstr, "%%2.2l%c ", fmtchar);
1661 return KDB_BADWIDTH;
1664 last_repeat = repeat;
1665 last_bytesperword = bytesperword;
1667 if (strcmp(argv[0], "mds") == 0) {
1669 /* Do not save these changes as last_*, they are temporary mds
1672 bytesperword = KDB_WORD_SIZE;
1674 kdbgetintenv("NOSECT", &nosect);
1677 /* Round address down modulo BYTESPERWORD */
1679 addr &= ~(bytesperword-1);
1681 while (repeat > 0) {
1683 int n, z, num = (symbolic ? 1 : (16 / bytesperword));
1685 if (KDB_FLAG(CMD_INTERRUPT))
1687 for (a = addr, z = 0; z < repeat; a += bytesperword, ++z) {
1689 if (kdb_getphysword(&word, a, bytesperword)
1692 } else if (kdb_getword(&word, a, bytesperword) || word)
1695 n = min(num, repeat);
1696 kdb_md_line(fmtstr, addr, symbolic, nosect, bytesperword,
1698 addr += bytesperword * n;
1700 z = (z + num - 1) / num;
1702 int s = num * (z-2);
1703 kdb_printf(kdb_machreg_fmt0 "-" kdb_machreg_fmt0
1704 " zero suppressed\n",
1705 addr, addr + bytesperword * s - 1);
1706 addr += bytesperword * s;
1716 * kdb_mm - This function implements the 'mm' command.
1717 * mm address-expression new-value
1719 * mm works on machine words, mmW works on bytes.
1721 static int kdb_mm(int argc, const char **argv)
1726 unsigned long contents;
1730 if (argv[0][2] && !isdigit(argv[0][2]))
1731 return KDB_NOTFOUND;
1734 return KDB_ARGCOUNT;
1737 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
1742 return KDB_ARGCOUNT;
1743 diag = kdbgetaddrarg(argc, argv, &nextarg, &contents, NULL, NULL);
1747 if (nextarg != argc + 1)
1748 return KDB_ARGCOUNT;
1750 width = argv[0][2] ? (argv[0][2] - '0') : (KDB_WORD_SIZE);
1751 diag = kdb_putword(addr, contents, width);
1755 kdb_printf(kdb_machreg_fmt " = " kdb_machreg_fmt "\n", addr, contents);
1761 * kdb_go - This function implements the 'go' command.
1762 * go [address-expression]
1764 static int kdb_go(int argc, const char **argv)
1771 if (raw_smp_processor_id() != kdb_initial_cpu) {
1772 kdb_printf("go must execute on the entry cpu, "
1773 "please use \"cpu %d\" and then execute go\n",
1775 return KDB_BADCPUNUM;
1779 diag = kdbgetaddrarg(argc, argv, &nextarg,
1780 &addr, &offset, NULL);
1784 return KDB_ARGCOUNT;
1788 if (KDB_FLAG(CATASTROPHIC)) {
1789 kdb_printf("Catastrophic error detected\n");
1790 kdb_printf("kdb_continue_catastrophic=%d, ",
1791 kdb_continue_catastrophic);
1792 if (kdb_continue_catastrophic == 0 && kdb_go_count++ == 0) {
1793 kdb_printf("type go a second time if you really want "
1797 if (kdb_continue_catastrophic == 2) {
1798 kdb_printf("forcing reboot\n");
1799 kdb_reboot(0, NULL);
1801 kdb_printf("attempting to continue\n");
1807 * kdb_rd - This function implements the 'rd' command.
1809 static int kdb_rd(int argc, const char **argv)
1811 int len = kdb_check_regs();
1812 #if DBG_MAX_REG_NUM > 0
1824 for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1825 rsize = dbg_reg_def[i].size * 2;
1828 if (len + strlen(dbg_reg_def[i].name) + 4 + rsize > 80) {
1833 len += kdb_printf(" ");
1834 switch(dbg_reg_def[i].size * 8) {
1836 rname = dbg_get_reg(i, ®8, kdb_current_regs);
1839 len += kdb_printf("%s: %02x", rname, reg8);
1842 rname = dbg_get_reg(i, ®16, kdb_current_regs);
1845 len += kdb_printf("%s: %04x", rname, reg16);
1848 rname = dbg_get_reg(i, ®32, kdb_current_regs);
1851 len += kdb_printf("%s: %08x", rname, reg32);
1854 rname = dbg_get_reg(i, ®64, kdb_current_regs);
1857 len += kdb_printf("%s: %016llx", rname, reg64);
1860 len += kdb_printf("%s: ??", dbg_reg_def[i].name);
1868 kdb_dumpregs(kdb_current_regs);
1874 * kdb_rm - This function implements the 'rm' (register modify) command.
1875 * rm register-name new-contents
1877 * Allows register modification with the same restrictions as gdb
1879 static int kdb_rm(int argc, const char **argv)
1881 #if DBG_MAX_REG_NUM > 0
1891 return KDB_ARGCOUNT;
1893 * Allow presence or absence of leading '%' symbol.
1899 diag = kdbgetu64arg(argv[2], ®64);
1903 diag = kdb_check_regs();
1908 for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1909 if (strcmp(rname, dbg_reg_def[i].name) == 0) {
1915 switch(dbg_reg_def[i].size * 8) {
1918 dbg_set_reg(i, ®8, kdb_current_regs);
1922 dbg_set_reg(i, ®16, kdb_current_regs);
1926 dbg_set_reg(i, ®32, kdb_current_regs);
1929 dbg_set_reg(i, ®64, kdb_current_regs);
1935 kdb_printf("ERROR: Register set currently not implemented\n");
1940 #if defined(CONFIG_MAGIC_SYSRQ)
1942 * kdb_sr - This function implements the 'sr' (SYSRQ key) command
1943 * which interfaces to the soi-disant MAGIC SYSRQ functionality.
1944 * sr <magic-sysrq-code>
1946 static int kdb_sr(int argc, const char **argv)
1949 !kdb_check_flags(KDB_ENABLE_ALL, kdb_cmd_enabled, false);
1952 return KDB_ARGCOUNT;
1955 __handle_sysrq(*argv[1], check_mask);
1960 #endif /* CONFIG_MAGIC_SYSRQ */
1963 * kdb_ef - This function implements the 'regs' (display exception
1964 * frame) command. This command takes an address and expects to
1965 * find an exception frame at that address, formats and prints
1967 * regs address-expression
1971 static int kdb_ef(int argc, const char **argv)
1979 return KDB_ARGCOUNT;
1982 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
1985 show_regs((struct pt_regs *)addr);
1990 * kdb_env - This function implements the 'env' command. Display the
1991 * current environment variables.
1994 static int kdb_env(int argc, const char **argv)
1998 if (KDB_DEBUG(MASK))
1999 kdb_printf("KDBDEBUG=0x%x\n",
2000 (kdb_flags & KDB_DEBUG(MASK)) >> KDB_DEBUG_FLAG_SHIFT);
2005 #ifdef CONFIG_PRINTK
2007 * kdb_dmesg - This function implements the 'dmesg' command to display
2008 * the contents of the syslog buffer.
2009 * dmesg [lines] [adjust]
2011 static int kdb_dmesg(int argc, const char **argv)
2019 struct kmsg_dump_iter iter;
2024 return KDB_ARGCOUNT;
2026 if (kstrtoint(argv[1], 0, &lines))
2028 if (argc > 1 && (kstrtoint(argv[2], 0, &adjust) || adjust < 0))
2032 /* disable LOGGING if set */
2033 diag = kdbgetintenv("LOGGING", &logging);
2034 if (!diag && logging) {
2035 const char *setargs[] = { "set", "LOGGING", "0" };
2036 kdb_set(2, setargs);
2039 kmsg_dump_rewind(&iter);
2040 while (kmsg_dump_get_line(&iter, 1, NULL, 0, NULL))
2045 kdb_printf("buffer only contains %d lines, nothing "
2047 else if (adjust - lines >= n)
2048 kdb_printf("buffer only contains %d lines, last %d "
2049 "lines printed\n", n, n - adjust);
2052 } else if (lines > 0) {
2053 skip = n - lines - adjust;
2056 kdb_printf("buffer only contains %d lines, "
2057 "nothing printed\n", n);
2059 } else if (skip < 0) {
2062 kdb_printf("buffer only contains %d lines, first "
2063 "%d lines printed\n", n, lines);
2069 if (skip >= n || skip < 0)
2072 kmsg_dump_rewind(&iter);
2073 while (kmsg_dump_get_line(&iter, 1, buf, sizeof(buf), &len)) {
2080 if (KDB_FLAG(CMD_INTERRUPT))
2083 kdb_printf("%.*s\n", (int)len - 1, buf);
2088 #endif /* CONFIG_PRINTK */
2090 * kdb_cpu - This function implements the 'cpu' command.
2093 * KDB_CMD_CPU for success, a kdb diagnostic if error
2095 static void kdb_cpu_status(void)
2097 int i, start_cpu, first_print = 1;
2098 char state, prev_state = '?';
2100 kdb_printf("Currently on cpu %d\n", raw_smp_processor_id());
2101 kdb_printf("Available cpus: ");
2102 for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
2103 if (!cpu_online(i)) {
2104 state = 'F'; /* cpu is offline */
2105 } else if (!kgdb_info[i].enter_kgdb) {
2106 state = 'D'; /* cpu is online but unresponsive */
2108 state = ' '; /* cpu is responding to kdb */
2109 if (kdb_task_state_char(KDB_TSK(i)) == '-')
2110 state = '-'; /* idle task */
2112 if (state != prev_state) {
2113 if (prev_state != '?') {
2117 kdb_printf("%d", start_cpu);
2118 if (start_cpu < i-1)
2119 kdb_printf("-%d", i-1);
2120 if (prev_state != ' ')
2121 kdb_printf("(%c)", prev_state);
2127 /* print the trailing cpus, ignoring them if they are all offline */
2128 if (prev_state != 'F') {
2131 kdb_printf("%d", start_cpu);
2132 if (start_cpu < i-1)
2133 kdb_printf("-%d", i-1);
2134 if (prev_state != ' ')
2135 kdb_printf("(%c)", prev_state);
2140 static int kdb_cpu(int argc, const char **argv)
2142 unsigned long cpunum;
2151 return KDB_ARGCOUNT;
2153 diag = kdbgetularg(argv[1], &cpunum);
2160 if ((cpunum >= CONFIG_NR_CPUS) || !kgdb_info[cpunum].enter_kgdb)
2161 return KDB_BADCPUNUM;
2163 dbg_switch_cpu = cpunum;
2166 * Switch to other cpu
2171 /* The user may not realize that ps/bta with no parameters does not print idle
2172 * or sleeping system daemon processes, so tell them how many were suppressed.
2174 void kdb_ps_suppressed(void)
2176 int idle = 0, daemon = 0;
2178 const struct task_struct *p, *g;
2179 for_each_online_cpu(cpu) {
2181 if (kdb_task_state(p, "-"))
2184 for_each_process_thread(g, p) {
2185 if (kdb_task_state(p, "ims"))
2188 if (idle || daemon) {
2190 kdb_printf("%d idle process%s (state -)%s\n",
2191 idle, idle == 1 ? "" : "es",
2192 daemon ? " and " : "");
2194 kdb_printf("%d sleeping system daemon (state [ims]) "
2195 "process%s", daemon,
2196 daemon == 1 ? "" : "es");
2197 kdb_printf(" suppressed,\nuse 'ps A' to see all.\n");
2201 void kdb_ps1(const struct task_struct *p)
2207 copy_from_kernel_nofault(&tmp, (char *)p, sizeof(unsigned long)))
2210 cpu = kdb_process_cpu(p);
2211 kdb_printf("0x%px %8d %8d %d %4d %c 0x%px %c%s\n",
2212 (void *)p, p->pid, p->parent->pid,
2213 kdb_task_has_cpu(p), kdb_process_cpu(p),
2214 kdb_task_state_char(p),
2215 (void *)(&p->thread),
2216 p == curr_task(raw_smp_processor_id()) ? '*' : ' ',
2218 if (kdb_task_has_cpu(p)) {
2219 if (!KDB_TSK(cpu)) {
2220 kdb_printf(" Error: no saved data for this cpu\n");
2222 if (KDB_TSK(cpu) != p)
2223 kdb_printf(" Error: does not match running "
2224 "process table (0x%px)\n", KDB_TSK(cpu));
2230 * kdb_ps - This function implements the 'ps' command which shows a
2231 * list of the active processes.
2233 * ps [<state_chars>] Show processes, optionally selecting only those whose
2234 * state character is found in <state_chars>.
2236 static int kdb_ps(int argc, const char **argv)
2238 struct task_struct *g, *p;
2243 kdb_ps_suppressed();
2244 kdb_printf("%-*s Pid Parent [*] cpu State %-*s Command\n",
2245 (int)(2*sizeof(void *))+2, "Task Addr",
2246 (int)(2*sizeof(void *))+2, "Thread");
2247 mask = argc ? argv[1] : kdbgetenv("PS");
2248 /* Run the active tasks first */
2249 for_each_online_cpu(cpu) {
2250 if (KDB_FLAG(CMD_INTERRUPT))
2253 if (kdb_task_state(p, mask))
2257 /* Now the real tasks */
2258 for_each_process_thread(g, p) {
2259 if (KDB_FLAG(CMD_INTERRUPT))
2261 if (kdb_task_state(p, mask))
2269 * kdb_pid - This function implements the 'pid' command which switches
2270 * the currently active process.
2273 static int kdb_pid(int argc, const char **argv)
2275 struct task_struct *p;
2280 return KDB_ARGCOUNT;
2283 if (strcmp(argv[1], "R") == 0) {
2284 p = KDB_TSK(kdb_initial_cpu);
2286 diag = kdbgetularg(argv[1], &val);
2290 p = find_task_by_pid_ns((pid_t)val, &init_pid_ns);
2292 kdb_printf("No task with pid=%d\n", (pid_t)val);
2296 kdb_set_current_task(p);
2298 kdb_printf("KDB current process is %s(pid=%d)\n",
2299 kdb_current_task->comm,
2300 kdb_current_task->pid);
2305 static int kdb_kgdb(int argc, const char **argv)
2307 return KDB_CMD_KGDB;
2311 * kdb_help - This function implements the 'help' and '?' commands.
2313 static int kdb_help(int argc, const char **argv)
2317 kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
2318 kdb_printf("-----------------------------"
2319 "-----------------------------\n");
2320 list_for_each_entry(kt, &kdb_cmds_head, list_node) {
2322 if (KDB_FLAG(CMD_INTERRUPT))
2324 if (!kdb_check_flags(kt->flags, kdb_cmd_enabled, true))
2326 if (strlen(kt->usage) > 20)
2328 kdb_printf("%-15.15s %-20s%s%s\n", kt->name,
2329 kt->usage, space, kt->help);
2335 * kdb_kill - This function implements the 'kill' commands.
2337 static int kdb_kill(int argc, const char **argv)
2340 struct task_struct *p;
2343 return KDB_ARGCOUNT;
2345 if (kstrtol(argv[1], 0, &sig))
2347 if ((sig >= 0) || !valid_signal(-sig)) {
2348 kdb_printf("Invalid signal parameter.<-signal>\n");
2353 if (kstrtol(argv[2], 0, &pid))
2356 kdb_printf("Process ID must be large than 0.\n");
2360 /* Find the process. */
2361 p = find_task_by_pid_ns(pid, &init_pid_ns);
2363 kdb_printf("The specified process isn't found.\n");
2366 p = p->group_leader;
2367 kdb_send_sig(p, sig);
2372 * Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
2373 * I cannot call that code directly from kdb, it has an unconditional
2374 * cli()/sti() and calls routines that take locks which can stop the debugger.
2376 static void kdb_sysinfo(struct sysinfo *val)
2378 u64 uptime = ktime_get_mono_fast_ns();
2380 memset(val, 0, sizeof(*val));
2381 val->uptime = div_u64(uptime, NSEC_PER_SEC);
2382 val->loads[0] = avenrun[0];
2383 val->loads[1] = avenrun[1];
2384 val->loads[2] = avenrun[2];
2385 val->procs = nr_threads-1;
2392 * kdb_summary - This function implements the 'summary' command.
2394 static int kdb_summary(int argc, const char **argv)
2400 return KDB_ARGCOUNT;
2402 kdb_printf("sysname %s\n", init_uts_ns.name.sysname);
2403 kdb_printf("release %s\n", init_uts_ns.name.release);
2404 kdb_printf("version %s\n", init_uts_ns.name.version);
2405 kdb_printf("machine %s\n", init_uts_ns.name.machine);
2406 kdb_printf("nodename %s\n", init_uts_ns.name.nodename);
2407 kdb_printf("domainname %s\n", init_uts_ns.name.domainname);
2409 now = __ktime_get_real_seconds();
2410 kdb_printf("date %ptTs tz_minuteswest %d\n", &now, sys_tz.tz_minuteswest);
2412 kdb_printf("uptime ");
2413 if (val.uptime > (24*60*60)) {
2414 int days = val.uptime / (24*60*60);
2415 val.uptime %= (24*60*60);
2416 kdb_printf("%d day%s ", days, str_plural(days));
2418 kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
2420 kdb_printf("load avg %ld.%02ld %ld.%02ld %ld.%02ld\n",
2421 LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
2422 LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
2423 LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
2425 /* Display in kilobytes */
2426 #define K(x) ((x) << (PAGE_SHIFT - 10))
2427 kdb_printf("\nMemTotal: %8lu kB\nMemFree: %8lu kB\n"
2428 "Buffers: %8lu kB\n",
2429 K(val.totalram), K(val.freeram), K(val.bufferram));
2434 * kdb_per_cpu - This function implements the 'per_cpu' command.
2436 static int kdb_per_cpu(int argc, const char **argv)
2439 int cpu, diag, nextarg = 1;
2440 unsigned long addr, symaddr, val, bytesperword = 0, whichcpu = ~0UL;
2442 if (argc < 1 || argc > 3)
2443 return KDB_ARGCOUNT;
2445 diag = kdbgetaddrarg(argc, argv, &nextarg, &symaddr, NULL, NULL);
2450 diag = kdbgetularg(argv[2], &bytesperword);
2455 bytesperword = KDB_WORD_SIZE;
2456 else if (bytesperword > KDB_WORD_SIZE)
2457 return KDB_BADWIDTH;
2458 sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
2460 diag = kdbgetularg(argv[3], &whichcpu);
2463 if (whichcpu >= nr_cpu_ids || !cpu_online(whichcpu)) {
2464 kdb_printf("cpu %ld is not online\n", whichcpu);
2465 return KDB_BADCPUNUM;
2469 /* Most architectures use __per_cpu_offset[cpu], some use
2470 * __per_cpu_offset(cpu), smp has no __per_cpu_offset.
2472 #ifdef __per_cpu_offset
2473 #define KDB_PCU(cpu) __per_cpu_offset(cpu)
2476 #define KDB_PCU(cpu) __per_cpu_offset[cpu]
2478 #define KDB_PCU(cpu) 0
2481 for_each_online_cpu(cpu) {
2482 if (KDB_FLAG(CMD_INTERRUPT))
2485 if (whichcpu != ~0UL && whichcpu != cpu)
2487 addr = symaddr + KDB_PCU(cpu);
2488 diag = kdb_getword(&val, addr, bytesperword);
2490 kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to "
2491 "read, diag=%d\n", cpu, addr, diag);
2494 kdb_printf("%5d ", cpu);
2495 kdb_md_line(fmtstr, addr,
2496 bytesperword == KDB_WORD_SIZE,
2497 1, bytesperword, 1, 1, 0);
2504 * display help for the use of cmd | grep pattern
2506 static int kdb_grep_help(int argc, const char **argv)
2508 kdb_printf("Usage of cmd args | grep pattern:\n");
2509 kdb_printf(" Any command's output may be filtered through an ");
2510 kdb_printf("emulated 'pipe'.\n");
2511 kdb_printf(" 'grep' is just a key word.\n");
2512 kdb_printf(" The pattern may include a very limited set of "
2513 "metacharacters:\n");
2514 kdb_printf(" pattern or ^pattern or pattern$ or ^pattern$\n");
2515 kdb_printf(" And if there are spaces in the pattern, you may "
2517 kdb_printf(" \"pat tern\" or \"^pat tern\" or \"pat tern$\""
2518 " or \"^pat tern$\"\n");
2523 * kdb_register() - This function is used to register a kernel debugger
2525 * @cmd: pointer to kdb command
2527 * Note that it's the job of the caller to keep the memory for the cmd
2528 * allocated until unregister is called.
2530 int kdb_register(kdbtab_t *cmd)
2534 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
2535 if (strcmp(kp->name, cmd->name) == 0) {
2536 kdb_printf("Duplicate kdb cmd: %s, func %p help %s\n",
2537 cmd->name, cmd->func, cmd->help);
2542 list_add_tail(&cmd->list_node, &kdb_cmds_head);
2545 EXPORT_SYMBOL_GPL(kdb_register);
2548 * kdb_register_table() - This function is used to register a kdb command
2550 * @kp: pointer to kdb command table
2551 * @len: length of kdb command table
2553 void kdb_register_table(kdbtab_t *kp, size_t len)
2556 list_add_tail(&kp->list_node, &kdb_cmds_head);
2562 * kdb_unregister() - This function is used to unregister a kernel debugger
2563 * command. It is generally called when a module which
2564 * implements kdb command is unloaded.
2565 * @cmd: pointer to kdb command
2567 void kdb_unregister(kdbtab_t *cmd)
2569 list_del(&cmd->list_node);
2571 EXPORT_SYMBOL_GPL(kdb_unregister);
2573 static kdbtab_t maintab[] = {
2577 .help = "Display Memory Contents, also mdWcN, e.g. md8c1",
2579 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2583 .usage = "<vaddr> <bytes>",
2584 .help = "Display Raw Memory",
2585 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2589 .usage = "<paddr> <bytes>",
2590 .help = "Display Physical Memory",
2591 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2596 .help = "Display Memory Symbolically",
2597 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2601 .usage = "<vaddr> <contents>",
2602 .help = "Modify Memory Contents",
2603 .flags = KDB_ENABLE_MEM_WRITE | KDB_REPEAT_NO_ARGS,
2607 .usage = "[<vaddr>]",
2608 .help = "Continue Execution",
2610 .flags = KDB_ENABLE_REG_WRITE |
2611 KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2616 .help = "Display Registers",
2617 .flags = KDB_ENABLE_REG_READ,
2621 .usage = "<reg> <contents>",
2622 .help = "Modify Registers",
2623 .flags = KDB_ENABLE_REG_WRITE,
2628 .help = "Display exception frame",
2629 .flags = KDB_ENABLE_MEM_READ,
2633 .usage = "[<vaddr>]",
2634 .help = "Stack traceback",
2636 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2641 .help = "Display stack for process <pid>",
2642 .flags = KDB_ENABLE_INSPECT,
2646 .usage = "[<state_chars>|A]",
2647 .help = "Backtrace all processes whose state matches",
2648 .flags = KDB_ENABLE_INSPECT,
2653 .help = "Backtrace current process on each cpu",
2654 .flags = KDB_ENABLE_INSPECT,
2659 .help = "Backtrace process given its struct task address",
2660 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2665 .help = "Show environment variables",
2666 .flags = KDB_ENABLE_ALWAYS_SAFE,
2671 .help = "Set environment variables",
2672 .flags = KDB_ENABLE_ALWAYS_SAFE,
2677 .help = "Display Help Message",
2679 .flags = KDB_ENABLE_ALWAYS_SAFE,
2684 .help = "Display Help Message",
2685 .flags = KDB_ENABLE_ALWAYS_SAFE,
2689 .usage = "<cpunum>",
2690 .help = "Switch to new cpu",
2691 .flags = KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2696 .help = "Enter kgdb mode",
2701 .usage = "[<state_chars>|A]",
2702 .help = "Display active task list",
2703 .flags = KDB_ENABLE_INSPECT,
2707 .usage = "<pidnum>",
2708 .help = "Switch to another task",
2709 .flags = KDB_ENABLE_INSPECT,
2714 .help = "Reboot the machine immediately",
2715 .flags = KDB_ENABLE_REBOOT,
2717 #if defined(CONFIG_MODULES)
2721 .help = "List loaded kernel modules",
2722 .flags = KDB_ENABLE_INSPECT,
2725 #if defined(CONFIG_MAGIC_SYSRQ)
2729 .help = "Magic SysRq key",
2730 .flags = KDB_ENABLE_ALWAYS_SAFE,
2733 #if defined(CONFIG_PRINTK)
2737 .help = "Display syslog buffer",
2738 .flags = KDB_ENABLE_ALWAYS_SAFE,
2743 .usage = "name \"usage\" \"help\"",
2744 .help = "Define a set of commands, down to endefcmd",
2746 * Macros are always safe because when executed each
2747 * internal command re-enters kdb_parse() and is safety
2748 * checked individually.
2750 .flags = KDB_ENABLE_ALWAYS_SAFE,
2754 .usage = "<-signal> <pid>",
2755 .help = "Send a signal to a process",
2756 .flags = KDB_ENABLE_SIGNAL,
2758 { .name = "summary",
2759 .func = kdb_summary,
2761 .help = "Summarize the system",
2763 .flags = KDB_ENABLE_ALWAYS_SAFE,
2765 { .name = "per_cpu",
2766 .func = kdb_per_cpu,
2767 .usage = "<sym> [<bytes>] [<cpu>]",
2768 .help = "Display per_cpu variables",
2770 .flags = KDB_ENABLE_MEM_READ,
2772 { .name = "grephelp",
2773 .func = kdb_grep_help,
2775 .help = "Display help on | grep",
2776 .flags = KDB_ENABLE_ALWAYS_SAFE,
2780 /* Initialize the kdb command table. */
2781 static void __init kdb_inittab(void)
2783 kdb_register_table(maintab, ARRAY_SIZE(maintab));
2786 /* Execute any commands defined in kdb_cmds. */
2787 static void __init kdb_cmd_init(void)
2790 for (i = 0; kdb_cmds[i]; ++i) {
2791 diag = kdb_parse(kdb_cmds[i]);
2793 kdb_printf("kdb command %s failed, kdb diag %d\n",
2796 if (defcmd_in_progress) {
2797 kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
2798 kdb_parse("endefcmd");
2802 /* Initialize kdb_printf, breakpoint tables and kdb state */
2803 void __init kdb_init(int lvl)
2805 static int kdb_init_lvl = KDB_NOT_INITIALIZED;
2808 if (kdb_init_lvl == KDB_INIT_FULL || lvl <= kdb_init_lvl)
2810 for (i = kdb_init_lvl; i < lvl; i++) {
2812 case KDB_NOT_INITIALIZED:
2813 kdb_inittab(); /* Initialize Command Table */
2814 kdb_initbptab(); /* Initialize Breakpoints */
2816 case KDB_INIT_EARLY:
2817 kdb_cmd_init(); /* Build kdb_cmds tables */