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