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