xref: /openbmc/linux/kernel/debug/kdb/kdb_main.c (revision b78412b8)
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 EXPORT_SYMBOL(kdb_current_task);
77 struct pt_regs *kdb_current_regs;
78 
79 const char *kdb_diemsg;
80 static int kdb_go_count;
81 #ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
82 static unsigned int kdb_continue_catastrophic =
83 	CONFIG_KDB_CONTINUE_CATASTROPHIC;
84 #else
85 static unsigned int kdb_continue_catastrophic;
86 #endif
87 
88 /* kdb_commands describes the available commands. */
89 static kdbtab_t *kdb_commands;
90 #define KDB_BASE_CMD_MAX 50
91 static int kdb_max_commands = KDB_BASE_CMD_MAX;
92 static kdbtab_t kdb_base_commands[KDB_BASE_CMD_MAX];
93 #define for_each_kdbcmd(cmd, num)					\
94 	for ((cmd) = kdb_base_commands, (num) = 0;			\
95 	     num < kdb_max_commands;					\
96 	     num++, num == KDB_BASE_CMD_MAX ? cmd = kdb_commands : cmd++)
97 
98 typedef struct _kdbmsg {
99 	int	km_diag;	/* kdb diagnostic */
100 	char	*km_msg;	/* Corresponding message text */
101 } kdbmsg_t;
102 
103 #define KDBMSG(msgnum, text) \
104 	{ KDB_##msgnum, text }
105 
106 static kdbmsg_t kdbmsgs[] = {
107 	KDBMSG(NOTFOUND, "Command Not Found"),
108 	KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
109 	KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, "
110 	       "8 is only allowed on 64 bit systems"),
111 	KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
112 	KDBMSG(NOTENV, "Cannot find environment variable"),
113 	KDBMSG(NOENVVALUE, "Environment variable should have value"),
114 	KDBMSG(NOTIMP, "Command not implemented"),
115 	KDBMSG(ENVFULL, "Environment full"),
116 	KDBMSG(ENVBUFFULL, "Environment buffer full"),
117 	KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
118 #ifdef CONFIG_CPU_XSCALE
119 	KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
120 #else
121 	KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
122 #endif
123 	KDBMSG(DUPBPT, "Duplicate breakpoint address"),
124 	KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
125 	KDBMSG(BADMODE, "Invalid IDMODE"),
126 	KDBMSG(BADINT, "Illegal numeric value"),
127 	KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
128 	KDBMSG(BADREG, "Invalid register name"),
129 	KDBMSG(BADCPUNUM, "Invalid cpu number"),
130 	KDBMSG(BADLENGTH, "Invalid length field"),
131 	KDBMSG(NOBP, "No Breakpoint exists"),
132 	KDBMSG(BADADDR, "Invalid address"),
133 	KDBMSG(NOPERM, "Permission denied"),
134 };
135 #undef KDBMSG
136 
137 static const int __nkdb_err = ARRAY_SIZE(kdbmsgs);
138 
139 
140 /*
141  * Initial environment.   This is all kept static and local to
142  * this file.   We don't want to rely on the memory allocation
143  * mechanisms in the kernel, so we use a very limited allocate-only
144  * heap for new and altered environment variables.  The entire
145  * environment is limited to a fixed number of entries (add more
146  * to __env[] if required) and a fixed amount of heap (add more to
147  * KDB_ENVBUFSIZE if required).
148  */
149 
150 static char *__env[] = {
151 #if defined(CONFIG_SMP)
152  "PROMPT=[%d]kdb> ",
153 #else
154  "PROMPT=kdb> ",
155 #endif
156  "MOREPROMPT=more> ",
157  "RADIX=16",
158  "MDCOUNT=8",			/* lines of md output */
159  KDB_PLATFORM_ENV,
160  "DTABCOUNT=30",
161  "NOSECT=1",
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  (char *)0,
186 };
187 
188 static const int __nenv = ARRAY_SIZE(__env);
189 
190 struct task_struct *kdb_curr_task(int cpu)
191 {
192 	struct task_struct *p = curr_task(cpu);
193 #ifdef	_TIF_MCA_INIT
194 	if ((task_thread_info(p)->flags & _TIF_MCA_INIT) && KDB_TSK(cpu))
195 		p = krp->p;
196 #endif
197 	return p;
198 }
199 
200 /*
201  * Check whether the flags of the current command and the permissions
202  * of the kdb console has allow a command to be run.
203  */
204 static inline bool kdb_check_flags(kdb_cmdflags_t flags, int permissions,
205 				   bool no_args)
206 {
207 	/* permissions comes from userspace so needs massaging slightly */
208 	permissions &= KDB_ENABLE_MASK;
209 	permissions |= KDB_ENABLE_ALWAYS_SAFE;
210 
211 	/* some commands change group when launched with no arguments */
212 	if (no_args)
213 		permissions |= permissions << KDB_ENABLE_NO_ARGS_SHIFT;
214 
215 	flags |= KDB_ENABLE_ALL;
216 
217 	return permissions & flags;
218 }
219 
220 /*
221  * kdbgetenv - This function will return the character string value of
222  *	an environment variable.
223  * Parameters:
224  *	match	A character string representing an environment variable.
225  * Returns:
226  *	NULL	No environment variable matches 'match'
227  *	char*	Pointer to string value of environment variable.
228  */
229 char *kdbgetenv(const char *match)
230 {
231 	char **ep = __env;
232 	int matchlen = strlen(match);
233 	int i;
234 
235 	for (i = 0; i < __nenv; i++) {
236 		char *e = *ep++;
237 
238 		if (!e)
239 			continue;
240 
241 		if ((strncmp(match, e, matchlen) == 0)
242 		 && ((e[matchlen] == '\0')
243 		   || (e[matchlen] == '='))) {
244 			char *cp = strchr(e, '=');
245 			return cp ? ++cp : "";
246 		}
247 	}
248 	return NULL;
249 }
250 
251 /*
252  * kdballocenv - This function is used to allocate bytes for
253  *	environment entries.
254  * Parameters:
255  *	match	A character string representing a numeric value
256  * Outputs:
257  *	*value  the unsigned long representation of the env variable 'match'
258  * Returns:
259  *	Zero on success, a kdb diagnostic on failure.
260  * Remarks:
261  *	We use a static environment buffer (envbuffer) to hold the values
262  *	of dynamically generated environment variables (see kdb_set).  Buffer
263  *	space once allocated is never free'd, so over time, the amount of space
264  *	(currently 512 bytes) will be exhausted if env variables are changed
265  *	frequently.
266  */
267 static char *kdballocenv(size_t bytes)
268 {
269 #define	KDB_ENVBUFSIZE	512
270 	static char envbuffer[KDB_ENVBUFSIZE];
271 	static int envbufsize;
272 	char *ep = NULL;
273 
274 	if ((KDB_ENVBUFSIZE - envbufsize) >= bytes) {
275 		ep = &envbuffer[envbufsize];
276 		envbufsize += bytes;
277 	}
278 	return ep;
279 }
280 
281 /*
282  * kdbgetulenv - This function will return the value of an unsigned
283  *	long-valued environment variable.
284  * Parameters:
285  *	match	A character string representing a numeric value
286  * Outputs:
287  *	*value  the unsigned long represntation of the env variable 'match'
288  * Returns:
289  *	Zero on success, a kdb diagnostic on failure.
290  */
291 static int kdbgetulenv(const char *match, unsigned long *value)
292 {
293 	char *ep;
294 
295 	ep = kdbgetenv(match);
296 	if (!ep)
297 		return KDB_NOTENV;
298 	if (strlen(ep) == 0)
299 		return KDB_NOENVVALUE;
300 
301 	*value = simple_strtoul(ep, NULL, 0);
302 
303 	return 0;
304 }
305 
306 /*
307  * kdbgetintenv - This function will return the value of an
308  *	integer-valued environment variable.
309  * Parameters:
310  *	match	A character string representing an integer-valued env variable
311  * Outputs:
312  *	*value  the integer representation of the environment variable 'match'
313  * Returns:
314  *	Zero on success, a kdb diagnostic on failure.
315  */
316 int kdbgetintenv(const char *match, int *value)
317 {
318 	unsigned long val;
319 	int diag;
320 
321 	diag = kdbgetulenv(match, &val);
322 	if (!diag)
323 		*value = (int) val;
324 	return diag;
325 }
326 
327 /*
328  * kdbgetularg - This function will convert a numeric string into an
329  *	unsigned long value.
330  * Parameters:
331  *	arg	A character string representing a numeric value
332  * Outputs:
333  *	*value  the unsigned long represntation of arg.
334  * Returns:
335  *	Zero on success, a kdb diagnostic on failure.
336  */
337 int kdbgetularg(const char *arg, unsigned long *value)
338 {
339 	char *endp;
340 	unsigned long val;
341 
342 	val = simple_strtoul(arg, &endp, 0);
343 
344 	if (endp == arg) {
345 		/*
346 		 * Also try base 16, for us folks too lazy to type the
347 		 * leading 0x...
348 		 */
349 		val = simple_strtoul(arg, &endp, 16);
350 		if (endp == arg)
351 			return KDB_BADINT;
352 	}
353 
354 	*value = val;
355 
356 	return 0;
357 }
358 
359 int kdbgetu64arg(const char *arg, u64 *value)
360 {
361 	char *endp;
362 	u64 val;
363 
364 	val = simple_strtoull(arg, &endp, 0);
365 
366 	if (endp == arg) {
367 
368 		val = simple_strtoull(arg, &endp, 16);
369 		if (endp == arg)
370 			return KDB_BADINT;
371 	}
372 
373 	*value = val;
374 
375 	return 0;
376 }
377 
378 /*
379  * kdb_set - This function implements the 'set' command.  Alter an
380  *	existing environment variable or create a new one.
381  */
382 int kdb_set(int argc, const char **argv)
383 {
384 	int i;
385 	char *ep;
386 	size_t varlen, vallen;
387 
388 	/*
389 	 * we can be invoked two ways:
390 	 *   set var=value    argv[1]="var", argv[2]="value"
391 	 *   set var = value  argv[1]="var", argv[2]="=", argv[3]="value"
392 	 * - if the latter, shift 'em down.
393 	 */
394 	if (argc == 3) {
395 		argv[2] = argv[3];
396 		argc--;
397 	}
398 
399 	if (argc != 2)
400 		return KDB_ARGCOUNT;
401 
402 	/*
403 	 * Check for internal variables
404 	 */
405 	if (strcmp(argv[1], "KDBDEBUG") == 0) {
406 		unsigned int debugflags;
407 		char *cp;
408 
409 		debugflags = simple_strtoul(argv[2], &cp, 0);
410 		if (cp == argv[2] || debugflags & ~KDB_DEBUG_FLAG_MASK) {
411 			kdb_printf("kdb: illegal debug flags '%s'\n",
412 				    argv[2]);
413 			return 0;
414 		}
415 		kdb_flags = (kdb_flags &
416 			     ~(KDB_DEBUG_FLAG_MASK << KDB_DEBUG_FLAG_SHIFT))
417 			| (debugflags << KDB_DEBUG_FLAG_SHIFT);
418 
419 		return 0;
420 	}
421 
422 	/*
423 	 * Tokenizer squashed the '=' sign.  argv[1] is variable
424 	 * name, argv[2] = value.
425 	 */
426 	varlen = strlen(argv[1]);
427 	vallen = strlen(argv[2]);
428 	ep = kdballocenv(varlen + vallen + 2);
429 	if (ep == (char *)0)
430 		return KDB_ENVBUFFULL;
431 
432 	sprintf(ep, "%s=%s", argv[1], argv[2]);
433 
434 	ep[varlen+vallen+1] = '\0';
435 
436 	for (i = 0; i < __nenv; i++) {
437 		if (__env[i]
438 		 && ((strncmp(__env[i], argv[1], varlen) == 0)
439 		   && ((__env[i][varlen] == '\0')
440 		    || (__env[i][varlen] == '=')))) {
441 			__env[i] = ep;
442 			return 0;
443 		}
444 	}
445 
446 	/*
447 	 * Wasn't existing variable.  Fit into slot.
448 	 */
449 	for (i = 0; i < __nenv-1; i++) {
450 		if (__env[i] == (char *)0) {
451 			__env[i] = ep;
452 			return 0;
453 		}
454 	}
455 
456 	return KDB_ENVFULL;
457 }
458 
459 static int kdb_check_regs(void)
460 {
461 	if (!kdb_current_regs) {
462 		kdb_printf("No current kdb registers."
463 			   "  You may need to select another task\n");
464 		return KDB_BADREG;
465 	}
466 	return 0;
467 }
468 
469 /*
470  * kdbgetaddrarg - This function is responsible for parsing an
471  *	address-expression and returning the value of the expression,
472  *	symbol name, and offset to the caller.
473  *
474  *	The argument may consist of a numeric value (decimal or
475  *	hexidecimal), a symbol name, a register name (preceded by the
476  *	percent sign), an environment variable with a numeric value
477  *	(preceded by a dollar sign) or a simple arithmetic expression
478  *	consisting of a symbol name, +/-, and a numeric constant value
479  *	(offset).
480  * Parameters:
481  *	argc	- count of arguments in argv
482  *	argv	- argument vector
483  *	*nextarg - index to next unparsed argument in argv[]
484  *	regs	- Register state at time of KDB entry
485  * Outputs:
486  *	*value	- receives the value of the address-expression
487  *	*offset - receives the offset specified, if any
488  *	*name   - receives the symbol name, if any
489  *	*nextarg - index to next unparsed argument in argv[]
490  * Returns:
491  *	zero is returned on success, a kdb diagnostic code is
492  *      returned on error.
493  */
494 int kdbgetaddrarg(int argc, const char **argv, int *nextarg,
495 		  unsigned long *value,  long *offset,
496 		  char **name)
497 {
498 	unsigned long addr;
499 	unsigned long off = 0;
500 	int positive;
501 	int diag;
502 	int found = 0;
503 	char *symname;
504 	char symbol = '\0';
505 	char *cp;
506 	kdb_symtab_t symtab;
507 
508 	/*
509 	 * If the enable flags prohibit both arbitrary memory access
510 	 * and flow control then there are no reasonable grounds to
511 	 * provide symbol lookup.
512 	 */
513 	if (!kdb_check_flags(KDB_ENABLE_MEM_READ | KDB_ENABLE_FLOW_CTRL,
514 			     kdb_cmd_enabled, false))
515 		return KDB_NOPERM;
516 
517 	/*
518 	 * Process arguments which follow the following syntax:
519 	 *
520 	 *  symbol | numeric-address [+/- numeric-offset]
521 	 *  %register
522 	 *  $environment-variable
523 	 */
524 
525 	if (*nextarg > argc)
526 		return KDB_ARGCOUNT;
527 
528 	symname = (char *)argv[*nextarg];
529 
530 	/*
531 	 * If there is no whitespace between the symbol
532 	 * or address and the '+' or '-' symbols, we
533 	 * remember the character and replace it with a
534 	 * null so the symbol/value can be properly parsed
535 	 */
536 	cp = strpbrk(symname, "+-");
537 	if (cp != NULL) {
538 		symbol = *cp;
539 		*cp++ = '\0';
540 	}
541 
542 	if (symname[0] == '$') {
543 		diag = kdbgetulenv(&symname[1], &addr);
544 		if (diag)
545 			return diag;
546 	} else if (symname[0] == '%') {
547 		diag = kdb_check_regs();
548 		if (diag)
549 			return diag;
550 		/* Implement register values with % at a later time as it is
551 		 * arch optional.
552 		 */
553 		return KDB_NOTIMP;
554 	} else {
555 		found = kdbgetsymval(symname, &symtab);
556 		if (found) {
557 			addr = symtab.sym_start;
558 		} else {
559 			diag = kdbgetularg(argv[*nextarg], &addr);
560 			if (diag)
561 				return diag;
562 		}
563 	}
564 
565 	if (!found)
566 		found = kdbnearsym(addr, &symtab);
567 
568 	(*nextarg)++;
569 
570 	if (name)
571 		*name = symname;
572 	if (value)
573 		*value = addr;
574 	if (offset && name && *name)
575 		*offset = addr - symtab.sym_start;
576 
577 	if ((*nextarg > argc)
578 	 && (symbol == '\0'))
579 		return 0;
580 
581 	/*
582 	 * check for +/- and offset
583 	 */
584 
585 	if (symbol == '\0') {
586 		if ((argv[*nextarg][0] != '+')
587 		 && (argv[*nextarg][0] != '-')) {
588 			/*
589 			 * Not our argument.  Return.
590 			 */
591 			return 0;
592 		} else {
593 			positive = (argv[*nextarg][0] == '+');
594 			(*nextarg)++;
595 		}
596 	} else
597 		positive = (symbol == '+');
598 
599 	/*
600 	 * Now there must be an offset!
601 	 */
602 	if ((*nextarg > argc)
603 	 && (symbol == '\0')) {
604 		return KDB_INVADDRFMT;
605 	}
606 
607 	if (!symbol) {
608 		cp = (char *)argv[*nextarg];
609 		(*nextarg)++;
610 	}
611 
612 	diag = kdbgetularg(cp, &off);
613 	if (diag)
614 		return diag;
615 
616 	if (!positive)
617 		off = -off;
618 
619 	if (offset)
620 		*offset += off;
621 
622 	if (value)
623 		*value += off;
624 
625 	return 0;
626 }
627 
628 static void kdb_cmderror(int diag)
629 {
630 	int i;
631 
632 	if (diag >= 0) {
633 		kdb_printf("no error detected (diagnostic is %d)\n", diag);
634 		return;
635 	}
636 
637 	for (i = 0; i < __nkdb_err; i++) {
638 		if (kdbmsgs[i].km_diag == diag) {
639 			kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
640 			return;
641 		}
642 	}
643 
644 	kdb_printf("Unknown diag %d\n", -diag);
645 }
646 
647 /*
648  * kdb_defcmd, kdb_defcmd2 - This function implements the 'defcmd'
649  *	command which defines one command as a set of other commands,
650  *	terminated by endefcmd.  kdb_defcmd processes the initial
651  *	'defcmd' command, kdb_defcmd2 is invoked from kdb_parse for
652  *	the following commands until 'endefcmd'.
653  * Inputs:
654  *	argc	argument count
655  *	argv	argument vector
656  * Returns:
657  *	zero for success, a kdb diagnostic if error
658  */
659 struct defcmd_set {
660 	int count;
661 	int usable;
662 	char *name;
663 	char *usage;
664 	char *help;
665 	char **command;
666 };
667 static struct defcmd_set *defcmd_set;
668 static int defcmd_set_count;
669 static int defcmd_in_progress;
670 
671 /* Forward references */
672 static int kdb_exec_defcmd(int argc, const char **argv);
673 
674 static int kdb_defcmd2(const char *cmdstr, const char *argv0)
675 {
676 	struct defcmd_set *s = defcmd_set + defcmd_set_count - 1;
677 	char **save_command = s->command;
678 	if (strcmp(argv0, "endefcmd") == 0) {
679 		defcmd_in_progress = 0;
680 		if (!s->count)
681 			s->usable = 0;
682 		if (s->usable)
683 			/* macros are always safe because when executed each
684 			 * internal command re-enters kdb_parse() and is
685 			 * safety checked individually.
686 			 */
687 			kdb_register_flags(s->name, kdb_exec_defcmd, s->usage,
688 					   s->help, 0,
689 					   KDB_ENABLE_ALWAYS_SAFE);
690 		return 0;
691 	}
692 	if (!s->usable)
693 		return KDB_NOTIMP;
694 	s->command = kzalloc((s->count + 1) * sizeof(*(s->command)), GFP_KDB);
695 	if (!s->command) {
696 		kdb_printf("Could not allocate new kdb_defcmd table for %s\n",
697 			   cmdstr);
698 		s->usable = 0;
699 		return KDB_NOTIMP;
700 	}
701 	memcpy(s->command, save_command, s->count * sizeof(*(s->command)));
702 	s->command[s->count++] = kdb_strdup(cmdstr, GFP_KDB);
703 	kfree(save_command);
704 	return 0;
705 }
706 
707 static int kdb_defcmd(int argc, const char **argv)
708 {
709 	struct defcmd_set *save_defcmd_set = defcmd_set, *s;
710 	if (defcmd_in_progress) {
711 		kdb_printf("kdb: nested defcmd detected, assuming missing "
712 			   "endefcmd\n");
713 		kdb_defcmd2("endefcmd", "endefcmd");
714 	}
715 	if (argc == 0) {
716 		int i;
717 		for (s = defcmd_set; s < defcmd_set + defcmd_set_count; ++s) {
718 			kdb_printf("defcmd %s \"%s\" \"%s\"\n", s->name,
719 				   s->usage, s->help);
720 			for (i = 0; i < s->count; ++i)
721 				kdb_printf("%s", s->command[i]);
722 			kdb_printf("endefcmd\n");
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 	defcmd_set = kmalloc((defcmd_set_count + 1) * sizeof(*defcmd_set),
733 			     GFP_KDB);
734 	if (!defcmd_set)
735 		goto fail_defcmd;
736 	memcpy(defcmd_set, save_defcmd_set,
737 	       defcmd_set_count * sizeof(*defcmd_set));
738 	s = defcmd_set + defcmd_set_count;
739 	memset(s, 0, sizeof(*s));
740 	s->usable = 1;
741 	s->name = kdb_strdup(argv[1], GFP_KDB);
742 	if (!s->name)
743 		goto fail_name;
744 	s->usage = kdb_strdup(argv[2], GFP_KDB);
745 	if (!s->usage)
746 		goto fail_usage;
747 	s->help = kdb_strdup(argv[3], GFP_KDB);
748 	if (!s->help)
749 		goto fail_help;
750 	if (s->usage[0] == '"') {
751 		strcpy(s->usage, argv[2]+1);
752 		s->usage[strlen(s->usage)-1] = '\0';
753 	}
754 	if (s->help[0] == '"') {
755 		strcpy(s->help, argv[3]+1);
756 		s->help[strlen(s->help)-1] = '\0';
757 	}
758 	++defcmd_set_count;
759 	defcmd_in_progress = 1;
760 	kfree(save_defcmd_set);
761 	return 0;
762 fail_help:
763 	kfree(s->usage);
764 fail_usage:
765 	kfree(s->name);
766 fail_name:
767 	kfree(defcmd_set);
768 fail_defcmd:
769 	kdb_printf("Could not allocate new defcmd_set entry for %s\n", argv[1]);
770 	defcmd_set = save_defcmd_set;
771 	return KDB_NOTIMP;
772 }
773 
774 /*
775  * kdb_exec_defcmd - Execute the set of commands associated with this
776  *	defcmd name.
777  * Inputs:
778  *	argc	argument count
779  *	argv	argument vector
780  * Returns:
781  *	zero for success, a kdb diagnostic if error
782  */
783 static int kdb_exec_defcmd(int argc, const char **argv)
784 {
785 	int i, ret;
786 	struct defcmd_set *s;
787 	if (argc != 0)
788 		return KDB_ARGCOUNT;
789 	for (s = defcmd_set, i = 0; i < defcmd_set_count; ++i, ++s) {
790 		if (strcmp(s->name, argv[0]) == 0)
791 			break;
792 	}
793 	if (i == defcmd_set_count) {
794 		kdb_printf("kdb_exec_defcmd: could not find commands for %s\n",
795 			   argv[0]);
796 		return KDB_NOTIMP;
797 	}
798 	for (i = 0; i < s->count; ++i) {
799 		/* Recursive use of kdb_parse, do not use argv after
800 		 * this point */
801 		argv = NULL;
802 		kdb_printf("[%s]kdb> %s\n", s->name, s->command[i]);
803 		ret = kdb_parse(s->command[i]);
804 		if (ret)
805 			return ret;
806 	}
807 	return 0;
808 }
809 
810 /* Command history */
811 #define KDB_CMD_HISTORY_COUNT	32
812 #define CMD_BUFLEN		200	/* kdb_printf: max printline
813 					 * size == 256 */
814 static unsigned int cmd_head, cmd_tail;
815 static unsigned int cmdptr;
816 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
817 static char cmd_cur[CMD_BUFLEN];
818 
819 /*
820  * The "str" argument may point to something like  | grep xyz
821  */
822 static void parse_grep(const char *str)
823 {
824 	int	len;
825 	char	*cp = (char *)str, *cp2;
826 
827 	/* sanity check: we should have been called with the \ first */
828 	if (*cp != '|')
829 		return;
830 	cp++;
831 	while (isspace(*cp))
832 		cp++;
833 	if (strncmp(cp, "grep ", 5)) {
834 		kdb_printf("invalid 'pipe', see grephelp\n");
835 		return;
836 	}
837 	cp += 5;
838 	while (isspace(*cp))
839 		cp++;
840 	cp2 = strchr(cp, '\n');
841 	if (cp2)
842 		*cp2 = '\0'; /* remove the trailing newline */
843 	len = strlen(cp);
844 	if (len == 0) {
845 		kdb_printf("invalid 'pipe', see grephelp\n");
846 		return;
847 	}
848 	/* now cp points to a nonzero length search string */
849 	if (*cp == '"') {
850 		/* allow it be "x y z" by removing the "'s - there must
851 		   be two of them */
852 		cp++;
853 		cp2 = strchr(cp, '"');
854 		if (!cp2) {
855 			kdb_printf("invalid quoted string, see grephelp\n");
856 			return;
857 		}
858 		*cp2 = '\0'; /* end the string where the 2nd " was */
859 	}
860 	kdb_grep_leading = 0;
861 	if (*cp == '^') {
862 		kdb_grep_leading = 1;
863 		cp++;
864 	}
865 	len = strlen(cp);
866 	kdb_grep_trailing = 0;
867 	if (*(cp+len-1) == '$') {
868 		kdb_grep_trailing = 1;
869 		*(cp+len-1) = '\0';
870 	}
871 	len = strlen(cp);
872 	if (!len)
873 		return;
874 	if (len >= KDB_GREP_STRLEN) {
875 		kdb_printf("search string too long\n");
876 		return;
877 	}
878 	strcpy(kdb_grep_string, cp);
879 	kdb_grepping_flag++;
880 	return;
881 }
882 
883 /*
884  * kdb_parse - Parse the command line, search the command table for a
885  *	matching command and invoke the command function.  This
886  *	function may be called recursively, if it is, the second call
887  *	will overwrite argv and cbuf.  It is the caller's
888  *	responsibility to save their argv if they recursively call
889  *	kdb_parse().
890  * Parameters:
891  *      cmdstr	The input command line to be parsed.
892  *	regs	The registers at the time kdb was entered.
893  * Returns:
894  *	Zero for success, a kdb diagnostic if failure.
895  * Remarks:
896  *	Limited to 20 tokens.
897  *
898  *	Real rudimentary tokenization. Basically only whitespace
899  *	is considered a token delimeter (but special consideration
900  *	is taken of the '=' sign as used by the 'set' command).
901  *
902  *	The algorithm used to tokenize the input string relies on
903  *	there being at least one whitespace (or otherwise useless)
904  *	character between tokens as the character immediately following
905  *	the token is altered in-place to a null-byte to terminate the
906  *	token string.
907  */
908 
909 #define MAXARGC	20
910 
911 int kdb_parse(const char *cmdstr)
912 {
913 	static char *argv[MAXARGC];
914 	static int argc;
915 	static char cbuf[CMD_BUFLEN+2];
916 	char *cp;
917 	char *cpp, quoted;
918 	kdbtab_t *tp;
919 	int i, escaped, ignore_errors = 0, check_grep = 0;
920 
921 	/*
922 	 * First tokenize the command string.
923 	 */
924 	cp = (char *)cmdstr;
925 
926 	if (KDB_FLAG(CMD_INTERRUPT)) {
927 		/* Previous command was interrupted, newline must not
928 		 * repeat the command */
929 		KDB_FLAG_CLEAR(CMD_INTERRUPT);
930 		KDB_STATE_SET(PAGER);
931 		argc = 0;	/* no repeat */
932 	}
933 
934 	if (*cp != '\n' && *cp != '\0') {
935 		argc = 0;
936 		cpp = cbuf;
937 		while (*cp) {
938 			/* skip whitespace */
939 			while (isspace(*cp))
940 				cp++;
941 			if ((*cp == '\0') || (*cp == '\n') ||
942 			    (*cp == '#' && !defcmd_in_progress))
943 				break;
944 			/* special case: check for | grep pattern */
945 			if (*cp == '|') {
946 				check_grep++;
947 				break;
948 			}
949 			if (cpp >= cbuf + CMD_BUFLEN) {
950 				kdb_printf("kdb_parse: command buffer "
951 					   "overflow, command ignored\n%s\n",
952 					   cmdstr);
953 				return KDB_NOTFOUND;
954 			}
955 			if (argc >= MAXARGC - 1) {
956 				kdb_printf("kdb_parse: too many arguments, "
957 					   "command ignored\n%s\n", cmdstr);
958 				return KDB_NOTFOUND;
959 			}
960 			argv[argc++] = cpp;
961 			escaped = 0;
962 			quoted = '\0';
963 			/* Copy to next unquoted and unescaped
964 			 * whitespace or '=' */
965 			while (*cp && *cp != '\n' &&
966 			       (escaped || quoted || !isspace(*cp))) {
967 				if (cpp >= cbuf + CMD_BUFLEN)
968 					break;
969 				if (escaped) {
970 					escaped = 0;
971 					*cpp++ = *cp++;
972 					continue;
973 				}
974 				if (*cp == '\\') {
975 					escaped = 1;
976 					++cp;
977 					continue;
978 				}
979 				if (*cp == quoted)
980 					quoted = '\0';
981 				else if (*cp == '\'' || *cp == '"')
982 					quoted = *cp;
983 				*cpp = *cp++;
984 				if (*cpp == '=' && !quoted)
985 					break;
986 				++cpp;
987 			}
988 			*cpp++ = '\0';	/* Squash a ws or '=' character */
989 		}
990 	}
991 	if (!argc)
992 		return 0;
993 	if (check_grep)
994 		parse_grep(cp);
995 	if (defcmd_in_progress) {
996 		int result = kdb_defcmd2(cmdstr, argv[0]);
997 		if (!defcmd_in_progress) {
998 			argc = 0;	/* avoid repeat on endefcmd */
999 			*(argv[0]) = '\0';
1000 		}
1001 		return result;
1002 	}
1003 	if (argv[0][0] == '-' && argv[0][1] &&
1004 	    (argv[0][1] < '0' || argv[0][1] > '9')) {
1005 		ignore_errors = 1;
1006 		++argv[0];
1007 	}
1008 
1009 	for_each_kdbcmd(tp, i) {
1010 		if (tp->cmd_name) {
1011 			/*
1012 			 * If this command is allowed to be abbreviated,
1013 			 * check to see if this is it.
1014 			 */
1015 
1016 			if (tp->cmd_minlen
1017 			 && (strlen(argv[0]) <= tp->cmd_minlen)) {
1018 				if (strncmp(argv[0],
1019 					    tp->cmd_name,
1020 					    tp->cmd_minlen) == 0) {
1021 					break;
1022 				}
1023 			}
1024 
1025 			if (strcmp(argv[0], tp->cmd_name) == 0)
1026 				break;
1027 		}
1028 	}
1029 
1030 	/*
1031 	 * If we don't find a command by this name, see if the first
1032 	 * few characters of this match any of the known commands.
1033 	 * e.g., md1c20 should match md.
1034 	 */
1035 	if (i == kdb_max_commands) {
1036 		for_each_kdbcmd(tp, i) {
1037 			if (tp->cmd_name) {
1038 				if (strncmp(argv[0],
1039 					    tp->cmd_name,
1040 					    strlen(tp->cmd_name)) == 0) {
1041 					break;
1042 				}
1043 			}
1044 		}
1045 	}
1046 
1047 	if (i < kdb_max_commands) {
1048 		int result;
1049 
1050 		if (!kdb_check_flags(tp->cmd_flags, kdb_cmd_enabled, argc <= 1))
1051 			return KDB_NOPERM;
1052 
1053 		KDB_STATE_SET(CMD);
1054 		result = (*tp->cmd_func)(argc-1, (const char **)argv);
1055 		if (result && ignore_errors && result > KDB_CMD_GO)
1056 			result = 0;
1057 		KDB_STATE_CLEAR(CMD);
1058 
1059 		if (tp->cmd_flags & KDB_REPEAT_WITH_ARGS)
1060 			return result;
1061 
1062 		argc = tp->cmd_flags & KDB_REPEAT_NO_ARGS ? 1 : 0;
1063 		if (argv[argc])
1064 			*(argv[argc]) = '\0';
1065 		return result;
1066 	}
1067 
1068 	/*
1069 	 * If the input with which we were presented does not
1070 	 * map to an existing command, attempt to parse it as an
1071 	 * address argument and display the result.   Useful for
1072 	 * obtaining the address of a variable, or the nearest symbol
1073 	 * to an address contained in a register.
1074 	 */
1075 	{
1076 		unsigned long value;
1077 		char *name = NULL;
1078 		long offset;
1079 		int nextarg = 0;
1080 
1081 		if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
1082 				  &value, &offset, &name)) {
1083 			return KDB_NOTFOUND;
1084 		}
1085 
1086 		kdb_printf("%s = ", argv[0]);
1087 		kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
1088 		kdb_printf("\n");
1089 		return 0;
1090 	}
1091 }
1092 
1093 
1094 static int handle_ctrl_cmd(char *cmd)
1095 {
1096 #define CTRL_P	16
1097 #define CTRL_N	14
1098 
1099 	/* initial situation */
1100 	if (cmd_head == cmd_tail)
1101 		return 0;
1102 	switch (*cmd) {
1103 	case CTRL_P:
1104 		if (cmdptr != cmd_tail)
1105 			cmdptr = (cmdptr-1) % KDB_CMD_HISTORY_COUNT;
1106 		strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1107 		return 1;
1108 	case CTRL_N:
1109 		if (cmdptr != cmd_head)
1110 			cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
1111 		strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1112 		return 1;
1113 	}
1114 	return 0;
1115 }
1116 
1117 /*
1118  * kdb_reboot - This function implements the 'reboot' command.  Reboot
1119  *	the system immediately, or loop for ever on failure.
1120  */
1121 static int kdb_reboot(int argc, const char **argv)
1122 {
1123 	emergency_restart();
1124 	kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
1125 	while (1)
1126 		cpu_relax();
1127 	/* NOTREACHED */
1128 	return 0;
1129 }
1130 
1131 static void kdb_dumpregs(struct pt_regs *regs)
1132 {
1133 	int old_lvl = console_loglevel;
1134 	console_loglevel = CONSOLE_LOGLEVEL_MOTORMOUTH;
1135 	kdb_trap_printk++;
1136 	show_regs(regs);
1137 	kdb_trap_printk--;
1138 	kdb_printf("\n");
1139 	console_loglevel = old_lvl;
1140 }
1141 
1142 void kdb_set_current_task(struct task_struct *p)
1143 {
1144 	kdb_current_task = p;
1145 
1146 	if (kdb_task_has_cpu(p)) {
1147 		kdb_current_regs = KDB_TSKREGS(kdb_process_cpu(p));
1148 		return;
1149 	}
1150 	kdb_current_regs = NULL;
1151 }
1152 
1153 /*
1154  * kdb_local - The main code for kdb.  This routine is invoked on a
1155  *	specific processor, it is not global.  The main kdb() routine
1156  *	ensures that only one processor at a time is in this routine.
1157  *	This code is called with the real reason code on the first
1158  *	entry to a kdb session, thereafter it is called with reason
1159  *	SWITCH, even if the user goes back to the original cpu.
1160  * Inputs:
1161  *	reason		The reason KDB was invoked
1162  *	error		The hardware-defined error code
1163  *	regs		The exception frame at time of fault/breakpoint.
1164  *	db_result	Result code from the break or debug point.
1165  * Returns:
1166  *	0	KDB was invoked for an event which it wasn't responsible
1167  *	1	KDB handled the event for which it was invoked.
1168  *	KDB_CMD_GO	User typed 'go'.
1169  *	KDB_CMD_CPU	User switched to another cpu.
1170  *	KDB_CMD_SS	Single step.
1171  */
1172 static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
1173 		     kdb_dbtrap_t db_result)
1174 {
1175 	char *cmdbuf;
1176 	int diag;
1177 	struct task_struct *kdb_current =
1178 		kdb_curr_task(raw_smp_processor_id());
1179 
1180 	KDB_DEBUG_STATE("kdb_local 1", reason);
1181 	kdb_go_count = 0;
1182 	if (reason == KDB_REASON_DEBUG) {
1183 		/* special case below */
1184 	} else {
1185 		kdb_printf("\nEntering kdb (current=0x%p, pid %d) ",
1186 			   kdb_current, kdb_current ? kdb_current->pid : 0);
1187 #if defined(CONFIG_SMP)
1188 		kdb_printf("on processor %d ", raw_smp_processor_id());
1189 #endif
1190 	}
1191 
1192 	switch (reason) {
1193 	case KDB_REASON_DEBUG:
1194 	{
1195 		/*
1196 		 * If re-entering kdb after a single step
1197 		 * command, don't print the message.
1198 		 */
1199 		switch (db_result) {
1200 		case KDB_DB_BPT:
1201 			kdb_printf("\nEntering kdb (0x%p, pid %d) ",
1202 				   kdb_current, kdb_current->pid);
1203 #if defined(CONFIG_SMP)
1204 			kdb_printf("on processor %d ", raw_smp_processor_id());
1205 #endif
1206 			kdb_printf("due to Debug @ " kdb_machreg_fmt "\n",
1207 				   instruction_pointer(regs));
1208 			break;
1209 		case KDB_DB_SS:
1210 			break;
1211 		case KDB_DB_SSBPT:
1212 			KDB_DEBUG_STATE("kdb_local 4", reason);
1213 			return 1;	/* kdba_db_trap did the work */
1214 		default:
1215 			kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
1216 				   db_result);
1217 			break;
1218 		}
1219 
1220 	}
1221 		break;
1222 	case KDB_REASON_ENTER:
1223 		if (KDB_STATE(KEYBOARD))
1224 			kdb_printf("due to Keyboard Entry\n");
1225 		else
1226 			kdb_printf("due to KDB_ENTER()\n");
1227 		break;
1228 	case KDB_REASON_KEYBOARD:
1229 		KDB_STATE_SET(KEYBOARD);
1230 		kdb_printf("due to Keyboard Entry\n");
1231 		break;
1232 	case KDB_REASON_ENTER_SLAVE:
1233 		/* drop through, slaves only get released via cpu switch */
1234 	case KDB_REASON_SWITCH:
1235 		kdb_printf("due to cpu switch\n");
1236 		break;
1237 	case KDB_REASON_OOPS:
1238 		kdb_printf("Oops: %s\n", kdb_diemsg);
1239 		kdb_printf("due to oops @ " kdb_machreg_fmt "\n",
1240 			   instruction_pointer(regs));
1241 		kdb_dumpregs(regs);
1242 		break;
1243 	case KDB_REASON_SYSTEM_NMI:
1244 		kdb_printf("due to System NonMaskable Interrupt\n");
1245 		break;
1246 	case KDB_REASON_NMI:
1247 		kdb_printf("due to NonMaskable Interrupt @ "
1248 			   kdb_machreg_fmt "\n",
1249 			   instruction_pointer(regs));
1250 		break;
1251 	case KDB_REASON_SSTEP:
1252 	case KDB_REASON_BREAK:
1253 		kdb_printf("due to %s @ " kdb_machreg_fmt "\n",
1254 			   reason == KDB_REASON_BREAK ?
1255 			   "Breakpoint" : "SS trap", instruction_pointer(regs));
1256 		/*
1257 		 * Determine if this breakpoint is one that we
1258 		 * are interested in.
1259 		 */
1260 		if (db_result != KDB_DB_BPT) {
1261 			kdb_printf("kdb: error return from kdba_bp_trap: %d\n",
1262 				   db_result);
1263 			KDB_DEBUG_STATE("kdb_local 6", reason);
1264 			return 0;	/* Not for us, dismiss it */
1265 		}
1266 		break;
1267 	case KDB_REASON_RECURSE:
1268 		kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n",
1269 			   instruction_pointer(regs));
1270 		break;
1271 	default:
1272 		kdb_printf("kdb: unexpected reason code: %d\n", reason);
1273 		KDB_DEBUG_STATE("kdb_local 8", reason);
1274 		return 0;	/* Not for us, dismiss it */
1275 	}
1276 
1277 	while (1) {
1278 		/*
1279 		 * Initialize pager context.
1280 		 */
1281 		kdb_nextline = 1;
1282 		KDB_STATE_CLEAR(SUPPRESS);
1283 		kdb_grepping_flag = 0;
1284 		/* ensure the old search does not leak into '/' commands */
1285 		kdb_grep_string[0] = '\0';
1286 
1287 		cmdbuf = cmd_cur;
1288 		*cmdbuf = '\0';
1289 		*(cmd_hist[cmd_head]) = '\0';
1290 
1291 do_full_getstr:
1292 #if defined(CONFIG_SMP)
1293 		snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
1294 			 raw_smp_processor_id());
1295 #else
1296 		snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"));
1297 #endif
1298 		if (defcmd_in_progress)
1299 			strncat(kdb_prompt_str, "[defcmd]", CMD_BUFLEN);
1300 
1301 		/*
1302 		 * Fetch command from keyboard
1303 		 */
1304 		cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
1305 		if (*cmdbuf != '\n') {
1306 			if (*cmdbuf < 32) {
1307 				if (cmdptr == cmd_head) {
1308 					strncpy(cmd_hist[cmd_head], cmd_cur,
1309 						CMD_BUFLEN);
1310 					*(cmd_hist[cmd_head] +
1311 					  strlen(cmd_hist[cmd_head])-1) = '\0';
1312 				}
1313 				if (!handle_ctrl_cmd(cmdbuf))
1314 					*(cmd_cur+strlen(cmd_cur)-1) = '\0';
1315 				cmdbuf = cmd_cur;
1316 				goto do_full_getstr;
1317 			} else {
1318 				strncpy(cmd_hist[cmd_head], cmd_cur,
1319 					CMD_BUFLEN);
1320 			}
1321 
1322 			cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
1323 			if (cmd_head == cmd_tail)
1324 				cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
1325 		}
1326 
1327 		cmdptr = cmd_head;
1328 		diag = kdb_parse(cmdbuf);
1329 		if (diag == KDB_NOTFOUND) {
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 	unsigned long word;
1486 
1487 	memset(cbuf, '\0', sizeof(cbuf));
1488 	if (phys)
1489 		kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
1490 	else
1491 		kdb_printf(kdb_machreg_fmt0 " ", addr);
1492 
1493 	for (i = 0; i < num && repeat--; i++) {
1494 		if (phys) {
1495 			if (kdb_getphysword(&word, addr, bytesperword))
1496 				break;
1497 		} else if (kdb_getword(&word, addr, bytesperword))
1498 			break;
1499 		kdb_printf(fmtstr, word);
1500 		if (symbolic)
1501 			kdbnearsym(word, &symtab);
1502 		else
1503 			memset(&symtab, 0, sizeof(symtab));
1504 		if (symtab.sym_name) {
1505 			kdb_symbol_print(word, &symtab, 0);
1506 			if (!nosect) {
1507 				kdb_printf("\n");
1508 				kdb_printf("                       %s %s "
1509 					   kdb_machreg_fmt " "
1510 					   kdb_machreg_fmt " "
1511 					   kdb_machreg_fmt, symtab.mod_name,
1512 					   symtab.sec_name, symtab.sec_start,
1513 					   symtab.sym_start, symtab.sym_end);
1514 			}
1515 			addr += bytesperword;
1516 		} else {
1517 			union {
1518 				u64 word;
1519 				unsigned char c[8];
1520 			} wc;
1521 			unsigned char *cp;
1522 #ifdef	__BIG_ENDIAN
1523 			cp = wc.c + 8 - bytesperword;
1524 #else
1525 			cp = wc.c;
1526 #endif
1527 			wc.word = word;
1528 #define printable_char(c) \
1529 	({unsigned char __c = c; isascii(__c) && isprint(__c) ? __c : '.'; })
1530 			switch (bytesperword) {
1531 			case 8:
1532 				*c++ = printable_char(*cp++);
1533 				*c++ = printable_char(*cp++);
1534 				*c++ = printable_char(*cp++);
1535 				*c++ = printable_char(*cp++);
1536 				addr += 4;
1537 			case 4:
1538 				*c++ = printable_char(*cp++);
1539 				*c++ = printable_char(*cp++);
1540 				addr += 2;
1541 			case 2:
1542 				*c++ = printable_char(*cp++);
1543 				addr++;
1544 			case 1:
1545 				*c++ = printable_char(*cp++);
1546 				addr++;
1547 				break;
1548 			}
1549 #undef printable_char
1550 		}
1551 	}
1552 	kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1),
1553 		   " ", cbuf);
1554 }
1555 
1556 static int kdb_md(int argc, const char **argv)
1557 {
1558 	static unsigned long last_addr;
1559 	static int last_radix, last_bytesperword, last_repeat;
1560 	int radix = 16, mdcount = 8, bytesperword = KDB_WORD_SIZE, repeat;
1561 	int nosect = 0;
1562 	char fmtchar, fmtstr[64];
1563 	unsigned long addr;
1564 	unsigned long word;
1565 	long offset = 0;
1566 	int symbolic = 0;
1567 	int valid = 0;
1568 	int phys = 0;
1569 
1570 	kdbgetintenv("MDCOUNT", &mdcount);
1571 	kdbgetintenv("RADIX", &radix);
1572 	kdbgetintenv("BYTESPERWORD", &bytesperword);
1573 
1574 	/* Assume 'md <addr>' and start with environment values */
1575 	repeat = mdcount * 16 / bytesperword;
1576 
1577 	if (strcmp(argv[0], "mdr") == 0) {
1578 		if (argc != 2)
1579 			return KDB_ARGCOUNT;
1580 		valid = 1;
1581 	} else if (isdigit(argv[0][2])) {
1582 		bytesperword = (int)(argv[0][2] - '0');
1583 		if (bytesperword == 0) {
1584 			bytesperword = last_bytesperword;
1585 			if (bytesperword == 0)
1586 				bytesperword = 4;
1587 		}
1588 		last_bytesperword = bytesperword;
1589 		repeat = mdcount * 16 / bytesperword;
1590 		if (!argv[0][3])
1591 			valid = 1;
1592 		else if (argv[0][3] == 'c' && argv[0][4]) {
1593 			char *p;
1594 			repeat = simple_strtoul(argv[0] + 4, &p, 10);
1595 			mdcount = ((repeat * bytesperword) + 15) / 16;
1596 			valid = !*p;
1597 		}
1598 		last_repeat = repeat;
1599 	} else if (strcmp(argv[0], "md") == 0)
1600 		valid = 1;
1601 	else if (strcmp(argv[0], "mds") == 0)
1602 		valid = 1;
1603 	else if (strcmp(argv[0], "mdp") == 0) {
1604 		phys = valid = 1;
1605 	}
1606 	if (!valid)
1607 		return KDB_NOTFOUND;
1608 
1609 	if (argc == 0) {
1610 		if (last_addr == 0)
1611 			return KDB_ARGCOUNT;
1612 		addr = last_addr;
1613 		radix = last_radix;
1614 		bytesperword = last_bytesperword;
1615 		repeat = last_repeat;
1616 		mdcount = ((repeat * bytesperword) + 15) / 16;
1617 	}
1618 
1619 	if (argc) {
1620 		unsigned long val;
1621 		int diag, nextarg = 1;
1622 		diag = kdbgetaddrarg(argc, argv, &nextarg, &addr,
1623 				     &offset, NULL);
1624 		if (diag)
1625 			return diag;
1626 		if (argc > nextarg+2)
1627 			return KDB_ARGCOUNT;
1628 
1629 		if (argc >= nextarg) {
1630 			diag = kdbgetularg(argv[nextarg], &val);
1631 			if (!diag) {
1632 				mdcount = (int) val;
1633 				repeat = mdcount * 16 / bytesperword;
1634 			}
1635 		}
1636 		if (argc >= nextarg+1) {
1637 			diag = kdbgetularg(argv[nextarg+1], &val);
1638 			if (!diag)
1639 				radix = (int) val;
1640 		}
1641 	}
1642 
1643 	if (strcmp(argv[0], "mdr") == 0)
1644 		return kdb_mdr(addr, mdcount);
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%p ", 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%p", 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 	int i;
2063 
2064 	for (i = 0; i < __nenv; i++) {
2065 		if (__env[i])
2066 			kdb_printf("%s\n", __env[i]);
2067 	}
2068 
2069 	if (KDB_DEBUG(MASK))
2070 		kdb_printf("KDBFLAGS=0x%x\n", kdb_flags);
2071 
2072 	return 0;
2073 }
2074 
2075 #ifdef CONFIG_PRINTK
2076 /*
2077  * kdb_dmesg - This function implements the 'dmesg' command to display
2078  *	the contents of the syslog buffer.
2079  *		dmesg [lines] [adjust]
2080  */
2081 static int kdb_dmesg(int argc, const char **argv)
2082 {
2083 	int diag;
2084 	int logging;
2085 	int lines = 0;
2086 	int adjust = 0;
2087 	int n = 0;
2088 	int skip = 0;
2089 	struct kmsg_dumper dumper = { .active = 1 };
2090 	size_t len;
2091 	char buf[201];
2092 
2093 	if (argc > 2)
2094 		return KDB_ARGCOUNT;
2095 	if (argc) {
2096 		char *cp;
2097 		lines = simple_strtol(argv[1], &cp, 0);
2098 		if (*cp)
2099 			lines = 0;
2100 		if (argc > 1) {
2101 			adjust = simple_strtoul(argv[2], &cp, 0);
2102 			if (*cp || adjust < 0)
2103 				adjust = 0;
2104 		}
2105 	}
2106 
2107 	/* disable LOGGING if set */
2108 	diag = kdbgetintenv("LOGGING", &logging);
2109 	if (!diag && logging) {
2110 		const char *setargs[] = { "set", "LOGGING", "0" };
2111 		kdb_set(2, setargs);
2112 	}
2113 
2114 	kmsg_dump_rewind_nolock(&dumper);
2115 	while (kmsg_dump_get_line_nolock(&dumper, 1, NULL, 0, NULL))
2116 		n++;
2117 
2118 	if (lines < 0) {
2119 		if (adjust >= n)
2120 			kdb_printf("buffer only contains %d lines, nothing "
2121 				   "printed\n", n);
2122 		else if (adjust - lines >= n)
2123 			kdb_printf("buffer only contains %d lines, last %d "
2124 				   "lines printed\n", n, n - adjust);
2125 		skip = adjust;
2126 		lines = abs(lines);
2127 	} else if (lines > 0) {
2128 		skip = n - lines - adjust;
2129 		lines = abs(lines);
2130 		if (adjust >= n) {
2131 			kdb_printf("buffer only contains %d lines, "
2132 				   "nothing printed\n", n);
2133 			skip = n;
2134 		} else if (skip < 0) {
2135 			lines += skip;
2136 			skip = 0;
2137 			kdb_printf("buffer only contains %d lines, first "
2138 				   "%d lines printed\n", n, lines);
2139 		}
2140 	} else {
2141 		lines = n;
2142 	}
2143 
2144 	if (skip >= n || skip < 0)
2145 		return 0;
2146 
2147 	kmsg_dump_rewind_nolock(&dumper);
2148 	while (kmsg_dump_get_line_nolock(&dumper, 1, buf, sizeof(buf), &len)) {
2149 		if (skip) {
2150 			skip--;
2151 			continue;
2152 		}
2153 		if (!lines--)
2154 			break;
2155 		if (KDB_FLAG(CMD_INTERRUPT))
2156 			return 0;
2157 
2158 		kdb_printf("%.*s\n", (int)len - 1, buf);
2159 	}
2160 
2161 	return 0;
2162 }
2163 #endif /* CONFIG_PRINTK */
2164 
2165 /* Make sure we balance enable/disable calls, must disable first. */
2166 static atomic_t kdb_nmi_disabled;
2167 
2168 static int kdb_disable_nmi(int argc, const char *argv[])
2169 {
2170 	if (atomic_read(&kdb_nmi_disabled))
2171 		return 0;
2172 	atomic_set(&kdb_nmi_disabled, 1);
2173 	arch_kgdb_ops.enable_nmi(0);
2174 	return 0;
2175 }
2176 
2177 static int kdb_param_enable_nmi(const char *val, const struct kernel_param *kp)
2178 {
2179 	if (!atomic_add_unless(&kdb_nmi_disabled, -1, 0))
2180 		return -EINVAL;
2181 	arch_kgdb_ops.enable_nmi(1);
2182 	return 0;
2183 }
2184 
2185 static const struct kernel_param_ops kdb_param_ops_enable_nmi = {
2186 	.set = kdb_param_enable_nmi,
2187 };
2188 module_param_cb(enable_nmi, &kdb_param_ops_enable_nmi, NULL, 0600);
2189 
2190 /*
2191  * kdb_cpu - This function implements the 'cpu' command.
2192  *	cpu	[<cpunum>]
2193  * Returns:
2194  *	KDB_CMD_CPU for success, a kdb diagnostic if error
2195  */
2196 static void kdb_cpu_status(void)
2197 {
2198 	int i, start_cpu, first_print = 1;
2199 	char state, prev_state = '?';
2200 
2201 	kdb_printf("Currently on cpu %d\n", raw_smp_processor_id());
2202 	kdb_printf("Available cpus: ");
2203 	for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
2204 		if (!cpu_online(i)) {
2205 			state = 'F';	/* cpu is offline */
2206 		} else if (!kgdb_info[i].enter_kgdb) {
2207 			state = 'D';	/* cpu is online but unresponsive */
2208 		} else {
2209 			state = ' ';	/* cpu is responding to kdb */
2210 			if (kdb_task_state_char(KDB_TSK(i)) == 'I')
2211 				state = 'I';	/* idle task */
2212 		}
2213 		if (state != prev_state) {
2214 			if (prev_state != '?') {
2215 				if (!first_print)
2216 					kdb_printf(", ");
2217 				first_print = 0;
2218 				kdb_printf("%d", start_cpu);
2219 				if (start_cpu < i-1)
2220 					kdb_printf("-%d", i-1);
2221 				if (prev_state != ' ')
2222 					kdb_printf("(%c)", prev_state);
2223 			}
2224 			prev_state = state;
2225 			start_cpu = i;
2226 		}
2227 	}
2228 	/* print the trailing cpus, ignoring them if they are all offline */
2229 	if (prev_state != 'F') {
2230 		if (!first_print)
2231 			kdb_printf(", ");
2232 		kdb_printf("%d", start_cpu);
2233 		if (start_cpu < i-1)
2234 			kdb_printf("-%d", i-1);
2235 		if (prev_state != ' ')
2236 			kdb_printf("(%c)", prev_state);
2237 	}
2238 	kdb_printf("\n");
2239 }
2240 
2241 static int kdb_cpu(int argc, const char **argv)
2242 {
2243 	unsigned long cpunum;
2244 	int diag;
2245 
2246 	if (argc == 0) {
2247 		kdb_cpu_status();
2248 		return 0;
2249 	}
2250 
2251 	if (argc != 1)
2252 		return KDB_ARGCOUNT;
2253 
2254 	diag = kdbgetularg(argv[1], &cpunum);
2255 	if (diag)
2256 		return diag;
2257 
2258 	/*
2259 	 * Validate cpunum
2260 	 */
2261 	if ((cpunum >= CONFIG_NR_CPUS) || !kgdb_info[cpunum].enter_kgdb)
2262 		return KDB_BADCPUNUM;
2263 
2264 	dbg_switch_cpu = cpunum;
2265 
2266 	/*
2267 	 * Switch to other cpu
2268 	 */
2269 	return KDB_CMD_CPU;
2270 }
2271 
2272 /* The user may not realize that ps/bta with no parameters does not print idle
2273  * or sleeping system daemon processes, so tell them how many were suppressed.
2274  */
2275 void kdb_ps_suppressed(void)
2276 {
2277 	int idle = 0, daemon = 0;
2278 	unsigned long mask_I = kdb_task_state_string("I"),
2279 		      mask_M = kdb_task_state_string("M");
2280 	unsigned long cpu;
2281 	const struct task_struct *p, *g;
2282 	for_each_online_cpu(cpu) {
2283 		p = kdb_curr_task(cpu);
2284 		if (kdb_task_state(p, mask_I))
2285 			++idle;
2286 	}
2287 	kdb_do_each_thread(g, p) {
2288 		if (kdb_task_state(p, mask_M))
2289 			++daemon;
2290 	} kdb_while_each_thread(g, p);
2291 	if (idle || daemon) {
2292 		if (idle)
2293 			kdb_printf("%d idle process%s (state I)%s\n",
2294 				   idle, idle == 1 ? "" : "es",
2295 				   daemon ? " and " : "");
2296 		if (daemon)
2297 			kdb_printf("%d sleeping system daemon (state M) "
2298 				   "process%s", daemon,
2299 				   daemon == 1 ? "" : "es");
2300 		kdb_printf(" suppressed,\nuse 'ps A' to see all.\n");
2301 	}
2302 }
2303 
2304 /*
2305  * kdb_ps - This function implements the 'ps' command which shows a
2306  *	list of the active processes.
2307  *		ps [DRSTCZEUIMA]   All processes, optionally filtered by state
2308  */
2309 void kdb_ps1(const struct task_struct *p)
2310 {
2311 	int cpu;
2312 	unsigned long tmp;
2313 
2314 	if (!p || probe_kernel_read(&tmp, (char *)p, sizeof(unsigned long)))
2315 		return;
2316 
2317 	cpu = kdb_process_cpu(p);
2318 	kdb_printf("0x%p %8d %8d  %d %4d   %c  0x%p %c%s\n",
2319 		   (void *)p, p->pid, p->parent->pid,
2320 		   kdb_task_has_cpu(p), kdb_process_cpu(p),
2321 		   kdb_task_state_char(p),
2322 		   (void *)(&p->thread),
2323 		   p == kdb_curr_task(raw_smp_processor_id()) ? '*' : ' ',
2324 		   p->comm);
2325 	if (kdb_task_has_cpu(p)) {
2326 		if (!KDB_TSK(cpu)) {
2327 			kdb_printf("  Error: no saved data for this cpu\n");
2328 		} else {
2329 			if (KDB_TSK(cpu) != p)
2330 				kdb_printf("  Error: does not match running "
2331 				   "process table (0x%p)\n", KDB_TSK(cpu));
2332 		}
2333 	}
2334 }
2335 
2336 static int kdb_ps(int argc, const char **argv)
2337 {
2338 	struct task_struct *g, *p;
2339 	unsigned long mask, cpu;
2340 
2341 	if (argc == 0)
2342 		kdb_ps_suppressed();
2343 	kdb_printf("%-*s      Pid   Parent [*] cpu State %-*s Command\n",
2344 		(int)(2*sizeof(void *))+2, "Task Addr",
2345 		(int)(2*sizeof(void *))+2, "Thread");
2346 	mask = kdb_task_state_string(argc ? argv[1] : NULL);
2347 	/* Run the active tasks first */
2348 	for_each_online_cpu(cpu) {
2349 		if (KDB_FLAG(CMD_INTERRUPT))
2350 			return 0;
2351 		p = kdb_curr_task(cpu);
2352 		if (kdb_task_state(p, mask))
2353 			kdb_ps1(p);
2354 	}
2355 	kdb_printf("\n");
2356 	/* Now the real tasks */
2357 	kdb_do_each_thread(g, p) {
2358 		if (KDB_FLAG(CMD_INTERRUPT))
2359 			return 0;
2360 		if (kdb_task_state(p, mask))
2361 			kdb_ps1(p);
2362 	} kdb_while_each_thread(g, p);
2363 
2364 	return 0;
2365 }
2366 
2367 /*
2368  * kdb_pid - This function implements the 'pid' command which switches
2369  *	the currently active process.
2370  *		pid [<pid> | R]
2371  */
2372 static int kdb_pid(int argc, const char **argv)
2373 {
2374 	struct task_struct *p;
2375 	unsigned long val;
2376 	int diag;
2377 
2378 	if (argc > 1)
2379 		return KDB_ARGCOUNT;
2380 
2381 	if (argc) {
2382 		if (strcmp(argv[1], "R") == 0) {
2383 			p = KDB_TSK(kdb_initial_cpu);
2384 		} else {
2385 			diag = kdbgetularg(argv[1], &val);
2386 			if (diag)
2387 				return KDB_BADINT;
2388 
2389 			p = find_task_by_pid_ns((pid_t)val,	&init_pid_ns);
2390 			if (!p) {
2391 				kdb_printf("No task with pid=%d\n", (pid_t)val);
2392 				return 0;
2393 			}
2394 		}
2395 		kdb_set_current_task(p);
2396 	}
2397 	kdb_printf("KDB current process is %s(pid=%d)\n",
2398 		   kdb_current_task->comm,
2399 		   kdb_current_task->pid);
2400 
2401 	return 0;
2402 }
2403 
2404 static int kdb_kgdb(int argc, const char **argv)
2405 {
2406 	return KDB_CMD_KGDB;
2407 }
2408 
2409 /*
2410  * kdb_help - This function implements the 'help' and '?' commands.
2411  */
2412 static int kdb_help(int argc, const char **argv)
2413 {
2414 	kdbtab_t *kt;
2415 	int i;
2416 
2417 	kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
2418 	kdb_printf("-----------------------------"
2419 		   "-----------------------------\n");
2420 	for_each_kdbcmd(kt, i) {
2421 		char *space = "";
2422 		if (KDB_FLAG(CMD_INTERRUPT))
2423 			return 0;
2424 		if (!kt->cmd_name)
2425 			continue;
2426 		if (!kdb_check_flags(kt->cmd_flags, kdb_cmd_enabled, true))
2427 			continue;
2428 		if (strlen(kt->cmd_usage) > 20)
2429 			space = "\n                                    ";
2430 		kdb_printf("%-15.15s %-20s%s%s\n", kt->cmd_name,
2431 			   kt->cmd_usage, space, kt->cmd_help);
2432 	}
2433 	return 0;
2434 }
2435 
2436 /*
2437  * kdb_kill - This function implements the 'kill' commands.
2438  */
2439 static int kdb_kill(int argc, const char **argv)
2440 {
2441 	long sig, pid;
2442 	char *endp;
2443 	struct task_struct *p;
2444 	struct siginfo info;
2445 
2446 	if (argc != 2)
2447 		return KDB_ARGCOUNT;
2448 
2449 	sig = simple_strtol(argv[1], &endp, 0);
2450 	if (*endp)
2451 		return KDB_BADINT;
2452 	if (sig >= 0) {
2453 		kdb_printf("Invalid signal parameter.<-signal>\n");
2454 		return 0;
2455 	}
2456 	sig = -sig;
2457 
2458 	pid = simple_strtol(argv[2], &endp, 0);
2459 	if (*endp)
2460 		return KDB_BADINT;
2461 	if (pid <= 0) {
2462 		kdb_printf("Process ID must be large than 0.\n");
2463 		return 0;
2464 	}
2465 
2466 	/* Find the process. */
2467 	p = find_task_by_pid_ns(pid, &init_pid_ns);
2468 	if (!p) {
2469 		kdb_printf("The specified process isn't found.\n");
2470 		return 0;
2471 	}
2472 	p = p->group_leader;
2473 	info.si_signo = sig;
2474 	info.si_errno = 0;
2475 	info.si_code = SI_USER;
2476 	info.si_pid = pid;  /* same capabilities as process being signalled */
2477 	info.si_uid = 0;    /* kdb has root authority */
2478 	kdb_send_sig_info(p, &info);
2479 	return 0;
2480 }
2481 
2482 struct kdb_tm {
2483 	int tm_sec;	/* seconds */
2484 	int tm_min;	/* minutes */
2485 	int tm_hour;	/* hours */
2486 	int tm_mday;	/* day of the month */
2487 	int tm_mon;	/* month */
2488 	int tm_year;	/* year */
2489 };
2490 
2491 static void kdb_gmtime(struct timespec *tv, struct kdb_tm *tm)
2492 {
2493 	/* This will work from 1970-2099, 2100 is not a leap year */
2494 	static int mon_day[] = { 31, 29, 31, 30, 31, 30, 31,
2495 				 31, 30, 31, 30, 31 };
2496 	memset(tm, 0, sizeof(*tm));
2497 	tm->tm_sec  = tv->tv_sec % (24 * 60 * 60);
2498 	tm->tm_mday = tv->tv_sec / (24 * 60 * 60) +
2499 		(2 * 365 + 1); /* shift base from 1970 to 1968 */
2500 	tm->tm_min =  tm->tm_sec / 60 % 60;
2501 	tm->tm_hour = tm->tm_sec / 60 / 60;
2502 	tm->tm_sec =  tm->tm_sec % 60;
2503 	tm->tm_year = 68 + 4*(tm->tm_mday / (4*365+1));
2504 	tm->tm_mday %= (4*365+1);
2505 	mon_day[1] = 29;
2506 	while (tm->tm_mday >= mon_day[tm->tm_mon]) {
2507 		tm->tm_mday -= mon_day[tm->tm_mon];
2508 		if (++tm->tm_mon == 12) {
2509 			tm->tm_mon = 0;
2510 			++tm->tm_year;
2511 			mon_day[1] = 28;
2512 		}
2513 	}
2514 	++tm->tm_mday;
2515 }
2516 
2517 /*
2518  * Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
2519  * I cannot call that code directly from kdb, it has an unconditional
2520  * cli()/sti() and calls routines that take locks which can stop the debugger.
2521  */
2522 static void kdb_sysinfo(struct sysinfo *val)
2523 {
2524 	struct timespec uptime;
2525 	ktime_get_ts(&uptime);
2526 	memset(val, 0, sizeof(*val));
2527 	val->uptime = uptime.tv_sec;
2528 	val->loads[0] = avenrun[0];
2529 	val->loads[1] = avenrun[1];
2530 	val->loads[2] = avenrun[2];
2531 	val->procs = nr_threads-1;
2532 	si_meminfo(val);
2533 
2534 	return;
2535 }
2536 
2537 /*
2538  * kdb_summary - This function implements the 'summary' command.
2539  */
2540 static int kdb_summary(int argc, const char **argv)
2541 {
2542 	struct timespec now;
2543 	struct kdb_tm tm;
2544 	struct sysinfo val;
2545 
2546 	if (argc)
2547 		return KDB_ARGCOUNT;
2548 
2549 	kdb_printf("sysname    %s\n", init_uts_ns.name.sysname);
2550 	kdb_printf("release    %s\n", init_uts_ns.name.release);
2551 	kdb_printf("version    %s\n", init_uts_ns.name.version);
2552 	kdb_printf("machine    %s\n", init_uts_ns.name.machine);
2553 	kdb_printf("nodename   %s\n", init_uts_ns.name.nodename);
2554 	kdb_printf("domainname %s\n", init_uts_ns.name.domainname);
2555 	kdb_printf("ccversion  %s\n", __stringify(CCVERSION));
2556 
2557 	now = __current_kernel_time();
2558 	kdb_gmtime(&now, &tm);
2559 	kdb_printf("date       %04d-%02d-%02d %02d:%02d:%02d "
2560 		   "tz_minuteswest %d\n",
2561 		1900+tm.tm_year, tm.tm_mon+1, tm.tm_mday,
2562 		tm.tm_hour, tm.tm_min, tm.tm_sec,
2563 		sys_tz.tz_minuteswest);
2564 
2565 	kdb_sysinfo(&val);
2566 	kdb_printf("uptime     ");
2567 	if (val.uptime > (24*60*60)) {
2568 		int days = val.uptime / (24*60*60);
2569 		val.uptime %= (24*60*60);
2570 		kdb_printf("%d day%s ", days, days == 1 ? "" : "s");
2571 	}
2572 	kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
2573 
2574 	/* lifted from fs/proc/proc_misc.c::loadavg_read_proc() */
2575 
2576 #define LOAD_INT(x) ((x) >> FSHIFT)
2577 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
2578 	kdb_printf("load avg   %ld.%02ld %ld.%02ld %ld.%02ld\n",
2579 		LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
2580 		LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
2581 		LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
2582 #undef LOAD_INT
2583 #undef LOAD_FRAC
2584 	/* Display in kilobytes */
2585 #define K(x) ((x) << (PAGE_SHIFT - 10))
2586 	kdb_printf("\nMemTotal:       %8lu kB\nMemFree:        %8lu kB\n"
2587 		   "Buffers:        %8lu kB\n",
2588 		   K(val.totalram), K(val.freeram), K(val.bufferram));
2589 	return 0;
2590 }
2591 
2592 /*
2593  * kdb_per_cpu - This function implements the 'per_cpu' command.
2594  */
2595 static int kdb_per_cpu(int argc, const char **argv)
2596 {
2597 	char fmtstr[64];
2598 	int cpu, diag, nextarg = 1;
2599 	unsigned long addr, symaddr, val, bytesperword = 0, whichcpu = ~0UL;
2600 
2601 	if (argc < 1 || argc > 3)
2602 		return KDB_ARGCOUNT;
2603 
2604 	diag = kdbgetaddrarg(argc, argv, &nextarg, &symaddr, NULL, NULL);
2605 	if (diag)
2606 		return diag;
2607 
2608 	if (argc >= 2) {
2609 		diag = kdbgetularg(argv[2], &bytesperword);
2610 		if (diag)
2611 			return diag;
2612 	}
2613 	if (!bytesperword)
2614 		bytesperword = KDB_WORD_SIZE;
2615 	else if (bytesperword > KDB_WORD_SIZE)
2616 		return KDB_BADWIDTH;
2617 	sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
2618 	if (argc >= 3) {
2619 		diag = kdbgetularg(argv[3], &whichcpu);
2620 		if (diag)
2621 			return diag;
2622 		if (!cpu_online(whichcpu)) {
2623 			kdb_printf("cpu %ld is not online\n", whichcpu);
2624 			return KDB_BADCPUNUM;
2625 		}
2626 	}
2627 
2628 	/* Most architectures use __per_cpu_offset[cpu], some use
2629 	 * __per_cpu_offset(cpu), smp has no __per_cpu_offset.
2630 	 */
2631 #ifdef	__per_cpu_offset
2632 #define KDB_PCU(cpu) __per_cpu_offset(cpu)
2633 #else
2634 #ifdef	CONFIG_SMP
2635 #define KDB_PCU(cpu) __per_cpu_offset[cpu]
2636 #else
2637 #define KDB_PCU(cpu) 0
2638 #endif
2639 #endif
2640 	for_each_online_cpu(cpu) {
2641 		if (KDB_FLAG(CMD_INTERRUPT))
2642 			return 0;
2643 
2644 		if (whichcpu != ~0UL && whichcpu != cpu)
2645 			continue;
2646 		addr = symaddr + KDB_PCU(cpu);
2647 		diag = kdb_getword(&val, addr, bytesperword);
2648 		if (diag) {
2649 			kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to "
2650 				   "read, diag=%d\n", cpu, addr, diag);
2651 			continue;
2652 		}
2653 		kdb_printf("%5d ", cpu);
2654 		kdb_md_line(fmtstr, addr,
2655 			bytesperword == KDB_WORD_SIZE,
2656 			1, bytesperword, 1, 1, 0);
2657 	}
2658 #undef KDB_PCU
2659 	return 0;
2660 }
2661 
2662 /*
2663  * display help for the use of cmd | grep pattern
2664  */
2665 static int kdb_grep_help(int argc, const char **argv)
2666 {
2667 	kdb_printf("Usage of  cmd args | grep pattern:\n");
2668 	kdb_printf("  Any command's output may be filtered through an ");
2669 	kdb_printf("emulated 'pipe'.\n");
2670 	kdb_printf("  'grep' is just a key word.\n");
2671 	kdb_printf("  The pattern may include a very limited set of "
2672 		   "metacharacters:\n");
2673 	kdb_printf("   pattern or ^pattern or pattern$ or ^pattern$\n");
2674 	kdb_printf("  And if there are spaces in the pattern, you may "
2675 		   "quote it:\n");
2676 	kdb_printf("   \"pat tern\" or \"^pat tern\" or \"pat tern$\""
2677 		   " or \"^pat tern$\"\n");
2678 	return 0;
2679 }
2680 
2681 /*
2682  * kdb_register_flags - This function is used to register a kernel
2683  * 	debugger command.
2684  * Inputs:
2685  *	cmd	Command name
2686  *	func	Function to execute the command
2687  *	usage	A simple usage string showing arguments
2688  *	help	A simple help string describing command
2689  *	repeat	Does the command auto repeat on enter?
2690  * Returns:
2691  *	zero for success, one if a duplicate command.
2692  */
2693 #define kdb_command_extend 50	/* arbitrary */
2694 int kdb_register_flags(char *cmd,
2695 		       kdb_func_t func,
2696 		       char *usage,
2697 		       char *help,
2698 		       short minlen,
2699 		       kdb_cmdflags_t flags)
2700 {
2701 	int i;
2702 	kdbtab_t *kp;
2703 
2704 	/*
2705 	 *  Brute force method to determine duplicates
2706 	 */
2707 	for_each_kdbcmd(kp, i) {
2708 		if (kp->cmd_name && (strcmp(kp->cmd_name, cmd) == 0)) {
2709 			kdb_printf("Duplicate kdb command registered: "
2710 				"%s, func %p help %s\n", cmd, func, help);
2711 			return 1;
2712 		}
2713 	}
2714 
2715 	/*
2716 	 * Insert command into first available location in table
2717 	 */
2718 	for_each_kdbcmd(kp, i) {
2719 		if (kp->cmd_name == NULL)
2720 			break;
2721 	}
2722 
2723 	if (i >= kdb_max_commands) {
2724 		kdbtab_t *new = kmalloc((kdb_max_commands - KDB_BASE_CMD_MAX +
2725 			 kdb_command_extend) * sizeof(*new), GFP_KDB);
2726 		if (!new) {
2727 			kdb_printf("Could not allocate new kdb_command "
2728 				   "table\n");
2729 			return 1;
2730 		}
2731 		if (kdb_commands) {
2732 			memcpy(new, kdb_commands,
2733 			  (kdb_max_commands - KDB_BASE_CMD_MAX) * sizeof(*new));
2734 			kfree(kdb_commands);
2735 		}
2736 		memset(new + kdb_max_commands - KDB_BASE_CMD_MAX, 0,
2737 		       kdb_command_extend * sizeof(*new));
2738 		kdb_commands = new;
2739 		kp = kdb_commands + kdb_max_commands - KDB_BASE_CMD_MAX;
2740 		kdb_max_commands += kdb_command_extend;
2741 	}
2742 
2743 	kp->cmd_name   = cmd;
2744 	kp->cmd_func   = func;
2745 	kp->cmd_usage  = usage;
2746 	kp->cmd_help   = help;
2747 	kp->cmd_minlen = minlen;
2748 	kp->cmd_flags  = flags;
2749 
2750 	return 0;
2751 }
2752 EXPORT_SYMBOL_GPL(kdb_register_flags);
2753 
2754 
2755 /*
2756  * kdb_register - Compatibility register function for commands that do
2757  *	not need to specify a repeat state.  Equivalent to
2758  *	kdb_register_flags with flags set to 0.
2759  * Inputs:
2760  *	cmd	Command name
2761  *	func	Function to execute the command
2762  *	usage	A simple usage string showing arguments
2763  *	help	A simple help string describing command
2764  * Returns:
2765  *	zero for success, one if a duplicate command.
2766  */
2767 int kdb_register(char *cmd,
2768 	     kdb_func_t func,
2769 	     char *usage,
2770 	     char *help,
2771 	     short minlen)
2772 {
2773 	return kdb_register_flags(cmd, func, usage, help, minlen, 0);
2774 }
2775 EXPORT_SYMBOL_GPL(kdb_register);
2776 
2777 /*
2778  * kdb_unregister - This function is used to unregister a kernel
2779  *	debugger command.  It is generally called when a module which
2780  *	implements kdb commands is unloaded.
2781  * Inputs:
2782  *	cmd	Command name
2783  * Returns:
2784  *	zero for success, one command not registered.
2785  */
2786 int kdb_unregister(char *cmd)
2787 {
2788 	int i;
2789 	kdbtab_t *kp;
2790 
2791 	/*
2792 	 *  find the command.
2793 	 */
2794 	for_each_kdbcmd(kp, i) {
2795 		if (kp->cmd_name && (strcmp(kp->cmd_name, cmd) == 0)) {
2796 			kp->cmd_name = NULL;
2797 			return 0;
2798 		}
2799 	}
2800 
2801 	/* Couldn't find it.  */
2802 	return 1;
2803 }
2804 EXPORT_SYMBOL_GPL(kdb_unregister);
2805 
2806 /* Initialize the kdb command table. */
2807 static void __init kdb_inittab(void)
2808 {
2809 	int i;
2810 	kdbtab_t *kp;
2811 
2812 	for_each_kdbcmd(kp, i)
2813 		kp->cmd_name = NULL;
2814 
2815 	kdb_register_flags("md", kdb_md, "<vaddr>",
2816 	  "Display Memory Contents, also mdWcN, e.g. md8c1", 1,
2817 	  KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS);
2818 	kdb_register_flags("mdr", kdb_md, "<vaddr> <bytes>",
2819 	  "Display Raw Memory", 0,
2820 	  KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS);
2821 	kdb_register_flags("mdp", kdb_md, "<paddr> <bytes>",
2822 	  "Display Physical Memory", 0,
2823 	  KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS);
2824 	kdb_register_flags("mds", kdb_md, "<vaddr>",
2825 	  "Display Memory Symbolically", 0,
2826 	  KDB_ENABLE_MEM_READ | KDB_REPEAT_NO_ARGS);
2827 	kdb_register_flags("mm", kdb_mm, "<vaddr> <contents>",
2828 	  "Modify Memory Contents", 0,
2829 	  KDB_ENABLE_MEM_WRITE | KDB_REPEAT_NO_ARGS);
2830 	kdb_register_flags("go", kdb_go, "[<vaddr>]",
2831 	  "Continue Execution", 1,
2832 	  KDB_ENABLE_REG_WRITE | KDB_ENABLE_ALWAYS_SAFE_NO_ARGS);
2833 	kdb_register_flags("rd", kdb_rd, "",
2834 	  "Display Registers", 0,
2835 	  KDB_ENABLE_REG_READ);
2836 	kdb_register_flags("rm", kdb_rm, "<reg> <contents>",
2837 	  "Modify Registers", 0,
2838 	  KDB_ENABLE_REG_WRITE);
2839 	kdb_register_flags("ef", kdb_ef, "<vaddr>",
2840 	  "Display exception frame", 0,
2841 	  KDB_ENABLE_MEM_READ);
2842 	kdb_register_flags("bt", kdb_bt, "[<vaddr>]",
2843 	  "Stack traceback", 1,
2844 	  KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS);
2845 	kdb_register_flags("btp", kdb_bt, "<pid>",
2846 	  "Display stack for process <pid>", 0,
2847 	  KDB_ENABLE_INSPECT);
2848 	kdb_register_flags("bta", kdb_bt, "[D|R|S|T|C|Z|E|U|I|M|A]",
2849 	  "Backtrace all processes matching state flag", 0,
2850 	  KDB_ENABLE_INSPECT);
2851 	kdb_register_flags("btc", kdb_bt, "",
2852 	  "Backtrace current process on each cpu", 0,
2853 	  KDB_ENABLE_INSPECT);
2854 	kdb_register_flags("btt", kdb_bt, "<vaddr>",
2855 	  "Backtrace process given its struct task address", 0,
2856 	  KDB_ENABLE_MEM_READ | KDB_ENABLE_INSPECT_NO_ARGS);
2857 	kdb_register_flags("env", kdb_env, "",
2858 	  "Show environment variables", 0,
2859 	  KDB_ENABLE_ALWAYS_SAFE);
2860 	kdb_register_flags("set", kdb_set, "",
2861 	  "Set environment variables", 0,
2862 	  KDB_ENABLE_ALWAYS_SAFE);
2863 	kdb_register_flags("help", kdb_help, "",
2864 	  "Display Help Message", 1,
2865 	  KDB_ENABLE_ALWAYS_SAFE);
2866 	kdb_register_flags("?", kdb_help, "",
2867 	  "Display Help Message", 0,
2868 	  KDB_ENABLE_ALWAYS_SAFE);
2869 	kdb_register_flags("cpu", kdb_cpu, "<cpunum>",
2870 	  "Switch to new cpu", 0,
2871 	  KDB_ENABLE_ALWAYS_SAFE_NO_ARGS);
2872 	kdb_register_flags("kgdb", kdb_kgdb, "",
2873 	  "Enter kgdb mode", 0, 0);
2874 	kdb_register_flags("ps", kdb_ps, "[<flags>|A]",
2875 	  "Display active task list", 0,
2876 	  KDB_ENABLE_INSPECT);
2877 	kdb_register_flags("pid", kdb_pid, "<pidnum>",
2878 	  "Switch to another task", 0,
2879 	  KDB_ENABLE_INSPECT);
2880 	kdb_register_flags("reboot", kdb_reboot, "",
2881 	  "Reboot the machine immediately", 0,
2882 	  KDB_ENABLE_REBOOT);
2883 #if defined(CONFIG_MODULES)
2884 	kdb_register_flags("lsmod", kdb_lsmod, "",
2885 	  "List loaded kernel modules", 0,
2886 	  KDB_ENABLE_INSPECT);
2887 #endif
2888 #if defined(CONFIG_MAGIC_SYSRQ)
2889 	kdb_register_flags("sr", kdb_sr, "<key>",
2890 	  "Magic SysRq key", 0,
2891 	  KDB_ENABLE_ALWAYS_SAFE);
2892 #endif
2893 #if defined(CONFIG_PRINTK)
2894 	kdb_register_flags("dmesg", kdb_dmesg, "[lines]",
2895 	  "Display syslog buffer", 0,
2896 	  KDB_ENABLE_ALWAYS_SAFE);
2897 #endif
2898 	if (arch_kgdb_ops.enable_nmi) {
2899 		kdb_register_flags("disable_nmi", kdb_disable_nmi, "",
2900 		  "Disable NMI entry to KDB", 0,
2901 		  KDB_ENABLE_ALWAYS_SAFE);
2902 	}
2903 	kdb_register_flags("defcmd", kdb_defcmd, "name \"usage\" \"help\"",
2904 	  "Define a set of commands, down to endefcmd", 0,
2905 	  KDB_ENABLE_ALWAYS_SAFE);
2906 	kdb_register_flags("kill", kdb_kill, "<-signal> <pid>",
2907 	  "Send a signal to a process", 0,
2908 	  KDB_ENABLE_SIGNAL);
2909 	kdb_register_flags("summary", kdb_summary, "",
2910 	  "Summarize the system", 4,
2911 	  KDB_ENABLE_ALWAYS_SAFE);
2912 	kdb_register_flags("per_cpu", kdb_per_cpu, "<sym> [<bytes>] [<cpu>]",
2913 	  "Display per_cpu variables", 3,
2914 	  KDB_ENABLE_MEM_READ);
2915 	kdb_register_flags("grephelp", kdb_grep_help, "",
2916 	  "Display help on | grep", 0,
2917 	  KDB_ENABLE_ALWAYS_SAFE);
2918 }
2919 
2920 /* Execute any commands defined in kdb_cmds.  */
2921 static void __init kdb_cmd_init(void)
2922 {
2923 	int i, diag;
2924 	for (i = 0; kdb_cmds[i]; ++i) {
2925 		diag = kdb_parse(kdb_cmds[i]);
2926 		if (diag)
2927 			kdb_printf("kdb command %s failed, kdb diag %d\n",
2928 				kdb_cmds[i], diag);
2929 	}
2930 	if (defcmd_in_progress) {
2931 		kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
2932 		kdb_parse("endefcmd");
2933 	}
2934 }
2935 
2936 /* Initialize kdb_printf, breakpoint tables and kdb state */
2937 void __init kdb_init(int lvl)
2938 {
2939 	static int kdb_init_lvl = KDB_NOT_INITIALIZED;
2940 	int i;
2941 
2942 	if (kdb_init_lvl == KDB_INIT_FULL || lvl <= kdb_init_lvl)
2943 		return;
2944 	for (i = kdb_init_lvl; i < lvl; i++) {
2945 		switch (i) {
2946 		case KDB_NOT_INITIALIZED:
2947 			kdb_inittab();		/* Initialize Command Table */
2948 			kdb_initbptab();	/* Initialize Breakpoints */
2949 			break;
2950 		case KDB_INIT_EARLY:
2951 			kdb_cmd_init();		/* Build kdb_cmds tables */
2952 			break;
2953 		}
2954 	}
2955 	kdb_init_lvl = lvl;
2956 }
2957