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