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