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