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/atomic.h>
29 #include <linux/module.h>
30 #include <linux/moduleparam.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 "kdb_private.h"
50 #undef MODULE_PARAM_PREFIX
51 #define MODULE_PARAM_PREFIX "kdb."
53 static int kdb_cmd_enabled = CONFIG_KDB_DEFAULT_ENABLE;
54 module_param_named(cmd_enable, kdb_cmd_enabled, int, 0600);
56 char kdb_grep_string[KDB_GREP_STRLEN];
57 int kdb_grepping_flag;
58 EXPORT_SYMBOL(kdb_grepping_flag);
60 int kdb_grep_trailing;
63 * Kernel debugger state flags
65 unsigned int kdb_flags;
68 * kdb_lock protects updates to kdb_initial_cpu. Used to
69 * single thread processors through the kernel debugger.
71 int kdb_initial_cpu = -1; /* cpu number that owns kdb */
73 int kdb_state; /* General KDB state */
75 struct task_struct *kdb_current_task;
76 struct pt_regs *kdb_current_regs;
78 const char *kdb_diemsg;
79 static int kdb_go_count;
80 #ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
81 static unsigned int kdb_continue_catastrophic =
82 CONFIG_KDB_CONTINUE_CATASTROPHIC;
84 static unsigned int kdb_continue_catastrophic;
87 /* kdb_cmds_head describes the available commands. */
88 static LIST_HEAD(kdb_cmds_head);
90 typedef struct _kdbmsg {
91 int km_diag; /* kdb diagnostic */
92 char *km_msg; /* Corresponding message text */
95 #define KDBMSG(msgnum, text) \
96 { KDB_##msgnum, text }
98 static kdbmsg_t kdbmsgs[] = {
99 KDBMSG(NOTFOUND, "Command Not Found"),
100 KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
101 KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, "
102 "8 is only allowed on 64 bit systems"),
103 KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
104 KDBMSG(NOTENV, "Cannot find environment variable"),
105 KDBMSG(NOENVVALUE, "Environment variable should have value"),
106 KDBMSG(NOTIMP, "Command not implemented"),
107 KDBMSG(ENVFULL, "Environment full"),
108 KDBMSG(ENVBUFFULL, "Environment buffer full"),
109 KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
110 #ifdef CONFIG_CPU_XSCALE
111 KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
113 KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
115 KDBMSG(DUPBPT, "Duplicate breakpoint address"),
116 KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
117 KDBMSG(BADMODE, "Invalid IDMODE"),
118 KDBMSG(BADINT, "Illegal numeric value"),
119 KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
120 KDBMSG(BADREG, "Invalid register name"),
121 KDBMSG(BADCPUNUM, "Invalid cpu number"),
122 KDBMSG(BADLENGTH, "Invalid length field"),
123 KDBMSG(NOBP, "No Breakpoint exists"),
124 KDBMSG(BADADDR, "Invalid address"),
125 KDBMSG(NOPERM, "Permission denied"),
129 static const int __nkdb_err = ARRAY_SIZE(kdbmsgs);
133 * Initial environment. This is all kept static and local to
134 * this file. We don't want to rely on the memory allocation
135 * mechanisms in the kernel, so we use a very limited allocate-only
136 * heap for new and altered environment variables. The entire
137 * environment is limited to a fixed number of entries (add more
138 * to __env[] if required) and a fixed amount of heap (add more to
139 * KDB_ENVBUFSIZE if required).
142 static char *__env[31] = {
143 #if defined(CONFIG_SMP)
150 "MDCOUNT=8", /* lines of md output */
156 static const int __nenv = ARRAY_SIZE(__env);
158 struct task_struct *kdb_curr_task(int cpu)
160 struct task_struct *p = curr_task(cpu);
162 if ((task_thread_info(p)->flags & _TIF_MCA_INIT) && KDB_TSK(cpu))
169 * Check whether the flags of the current command and the permissions
170 * of the kdb console has allow a command to be run.
172 static inline bool kdb_check_flags(kdb_cmdflags_t flags, int permissions,
175 /* permissions comes from userspace so needs massaging slightly */
176 permissions &= KDB_ENABLE_MASK;
177 permissions |= KDB_ENABLE_ALWAYS_SAFE;
179 /* some commands change group when launched with no arguments */
181 permissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT;
183 flags |= KDB_ENABLE_ALL;
185 return permissions & flags;
189 * kdbgetenv - This function will return the character string value of
190 * an environment variable.
192 * match A character string representing an environment variable.
194 * NULL No environment variable matches 'match'
195 * char* Pointer to string value of environment variable.
197 char *kdbgetenv(const char *match)
200 int matchlen = strlen(match);
203 for (i = 0; i < __nenv; i++) {
209 if ((strncmp(match, e, matchlen) == 0)
210 && ((e[matchlen] == '\0')
211 || (e[matchlen] == '='))) {
212 char *cp = strchr(e, '=');
213 return cp ? ++cp : "";
220 * kdballocenv - This function is used to allocate bytes for
221 * environment entries.
223 * match A character string representing a numeric value
225 * *value the unsigned long representation of the env variable 'match'
227 * Zero on success, a kdb diagnostic on failure.
229 * We use a static environment buffer (envbuffer) to hold the values
230 * of dynamically generated environment variables (see kdb_set). Buffer
231 * space once allocated is never free'd, so over time, the amount of space
232 * (currently 512 bytes) will be exhausted if env variables are changed
235 static char *kdballocenv(size_t bytes)
237 #define KDB_ENVBUFSIZE 512
238 static char envbuffer[KDB_ENVBUFSIZE];
239 static int envbufsize;
242 if ((KDB_ENVBUFSIZE - envbufsize) >= bytes) {
243 ep = &envbuffer[envbufsize];
250 * kdbgetulenv - This function will return the value of an unsigned
251 * long-valued environment variable.
253 * match A character string representing a numeric value
255 * *value the unsigned long representation of the env variable 'match'
257 * Zero on success, a kdb diagnostic on failure.
259 static int kdbgetulenv(const char *match, unsigned long *value)
263 ep = kdbgetenv(match);
267 return KDB_NOENVVALUE;
269 *value = simple_strtoul(ep, NULL, 0);
275 * kdbgetintenv - This function will return the value of an
276 * integer-valued environment variable.
278 * match A character string representing an integer-valued env variable
280 * *value the integer representation of the environment variable 'match'
282 * Zero on success, a kdb diagnostic on failure.
284 int kdbgetintenv(const char *match, int *value)
289 diag = kdbgetulenv(match, &val);
296 * kdb_setenv() - Alter an existing environment variable or create a new one.
297 * @var: Name of the variable
298 * @val: Value of the variable
300 * Return: Zero on success, a kdb diagnostic on failure.
302 static int kdb_setenv(const char *var, const char *val)
306 size_t varlen, vallen;
308 varlen = strlen(var);
309 vallen = strlen(val);
310 ep = kdballocenv(varlen + vallen + 2);
312 return KDB_ENVBUFFULL;
314 sprintf(ep, "%s=%s", var, val);
316 for (i = 0; i < __nenv; i++) {
318 && ((strncmp(__env[i], var, varlen) == 0)
319 && ((__env[i][varlen] == '\0')
320 || (__env[i][varlen] == '=')))) {
327 * Wasn't existing variable. Fit into slot.
329 for (i = 0; i < __nenv-1; i++) {
330 if (__env[i] == (char *)0) {
340 * kdb_printenv() - Display the current environment variables.
342 static void kdb_printenv(void)
346 for (i = 0; i < __nenv; i++) {
348 kdb_printf("%s\n", __env[i]);
353 * kdbgetularg - This function will convert a numeric string into an
354 * unsigned long value.
356 * arg A character string representing a numeric value
358 * *value the unsigned long representation of arg.
360 * Zero on success, a kdb diagnostic on failure.
362 int kdbgetularg(const char *arg, unsigned long *value)
367 val = simple_strtoul(arg, &endp, 0);
371 * Also try base 16, for us folks too lazy to type the
374 val = simple_strtoul(arg, &endp, 16);
384 int kdbgetu64arg(const char *arg, u64 *value)
389 val = simple_strtoull(arg, &endp, 0);
393 val = simple_strtoull(arg, &endp, 16);
404 * kdb_set - This function implements the 'set' command. Alter an
405 * existing environment variable or create a new one.
407 int kdb_set(int argc, const char **argv)
410 * we can be invoked two ways:
411 * set var=value argv[1]="var", argv[2]="value"
412 * set var = value argv[1]="var", argv[2]="=", argv[3]="value"
413 * - if the latter, shift 'em down.
424 * Censor sensitive variables
426 if (strcmp(argv[1], "PROMPT") == 0 &&
427 !kdb_check_flags(KDB_ENABLE_MEM_READ, kdb_cmd_enabled, false))
431 * Check for internal variables
433 if (strcmp(argv[1], "KDBDEBUG") == 0) {
434 unsigned int debugflags;
437 debugflags = simple_strtoul(argv[2], &cp, 0);
438 if (cp == argv[2] || debugflags & ~KDB_DEBUG_FLAG_MASK) {
439 kdb_printf("kdb: illegal debug flags '%s'\n",
443 kdb_flags = (kdb_flags & ~KDB_DEBUG(MASK))
444 | (debugflags << KDB_DEBUG_FLAG_SHIFT);
450 * Tokenizer squashed the '=' sign. argv[1] is variable
451 * name, argv[2] = value.
453 return kdb_setenv(argv[1], argv[2]);
456 static int kdb_check_regs(void)
458 if (!kdb_current_regs) {
459 kdb_printf("No current kdb registers."
460 " You may need to select another task\n");
467 * kdbgetaddrarg - This function is responsible for parsing an
468 * address-expression and returning the value of the expression,
469 * symbol name, and offset to the caller.
471 * The argument may consist of a numeric value (decimal or
472 * hexadecimal), a symbol name, a register name (preceded by the
473 * percent sign), an environment variable with a numeric value
474 * (preceded by a dollar sign) or a simple arithmetic expression
475 * consisting of a symbol name, +/-, and a numeric constant value
478 * argc - count of arguments in argv
479 * argv - argument vector
480 * *nextarg - index to next unparsed argument in argv[]
481 * regs - Register state at time of KDB entry
483 * *value - receives the value of the address-expression
484 * *offset - receives the offset specified, if any
485 * *name - receives the symbol name, if any
486 * *nextarg - index to next unparsed argument in argv[]
488 * zero is returned on success, a kdb diagnostic code is
491 int kdbgetaddrarg(int argc, const char **argv, int *nextarg,
492 unsigned long *value, long *offset,
496 unsigned long off = 0;
506 * If the enable flags prohibit both arbitrary memory access
507 * and flow control then there are no reasonable grounds to
508 * provide symbol lookup.
510 if (!kdb_check_flags(KDB_ENABLE_MEM_READ | KDB_ENABLE_FLOW_CTRL,
511 kdb_cmd_enabled, false))
515 * Process arguments which follow the following syntax:
517 * symbol | numeric-address [+/- numeric-offset]
519 * $environment-variable
525 symname = (char *)argv[*nextarg];
528 * If there is no whitespace between the symbol
529 * or address and the '+' or '-' symbols, we
530 * remember the character and replace it with a
531 * null so the symbol/value can be properly parsed
533 cp = strpbrk(symname, "+-");
539 if (symname[0] == '$') {
540 diag = kdbgetulenv(&symname[1], &addr);
543 } else if (symname[0] == '%') {
544 diag = kdb_check_regs();
547 /* Implement register values with % at a later time as it is
552 found = kdbgetsymval(symname, &symtab);
554 addr = symtab.sym_start;
556 diag = kdbgetularg(argv[*nextarg], &addr);
563 found = kdbnearsym(addr, &symtab);
571 if (offset && name && *name)
572 *offset = addr - symtab.sym_start;
574 if ((*nextarg > argc)
579 * check for +/- and offset
582 if (symbol == '\0') {
583 if ((argv[*nextarg][0] != '+')
584 && (argv[*nextarg][0] != '-')) {
586 * Not our argument. Return.
590 positive = (argv[*nextarg][0] == '+');
594 positive = (symbol == '+');
597 * Now there must be an offset!
599 if ((*nextarg > argc)
600 && (symbol == '\0')) {
601 return KDB_INVADDRFMT;
605 cp = (char *)argv[*nextarg];
609 diag = kdbgetularg(cp, &off);
625 static void kdb_cmderror(int diag)
630 kdb_printf("no error detected (diagnostic is %d)\n", diag);
634 for (i = 0; i < __nkdb_err; i++) {
635 if (kdbmsgs[i].km_diag == diag) {
636 kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
641 kdb_printf("Unknown diag %d\n", -diag);
645 * kdb_defcmd, kdb_defcmd2 - This function implements the 'defcmd'
646 * command which defines one command as a set of other commands,
647 * terminated by endefcmd. kdb_defcmd processes the initial
648 * 'defcmd' command, kdb_defcmd2 is invoked from kdb_parse for
649 * the following commands until 'endefcmd'.
651 * argc argument count
652 * argv argument vector
654 * zero for success, a kdb diagnostic if error
657 kdbtab_t cmd; /* Macro command */
658 struct list_head statements; /* Associated statement list */
661 struct kdb_macro_statement {
662 char *statement; /* Statement text */
663 struct list_head list_node; /* Statement list node */
666 static struct kdb_macro *kdb_macro;
667 static bool defcmd_in_progress;
669 /* Forward references */
670 static int kdb_exec_defcmd(int argc, const char **argv);
672 static int kdb_defcmd2(const char *cmdstr, const char *argv0)
674 struct kdb_macro_statement *kms;
679 if (strcmp(argv0, "endefcmd") == 0) {
680 defcmd_in_progress = false;
681 if (!list_empty(&kdb_macro->statements))
682 kdb_register(&kdb_macro->cmd);
686 kms = kmalloc(sizeof(*kms), GFP_KDB);
688 kdb_printf("Could not allocate new kdb macro command: %s\n",
693 kms->statement = kdb_strdup(cmdstr, GFP_KDB);
694 list_add_tail(&kms->list_node, &kdb_macro->statements);
699 static int kdb_defcmd(int argc, const char **argv)
703 if (defcmd_in_progress) {
704 kdb_printf("kdb: nested defcmd detected, assuming missing "
706 kdb_defcmd2("endefcmd", "endefcmd");
710 struct kdb_macro *kmp;
711 struct kdb_macro_statement *kms;
713 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
714 if (kp->func == kdb_exec_defcmd) {
715 kdb_printf("defcmd %s \"%s\" \"%s\"\n",
716 kp->name, kp->usage, kp->help);
717 kmp = container_of(kp, struct kdb_macro, cmd);
718 list_for_each_entry(kms, &kmp->statements,
720 kdb_printf("%s", kms->statement);
721 kdb_printf("endefcmd\n");
728 if (in_dbg_master()) {
729 kdb_printf("Command only available during kdb_init()\n");
732 kdb_macro = kzalloc(sizeof(*kdb_macro), GFP_KDB);
736 mp = &kdb_macro->cmd;
737 mp->func = kdb_exec_defcmd;
739 mp->flags = KDB_ENABLE_ALWAYS_SAFE;
740 mp->name = kdb_strdup(argv[1], GFP_KDB);
743 mp->usage = kdb_strdup(argv[2], GFP_KDB);
746 mp->help = kdb_strdup(argv[3], GFP_KDB);
749 if (mp->usage[0] == '"') {
750 strcpy(mp->usage, argv[2]+1);
751 mp->usage[strlen(mp->usage)-1] = '\0';
753 if (mp->help[0] == '"') {
754 strcpy(mp->help, argv[3]+1);
755 mp->help[strlen(mp->help)-1] = '\0';
758 INIT_LIST_HEAD(&kdb_macro->statements);
759 defcmd_in_progress = true;
768 kdb_printf("Could not allocate new kdb_macro entry for %s\n", argv[1]);
773 * kdb_exec_defcmd - Execute the set of commands associated with this
776 * argc argument count
777 * argv argument vector
779 * zero for success, a kdb diagnostic if error
781 static int kdb_exec_defcmd(int argc, const char **argv)
785 struct kdb_macro *kmp;
786 struct kdb_macro_statement *kms;
791 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
792 if (strcmp(kp->name, argv[0]) == 0)
795 if (list_entry_is_head(kp, &kdb_cmds_head, list_node)) {
796 kdb_printf("kdb_exec_defcmd: could not find commands for %s\n",
800 kmp = container_of(kp, struct kdb_macro, cmd);
801 list_for_each_entry(kms, &kmp->statements, list_node) {
803 * Recursive use of kdb_parse, do not use argv after this point.
806 kdb_printf("[%s]kdb> %s\n", kmp->cmd.name, kms->statement);
807 ret = kdb_parse(kms->statement);
814 /* Command history */
815 #define KDB_CMD_HISTORY_COUNT 32
816 #define CMD_BUFLEN 200 /* kdb_printf: max printline
818 static unsigned int cmd_head, cmd_tail;
819 static unsigned int cmdptr;
820 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
821 static char cmd_cur[CMD_BUFLEN];
824 * The "str" argument may point to something like | grep xyz
826 static void parse_grep(const char *str)
829 char *cp = (char *)str, *cp2;
831 /* sanity check: we should have been called with the \ first */
837 if (!str_has_prefix(cp, "grep ")) {
838 kdb_printf("invalid 'pipe', see grephelp\n");
844 cp2 = strchr(cp, '\n');
846 *cp2 = '\0'; /* remove the trailing newline */
849 kdb_printf("invalid 'pipe', see grephelp\n");
852 /* now cp points to a nonzero length search string */
854 /* allow it be "x y z" by removing the "'s - there must
857 cp2 = strchr(cp, '"');
859 kdb_printf("invalid quoted string, see grephelp\n");
862 *cp2 = '\0'; /* end the string where the 2nd " was */
864 kdb_grep_leading = 0;
866 kdb_grep_leading = 1;
870 kdb_grep_trailing = 0;
871 if (*(cp+len-1) == '$') {
872 kdb_grep_trailing = 1;
878 if (len >= KDB_GREP_STRLEN) {
879 kdb_printf("search string too long\n");
882 strcpy(kdb_grep_string, cp);
888 * kdb_parse - Parse the command line, search the command table for a
889 * matching command and invoke the command function. This
890 * function may be called recursively, if it is, the second call
891 * will overwrite argv and cbuf. It is the caller's
892 * responsibility to save their argv if they recursively call
895 * cmdstr The input command line to be parsed.
896 * regs The registers at the time kdb was entered.
898 * Zero for success, a kdb diagnostic if failure.
900 * Limited to 20 tokens.
902 * Real rudimentary tokenization. Basically only whitespace
903 * is considered a token delimiter (but special consideration
904 * is taken of the '=' sign as used by the 'set' command).
906 * The algorithm used to tokenize the input string relies on
907 * there being at least one whitespace (or otherwise useless)
908 * character between tokens as the character immediately following
909 * the token is altered in-place to a null-byte to terminate the
915 int kdb_parse(const char *cmdstr)
917 static char *argv[MAXARGC];
919 static char cbuf[CMD_BUFLEN+2];
923 int escaped, ignore_errors = 0, check_grep = 0;
926 * First tokenize the command string.
930 if (KDB_FLAG(CMD_INTERRUPT)) {
931 /* Previous command was interrupted, newline must not
932 * repeat the command */
933 KDB_FLAG_CLEAR(CMD_INTERRUPT);
934 KDB_STATE_SET(PAGER);
935 argc = 0; /* no repeat */
938 if (*cp != '\n' && *cp != '\0') {
942 /* skip whitespace */
945 if ((*cp == '\0') || (*cp == '\n') ||
946 (*cp == '#' && !defcmd_in_progress))
948 /* special case: check for | grep pattern */
953 if (cpp >= cbuf + CMD_BUFLEN) {
954 kdb_printf("kdb_parse: command buffer "
955 "overflow, command ignored\n%s\n",
959 if (argc >= MAXARGC - 1) {
960 kdb_printf("kdb_parse: too many arguments, "
961 "command ignored\n%s\n", cmdstr);
967 /* Copy to next unquoted and unescaped
968 * whitespace or '=' */
969 while (*cp && *cp != '\n' &&
970 (escaped || quoted || !isspace(*cp))) {
971 if (cpp >= cbuf + CMD_BUFLEN)
985 else if (*cp == '\'' || *cp == '"')
988 if (*cpp == '=' && !quoted)
992 *cpp++ = '\0'; /* Squash a ws or '=' character */
999 if (defcmd_in_progress) {
1000 int result = kdb_defcmd2(cmdstr, argv[0]);
1001 if (!defcmd_in_progress) {
1002 argc = 0; /* avoid repeat on endefcmd */
1007 if (argv[0][0] == '-' && argv[0][1] &&
1008 (argv[0][1] < '0' || argv[0][1] > '9')) {
1013 list_for_each_entry(tp, &kdb_cmds_head, list_node) {
1015 * If this command is allowed to be abbreviated,
1016 * check to see if this is it.
1018 if (tp->minlen && (strlen(argv[0]) <= tp->minlen) &&
1019 (strncmp(argv[0], tp->name, tp->minlen) == 0))
1022 if (strcmp(argv[0], tp->name) == 0)
1027 * If we don't find a command by this name, see if the first
1028 * few characters of this match any of the known commands.
1029 * e.g., md1c20 should match md.
1031 if (list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1032 list_for_each_entry(tp, &kdb_cmds_head, list_node) {
1033 if (strncmp(argv[0], tp->name, strlen(tp->name)) == 0)
1038 if (!list_entry_is_head(tp, &kdb_cmds_head, list_node)) {
1041 if (!kdb_check_flags(tp->flags, kdb_cmd_enabled, argc <= 1))
1045 result = (*tp->func)(argc-1, (const char **)argv);
1046 if (result && ignore_errors && result > KDB_CMD_GO)
1048 KDB_STATE_CLEAR(CMD);
1050 if (tp->flags & KDB_REPEAT_WITH_ARGS)
1053 argc = tp->flags & KDB_REPEAT_NO_ARGS ? 1 : 0;
1055 *(argv[argc]) = '\0';
1060 * If the input with which we were presented does not
1061 * map to an existing command, attempt to parse it as an
1062 * address argument and display the result. Useful for
1063 * obtaining the address of a variable, or the nearest symbol
1064 * to an address contained in a register.
1067 unsigned long value;
1072 if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
1073 &value, &offset, &name)) {
1074 return KDB_NOTFOUND;
1077 kdb_printf("%s = ", argv[0]);
1078 kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
1085 static int handle_ctrl_cmd(char *cmd)
1090 /* initial situation */
1091 if (cmd_head == cmd_tail)
1095 if (cmdptr != cmd_tail)
1096 cmdptr = (cmdptr + KDB_CMD_HISTORY_COUNT - 1) %
1097 KDB_CMD_HISTORY_COUNT;
1098 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1101 if (cmdptr != cmd_head)
1102 cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
1103 strscpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1110 * kdb_reboot - This function implements the 'reboot' command. Reboot
1111 * the system immediately, or loop for ever on failure.
1113 static int kdb_reboot(int argc, const char **argv)
1115 emergency_restart();
1116 kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
1123 static void kdb_dumpregs(struct pt_regs *regs)
1125 int old_lvl = console_loglevel;
1126 console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
1131 console_loglevel = old_lvl;
1134 static void kdb_set_current_task(struct task_struct *p)
1136 kdb_current_task = p;
1138 if (kdb_task_has_cpu(p)) {
1139 kdb_current_regs = KDB_TSKREGS(kdb_process_cpu(p));
1142 kdb_current_regs = NULL;
1145 static void drop_newline(char *buf)
1147 size_t len = strlen(buf);
1151 if (*(buf + len - 1) == '\n')
1152 *(buf + len - 1) = '\0';
1156 * kdb_local - The main code for kdb. This routine is invoked on a
1157 * specific processor, it is not global. The main kdb() routine
1158 * ensures that only one processor at a time is in this routine.
1159 * This code is called with the real reason code on the first
1160 * entry to a kdb session, thereafter it is called with reason
1161 * SWITCH, even if the user goes back to the original cpu.
1163 * reason The reason KDB was invoked
1164 * error The hardware-defined error code
1165 * regs The exception frame at time of fault/breakpoint.
1166 * db_result Result code from the break or debug point.
1168 * 0 KDB was invoked for an event which it wasn't responsible
1169 * 1 KDB handled the event for which it was invoked.
1170 * KDB_CMD_GO User typed 'go'.
1171 * KDB_CMD_CPU User switched to another cpu.
1172 * KDB_CMD_SS Single step.
1174 static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
1175 kdb_dbtrap_t db_result)
1179 struct task_struct *kdb_current =
1180 kdb_curr_task(raw_smp_processor_id());
1182 KDB_DEBUG_STATE("kdb_local 1", reason);
1184 if (reason == KDB_REASON_DEBUG) {
1185 /* special case below */
1187 kdb_printf("\nEntering kdb (current=0x%px, pid %d) ",
1188 kdb_current, kdb_current ? kdb_current->pid : 0);
1189 #if defined(CONFIG_SMP)
1190 kdb_printf("on processor %d ", raw_smp_processor_id());
1195 case KDB_REASON_DEBUG:
1198 * If re-entering kdb after a single step
1199 * command, don't print the message.
1201 switch (db_result) {
1203 kdb_printf("\nEntering kdb (0x%px, pid %d) ",
1204 kdb_current, kdb_current->pid);
1205 #if defined(CONFIG_SMP)
1206 kdb_printf("on processor %d ", raw_smp_processor_id());
1208 kdb_printf("due to Debug @ " kdb_machreg_fmt "\n",
1209 instruction_pointer(regs));
1214 KDB_DEBUG_STATE("kdb_local 4", reason);
1215 return 1; /* kdba_db_trap did the work */
1217 kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
1224 case KDB_REASON_ENTER:
1225 if (KDB_STATE(KEYBOARD))
1226 kdb_printf("due to Keyboard Entry\n");
1228 kdb_printf("due to KDB_ENTER()\n");
1230 case KDB_REASON_KEYBOARD:
1231 KDB_STATE_SET(KEYBOARD);
1232 kdb_printf("due to Keyboard Entry\n");
1234 case KDB_REASON_ENTER_SLAVE:
1235 /* drop through, slaves only get released via cpu switch */
1236 case KDB_REASON_SWITCH:
1237 kdb_printf("due to cpu switch\n");
1239 case KDB_REASON_OOPS:
1240 kdb_printf("Oops: %s\n", kdb_diemsg);
1241 kdb_printf("due to oops @ " kdb_machreg_fmt "\n",
1242 instruction_pointer(regs));
1245 case KDB_REASON_SYSTEM_NMI:
1246 kdb_printf("due to System NonMaskable Interrupt\n");
1248 case KDB_REASON_NMI:
1249 kdb_printf("due to NonMaskable Interrupt @ "
1250 kdb_machreg_fmt "\n",
1251 instruction_pointer(regs));
1253 case KDB_REASON_SSTEP:
1254 case KDB_REASON_BREAK:
1255 kdb_printf("due to %s @ " kdb_machreg_fmt "\n",
1256 reason == KDB_REASON_BREAK ?
1257 "Breakpoint" : "SS trap", instruction_pointer(regs));
1259 * Determine if this breakpoint is one that we
1260 * are interested in.
1262 if (db_result != KDB_DB_BPT) {
1263 kdb_printf("kdb: error return from kdba_bp_trap: %d\n",
1265 KDB_DEBUG_STATE("kdb_local 6", reason);
1266 return 0; /* Not for us, dismiss it */
1269 case KDB_REASON_RECURSE:
1270 kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n",
1271 instruction_pointer(regs));
1274 kdb_printf("kdb: unexpected reason code: %d\n", reason);
1275 KDB_DEBUG_STATE("kdb_local 8", reason);
1276 return 0; /* Not for us, dismiss it */
1281 * Initialize pager context.
1284 KDB_STATE_CLEAR(SUPPRESS);
1285 kdb_grepping_flag = 0;
1286 /* ensure the old search does not leak into '/' commands */
1287 kdb_grep_string[0] = '\0';
1291 *(cmd_hist[cmd_head]) = '\0';
1294 /* PROMPT can only be set if we have MEM_READ permission. */
1295 snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
1296 raw_smp_processor_id());
1297 if (defcmd_in_progress)
1298 strncat(kdb_prompt_str, "[defcmd]", CMD_BUFLEN);
1301 * Fetch command from keyboard
1303 cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
1304 if (*cmdbuf != '\n') {
1306 if (cmdptr == cmd_head) {
1307 strscpy(cmd_hist[cmd_head], cmd_cur,
1309 *(cmd_hist[cmd_head] +
1310 strlen(cmd_hist[cmd_head])-1) = '\0';
1312 if (!handle_ctrl_cmd(cmdbuf))
1313 *(cmd_cur+strlen(cmd_cur)-1) = '\0';
1315 goto do_full_getstr;
1317 strscpy(cmd_hist[cmd_head], cmd_cur,
1321 cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
1322 if (cmd_head == cmd_tail)
1323 cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
1327 diag = kdb_parse(cmdbuf);
1328 if (diag == KDB_NOTFOUND) {
1329 drop_newline(cmdbuf);
1330 kdb_printf("Unknown kdb command: '%s'\n", cmdbuf);
1333 if (diag == KDB_CMD_GO
1334 || diag == KDB_CMD_CPU
1335 || diag == KDB_CMD_SS
1336 || diag == KDB_CMD_KGDB)
1342 KDB_DEBUG_STATE("kdb_local 9", diag);
1348 * kdb_print_state - Print the state data for the current processor
1351 * text Identifies the debug point
1352 * value Any integer value to be printed, e.g. reason code.
1354 void kdb_print_state(const char *text, int value)
1356 kdb_printf("state: %s cpu %d value %d initial %d state %x\n",
1357 text, raw_smp_processor_id(), value, kdb_initial_cpu,
1362 * kdb_main_loop - After initial setup and assignment of the
1363 * controlling cpu, all cpus are in this loop. One cpu is in
1364 * control and will issue the kdb prompt, the others will spin
1365 * until 'go' or cpu switch.
1367 * To get a consistent view of the kernel stacks for all
1368 * processes, this routine is invoked from the main kdb code via
1369 * an architecture specific routine. kdba_main_loop is
1370 * responsible for making the kernel stacks consistent for all
1371 * processes, there should be no difference between a blocked
1372 * process and a running process as far as kdb is concerned.
1374 * reason The reason KDB was invoked
1375 * error The hardware-defined error code
1376 * reason2 kdb's current reason code.
1377 * Initially error but can change
1378 * according to kdb state.
1379 * db_result Result code from break or debug point.
1380 * regs The exception frame at time of fault/breakpoint.
1381 * should always be valid.
1383 * 0 KDB was invoked for an event which it wasn't responsible
1384 * 1 KDB handled the event for which it was invoked.
1386 int kdb_main_loop(kdb_reason_t reason, kdb_reason_t reason2, int error,
1387 kdb_dbtrap_t db_result, struct pt_regs *regs)
1390 /* Stay in kdb() until 'go', 'ss[b]' or an error */
1393 * All processors except the one that is in control
1396 KDB_DEBUG_STATE("kdb_main_loop 1", reason);
1397 while (KDB_STATE(HOLD_CPU)) {
1398 /* state KDB is turned off by kdb_cpu to see if the
1399 * other cpus are still live, each cpu in this loop
1402 if (!KDB_STATE(KDB))
1406 KDB_STATE_CLEAR(SUPPRESS);
1407 KDB_DEBUG_STATE("kdb_main_loop 2", reason);
1408 if (KDB_STATE(LEAVING))
1409 break; /* Another cpu said 'go' */
1410 /* Still using kdb, this processor is in control */
1411 result = kdb_local(reason2, error, regs, db_result);
1412 KDB_DEBUG_STATE("kdb_main_loop 3", result);
1414 if (result == KDB_CMD_CPU)
1417 if (result == KDB_CMD_SS) {
1418 KDB_STATE_SET(DOING_SS);
1422 if (result == KDB_CMD_KGDB) {
1423 if (!KDB_STATE(DOING_KGDB))
1424 kdb_printf("Entering please attach debugger "
1425 "or use $D#44+ or $3#33\n");
1428 if (result && result != 1 && result != KDB_CMD_GO)
1429 kdb_printf("\nUnexpected kdb_local return code %d\n",
1431 KDB_DEBUG_STATE("kdb_main_loop 4", reason);
1434 if (KDB_STATE(DOING_SS))
1435 KDB_STATE_CLEAR(SSBPT);
1437 /* Clean up any keyboard devices before leaving */
1438 kdb_kbd_cleanup_state();
1444 * kdb_mdr - This function implements the guts of the 'mdr', memory
1446 * mdr <addr arg>,<byte count>
1448 * addr Start address
1449 * count Number of bytes
1451 * Always 0. Any errors are detected and printed by kdb_getarea.
1453 static int kdb_mdr(unsigned long addr, unsigned int count)
1457 if (kdb_getarea(c, addr))
1459 kdb_printf("%02x", c);
1467 * kdb_md - This function implements the 'md', 'md1', 'md2', 'md4',
1468 * 'md8' 'mdr' and 'mds' commands.
1470 * md|mds [<addr arg> [<line count> [<radix>]]]
1471 * mdWcN [<addr arg> [<line count> [<radix>]]]
1472 * where W = is the width (1, 2, 4 or 8) and N is the count.
1473 * for eg., md1c20 reads 20 bytes, 1 at a time.
1474 * mdr <addr arg>,<byte count>
1476 static void kdb_md_line(const char *fmtstr, unsigned long addr,
1477 int symbolic, int nosect, int bytesperword,
1478 int num, int repeat, int phys)
1480 /* print just one line of data */
1481 kdb_symtab_t symtab;
1488 memset(cbuf, '\0', sizeof(cbuf));
1490 kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
1492 kdb_printf(kdb_machreg_fmt0 " ", addr);
1494 for (i = 0; i < num && repeat--; i++) {
1496 if (kdb_getphysword(&word, addr, bytesperword))
1498 } else if (kdb_getword(&word, addr, bytesperword))
1500 kdb_printf(fmtstr, word);
1502 kdbnearsym(word, &symtab);
1504 memset(&symtab, 0, sizeof(symtab));
1505 if (symtab.sym_name) {
1506 kdb_symbol_print(word, &symtab, 0);
1509 kdb_printf(" %s %s "
1512 kdb_machreg_fmt, symtab.mod_name,
1513 symtab.sec_name, symtab.sec_start,
1514 symtab.sym_start, symtab.sym_end);
1516 addr += bytesperword;
1524 cp = wc.c + 8 - bytesperword;
1529 #define printable_char(c) \
1530 ({unsigned char __c = c; isascii(__c) && isprint(__c) ? __c : '.'; })
1531 for (j = 0; j < bytesperword; j++)
1532 *c++ = printable_char(*cp++);
1533 addr += bytesperword;
1534 #undef printable_char
1537 kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1),
1541 static int kdb_md(int argc, const char **argv)
1543 static unsigned long last_addr;
1544 static int last_radix, last_bytesperword, last_repeat;
1545 int radix = 16, mdcount = 8, bytesperword = KDB_WORD_SIZE, repeat;
1547 char fmtchar, fmtstr[64];
1556 kdbgetintenv("MDCOUNT", &mdcount);
1557 kdbgetintenv("RADIX", &radix);
1558 kdbgetintenv("BYTESPERWORD", &bytesperword);
1560 /* Assume 'md <addr>' and start with environment values */
1561 repeat = mdcount * 16 / bytesperword;
1563 if (strcmp(argv[0], "mdr") == 0) {
1564 if (argc == 2 || (argc == 0 && last_addr != 0))
1567 return KDB_ARGCOUNT;
1568 } else if (isdigit(argv[0][2])) {
1569 bytesperword = (int)(argv[0][2] - '0');
1570 if (bytesperword == 0) {
1571 bytesperword = last_bytesperword;
1572 if (bytesperword == 0)
1575 last_bytesperword = bytesperword;
1576 repeat = mdcount * 16 / bytesperword;
1579 else if (argv[0][3] == 'c' && argv[0][4]) {
1581 repeat = simple_strtoul(argv[0] + 4, &p, 10);
1582 mdcount = ((repeat * bytesperword) + 15) / 16;
1585 last_repeat = repeat;
1586 } else if (strcmp(argv[0], "md") == 0)
1588 else if (strcmp(argv[0], "mds") == 0)
1590 else if (strcmp(argv[0], "mdp") == 0) {
1594 return KDB_NOTFOUND;
1598 return KDB_ARGCOUNT;
1601 bytesperword = last_bytesperword;
1602 repeat = last_repeat;
1606 mdcount = ((repeat * bytesperword) + 15) / 16;
1611 int diag, nextarg = 1;
1612 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr,
1616 if (argc > nextarg+2)
1617 return KDB_ARGCOUNT;
1619 if (argc >= nextarg) {
1620 diag = kdbgetularg(argv[nextarg], &val);
1622 mdcount = (int) val;
1626 repeat = mdcount * 16 / bytesperword;
1629 if (argc >= nextarg+1) {
1630 diag = kdbgetularg(argv[nextarg+1], &val);
1636 if (strcmp(argv[0], "mdr") == 0) {
1639 ret = kdb_mdr(addr, mdcount);
1640 last_addr += mdcount;
1641 last_repeat = mdcount;
1642 last_bytesperword = bytesperword; // to make REPEAT happy
1657 return KDB_BADRADIX;
1662 if (bytesperword > KDB_WORD_SIZE)
1663 return KDB_BADWIDTH;
1665 switch (bytesperword) {
1667 sprintf(fmtstr, "%%16.16l%c ", fmtchar);
1670 sprintf(fmtstr, "%%8.8l%c ", fmtchar);
1673 sprintf(fmtstr, "%%4.4l%c ", fmtchar);
1676 sprintf(fmtstr, "%%2.2l%c ", fmtchar);
1679 return KDB_BADWIDTH;
1682 last_repeat = repeat;
1683 last_bytesperword = bytesperword;
1685 if (strcmp(argv[0], "mds") == 0) {
1687 /* Do not save these changes as last_*, they are temporary mds
1690 bytesperword = KDB_WORD_SIZE;
1692 kdbgetintenv("NOSECT", &nosect);
1695 /* Round address down modulo BYTESPERWORD */
1697 addr &= ~(bytesperword-1);
1699 while (repeat > 0) {
1701 int n, z, num = (symbolic ? 1 : (16 / bytesperword));
1703 if (KDB_FLAG(CMD_INTERRUPT))
1705 for (a = addr, z = 0; z < repeat; a += bytesperword, ++z) {
1707 if (kdb_getphysword(&word, a, bytesperword)
1710 } else if (kdb_getword(&word, a, bytesperword) || word)
1713 n = min(num, repeat);
1714 kdb_md_line(fmtstr, addr, symbolic, nosect, bytesperword,
1716 addr += bytesperword * n;
1718 z = (z + num - 1) / num;
1720 int s = num * (z-2);
1721 kdb_printf(kdb_machreg_fmt0 "-" kdb_machreg_fmt0
1722 " zero suppressed\n",
1723 addr, addr + bytesperword * s - 1);
1724 addr += bytesperword * s;
1734 * kdb_mm - This function implements the 'mm' command.
1735 * mm address-expression new-value
1737 * mm works on machine words, mmW works on bytes.
1739 static int kdb_mm(int argc, const char **argv)
1744 unsigned long contents;
1748 if (argv[0][2] && !isdigit(argv[0][2]))
1749 return KDB_NOTFOUND;
1752 return KDB_ARGCOUNT;
1755 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
1760 return KDB_ARGCOUNT;
1761 diag = kdbgetaddrarg(argc, argv, &nextarg, &contents, NULL, NULL);
1765 if (nextarg != argc + 1)
1766 return KDB_ARGCOUNT;
1768 width = argv[0][2] ? (argv[0][2] - '0') : (KDB_WORD_SIZE);
1769 diag = kdb_putword(addr, contents, width);
1773 kdb_printf(kdb_machreg_fmt " = " kdb_machreg_fmt "\n", addr, contents);
1779 * kdb_go - This function implements the 'go' command.
1780 * go [address-expression]
1782 static int kdb_go(int argc, const char **argv)
1789 if (raw_smp_processor_id() != kdb_initial_cpu) {
1790 kdb_printf("go must execute on the entry cpu, "
1791 "please use \"cpu %d\" and then execute go\n",
1793 return KDB_BADCPUNUM;
1797 diag = kdbgetaddrarg(argc, argv, &nextarg,
1798 &addr, &offset, NULL);
1802 return KDB_ARGCOUNT;
1806 if (KDB_FLAG(CATASTROPHIC)) {
1807 kdb_printf("Catastrophic error detected\n");
1808 kdb_printf("kdb_continue_catastrophic=%d, ",
1809 kdb_continue_catastrophic);
1810 if (kdb_continue_catastrophic == 0 && kdb_go_count++ == 0) {
1811 kdb_printf("type go a second time if you really want "
1815 if (kdb_continue_catastrophic == 2) {
1816 kdb_printf("forcing reboot\n");
1817 kdb_reboot(0, NULL);
1819 kdb_printf("attempting to continue\n");
1825 * kdb_rd - This function implements the 'rd' command.
1827 static int kdb_rd(int argc, const char **argv)
1829 int len = kdb_check_regs();
1830 #if DBG_MAX_REG_NUM > 0
1842 for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1843 rsize = dbg_reg_def[i].size * 2;
1846 if (len + strlen(dbg_reg_def[i].name) + 4 + rsize > 80) {
1851 len += kdb_printf(" ");
1852 switch(dbg_reg_def[i].size * 8) {
1854 rname = dbg_get_reg(i, ®8, kdb_current_regs);
1857 len += kdb_printf("%s: %02x", rname, reg8);
1860 rname = dbg_get_reg(i, ®16, kdb_current_regs);
1863 len += kdb_printf("%s: %04x", rname, reg16);
1866 rname = dbg_get_reg(i, ®32, kdb_current_regs);
1869 len += kdb_printf("%s: %08x", rname, reg32);
1872 rname = dbg_get_reg(i, ®64, kdb_current_regs);
1875 len += kdb_printf("%s: %016llx", rname, reg64);
1878 len += kdb_printf("%s: ??", dbg_reg_def[i].name);
1886 kdb_dumpregs(kdb_current_regs);
1892 * kdb_rm - This function implements the 'rm' (register modify) command.
1893 * rm register-name new-contents
1895 * Allows register modification with the same restrictions as gdb
1897 static int kdb_rm(int argc, const char **argv)
1899 #if DBG_MAX_REG_NUM > 0
1909 return KDB_ARGCOUNT;
1911 * Allow presence or absence of leading '%' symbol.
1917 diag = kdbgetu64arg(argv[2], ®64);
1921 diag = kdb_check_regs();
1926 for (i = 0; i < DBG_MAX_REG_NUM; i++) {
1927 if (strcmp(rname, dbg_reg_def[i].name) == 0) {
1933 switch(dbg_reg_def[i].size * 8) {
1936 dbg_set_reg(i, ®8, kdb_current_regs);
1940 dbg_set_reg(i, ®16, kdb_current_regs);
1944 dbg_set_reg(i, ®32, kdb_current_regs);
1947 dbg_set_reg(i, ®64, kdb_current_regs);
1953 kdb_printf("ERROR: Register set currently not implemented\n");
1958 #if defined(CONFIG_MAGIC_SYSRQ)
1960 * kdb_sr - This function implements the 'sr' (SYSRQ key) command
1961 * which interfaces to the soi-disant MAGIC SYSRQ functionality.
1962 * sr <magic-sysrq-code>
1964 static int kdb_sr(int argc, const char **argv)
1967 !kdb_check_flags(KDB_ENABLE_ALL, kdb_cmd_enabled, false);
1970 return KDB_ARGCOUNT;
1973 __handle_sysrq(*argv[1], check_mask);
1978 #endif /* CONFIG_MAGIC_SYSRQ */
1981 * kdb_ef - This function implements the 'regs' (display exception
1982 * frame) command. This command takes an address and expects to
1983 * find an exception frame at that address, formats and prints
1985 * regs address-expression
1989 static int kdb_ef(int argc, const char **argv)
1997 return KDB_ARGCOUNT;
2000 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL);
2003 show_regs((struct pt_regs *)addr);
2007 #if defined(CONFIG_MODULES)
2009 * kdb_lsmod - This function implements the 'lsmod' command. Lists
2010 * currently loaded kernel modules.
2011 * Mostly taken from userland lsmod.
2013 static int kdb_lsmod(int argc, const char **argv)
2018 return KDB_ARGCOUNT;
2020 kdb_printf("Module Size modstruct Used by\n");
2021 list_for_each_entry(mod, kdb_modules, list) {
2022 if (mod->state == MODULE_STATE_UNFORMED)
2025 kdb_printf("%-20s%8u 0x%px ", mod->name,
2026 mod->core_layout.size, (void *)mod);
2027 #ifdef CONFIG_MODULE_UNLOAD
2028 kdb_printf("%4d ", module_refcount(mod));
2030 if (mod->state == MODULE_STATE_GOING)
2031 kdb_printf(" (Unloading)");
2032 else if (mod->state == MODULE_STATE_COMING)
2033 kdb_printf(" (Loading)");
2035 kdb_printf(" (Live)");
2036 kdb_printf(" 0x%px", mod->core_layout.base);
2038 #ifdef CONFIG_MODULE_UNLOAD
2040 struct module_use *use;
2042 list_for_each_entry(use, &mod->source_list,
2044 kdb_printf("%s ", use->target->name);
2053 #endif /* CONFIG_MODULES */
2056 * kdb_env - This function implements the 'env' command. Display the
2057 * current environment variables.
2060 static int kdb_env(int argc, const char **argv)
2064 if (KDB_DEBUG(MASK))
2065 kdb_printf("KDBDEBUG=0x%x\n",
2066 (kdb_flags & KDB_DEBUG(MASK)) >> KDB_DEBUG_FLAG_SHIFT);
2071 #ifdef CONFIG_PRINTK
2073 * kdb_dmesg - This function implements the 'dmesg' command to display
2074 * the contents of the syslog buffer.
2075 * dmesg [lines] [adjust]
2077 static int kdb_dmesg(int argc, const char **argv)
2085 struct kmsg_dump_iter iter;
2090 return KDB_ARGCOUNT;
2093 lines = simple_strtol(argv[1], &cp, 0);
2097 adjust = simple_strtoul(argv[2], &cp, 0);
2098 if (*cp || adjust < 0)
2103 /* disable LOGGING if set */
2104 diag = kdbgetintenv("LOGGING", &logging);
2105 if (!diag && logging) {
2106 const char *setargs[] = { "set", "LOGGING", "0" };
2107 kdb_set(2, setargs);
2110 kmsg_dump_rewind(&iter);
2111 while (kmsg_dump_get_line(&iter, 1, NULL, 0, NULL))
2116 kdb_printf("buffer only contains %d lines, nothing "
2118 else if (adjust - lines >= n)
2119 kdb_printf("buffer only contains %d lines, last %d "
2120 "lines printed\n", n, n - adjust);
2123 } else if (lines > 0) {
2124 skip = n - lines - adjust;
2127 kdb_printf("buffer only contains %d lines, "
2128 "nothing printed\n", n);
2130 } else if (skip < 0) {
2133 kdb_printf("buffer only contains %d lines, first "
2134 "%d lines printed\n", n, lines);
2140 if (skip >= n || skip < 0)
2143 kmsg_dump_rewind(&iter);
2144 while (kmsg_dump_get_line(&iter, 1, buf, sizeof(buf), &len)) {
2151 if (KDB_FLAG(CMD_INTERRUPT))
2154 kdb_printf("%.*s\n", (int)len - 1, buf);
2159 #endif /* CONFIG_PRINTK */
2161 /* Make sure we balance enable/disable calls, must disable first. */
2162 static atomic_t kdb_nmi_disabled;
2164 static int kdb_disable_nmi(int argc, const char *argv[])
2166 if (atomic_read(&kdb_nmi_disabled))
2168 atomic_set(&kdb_nmi_disabled, 1);
2169 arch_kgdb_ops.enable_nmi(0);
2173 static int kdb_param_enable_nmi(const char *val, const struct kernel_param *kp)
2175 if (!atomic_add_unless(&kdb_nmi_disabled, -1, 0))
2177 arch_kgdb_ops.enable_nmi(1);
2181 static const struct kernel_param_ops kdb_param_ops_enable_nmi = {
2182 .set = kdb_param_enable_nmi,
2184 module_param_cb(enable_nmi, &kdb_param_ops_enable_nmi, NULL, 0600);
2187 * kdb_cpu - This function implements the 'cpu' command.
2190 * KDB_CMD_CPU for success, a kdb diagnostic if error
2192 static void kdb_cpu_status(void)
2194 int i, start_cpu, first_print = 1;
2195 char state, prev_state = '?';
2197 kdb_printf("Currently on cpu %d\n", raw_smp_processor_id());
2198 kdb_printf("Available cpus: ");
2199 for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
2200 if (!cpu_online(i)) {
2201 state = 'F'; /* cpu is offline */
2202 } else if (!kgdb_info[i].enter_kgdb) {
2203 state = 'D'; /* cpu is online but unresponsive */
2205 state = ' '; /* cpu is responding to kdb */
2206 if (kdb_task_state_char(KDB_TSK(i)) == 'I')
2207 state = 'I'; /* idle task */
2209 if (state != prev_state) {
2210 if (prev_state != '?') {
2214 kdb_printf("%d", start_cpu);
2215 if (start_cpu < i-1)
2216 kdb_printf("-%d", i-1);
2217 if (prev_state != ' ')
2218 kdb_printf("(%c)", prev_state);
2224 /* print the trailing cpus, ignoring them if they are all offline */
2225 if (prev_state != 'F') {
2228 kdb_printf("%d", start_cpu);
2229 if (start_cpu < i-1)
2230 kdb_printf("-%d", i-1);
2231 if (prev_state != ' ')
2232 kdb_printf("(%c)", prev_state);
2237 static int kdb_cpu(int argc, const char **argv)
2239 unsigned long cpunum;
2248 return KDB_ARGCOUNT;
2250 diag = kdbgetularg(argv[1], &cpunum);
2257 if ((cpunum >= CONFIG_NR_CPUS) || !kgdb_info[cpunum].enter_kgdb)
2258 return KDB_BADCPUNUM;
2260 dbg_switch_cpu = cpunum;
2263 * Switch to other cpu
2268 /* The user may not realize that ps/bta with no parameters does not print idle
2269 * or sleeping system daemon processes, so tell them how many were suppressed.
2271 void kdb_ps_suppressed(void)
2273 int idle = 0, daemon = 0;
2274 unsigned long mask_I = kdb_task_state_string("I"),
2275 mask_M = kdb_task_state_string("M");
2277 const struct task_struct *p, *g;
2278 for_each_online_cpu(cpu) {
2279 p = kdb_curr_task(cpu);
2280 if (kdb_task_state(p, mask_I))
2283 for_each_process_thread(g, p) {
2284 if (kdb_task_state(p, mask_M))
2287 if (idle || daemon) {
2289 kdb_printf("%d idle process%s (state I)%s\n",
2290 idle, idle == 1 ? "" : "es",
2291 daemon ? " and " : "");
2293 kdb_printf("%d sleeping system daemon (state M) "
2294 "process%s", daemon,
2295 daemon == 1 ? "" : "es");
2296 kdb_printf(" suppressed,\nuse 'ps A' to see all.\n");
2301 * kdb_ps - This function implements the 'ps' command which shows a
2302 * list of the active processes.
2303 * ps [DRSTCZEUIMA] All processes, optionally filtered by state
2305 void kdb_ps1(const struct task_struct *p)
2311 copy_from_kernel_nofault(&tmp, (char *)p, sizeof(unsigned long)))
2314 cpu = kdb_process_cpu(p);
2315 kdb_printf("0x%px %8d %8d %d %4d %c 0x%px %c%s\n",
2316 (void *)p, p->pid, p->parent->pid,
2317 kdb_task_has_cpu(p), kdb_process_cpu(p),
2318 kdb_task_state_char(p),
2319 (void *)(&p->thread),
2320 p == kdb_curr_task(raw_smp_processor_id()) ? '*' : ' ',
2322 if (kdb_task_has_cpu(p)) {
2323 if (!KDB_TSK(cpu)) {
2324 kdb_printf(" Error: no saved data for this cpu\n");
2326 if (KDB_TSK(cpu) != p)
2327 kdb_printf(" Error: does not match running "
2328 "process table (0x%px)\n", KDB_TSK(cpu));
2333 static int kdb_ps(int argc, const char **argv)
2335 struct task_struct *g, *p;
2336 unsigned long mask, cpu;
2339 kdb_ps_suppressed();
2340 kdb_printf("%-*s Pid Parent [*] cpu State %-*s Command\n",
2341 (int)(2*sizeof(void *))+2, "Task Addr",
2342 (int)(2*sizeof(void *))+2, "Thread");
2343 mask = kdb_task_state_string(argc ? argv[1] : NULL);
2344 /* Run the active tasks first */
2345 for_each_online_cpu(cpu) {
2346 if (KDB_FLAG(CMD_INTERRUPT))
2348 p = kdb_curr_task(cpu);
2349 if (kdb_task_state(p, mask))
2353 /* Now the real tasks */
2354 for_each_process_thread(g, p) {
2355 if (KDB_FLAG(CMD_INTERRUPT))
2357 if (kdb_task_state(p, mask))
2365 * kdb_pid - This function implements the 'pid' command which switches
2366 * the currently active process.
2369 static int kdb_pid(int argc, const char **argv)
2371 struct task_struct *p;
2376 return KDB_ARGCOUNT;
2379 if (strcmp(argv[1], "R") == 0) {
2380 p = KDB_TSK(kdb_initial_cpu);
2382 diag = kdbgetularg(argv[1], &val);
2386 p = find_task_by_pid_ns((pid_t)val, &init_pid_ns);
2388 kdb_printf("No task with pid=%d\n", (pid_t)val);
2392 kdb_set_current_task(p);
2394 kdb_printf("KDB current process is %s(pid=%d)\n",
2395 kdb_current_task->comm,
2396 kdb_current_task->pid);
2401 static int kdb_kgdb(int argc, const char **argv)
2403 return KDB_CMD_KGDB;
2407 * kdb_help - This function implements the 'help' and '?' commands.
2409 static int kdb_help(int argc, const char **argv)
2413 kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
2414 kdb_printf("-----------------------------"
2415 "-----------------------------\n");
2416 list_for_each_entry(kt, &kdb_cmds_head, list_node) {
2418 if (KDB_FLAG(CMD_INTERRUPT))
2420 if (!kdb_check_flags(kt->flags, kdb_cmd_enabled, true))
2422 if (strlen(kt->usage) > 20)
2424 kdb_printf("%-15.15s %-20s%s%s\n", kt->name,
2425 kt->usage, space, kt->help);
2431 * kdb_kill - This function implements the 'kill' commands.
2433 static int kdb_kill(int argc, const char **argv)
2437 struct task_struct *p;
2440 return KDB_ARGCOUNT;
2442 sig = simple_strtol(argv[1], &endp, 0);
2445 if ((sig >= 0) || !valid_signal(-sig)) {
2446 kdb_printf("Invalid signal parameter.<-signal>\n");
2451 pid = simple_strtol(argv[2], &endp, 0);
2455 kdb_printf("Process ID must be large than 0.\n");
2459 /* Find the process. */
2460 p = find_task_by_pid_ns(pid, &init_pid_ns);
2462 kdb_printf("The specified process isn't found.\n");
2465 p = p->group_leader;
2466 kdb_send_sig(p, sig);
2471 * Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
2472 * I cannot call that code directly from kdb, it has an unconditional
2473 * cli()/sti() and calls routines that take locks which can stop the debugger.
2475 static void kdb_sysinfo(struct sysinfo *val)
2477 u64 uptime = ktime_get_mono_fast_ns();
2479 memset(val, 0, sizeof(*val));
2480 val->uptime = div_u64(uptime, NSEC_PER_SEC);
2481 val->loads[0] = avenrun[0];
2482 val->loads[1] = avenrun[1];
2483 val->loads[2] = avenrun[2];
2484 val->procs = nr_threads-1;
2491 * kdb_summary - This function implements the 'summary' command.
2493 static int kdb_summary(int argc, const char **argv)
2499 return KDB_ARGCOUNT;
2501 kdb_printf("sysname %s\n", init_uts_ns.name.sysname);
2502 kdb_printf("release %s\n", init_uts_ns.name.release);
2503 kdb_printf("version %s\n", init_uts_ns.name.version);
2504 kdb_printf("machine %s\n", init_uts_ns.name.machine);
2505 kdb_printf("nodename %s\n", init_uts_ns.name.nodename);
2506 kdb_printf("domainname %s\n", init_uts_ns.name.domainname);
2508 now = __ktime_get_real_seconds();
2509 kdb_printf("date %ptTs tz_minuteswest %d\n", &now, sys_tz.tz_minuteswest);
2511 kdb_printf("uptime ");
2512 if (val.uptime > (24*60*60)) {
2513 int days = val.uptime / (24*60*60);
2514 val.uptime %= (24*60*60);
2515 kdb_printf("%d day%s ", days, days == 1 ? "" : "s");
2517 kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
2519 kdb_printf("load avg %ld.%02ld %ld.%02ld %ld.%02ld\n",
2520 LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
2521 LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
2522 LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
2524 /* Display in kilobytes */
2525 #define K(x) ((x) << (PAGE_SHIFT - 10))
2526 kdb_printf("\nMemTotal: %8lu kB\nMemFree: %8lu kB\n"
2527 "Buffers: %8lu kB\n",
2528 K(val.totalram), K(val.freeram), K(val.bufferram));
2533 * kdb_per_cpu - This function implements the 'per_cpu' command.
2535 static int kdb_per_cpu(int argc, const char **argv)
2538 int cpu, diag, nextarg = 1;
2539 unsigned long addr, symaddr, val, bytesperword = 0, whichcpu = ~0UL;
2541 if (argc < 1 || argc > 3)
2542 return KDB_ARGCOUNT;
2544 diag = kdbgetaddrarg(argc, argv, &nextarg, &symaddr, NULL, NULL);
2549 diag = kdbgetularg(argv[2], &bytesperword);
2554 bytesperword = KDB_WORD_SIZE;
2555 else if (bytesperword > KDB_WORD_SIZE)
2556 return KDB_BADWIDTH;
2557 sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
2559 diag = kdbgetularg(argv[3], &whichcpu);
2562 if (whichcpu >= nr_cpu_ids || !cpu_online(whichcpu)) {
2563 kdb_printf("cpu %ld is not online\n", whichcpu);
2564 return KDB_BADCPUNUM;
2568 /* Most architectures use __per_cpu_offset[cpu], some use
2569 * __per_cpu_offset(cpu), smp has no __per_cpu_offset.
2571 #ifdef __per_cpu_offset
2572 #define KDB_PCU(cpu) __per_cpu_offset(cpu)
2575 #define KDB_PCU(cpu) __per_cpu_offset[cpu]
2577 #define KDB_PCU(cpu) 0
2580 for_each_online_cpu(cpu) {
2581 if (KDB_FLAG(CMD_INTERRUPT))
2584 if (whichcpu != ~0UL && whichcpu != cpu)
2586 addr = symaddr + KDB_PCU(cpu);
2587 diag = kdb_getword(&val, addr, bytesperword);
2589 kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to "
2590 "read, diag=%d\n", cpu, addr, diag);
2593 kdb_printf("%5d ", cpu);
2594 kdb_md_line(fmtstr, addr,
2595 bytesperword == KDB_WORD_SIZE,
2596 1, bytesperword, 1, 1, 0);
2603 * display help for the use of cmd | grep pattern
2605 static int kdb_grep_help(int argc, const char **argv)
2607 kdb_printf("Usage of cmd args | grep pattern:\n");
2608 kdb_printf(" Any command's output may be filtered through an ");
2609 kdb_printf("emulated 'pipe'.\n");
2610 kdb_printf(" 'grep' is just a key word.\n");
2611 kdb_printf(" The pattern may include a very limited set of "
2612 "metacharacters:\n");
2613 kdb_printf(" pattern or ^pattern or pattern$ or ^pattern$\n");
2614 kdb_printf(" And if there are spaces in the pattern, you may "
2616 kdb_printf(" \"pat tern\" or \"^pat tern\" or \"pat tern$\""
2617 " or \"^pat tern$\"\n");
2622 * kdb_register() - This function is used to register a kernel debugger
2624 * @cmd: pointer to kdb command
2626 * Note that it's the job of the caller to keep the memory for the cmd
2627 * allocated until unregister is called.
2629 int kdb_register(kdbtab_t *cmd)
2633 list_for_each_entry(kp, &kdb_cmds_head, list_node) {
2634 if (strcmp(kp->name, cmd->name) == 0) {
2635 kdb_printf("Duplicate kdb cmd: %s, func %p help %s\n",
2636 cmd->name, cmd->func, cmd->help);
2641 list_add_tail(&cmd->list_node, &kdb_cmds_head);
2644 EXPORT_SYMBOL_GPL(kdb_register);
2647 * kdb_register_table() - This function is used to register a kdb command
2649 * @kp: pointer to kdb command table
2650 * @len: length of kdb command table
2652 void kdb_register_table(kdbtab_t *kp, size_t len)
2655 list_add_tail(&kp->list_node, &kdb_cmds_head);
2661 * kdb_unregister() - This function is used to unregister a kernel debugger
2662 * command. It is generally called when a module which
2663 * implements kdb command is unloaded.
2664 * @cmd: pointer to kdb command
2666 void kdb_unregister(kdbtab_t *cmd)
2668 list_del(&cmd->list_node);
2670 EXPORT_SYMBOL_GPL(kdb_unregister);
2672 static kdbtab_t maintab[] = {
2676 .help = "Display Memory Contents, also mdWcN, e.g. md8c1",
2678 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2682 .usage = "<vaddr> <bytes>",
2683 .help = "Display Raw Memory",
2684 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2688 .usage = "<paddr> <bytes>",
2689 .help = "Display Physical Memory",
2690 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2695 .help = "Display Memory Symbolically",
2696 .flags = KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS,
2700 .usage = "<vaddr> <contents>",
2701 .help = "Modify Memory Contents",
2702 .flags = KDB_ENABLE_MEM_WRITE | KDB_REPEAT_NO_ARGS,
2706 .usage = "[<vaddr>]",
2707 .help = "Continue Execution",
2709 .flags = KDB_ENABLE_REG_WRITE |
2710 KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2715 .help = "Display Registers",
2716 .flags = KDB_ENABLE_REG_READ,
2720 .usage = "<reg> <contents>",
2721 .help = "Modify Registers",
2722 .flags = KDB_ENABLE_REG_WRITE,
2727 .help = "Display exception frame",
2728 .flags = KDB_ENABLE_MEM_READ,
2732 .usage = "[<vaddr>]",
2733 .help = "Stack traceback",
2735 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2740 .help = "Display stack for process <pid>",
2741 .flags = KDB_ENABLE_INSPECT,
2745 .usage = "[D|R|S|T|C|Z|E|U|I|M|A]",
2746 .help = "Backtrace all processes matching state flag",
2747 .flags = KDB_ENABLE_INSPECT,
2752 .help = "Backtrace current process on each cpu",
2753 .flags = KDB_ENABLE_INSPECT,
2758 .help = "Backtrace process given its struct task address",
2759 .flags = KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS,
2764 .help = "Show environment variables",
2765 .flags = KDB_ENABLE_ALWAYS_SAFE,
2770 .help = "Set environment variables",
2771 .flags = KDB_ENABLE_ALWAYS_SAFE,
2776 .help = "Display Help Message",
2778 .flags = KDB_ENABLE_ALWAYS_SAFE,
2783 .help = "Display Help Message",
2784 .flags = KDB_ENABLE_ALWAYS_SAFE,
2788 .usage = "<cpunum>",
2789 .help = "Switch to new cpu",
2790 .flags = KDB_ENABLE_ALWAYS_SAFE_NO_ARGS,
2795 .help = "Enter kgdb mode",
2800 .usage = "[<flags>|A]",
2801 .help = "Display active task list",
2802 .flags = KDB_ENABLE_INSPECT,
2806 .usage = "<pidnum>",
2807 .help = "Switch to another task",
2808 .flags = KDB_ENABLE_INSPECT,
2813 .help = "Reboot the machine immediately",
2814 .flags = KDB_ENABLE_REBOOT,
2816 #if defined(CONFIG_MODULES)
2820 .help = "List loaded kernel modules",
2821 .flags = KDB_ENABLE_INSPECT,
2824 #if defined(CONFIG_MAGIC_SYSRQ)
2828 .help = "Magic SysRq key",
2829 .flags = KDB_ENABLE_ALWAYS_SAFE,
2832 #if defined(CONFIG_PRINTK)
2836 .help = "Display syslog buffer",
2837 .flags = KDB_ENABLE_ALWAYS_SAFE,
2842 .usage = "name \"usage\" \"help\"",
2843 .help = "Define a set of commands, down to endefcmd",
2845 * Macros are always safe because when executed each
2846 * internal command re-enters kdb_parse() and is safety
2847 * checked individually.
2849 .flags = KDB_ENABLE_ALWAYS_SAFE,
2853 .usage = "<-signal> <pid>",
2854 .help = "Send a signal to a process",
2855 .flags = KDB_ENABLE_SIGNAL,
2857 { .name = "summary",
2858 .func = kdb_summary,
2860 .help = "Summarize the system",
2862 .flags = KDB_ENABLE_ALWAYS_SAFE,
2864 { .name = "per_cpu",
2865 .func = kdb_per_cpu,
2866 .usage = "<sym> [<bytes>] [<cpu>]",
2867 .help = "Display per_cpu variables",
2869 .flags = KDB_ENABLE_MEM_READ,
2871 { .name = "grephelp",
2872 .func = kdb_grep_help,
2874 .help = "Display help on | grep",
2875 .flags = KDB_ENABLE_ALWAYS_SAFE,
2879 static kdbtab_t nmicmd = {
2880 .name = "disable_nmi",
2881 .func = kdb_disable_nmi,
2883 .help = "Disable NMI entry to KDB",
2884 .flags = KDB_ENABLE_ALWAYS_SAFE,
2887 /* Initialize the kdb command table. */
2888 static void __init kdb_inittab(void)
2890 kdb_register_table(maintab, ARRAY_SIZE(maintab));
2891 if (arch_kgdb_ops.enable_nmi)
2892 kdb_register_table(&nmicmd, 1);
2895 /* Execute any commands defined in kdb_cmds. */
2896 static void __init kdb_cmd_init(void)
2899 for (i = 0; kdb_cmds[i]; ++i) {
2900 diag = kdb_parse(kdb_cmds[i]);
2902 kdb_printf("kdb command %s failed, kdb diag %d\n",
2905 if (defcmd_in_progress) {
2906 kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
2907 kdb_parse("endefcmd");
2911 /* Initialize kdb_printf, breakpoint tables and kdb state */
2912 void __init kdb_init(int lvl)
2914 static int kdb_init_lvl = KDB_NOT_INITIALIZED;
2917 if (kdb_init_lvl == KDB_INIT_FULL || lvl <= kdb_init_lvl)
2919 for (i = kdb_init_lvl; i < lvl; i++) {
2921 case KDB_NOT_INITIALIZED:
2922 kdb_inittab(); /* Initialize Command Table */
2923 kdb_initbptab(); /* Initialize Breakpoints */
2925 case KDB_INIT_EARLY:
2926 kdb_cmd_init(); /* Build kdb_cmds tables */