Drop obsoleted patch.
[linux-flexiantxendom0-3.2.10.git] / kdb / kdbmain.c
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  */
12
13 /*
14  * Updated for Xscale (R) architecture support
15  * Eddie Dong <eddie.dong@intel.com> 8 Jan 03
16  */
17
18 #include <linux/config.h>
19 #include <linux/ctype.h>
20 #include <linux/string.h>
21 #include <linux/kernel.h>
22 #include <linux/reboot.h>
23 #include <linux/sched.h>
24 #include <linux/sysrq.h>
25 #include <linux/smp.h>
26 #include <linux/utsname.h>
27 #include <linux/vmalloc.h>
28 #include <linux/module.h>
29 #include <linux/mm.h>
30 #include <linux/init.h>
31 #include <linux/kallsyms.h>
32 #include <linux/kdb.h>
33 #include <linux/kdbprivate.h>
34 #include <linux/notifier.h>
35 #include <linux/interrupt.h>
36 #include <linux/delay.h>
37 #include <linux/nmi.h>
38 #include <linux/ptrace.h>
39 #if defined(CONFIG_DUMP) || defined(CONFIG_DUMP_MODULE)
40 #include <linux/dump.h>
41 #endif
42
43 #include <asm/system.h>
44
45 /*
46  * Kernel debugger state flags
47  */
48 volatile int kdb_flags;
49 atomic_t kdb_event;
50
51 /*
52  * kdb_lock protects updates to kdb_initial_cpu.  Used to
53  * single thread processors through the kernel debugger.
54  */
55 static spinlock_t kdb_lock = SPIN_LOCK_UNLOCKED;
56 volatile int kdb_initial_cpu = -1;              /* cpu number that owns kdb */
57 int kdb_seqno = 2;                              /* how many times kdb has been entered */
58
59 volatile int kdb_nextline = 1;
60 static volatile int kdb_new_cpu;                /* Which cpu to switch to */
61
62 volatile int kdb_state[NR_CPUS];                /* Per cpu state */
63
64 struct task_struct *kdb_current_task;
65
66 #ifdef  CONFIG_KDB_OFF
67 int kdb_on = 0;                         /* Default is off */
68 #else
69 int kdb_on = 1;                         /* Default is on */
70 #endif  /* CONFIG_KDB_OFF */
71
72 const char *kdb_diemsg;
73 struct notifier_block *kdb_notifier_list;       /* racy for modules, see comments in kdb.h */
74 static int kdb_go_count;
75 #ifdef CONFIG_KDB_CONTINUE_CATASTROPHIC
76 static unsigned int kdb_continue_catastrophic = CONFIG_KDB_CONTINUE_CATASTROPHIC;
77 #else
78 static unsigned int kdb_continue_catastrophic = 0;
79 #endif
80
81 #ifdef KDB_HAVE_LONGJMP
82         /*
83          * Must have a setjmp buffer per CPU.  Switching cpus will
84          * cause the jump buffer to be setup for the new cpu, and
85          * subsequent switches (and pager aborts) will use the
86          * appropriate per-processor values.
87          */
88 kdb_jmp_buf *kdbjmpbuf;
89 #endif  /* KDB_HAVE_LONGJMP */
90
91         /*
92          * kdb_commands describes the available commands.
93          */
94 static kdbtab_t *kdb_commands;
95 static int kdb_max_commands;
96
97 typedef struct _kdbmsg {
98         int     km_diag;        /* kdb diagnostic */
99         char    *km_msg;        /* Corresponding message text */
100 } kdbmsg_t;
101
102 #define KDBMSG(msgnum, text) \
103         { KDB_##msgnum, text }
104
105 static kdbmsg_t kdbmsgs[] = {
106         KDBMSG(NOTFOUND,"Command Not Found"),
107         KDBMSG(ARGCOUNT, "Improper argument count, see usage."),
108         KDBMSG(BADWIDTH, "Illegal value for BYTESPERWORD use 1, 2, 4 or 8, 8 is only allowed on 64 bit systems"),
109         KDBMSG(BADRADIX, "Illegal value for RADIX use 8, 10 or 16"),
110         KDBMSG(NOTENV, "Cannot find environment variable"),
111         KDBMSG(NOENVVALUE, "Environment variable should have value"),
112         KDBMSG(NOTIMP, "Command not implemented"),
113         KDBMSG(ENVFULL, "Environment full"),
114         KDBMSG(ENVBUFFULL, "Environment buffer full"),
115         KDBMSG(TOOMANYBPT, "Too many breakpoints defined"),
116 #ifdef  CONFIG_CPU_XSCALE
117         KDBMSG(TOOMANYDBREGS, "More breakpoints than ibcr registers defined"),
118 #else
119         KDBMSG(TOOMANYDBREGS, "More breakpoints than db registers defined"),
120 #endif
121         KDBMSG(DUPBPT, "Duplicate breakpoint address"),
122         KDBMSG(BPTNOTFOUND, "Breakpoint not found"),
123         KDBMSG(BADMODE, "Invalid IDMODE"),
124         KDBMSG(BADINT, "Illegal numeric value"),
125         KDBMSG(INVADDRFMT, "Invalid symbolic address format"),
126         KDBMSG(BADREG, "Invalid register name"),
127         KDBMSG(BADCPUNUM, "Invalid cpu number"),
128         KDBMSG(BADLENGTH, "Invalid length field"),
129         KDBMSG(NOBP, "No Breakpoint exists"),
130         KDBMSG(BADADDR, "Invalid address"),
131 };
132 #undef KDBMSG
133
134 static const int __nkdb_err = sizeof(kdbmsgs) / sizeof(kdbmsg_t);
135
136
137 /*
138  * Initial environment.   This is all kept static and local to
139  * this file.   We don't want to rely on the memory allocation
140  * mechanisms in the kernel, so we use a very limited allocate-only
141  * heap for new and altered environment variables.  The entire
142  * environment is limited to a fixed number of entries (add more
143  * to __env[] if required) and a fixed amount of heap (add more to
144  * KDB_ENVBUFSIZE if required).
145  */
146
147 static char *__env[] = {
148 #if defined(CONFIG_SMP)
149  "PROMPT=[%d]kdb> ",
150  "MOREPROMPT=[%d]more> ",
151 #else
152  "PROMPT=kdb> ",
153  "MOREPROMPT=more> ",
154 #endif
155  "RADIX=16",
156  "LINES=24",
157  "COLUMNS=80",
158  "MDCOUNT=8",                   /* lines of md output */
159  "BTARGS=5",                    /* 5 possible args in bt */
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 };
187
188 static const int __nenv = (sizeof(__env) / sizeof(char *));
189
190 /*
191  * kdb_serial_str is the sequence that the user must enter on a serial
192  * console to invoke kdb.  It can be a single character such as "\001"
193  * (control-A) or multiple characters such as "\eKDB".  NOTE: All except the
194  * last character are passed through to the application reading from the serial
195  * console.
196  *
197  * I tried to make the sequence a CONFIG_ option but most of CML1 cannot cope
198  * with '\' in strings.  CML2 would have been able to do it but we lost CML2.
199  * KAO.
200  */
201 const char kdb_serial_str[] = "\eKDB";
202 EXPORT_SYMBOL(kdb_serial_str);
203
204 /*
205  * kdbgetenv
206  *
207  *      This function will return the character string value of
208  *      an environment variable.
209  *
210  * Parameters:
211  *      match   A character string representing an environment variable.
212  * Outputs:
213  *      None.
214  * Returns:
215  *      NULL    No environment variable matches 'match'
216  *      char*   Pointer to string value of environment variable.
217  * Locking:
218  *      No locking considerations required.
219  * Remarks:
220  */
221 char *
222 kdbgetenv(const char *match)
223 {
224         char **ep = __env;
225         int matchlen = strlen(match);
226         int i;
227
228         for(i=0; i<__nenv; i++) {
229                 char *e = *ep++;
230
231                 if (!e) continue;
232
233                 if ((strncmp(match, e, matchlen) == 0)
234                  && ((e[matchlen] == '\0')
235                    ||(e[matchlen] == '='))) {
236                         char *cp = strchr(e, '=');
237                         return (cp)?++cp:"";
238                 }
239         }
240         return (char *)0;
241 }
242
243 /*
244  * kdballocenv
245  *
246  *      This function is used to allocate bytes for environment entries.
247  *
248  * Parameters:
249  *      match   A character string representing a numeric value
250  * Outputs:
251  *      *value  the unsigned long represntation of the env variable 'match'
252  * Returns:
253  *      Zero on success, a kdb diagnostic on failure.
254  * Locking:
255  *      No locking considerations required.  Must be called with all
256  *      processors halted.
257  * Remarks:
258  *      We use a static environment buffer (envbuffer) to hold the values
259  *      of dynamically generated environment variables (see kdb_set).  Buffer
260  *      space once allocated is never free'd, so over time, the amount of space
261  *      (currently 512 bytes) will be exhausted if env variables are changed
262  *      frequently.
263  */
264 static char *
265 kdballocenv(size_t bytes)
266 {
267 #define KDB_ENVBUFSIZE  512
268         static char envbuffer[KDB_ENVBUFSIZE];
269         static int envbufsize;
270         char *ep = (char *)0;
271
272         if ((KDB_ENVBUFSIZE - envbufsize) >= bytes) {
273                 ep = &envbuffer[envbufsize];
274                 envbufsize += bytes;
275         }
276         return ep;
277 }
278
279 /*
280  * kdbgetulenv
281  *
282  *      This function will return the value of an unsigned long-valued
283  *      environment variable.
284  *
285  * Parameters:
286  *      match   A character string representing a numeric value
287  * Outputs:
288  *      *value  the unsigned long represntation of the env variable 'match'
289  * Returns:
290  *      Zero on success, a kdb diagnostic on failure.
291  * Locking:
292  *      No locking considerations required.
293  * Remarks:
294  */
295
296 static int
297 kdbgetulenv(const char *match, unsigned long *value)
298 {
299         char *ep;
300
301         ep = kdbgetenv(match);
302         if (!ep) return KDB_NOTENV;
303         if (strlen(ep) == 0) return KDB_NOENVVALUE;
304
305         *value = simple_strtoul(ep, 0, 0);
306
307         return 0;
308 }
309
310 /*
311  * kdbgetintenv
312  *
313  *      This function will return the value of an integer-valued
314  *      environment variable.
315  *
316  * Parameters:
317  *      match   A character string representing an integer-valued env variable
318  * Outputs:
319  *      *value  the integer representation of the environment variable 'match'
320  * Returns:
321  *      Zero on success, a kdb diagnostic on failure.
322  * Locking:
323  *      No locking considerations required.
324  * Remarks:
325  */
326
327 int
328 kdbgetintenv(const char *match, int *value) {
329         unsigned long val;
330         int diag;
331
332         diag = kdbgetulenv(match, &val);
333         if (!diag) {
334                 *value = (int) val;
335         }
336         return diag;
337 }
338
339 /*
340  * kdbgetularg
341  *
342  *      This function will convert a numeric string
343  *      into an unsigned long value.
344  *
345  * Parameters:
346  *      arg     A character string representing a numeric value
347  * Outputs:
348  *      *value  the unsigned long represntation of arg.
349  * Returns:
350  *      Zero on success, a kdb diagnostic on failure.
351  * Locking:
352  *      No locking considerations required.
353  * Remarks:
354  */
355
356 int
357 kdbgetularg(const char *arg, unsigned long *value)
358 {
359         char *endp;
360         unsigned long val;
361
362         val = simple_strtoul(arg, &endp, 0);
363
364         if (endp == arg) {
365                 /*
366                  * Try base 16, for us folks too lazy to type the
367                  * leading 0x...
368                  */
369                 val = simple_strtoul(arg, &endp, 16);
370                 if (endp == arg)
371                         return KDB_BADINT;
372         }
373
374         *value = val;
375
376         return 0;
377 }
378
379 /*
380  * kdb_set
381  *
382  *      This function implements the 'set' command.  Alter an existing
383  *      environment variable or create a new one.
384  *
385  * Inputs:
386  *      argc    argument count
387  *      argv    argument vector
388  *      envp    environment vector
389  *      regs    registers at time kdb was entered.
390  * Outputs:
391  *      None.
392  * Returns:
393  *      zero for success, a kdb diagnostic if error
394  * Locking:
395  *      none.
396  * Remarks:
397  */
398
399 static int
400 kdb_set(int argc, const char **argv, const char **envp, struct pt_regs *regs)
401 {
402         int i;
403         char *ep;
404         size_t varlen, vallen;
405
406         /*
407          * we can be invoked two ways:
408          *   set var=value    argv[1]="var", argv[2]="value"
409          *   set var = value  argv[1]="var", argv[2]="=", argv[3]="value"
410          * - if the latter, shift 'em down.
411          */
412         if (argc == 3) {
413                 argv[2] = argv[3];
414                 argc--;
415         }
416
417         if (argc != 2)
418                 return KDB_ARGCOUNT;
419
420         /*
421          * Check for internal variables
422          */
423         if (strcmp(argv[1], "KDBDEBUG") == 0) {
424                 unsigned int debugflags;
425                 char *cp;
426
427                 debugflags = simple_strtoul(argv[2], &cp, 0);
428                 if (cp == argv[2] || debugflags & ~KDB_DEBUG_FLAG_MASK) {
429                         kdb_printf("kdb: illegal debug flags '%s'\n",
430                                     argv[2]);
431                         return 0;
432                 }
433                 kdb_flags = (kdb_flags & ~(KDB_DEBUG_FLAG_MASK << KDB_DEBUG_FLAG_SHIFT))
434                           | (debugflags << KDB_DEBUG_FLAG_SHIFT);
435
436                 return 0;
437         }
438
439         /*
440          * Tokenizer squashed the '=' sign.  argv[1] is variable
441          * name, argv[2] = value.
442          */
443         varlen = strlen(argv[1]);
444         vallen = strlen(argv[2]);
445         ep = kdballocenv(varlen + vallen + 2);
446         if (ep == (char *)0)
447                 return KDB_ENVBUFFULL;
448
449         sprintf(ep, "%s=%s", argv[1], argv[2]);
450
451         ep[varlen+vallen+1]='\0';
452
453         for(i=0; i<__nenv; i++) {
454                 if (__env[i]
455                  && ((strncmp(__env[i], argv[1], varlen)==0)
456                    && ((__env[i][varlen] == '\0')
457                     || (__env[i][varlen] == '=')))) {
458                         __env[i] = ep;
459                         return 0;
460                 }
461         }
462
463         /*
464          * Wasn't existing variable.  Fit into slot.
465          */
466         for(i=0; i<__nenv-1; i++) {
467                 if (__env[i] == (char *)0) {
468                         __env[i] = ep;
469                         return 0;
470                 }
471         }
472
473         return KDB_ENVFULL;
474 }
475
476 /*
477  * kdbgetaddrarg
478  *
479  *      This function is responsible for parsing an
480  *      address-expression and returning the value of
481  *      the expression, symbol name, and offset to the caller.
482  *
483  *      The argument may consist of a numeric value (decimal or
484  *      hexidecimal), a symbol name, a register name (preceeded
485  *      by the percent sign), an environment variable with a numeric
486  *      value (preceeded by a dollar sign) or a simple arithmetic
487  *      expression consisting of a symbol name, +/-, and a numeric
488  *      constant value (offset).
489  *
490  * Parameters:
491  *      argc    - count of arguments in argv
492  *      argv    - argument vector
493  *      *nextarg - index to next unparsed argument in argv[]
494  *      regs    - Register state at time of KDB entry
495  * Outputs:
496  *      *value  - receives the value of the address-expression
497  *      *offset - receives the offset specified, if any
498  *      *name   - receives the symbol name, if any
499  *      *nextarg - index to next unparsed argument in argv[]
500  *
501  * Returns:
502  *      zero is returned on success, a kdb diagnostic code is
503  *      returned on error.
504  *
505  * Locking:
506  *      No locking requirements.
507  *
508  * Remarks:
509  *
510  */
511
512 int
513 kdbgetaddrarg(int argc, const char **argv, int *nextarg,
514               kdb_machreg_t *value,  long *offset,
515               char **name, struct pt_regs *regs)
516 {
517         kdb_machreg_t addr;
518         long off = 0;
519         int positive;
520         int diag;
521         int found = 0;
522         char *symname;
523         char symbol = '\0';
524         char *cp;
525         kdb_symtab_t symtab;
526
527         /*
528          * Process arguments which follow the following syntax:
529          *
530          *  symbol | numeric-address [+/- numeric-offset]
531          *  %register
532          *  $environment-variable
533          */
534
535         if (*nextarg > argc) {
536                 return KDB_ARGCOUNT;
537         }
538
539         symname = (char *)argv[*nextarg];
540
541         /*
542          * If there is no whitespace between the symbol
543          * or address and the '+' or '-' symbols, we
544          * remember the character and replace it with a
545          * null so the symbol/value can be properly parsed
546          */
547         if ((cp = strpbrk(symname, "+-")) != NULL) {
548                 symbol = *cp;
549                 *cp++ = '\0';
550         }
551
552         if (symname[0] == '$') {
553                 diag = kdbgetulenv(&symname[1], &addr);
554                 if (diag)
555                         return diag;
556         } else if (symname[0] == '%') {
557                 diag = kdba_getregcontents(&symname[1], regs, &addr);
558                 if (diag)
559                         return diag;
560         } else {
561                 found = kdbgetsymval(symname, &symtab);
562                 if (found) {
563                         addr = symtab.sym_start;
564                 } else {
565                         diag = kdbgetularg(argv[*nextarg], &addr);
566                         if (diag)
567                                 return diag;
568                 }
569         }
570
571         if (!found)
572                 found = kdbnearsym(addr, &symtab);
573
574         (*nextarg)++;
575
576         if (name)
577                 *name = symname;
578         if (value)
579                 *value = addr;
580         if (offset && name && *name)
581                 *offset = addr - symtab.sym_start;
582
583         if ((*nextarg > argc)
584          && (symbol == '\0'))
585                 return 0;
586
587         /*
588          * check for +/- and offset
589          */
590
591         if (symbol == '\0') {
592                 if ((argv[*nextarg][0] != '+')
593                  && (argv[*nextarg][0] != '-')) {
594                         /*
595                          * Not our argument.  Return.
596                          */
597                         return 0;
598                 } else {
599                         positive = (argv[*nextarg][0] == '+');
600                         (*nextarg)++;
601                 }
602         } else
603                 positive = (symbol == '+');
604
605         /*
606          * Now there must be an offset!
607          */
608         if ((*nextarg > argc)
609          && (symbol == '\0')) {
610                 return KDB_INVADDRFMT;
611         }
612
613         if (!symbol) {
614                 cp = (char *)argv[*nextarg];
615                 (*nextarg)++;
616         }
617
618         diag = kdbgetularg(cp, &off);
619         if (diag)
620                 return diag;
621
622         if (!positive)
623                 off = -off;
624
625         if (offset)
626                 *offset += off;
627
628         if (value)
629                 *value += off;
630
631         return 0;
632 }
633
634 static void
635 kdb_cmderror(int diag)
636 {
637         int i;
638
639         if (diag >= 0) {
640                 kdb_printf("no error detected\n");
641                 return;
642         }
643
644         for(i=0; i<__nkdb_err; i++) {
645                 if (kdbmsgs[i].km_diag == diag) {
646                         kdb_printf("diag: %d: %s\n", diag, kdbmsgs[i].km_msg);
647                         return;
648                 }
649         }
650
651         kdb_printf("Unknown diag %d\n", -diag);
652 }
653
654 /*
655  * kdb_defcmd, kdb_defcmd2
656  *
657  *      This function implements the 'defcmd' command which defines one
658  *      command as a set of other commands, terminated by endefcmd.
659  *      kdb_defcmd processes the initial 'defcmd' command, kdb_defcmd2
660  *      is invoked from kdb_parse for the following commands until
661  *      'endefcmd'.
662  *
663  * Inputs:
664  *      argc    argument count
665  *      argv    argument vector
666  *      envp    environment vector
667  *      regs    registers at time kdb was entered.
668  * Outputs:
669  *      None.
670  * Returns:
671  *      zero for success, a kdb diagnostic if error
672  * Locking:
673  *      none.
674  * Remarks:
675  */
676
677 struct defcmd_set {
678         int count;
679         int usable;
680         char *name;
681         char *usage;
682         char *help;
683         char **command;
684 };
685 static struct defcmd_set *defcmd_set;
686 static int defcmd_set_count;
687 static int defcmd_in_progress;
688
689 /* Forward references */
690 static int kdb_exec_defcmd(int argc, const char **argv, const char **envp, struct pt_regs *regs);
691
692 static int
693 kdb_defcmd2(const char *cmdstr, const char *argv0)
694 {
695         struct defcmd_set *s = defcmd_set + defcmd_set_count - 1;
696         char **save_command = s->command;
697         if (strcmp(argv0, "endefcmd") == 0) {
698                 defcmd_in_progress = 0;
699                 if (!s->count)
700                         s->usable = 0;
701                 if (s->usable)
702                         kdb_register(s->name, kdb_exec_defcmd, s->usage, s->help, 0);
703                 return 0;
704         }
705         if (!s->usable)
706                 return KDB_NOTIMP;
707         s->command = kmalloc((s->count + 1) * sizeof(*(s->command)), GFP_KDB);
708         if (!s->command) {
709                 kdb_printf("Could not allocate new kdb_defcmd table for %s\n", cmdstr);
710                 s->usable = 0;
711                 return KDB_NOTIMP;
712         }
713         memcpy(s->command, save_command, s->count * sizeof(*(s->command)));
714         s->command[s->count++] = kdb_strdup(cmdstr, GFP_KDB);
715         kfree(save_command);
716         return 0;
717 }
718
719 static int
720 kdb_defcmd(int argc, const char **argv, const char **envp, struct pt_regs *regs)
721 {
722         struct defcmd_set *save_defcmd_set = defcmd_set, *s;
723         if (defcmd_in_progress) {
724                 kdb_printf("kdb: nested defcmd detected, assuming missing endefcmd\n");
725                 kdb_defcmd2("endefcmd", "endefcmd");
726         }
727         if (argc == 0) {
728                 int i;
729                 for (s = defcmd_set; s < defcmd_set + defcmd_set_count; ++s) {
730                         kdb_printf("defcmd %s \"%s\" \"%s\"\n", s->name, s->usage, s->help);
731                         for (i = 0; i < s->count; ++i)
732                                 kdb_printf("%s", s->command[i]);
733                         kdb_printf("endefcmd\n");
734                 }
735                 return 0;
736         }
737         if (argc != 3)
738                 return KDB_ARGCOUNT;
739         defcmd_set = kmalloc((defcmd_set_count + 1) * sizeof(*defcmd_set), GFP_KDB);
740         if (!defcmd_set) {
741                 kdb_printf("Could not allocate new defcmd_set entry for %s\n", argv[1]);
742                 defcmd_set = save_defcmd_set;
743                 return KDB_NOTIMP;
744         }
745         memcpy(defcmd_set, save_defcmd_set, defcmd_set_count * sizeof(*defcmd_set));
746         kfree(save_defcmd_set);
747         s = defcmd_set + defcmd_set_count;
748         memset(s, 0, sizeof(*s));
749         s->usable = 1;
750         s->name = kdb_strdup(argv[1], GFP_KDB);
751         s->usage = kdb_strdup(argv[2], GFP_KDB);
752         s->help = kdb_strdup(argv[3], GFP_KDB);
753         if (s->usage[0] == '"') {
754                 strcpy(s->usage, s->usage+1);
755                 s->usage[strlen(s->usage)-1] = '\0';
756         }
757         if (s->help[0] == '"') {
758                 strcpy(s->help, s->help+1);
759                 s->help[strlen(s->help)-1] = '\0';
760         }
761         ++defcmd_set_count;
762         defcmd_in_progress = 1;
763         return 0;
764 }
765
766 /*
767  * kdb_exec_defcmd
768  *
769  *      Execute the set of commands associated with this defcmd name.
770  *
771  * Inputs:
772  *      argc    argument count
773  *      argv    argument vector
774  *      envp    environment vector
775  *      regs    registers at time kdb was entered.
776  * Outputs:
777  *      None.
778  * Returns:
779  *      zero for success, a kdb diagnostic if error
780  * Locking:
781  *      none.
782  * Remarks:
783  */
784
785 static int
786 kdb_exec_defcmd(int argc, const char **argv, const char **envp, struct pt_regs *regs)
787 {
788         int i, ret;
789         struct defcmd_set *s;
790         if (argc != 0)
791                 return KDB_ARGCOUNT;
792         for (s = defcmd_set, i = 0; i < defcmd_set_count; ++i, ++s) {
793                 if (strcmp(s->name, argv[0]) == 0)
794                         break;
795         }
796         if (i == defcmd_set_count) {
797                 kdb_printf("kdb_exec_defcmd: could not find commands for %s\n", argv[0]);
798                 return KDB_NOTIMP;
799         }
800         for (i = 0; i < s->count; ++i) {
801                 /* Recursive use of kdb_parse, do not use argv after this point */
802                 argv = NULL;
803                 kdb_printf("[%s]kdb> %s\n", s->name, s->command[i]);
804                 if ((ret = kdb_parse(s->command[i], regs)))
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 size == 256 */
813 static unsigned int cmd_head=0, cmd_tail=0;
814 static unsigned int cmdptr;
815 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
816 static char cmd_cur[CMD_BUFLEN];
817
818 /*
819  * kdb_parse
820  *
821  *      Parse the command line, search the command table for a
822  *      matching command and invoke the command function.
823  *      This function may be called recursively, if it is, the second call
824  *      will overwrite argv and cbuf.  It is the caller's responsibility to
825  *      save their argv if they recursively call kdb_parse().
826  *
827  * Parameters:
828  *      cmdstr  The input command line to be parsed.
829  *      regs    The registers at the time kdb was entered.
830  * Outputs:
831  *      None.
832  * Returns:
833  *      Zero for success, a kdb diagnostic if failure.
834  * Locking:
835  *      None.
836  * Remarks:
837  *      Limited to 20 tokens.
838  *
839  *      Real rudimentary tokenization. Basically only whitespace
840  *      is considered a token delimeter (but special consideration
841  *      is taken of the '=' sign as used by the 'set' command).
842  *
843  *      The algorithm used to tokenize the input string relies on
844  *      there being at least one whitespace (or otherwise useless)
845  *      character between tokens as the character immediately following
846  *      the token is altered in-place to a null-byte to terminate the
847  *      token string.
848  */
849
850 #define MAXARGC 20
851
852 int
853 kdb_parse(const char *cmdstr, struct pt_regs *regs)
854 {
855         static char *argv[MAXARGC];
856         static int argc = 0;
857         static char cbuf[CMD_BUFLEN+2];
858         const char *cp;
859         char *cpp, quoted;
860         kdbtab_t *tp;
861         int i, escaped, ignore_errors = 0;
862
863         /*
864          * First tokenize the command string.
865          */
866         cp = cmdstr;
867
868         if (KDB_FLAG(CMD_INTERRUPT)) {
869                 /* Previous command was interrupted, newline must not repeat the command */
870                 KDB_FLAG_CLEAR(CMD_INTERRUPT);
871                 argc = 0;       /* no repeat */
872         }
873
874         if (*cp != '\n' && *cp != '\0') {
875                 argc = 0;
876                 cpp = cbuf;
877                 while (*cp) {
878                         /* skip whitespace */
879                         while (isspace(*cp)) cp++;
880                         if ((*cp == '\0') || (*cp == '\n') || (*cp == '#' && !defcmd_in_progress))
881                                 break;
882                         if (cpp >= cbuf + CMD_BUFLEN) {
883                                 kdb_printf("kdb_parse: command buffer overflow, command ignored\n%s\n", cmdstr);
884                                 return KDB_NOTFOUND;
885                         }
886                         if (argc >= MAXARGC - 1) {
887                                 kdb_printf("kdb_parse: too many arguments, command ignored\n%s\n", cmdstr);
888                                 return KDB_NOTFOUND;
889                         }
890                         argv[argc++] = cpp;
891                         escaped = 0;
892                         quoted = '\0';
893                         /* Copy to next unquoted and unescaped whitespace or '=' */
894                         while (*cp && *cp != '\n' && (escaped || quoted || !isspace(*cp))) {
895                                 if (cpp >= cbuf + CMD_BUFLEN)
896                                         break;
897                                 if (escaped) {
898                                         escaped = 0;
899                                         *cpp++ = *cp++;
900                                         continue;
901                                 }
902                                 if (*cp == '\\') {
903                                         escaped = 1;
904                                         ++cp;
905                                         continue;
906                                 }
907                                 if (*cp == quoted) {
908                                         quoted = '\0';
909                                 } else if (*cp == '\'' || *cp == '"') {
910                                         quoted = *cp;
911                                 }
912                                 if ((*cpp = *cp++) == '=' && !quoted)
913                                         break;
914                                 ++cpp;
915                         }
916                         *cpp++ = '\0';  /* Squash a ws or '=' character */
917                 }
918         }
919         if (!argc)
920                 return 0;
921         if (defcmd_in_progress) {
922                 int result = kdb_defcmd2(cmdstr, argv[0]);
923                 if (!defcmd_in_progress) {
924                         argc = 0;       /* avoid repeat on endefcmd */
925                         *(argv[0]) = '\0';
926                 }
927                 return result;
928         }
929         if (argv[0][0] == '-' && argv[0][1] && (argv[0][1] < '0' || argv[0][1] > '9')) {
930                 ignore_errors = 1;
931                 ++argv[0];
932         }
933
934         for(tp=kdb_commands, i=0; i < kdb_max_commands; i++,tp++) {
935                 if (tp->cmd_name) {
936                         /*
937                          * If this command is allowed to be abbreviated,
938                          * check to see if this is it.
939                          */
940
941                         if (tp->cmd_minlen
942                          && (strlen(argv[0]) <= tp->cmd_minlen)) {
943                                 if (strncmp(argv[0],
944                                             tp->cmd_name,
945                                             tp->cmd_minlen) == 0) {
946                                         break;
947                                 }
948                         }
949
950                         if (strcmp(argv[0], tp->cmd_name)==0) {
951                                 break;
952                         }
953                 }
954         }
955
956         /*
957          * If we don't find a command by this name, see if the first
958          * few characters of this match any of the known commands.
959          * e.g., md1c20 should match md.
960          */
961         if (i == kdb_max_commands) {
962                 for(tp=kdb_commands, i=0; i < kdb_max_commands; i++,tp++) {
963                         if (tp->cmd_name) {
964                                 if (strncmp(argv[0],
965                                             tp->cmd_name,
966                                             strlen(tp->cmd_name))==0) {
967                                         break;
968                                 }
969                         }
970                 }
971         }
972
973         if (i < kdb_max_commands) {
974                 int result;
975                 KDB_STATE_SET(CMD);
976                 result = (*tp->cmd_func)(argc-1,
977                                        (const char**)argv,
978                                        (const char**)__env,
979                                        regs);
980                 if (result && ignore_errors && result > KDB_CMD_GO)
981                         result = 0;
982                 KDB_STATE_CLEAR(CMD);
983                 switch (tp->cmd_repeat) {
984                 case KDB_REPEAT_NONE:
985                         argc = 0;
986                         if (argv[0])
987                                 *(argv[0]) = '\0';
988                         break;
989                 case KDB_REPEAT_NO_ARGS:
990                         argc = 1;
991                         if (argv[1])
992                                 *(argv[1]) = '\0';
993                         break;
994                 case KDB_REPEAT_WITH_ARGS:
995                         break;
996                 }
997                 return result;
998         }
999
1000         /*
1001          * If the input with which we were presented does not
1002          * map to an existing command, attempt to parse it as an
1003          * address argument and display the result.   Useful for
1004          * obtaining the address of a variable, or the nearest symbol
1005          * to an address contained in a register.
1006          */
1007         {
1008                 kdb_machreg_t value;
1009                 char *name = NULL;
1010                 long offset;
1011                 int nextarg = 0;
1012
1013                 if (kdbgetaddrarg(0, (const char **)argv, &nextarg,
1014                                   &value, &offset, &name, regs)) {
1015                         return KDB_NOTFOUND;
1016                 }
1017
1018                 kdb_printf("%s = ", argv[0]);
1019                 kdb_symbol_print(value, NULL, KDB_SP_DEFAULT);
1020                 kdb_printf("\n");
1021                 return 0;
1022         }
1023 }
1024
1025
1026 static int
1027 handle_ctrl_cmd(char *cmd)
1028 {
1029 #define CTRL_P  16
1030 #define CTRL_N  14
1031
1032         /* initial situation */
1033         if (cmd_head == cmd_tail) return 0;
1034
1035         switch(*cmd) {
1036                 case CTRL_P:
1037                         if (cmdptr != cmd_tail)
1038                                 cmdptr = (cmdptr-1) % KDB_CMD_HISTORY_COUNT;
1039                         strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1040                         return 1;
1041                 case CTRL_N:
1042                         if (cmdptr != cmd_head)
1043                                 cmdptr = (cmdptr+1) % KDB_CMD_HISTORY_COUNT;
1044                         strncpy(cmd_cur, cmd_hist[cmdptr], CMD_BUFLEN);
1045                         return 1;
1046         }
1047         return 0;
1048 }
1049
1050 /*
1051  * kdb_do_dump
1052  *
1053  *      Call the dump() function if the kernel is configured for LKCD.
1054  * Inputs:
1055  *      None.
1056  * Outputs:
1057  *      None.
1058  * Returns:
1059  *      None.  dump() may or may not return.
1060  * Locking:
1061  *      none.
1062  * Remarks:
1063  */
1064
1065 static void
1066 kdb_do_dump(struct pt_regs *regs)
1067 {
1068 #if defined(CONFIG_DUMP) || defined(CONFIG_DUMP_MODULE)
1069         kdb_printf("Forcing dump (if configured)\n");
1070         console_loglevel = 8;   /* to see the dump messages */
1071         dump("kdb_do_dump", regs);
1072 #endif
1073 }
1074
1075 /*
1076  * kdb_reboot
1077  *
1078  *      This function implements the 'reboot' command.  Reboot the system
1079  *      immediately.
1080  *
1081  * Inputs:
1082  *      argc    argument count
1083  *      argv    argument vector
1084  *      envp    environment vector
1085  *      regs    registers at time kdb was entered.
1086  * Outputs:
1087  *      None.
1088  * Returns:
1089  *      zero for success, a kdb diagnostic if error
1090  * Locking:
1091  *      none.
1092  * Remarks:
1093  *      Shouldn't return from this function.
1094  */
1095
1096 static int
1097 kdb_reboot(int argc, const char **argv, const char **envp, struct pt_regs *regs)
1098 {
1099         machine_restart(0);
1100         kdb_printf("Hmm, kdb_reboot did not reboot, spinning here\n");
1101         while (1) {};
1102         /* NOTREACHED */
1103         return 0;
1104 }
1105
1106 /*
1107  * kdb_local
1108  *
1109  *      The main code for kdb.  This routine is invoked on a specific
1110  *      processor, it is not global.  The main kdb() routine ensures
1111  *      that only one processor at a time is in this routine.  This
1112  *      code is called with the real reason code on the first entry
1113  *      to a kdb session, thereafter it is called with reason SWITCH,
1114  *      even if the user goes back to the original cpu.
1115  *
1116  * Inputs:
1117  *      reason          The reason KDB was invoked
1118  *      error           The hardware-defined error code
1119  *      regs            The exception frame at time of fault/breakpoint.  NULL
1120  *                      for reason SILENT, otherwise valid.
1121  *      db_result       Result code from the break or debug point.
1122  * Returns:
1123  *      0       KDB was invoked for an event which it wasn't responsible
1124  *      1       KDB handled the event for which it was invoked.
1125  *      KDB_CMD_GO      User typed 'go'.
1126  *      KDB_CMD_CPU     User switched to another cpu.
1127  *      KDB_CMD_SS      Single step.
1128  *      KDB_CMD_SSB     Single step until branch.
1129  * Locking:
1130  *      none
1131  * Remarks:
1132  *      none
1133  */
1134
1135 extern char kdb_prompt_str[];
1136
1137 static int
1138 kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs, kdb_dbtrap_t db_result)
1139 {
1140         char *cmdbuf;
1141         int diag;
1142
1143         kdb_go_count = 0;
1144         if (reason != KDB_REASON_DEBUG &&
1145             reason != KDB_REASON_SILENT) {
1146                 kdb_printf("\nEntering kdb (current=0x%p, pid %d) ", (void *)current, current->pid);
1147 #if defined(CONFIG_SMP)
1148                 kdb_printf("on processor %d ", smp_processor_id());
1149 #endif
1150         }
1151
1152         switch (reason) {
1153         case KDB_REASON_DEBUG:
1154         {
1155                 /*
1156                  * If re-entering kdb after a single step
1157                  * command, don't print the message.
1158                  */
1159                 switch(db_result) {
1160                 case KDB_DB_BPT:
1161                         kdb_printf("\nEntering kdb (0x%p) ", (void *)current);
1162 #if defined(CONFIG_SMP)
1163                         kdb_printf("on processor %d ", smp_processor_id());
1164 #endif
1165                         kdb_printf("due to Debug @ " kdb_machreg_fmt "\n", kdba_getpc(regs));
1166                         break;
1167                 case KDB_DB_SSB:
1168                         /*
1169                          * In the midst of ssb command. Just return.
1170                          */
1171                         return KDB_CMD_SSB;     /* Continue with SSB command */
1172
1173                         break;
1174                 case KDB_DB_SS:
1175                         break;
1176                 case KDB_DB_SSBPT:
1177                         return 1;       /* kdba_db_trap did the work */
1178                 default:
1179                         kdb_printf("kdb: Bad result from kdba_db_trap: %d\n",
1180                                    db_result);
1181                         break;
1182                 }
1183
1184         }
1185                 break;
1186         case KDB_REASON_FAULT:
1187                 break;
1188         case KDB_REASON_ENTER:
1189                 if (KDB_STATE(KEYBOARD))
1190                         kdb_printf("due to Keyboard Entry\n");
1191                 else
1192                         kdb_printf("due to KDB_ENTER()\n");
1193                 break;
1194         case KDB_REASON_KEYBOARD:
1195                 KDB_STATE_SET(KEYBOARD);
1196                 kdb_printf("due to Keyboard Entry\n");
1197                 break;
1198         case KDB_REASON_SWITCH:
1199                 kdb_printf("due to cpu switch\n");
1200                 if (KDB_STATE(GO_SWITCH)) {
1201                         KDB_STATE_CLEAR(GO_SWITCH);
1202                         return KDB_CMD_GO;
1203                 }
1204                 break;
1205         case KDB_REASON_CALL:
1206                 if (!regs)
1207                         kdb_printf("kdb() called with no registers, restricted function");
1208                 kdb_printf("\n");
1209                 break;
1210         case KDB_REASON_OOPS:
1211                 kdb_printf("Oops: %s\n", kdb_diemsg);
1212                 kdb_printf("due to oops @ " kdb_machreg_fmt "\n", kdba_getpc(regs));
1213                 kdba_dumpregs(regs, NULL, NULL);
1214                 break;
1215         case KDB_REASON_NMI:
1216                 kdb_printf("due to NonMaskable Interrupt @ " kdb_machreg_fmt "\n",
1217                           kdba_getpc(regs));
1218                 kdba_dumpregs(regs, NULL, NULL);
1219                 break;
1220         case KDB_REASON_WATCHDOG:
1221                 kdb_printf("due to WatchDog Interrupt @ " kdb_machreg_fmt "\n",
1222                           kdba_getpc(regs));
1223                 kdba_dumpregs(regs, NULL, NULL);
1224                 break;
1225         case KDB_REASON_BREAK:
1226                 kdb_printf("due to Breakpoint @ " kdb_machreg_fmt "\n", kdba_getpc(regs));
1227                 /*
1228                  * Determine if this breakpoint is one that we
1229                  * are interested in.
1230                  */
1231                 if (db_result != KDB_DB_BPT) {
1232                         kdb_printf("kdb: error return from kdba_bp_trap: %d\n", db_result);
1233                         return 0;       /* Not for us, dismiss it */
1234                 }
1235                 break;
1236         case KDB_REASON_RECURSE:
1237                 kdb_printf("due to Recursion @ " kdb_machreg_fmt "\n", kdba_getpc(regs));
1238                 break;
1239         case KDB_REASON_SILENT:
1240                 return KDB_CMD_GO;      /* Silent entry, silent exit */
1241                 break;
1242         default:
1243                 kdb_printf("kdb: unexpected reason code: %d\n", reason);
1244                 return 0;       /* Not for us, dismiss it */
1245         }
1246
1247         kdba_local_arch_setup();
1248
1249         kdb_current_task = current;
1250
1251         while (1) {
1252                 /*
1253                  * Initialize pager context.
1254                  */
1255                 kdb_nextline = 1;
1256                 KDB_STATE_CLEAR(SUPPRESS);
1257 #ifdef KDB_HAVE_LONGJMP
1258                 /*
1259                  * Use kdba_setjmp/kdba_longjmp to break out of
1260                  * the pager early and to attempt to recover from kdb errors.
1261                  */
1262                 KDB_STATE_CLEAR(LONGJMP);
1263                 if (kdbjmpbuf) {
1264                         if (kdba_setjmp(&kdbjmpbuf[smp_processor_id()])) {
1265                                 /* Command aborted (usually in pager) */
1266                                 continue;
1267                         }
1268                         else
1269                                 KDB_STATE_SET(LONGJMP);
1270                 }
1271 #endif  /* KDB_HAVE_LONGJMP */
1272
1273                 cmdbuf = cmd_cur;
1274                 *cmdbuf = '\0';
1275                 *(cmd_hist[cmd_head])='\0';
1276
1277                 if (KDB_FLAG(ONLY_DO_DUMP)) {
1278                         /* kdb is off but a catastrophic error requires a dump.
1279                          * Take the dump and reboot.
1280                          * Turn on logging so the kdb output appears in the log
1281                          * buffer in the dump.
1282                          */
1283                         const char *setargs[] = { "set", "LOGGING", "1" };
1284                         kdb_set(2, setargs, NULL, regs);
1285                         kdb_do_dump(regs);
1286                         kdb_reboot(0, NULL, NULL, regs);
1287                         /*NOTREACHED*/
1288                 }
1289
1290 do_full_getstr:
1291 #if defined(CONFIG_SMP)
1292                 snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"), smp_processor_id());
1293 #else
1294                 snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"));
1295 #endif
1296                 if (defcmd_in_progress)
1297                         strncat(kdb_prompt_str, "[defcmd]", CMD_BUFLEN);
1298
1299                 /*
1300                  * Fetch command from keyboard
1301                  */
1302                 cmdbuf = kdb_getstr(cmdbuf, CMD_BUFLEN, kdb_prompt_str);
1303                 if (*cmdbuf != '\n') {
1304                         if (*cmdbuf < 32) {
1305                                 if(cmdptr == cmd_head) {
1306                                         strncpy(cmd_hist[cmd_head], cmd_cur, CMD_BUFLEN);
1307                                         *(cmd_hist[cmd_head]+strlen(cmd_hist[cmd_head])-1) = '\0';
1308                                 }
1309                                 if(!handle_ctrl_cmd(cmdbuf))
1310                                         *(cmd_cur+strlen(cmd_cur)-1) = '\0';
1311                                 cmdbuf = cmd_cur;
1312                                 goto do_full_getstr;
1313                         }
1314                         else
1315                                 strncpy(cmd_hist[cmd_head], cmd_cur, CMD_BUFLEN);
1316
1317                         cmd_head = (cmd_head+1) % KDB_CMD_HISTORY_COUNT;
1318                         if (cmd_head == cmd_tail) cmd_tail = (cmd_tail+1) % KDB_CMD_HISTORY_COUNT;
1319
1320                 }
1321
1322                 cmdptr = cmd_head;
1323                 diag = kdb_parse(cmdbuf, regs);
1324                 if (diag == KDB_NOTFOUND) {
1325                         kdb_printf("Unknown kdb command: '%s'\n", cmdbuf);
1326                         diag = 0;
1327                 }
1328                 if (diag == KDB_CMD_GO
1329                  || diag == KDB_CMD_CPU
1330                  || diag == KDB_CMD_SS
1331                  || diag == KDB_CMD_SSB)
1332                         break;
1333
1334                 if (diag)
1335                         kdb_cmderror(diag);
1336         }
1337
1338         kdba_local_arch_cleanup();
1339
1340         return(diag);
1341 }
1342
1343
1344 /*
1345  * kdb_print_state
1346  *
1347  *      Print the state data for the current processor for debugging.
1348  *
1349  * Inputs:
1350  *      text            Identifies the debug point
1351  *      value           Any integer value to be printed, e.g. reason code.
1352  * Returns:
1353  *      None.
1354  * Locking:
1355  *      none
1356  * Remarks:
1357  *      none
1358  */
1359
1360 void kdb_print_state(const char *text, int value)
1361 {
1362         kdb_printf("state: %s cpu %d value %d initial %d state %x\n",
1363                 text, smp_processor_id(), value, kdb_initial_cpu, kdb_state[smp_processor_id()]);
1364 }
1365
1366 /*
1367  * kdb_previous_event
1368  *
1369  *      Return a count of cpus that are leaving kdb, i.e. the number
1370  *      of processors that are still handling the previous kdb event.
1371  *
1372  * Inputs:
1373  *      None.
1374  * Returns:
1375  *      Count of cpus in previous event.
1376  * Locking:
1377  *      none
1378  * Remarks:
1379  *      none
1380  */
1381
1382 static int
1383 kdb_previous_event(void)
1384 {
1385         int i, leaving = 0;
1386         for (i = 0; i < NR_CPUS; ++i) {
1387                 if (KDB_STATE_CPU(LEAVING, i))
1388                         ++leaving;
1389         }
1390         return(leaving);
1391 }
1392
1393 /*
1394  * kdb_wait_for_cpus
1395  *
1396  * Invoked once at the start of a kdb event, from the controlling cpu.  Wait a
1397  * short period for the other cpus to enter kdb state.
1398  *
1399  * Inputs:
1400  *      none
1401  * Returns:
1402  *      none
1403  * Locking:
1404  *      none
1405  * Remarks:
1406  *      none
1407  */
1408
1409 int kdb_wait_for_cpus_secs = 10;                /* may be modified by ia64 MCA timeout */
1410
1411 static void
1412 kdb_wait_for_cpus(void)
1413 {
1414 #ifdef  CONFIG_SMP
1415         int online = 0, kdb_data = 0, prev_kdb_data = 0, i, time;
1416         mdelay(100);
1417         for (time = 0; time < kdb_wait_for_cpus_secs; ++time) {
1418                 online = 0;
1419                 kdb_data = 0;
1420                 for (i = 0; i < NR_CPUS; ++i) {
1421                         if (cpu_online(i)) {
1422                                 ++online;
1423                                 if (kdb_running_process[i].seqno >= kdb_seqno - 1)
1424                                         ++kdb_data;
1425                         }
1426                 }
1427                 if (online == kdb_data)
1428                         break;
1429                 if (prev_kdb_data != kdb_data) {
1430                         kdb_nextline = 0;       /* no prompt yet */
1431                         kdb_printf("  %d out of %d cpus in kdb, waiting for the rest, timeout in %d second(s)\n",
1432                                 kdb_data, online, kdb_wait_for_cpus_secs - time);
1433                         prev_kdb_data = kdb_data;
1434                 }
1435                 touch_nmi_watchdog();
1436                 mdelay(1000);
1437                 if (time % 4 == 0)
1438                         kdb_printf(".");
1439         }
1440         if (time) {
1441                 int wait = online - kdb_data;
1442                 if (wait == 0)
1443                         kdb_printf("All cpus are now in kdb\n");
1444                 else
1445                         kdb_printf("%d cpu%s not in kdb, %s state is unknown\n",
1446                                         wait,
1447                                         wait == 1 ? " is" : "s are",
1448                                         wait == 1 ? "its" : "their");
1449         }
1450 #endif  /* CONFIG_SMP */
1451 }
1452
1453 /*
1454  * kdb_main_loop
1455  *
1456  * The main kdb loop.  After initial setup and assignment of the controlling
1457  * cpu, all cpus are in this loop.  One cpu is in control and will issue the kdb
1458  * prompt, the others will spin until 'go' or cpu switch.
1459  *
1460  * To get a consistent view of the kernel stacks for all processes, this routine
1461  * is invoked from the main kdb code via an architecture specific routine.
1462  * kdba_main_loop is responsible for making the kernel stacks consistent for all
1463  * processes, there should be no difference between a blocked process and a
1464  * running process as far as kdb is concerned.
1465  *
1466  * Inputs:
1467  *      reason          The reason KDB was invoked
1468  *      error           The hardware-defined error code
1469  *      reason2         kdb's current reason code.  Initially error but can change
1470  *                      acording to kdb state.
1471  *      db_result       Result code from break or debug point.
1472  *      regs            The exception frame at time of fault/breakpoint.  If reason
1473  *                      is KDB_REASON_SILENT then regs is NULL, otherwise it
1474  *                      should always be valid.
1475  * Returns:
1476  *      0       KDB was invoked for an event which it wasn't responsible
1477  *      1       KDB handled the event for which it was invoked.
1478  * Locking:
1479  *      none
1480  * Remarks:
1481  *      none
1482  */
1483
1484 int
1485 kdb_main_loop(kdb_reason_t reason, kdb_reason_t reason2, int error,
1486               kdb_dbtrap_t db_result, struct pt_regs *regs)
1487 {
1488         int result = 1;
1489         int wait_for_cpus = reason != KDB_REASON_SILENT;
1490         /* Stay in kdb() until 'go', 'ss[b]' or an error */
1491         while (1) {
1492                 /*
1493                  * All processors except the one that is in control
1494                  * will spin here.
1495                  */
1496                 KDB_DEBUG_STATE("kdb_main_loop 1", reason);
1497                 while (KDB_STATE(HOLD_CPU)) {
1498                         /* state KDB is turned off by kdb_cpu to see if the
1499                          * other cpus are still live, each cpu in this loop
1500                          * turns it back on.
1501                          */
1502                         if (!KDB_STATE(KDB)) {
1503                                 KDB_STATE_SET(KDB);
1504                         }
1505                 }
1506                 KDB_STATE_CLEAR(SUPPRESS);
1507                 KDB_DEBUG_STATE("kdb_main_loop 2", reason);
1508                 if (KDB_STATE(LEAVING))
1509                         break;  /* Another cpu said 'go' */
1510
1511                 if (wait_for_cpus) {
1512                         wait_for_cpus = 0;
1513                         kdb_wait_for_cpus();
1514                 }
1515                 /* Still using kdb, this processor is in control */
1516                 result = kdb_local(reason2, error, regs, db_result);
1517                 KDB_DEBUG_STATE("kdb_main_loop 3", result);
1518
1519                 if (result == KDB_CMD_CPU) {
1520                         /* Cpu switch, hold the current cpu, release the target one. */
1521                         reason2 = KDB_REASON_SWITCH;
1522                         KDB_STATE_SET(HOLD_CPU);
1523                         KDB_STATE_CLEAR_CPU(HOLD_CPU, kdb_new_cpu);
1524                         continue;
1525                 }
1526
1527                 if (result == KDB_CMD_SS) {
1528                         KDB_STATE_SET(DOING_SS);
1529                         break;
1530                 }
1531
1532                 if (result == KDB_CMD_SSB) {
1533                         KDB_STATE_SET(DOING_SS);
1534                         KDB_STATE_SET(DOING_SSB);
1535                         break;
1536                 }
1537
1538                 if (result && result != 1 && result != KDB_CMD_GO)
1539                         kdb_printf("\nUnexpected kdb_local return code %d\n", result);
1540
1541                 KDB_DEBUG_STATE("kdb_main_loop 4", reason);
1542                 break;
1543         }
1544         if (KDB_STATE(DOING_SS))
1545                 KDB_STATE_CLEAR(SSBPT);
1546         return(result);
1547 }
1548
1549 /*
1550  * kdb
1551  *
1552  *      This function is the entry point for the kernel debugger.  It
1553  *      provides a command parser and associated support functions to
1554  *      allow examination and control of an active kernel.
1555  *
1556  *      This function may be invoked directly from any
1557  *      point in the kernel by calling with reason == KDB_REASON_CALL
1558  *
1559  *      The breakpoint trap code should invoke this function with
1560  *      one of KDB_REASON_BREAK (int 03) or KDB_REASON_DEBUG (debug register)
1561  *
1562  *      the die_if_kernel function should invoke this function with
1563  *      KDB_REASON_OOPS.
1564  *
1565  *      The kernel fault handler should invoke this function with
1566  *      reason == KDB_REASON_FAULT and error == trap vector #.
1567  *
1568  *      In single step mode, one cpu is released to run without
1569  *      breakpoints.   Interrupts and NMI are reset to their original values,
1570  *      the cpu is allowed to do one instruction which causes a trap
1571  *      into kdb with KDB_REASON_DEBUG.
1572  *
1573  * Inputs:
1574  *      reason          The reason KDB was invoked
1575  *      error           The hardware-defined error code
1576  *      regs            The exception frame at time of fault/breakpoint.  If reason
1577  *                      is KDB_REASON_SILENT then regs is NULL, otherwise it
1578  *                      should always be valid.
1579  * Returns:
1580  *      0       KDB was invoked for an event which it wasn't responsible
1581  *      1       KDB handled the event for which it was invoked.
1582  * Locking:
1583  *      none
1584  * Remarks:
1585  *      No assumptions of system state.  This function may be invoked
1586  *      with arbitrary locks held.  It will stop all other processors
1587  *      in an SMP environment, disable all interrupts and does not use
1588  *      the operating systems keyboard driver.
1589  *
1590  *      This code is reentrant but only for cpu switch.  Any other
1591  *      reentrancy is an error, although kdb will attempt to recover.
1592  *
1593  *      At the start of a kdb session the initial processor is running
1594  *      kdb() and the other processors can be doing anything.  When the
1595  *      initial processor calls smp_kdb_stop() the other processors are
1596  *      driven through kdb_ipi which calls kdb() with reason SWITCH.
1597  *      That brings all processors into this routine, one with a "real"
1598  *      reason code, the other with SWITCH.
1599  *
1600  *      Because the other processors are driven via smp_kdb_stop(),
1601  *      they enter here from the NMI handler.  Until the other
1602  *      processors exit from here and exit from kdb_ipi, they will not
1603  *      take any more NMI requests.  The initial cpu will still take NMI.
1604  *
1605  *      Multiple race and reentrancy conditions, each with different
1606  *      advoidance mechanisms.
1607  *
1608  *      Two cpus hit debug points at the same time.
1609  *
1610  *        kdb_lock and kdb_initial_cpu ensure that only one cpu gets
1611  *        control of kdb.  The others spin on kdb_initial_cpu until
1612  *        they are driven through NMI into kdb_ipi.  When the initial
1613  *        cpu releases the others from NMI, they resume trying to get
1614  *        kdb_initial_cpu to start a new event.
1615  *
1616  *      A cpu is released from kdb and starts a new event before the
1617  *      original event has completely ended.
1618  *
1619  *        kdb_previous_event() prevents any cpu from entering
1620  *        kdb_initial_cpu state until the previous event has completely
1621  *        ended on all cpus.
1622  *
1623  *      An exception occurs inside kdb.
1624  *
1625  *        kdb_initial_cpu detects recursive entry to kdb and attempts
1626  *        to recover.  The recovery uses longjmp() which means that
1627  *        recursive calls to kdb never return.  Beware of assumptions
1628  *        like
1629  *
1630  *          ++depth;
1631  *          kdb();
1632  *          --depth;
1633  *
1634  *        If the kdb call is recursive then longjmp takes over and
1635  *        --depth is never executed.
1636  *
1637  *      NMI handling.
1638  *
1639  *        NMI handling is tricky.  The initial cpu is invoked by some kdb event,
1640  *        this event could be NMI driven but usually is not.  The other cpus are
1641  *        driven into kdb() via kdb_ipi which uses NMI so at the start the other
1642  *        cpus will not accept NMI.  Some operations such as SS release one cpu
1643  *        but hold all the others.  Releasing a cpu means it drops back to
1644  *        whatever it was doing before the kdb event, this means it drops out of
1645  *        kdb_ipi and hence out of NMI status.  But the software watchdog uses
1646  *        NMI and we do not want spurious watchdog calls into kdb.  kdba_read()
1647  *        resets the watchdog counters in its input polling loop, when a kdb
1648  *        command is running it is subject to NMI watchdog events.
1649  *
1650  *        Another problem with NMI handling is the NMI used to drive the other
1651  *        cpus into kdb cannot be distinguished from the watchdog NMI.  State
1652  *        flag WAIT_IPI indicates that a cpu is waiting for NMI via kdb_ipi,
1653  *        if not set then software NMI is ignored by kdb_ipi.
1654  *
1655  *      Cpu switching.
1656  *
1657  *        All cpus are in kdb (or they should be), all but one are
1658  *        spinning on KDB_STATE(HOLD_CPU).  Only one cpu is not in
1659  *        HOLD_CPU state, only that cpu can handle commands.
1660  *
1661  *      Go command entered.
1662  *
1663  *        If necessary, go will switch to the initial cpu first.  If the event
1664  *        was caused by a software breakpoint (assumed to be global) that
1665  *        requires single-step to get over the breakpoint then only release the
1666  *        initial cpu, after the initial cpu has single-stepped the breakpoint
1667  *        then release the rest of the cpus.  If SSBPT is not required then
1668  *        release all the cpus at once.
1669  */
1670
1671 int
1672 kdb(kdb_reason_t reason, int error, struct pt_regs *regs)
1673 {
1674         kdb_intstate_t int_state;       /* Interrupt state */
1675         kdb_reason_t reason2 = reason;
1676         int result = 0; /* Default is kdb did not handle it */
1677         int ss_event;
1678         kdb_dbtrap_t db_result=KDB_DB_NOBPT;
1679         atomic_inc(&kdb_event);
1680
1681         switch(reason) {
1682         case KDB_REASON_OOPS:
1683         case KDB_REASON_NMI:
1684         case KDB_REASON_WATCHDOG:
1685                 KDB_FLAG_SET(CATASTROPHIC);     /* kernel state is dubious now */
1686                 break;
1687         default:
1688                 break;
1689         }
1690         if (kdb_continue_catastrophic > 2) {
1691                 kdb_printf("kdb_continue_catastrophic is out of range, setting to 2\n");
1692                 kdb_continue_catastrophic = 2;
1693         }
1694         if (!kdb_on && KDB_FLAG(CATASTROPHIC) && kdb_continue_catastrophic == 2) {
1695                 KDB_FLAG_SET(ONLY_DO_DUMP);
1696         }
1697         if (!kdb_on && !KDB_FLAG(ONLY_DO_DUMP))
1698                 goto out;
1699
1700         KDB_DEBUG_STATE("kdb 1", reason);
1701         KDB_STATE_CLEAR(SUPPRESS);
1702
1703         /* Filter out userspace breakpoints first, no point in doing all
1704          * the kdb smp fiddling when it is really a gdb trap.
1705          * Save the single step status first, kdba_db_trap clears ss status.
1706          * kdba_b[dp]_trap sets SSBPT if required.
1707          */
1708         ss_event = KDB_STATE(DOING_SS) || KDB_STATE(SSBPT);
1709 #ifdef  CONFIG_CPU_XSCALE
1710         if ( KDB_STATE(A_XSC_ICH) ) {
1711                 /* restore changed I_BIT */
1712                 KDB_STATE_CLEAR(A_XSC_ICH);
1713                 kdba_restore_retirq(regs, KDB_STATE(A_XSC_IRQ));
1714                 if ( !ss_event ) {
1715                         kdb_printf("Stranger!!! Why IRQ bit is changed====\n");
1716                 }
1717         }
1718 #endif
1719         if (reason == KDB_REASON_BREAK) {
1720                 db_result = kdba_bp_trap(regs, error);  /* Only call this once */
1721         }
1722         if (reason == KDB_REASON_DEBUG) {
1723                 db_result = kdba_db_trap(regs, error);  /* Only call this once */
1724         }
1725
1726         if ((reason == KDB_REASON_BREAK || reason == KDB_REASON_DEBUG)
1727          && db_result == KDB_DB_NOBPT) {
1728                 KDB_DEBUG_STATE("kdb 2", reason);
1729                 goto out;       /* Not one of mine */
1730         }
1731
1732         /* Turn off single step if it was being used */
1733         if (ss_event) {
1734                 kdba_clearsinglestep(regs);
1735                 /* Single step after a breakpoint removes the need for a delayed reinstall */
1736                 if (reason == KDB_REASON_BREAK || reason == KDB_REASON_DEBUG)
1737                         KDB_STATE_CLEAR(SSBPT);
1738         }
1739
1740         /* kdb can validly reenter but only for certain well defined conditions */
1741         if (reason == KDB_REASON_DEBUG
1742          && !KDB_STATE(HOLD_CPU)
1743          && ss_event)
1744                 KDB_STATE_SET(REENTRY);
1745         else
1746                 KDB_STATE_CLEAR(REENTRY);
1747
1748         /* Wait for previous kdb event to completely exit before starting
1749          * a new event.
1750          */
1751         while (kdb_previous_event())
1752                 ;
1753         KDB_DEBUG_STATE("kdb 3", reason);
1754
1755         /*
1756          * If kdb is already active, print a message and try to recover.
1757          * If recovery is not possible and recursion is allowed or
1758          * forced recursion without recovery is set then try to recurse
1759          * in kdb.  Not guaranteed to work but it makes an attempt at
1760          * debugging the debugger.
1761          */
1762         if (reason != KDB_REASON_SWITCH) {
1763                 if (KDB_IS_RUNNING() && !KDB_STATE(REENTRY)) {
1764                         int recover = 1;
1765                         unsigned long recurse = 0;
1766                         kdb_printf("kdb: Debugger re-entered on cpu %d, new reason = %d\n",
1767                                 smp_processor_id(), reason);
1768                         /* Should only re-enter from released cpu */
1769
1770                         if (KDB_STATE(HOLD_CPU)) {
1771                                 kdb_printf("     Strange, cpu %d should not be running\n", smp_processor_id());
1772                                 recover = 0;
1773                         }
1774                         if (!KDB_STATE(CMD)) {
1775                                 kdb_printf("     Not executing a kdb command\n");
1776                                 recover = 0;
1777                         }
1778                         if (!KDB_STATE(LONGJMP)) {
1779                                 kdb_printf("     No longjmp available for recovery\n");
1780                                 recover = 0;
1781                         }
1782                         kdbgetulenv("RECURSE", &recurse);
1783                         if (recurse > 1) {
1784                                 kdb_printf("     Forced recursion is set\n");
1785                                 recover = 0;
1786                         }
1787                         if (recover) {
1788                                 kdb_printf("     Attempting to abort command and recover\n");
1789 #ifdef KDB_HAVE_LONGJMP
1790                                 kdba_longjmp(&kdbjmpbuf[smp_processor_id()], 0);
1791 #endif
1792                         }
1793                         if (recurse) {
1794                                 if (KDB_STATE(RECURSE)) {
1795                                         kdb_printf("     Already in recursive mode\n");
1796                                 } else {
1797                                         kdb_printf("     Attempting recursive mode\n");
1798                                         KDB_STATE_SET(RECURSE);
1799                                         KDB_STATE_SET(REENTRY);
1800                                         reason2 = KDB_REASON_RECURSE;
1801                                         recover = 1;
1802                                 }
1803                         }
1804                         if (!recover) {
1805                                 kdb_printf("     Cannot recover, allowing event to proceed\n");
1806                                 goto out;
1807                         }
1808                 }
1809         } else if (!KDB_IS_RUNNING()) {
1810                 kdb_printf("kdb: CPU switch without kdb running, I'm confused\n");
1811                 goto out;
1812         }
1813
1814         /*
1815          * Disable interrupts, breakpoints etc. on this processor
1816          * during kdb command processing
1817          */
1818         KDB_STATE_SET(KDB);
1819         if (!ss_event) {
1820                 /* bh not re-enabled during single step */
1821                 local_bh_disable();
1822         }
1823         kdba_disableint(&int_state);
1824         if (!KDB_STATE(KDB_CONTROL)) {
1825                 kdb_bp_remove_local();
1826                 kdba_disable_lbr();
1827                 KDB_STATE_SET(KDB_CONTROL);
1828         }
1829         else if (KDB_DEBUG(LBR))
1830                 kdba_print_lbr();
1831
1832         /*
1833          * If not entering the debugger due to CPU switch or single step
1834          * reentry, serialize access here.
1835          * The processors may race getting to this point - if,
1836          * for example, more than one processor hits a breakpoint
1837          * at the same time.   We'll serialize access to kdb here -
1838          * other processors will loop here, and the NMI from the stop
1839          * IPI will take them into kdb as switch candidates.  Once
1840          * the initial processor releases the debugger, the rest of
1841          * the processors will race for it.
1842          */
1843         if (reason == KDB_REASON_SWITCH
1844          || KDB_STATE(REENTRY))
1845                 ;       /* drop through */
1846         else {
1847                 KDB_DEBUG_STATE("kdb 4", reason);
1848                 spin_lock(&kdb_lock);
1849
1850                 while (KDB_IS_RUNNING() || kdb_previous_event()) {
1851                         spin_unlock(&kdb_lock);
1852
1853                         while (KDB_IS_RUNNING() || kdb_previous_event())
1854                                 ;
1855
1856                         spin_lock(&kdb_lock);
1857                 }
1858                 KDB_DEBUG_STATE("kdb 5", reason);
1859
1860                 kdb_initial_cpu = smp_processor_id();
1861                 ++kdb_seqno;
1862                 spin_unlock(&kdb_lock);
1863                 notifier_call_chain(&kdb_notifier_list, 1, NULL);
1864         }
1865
1866         if (smp_processor_id() == kdb_initial_cpu
1867          && !KDB_STATE(REENTRY)) {
1868                 KDB_STATE_CLEAR(HOLD_CPU);
1869                 KDB_STATE_CLEAR(WAIT_IPI);
1870                 /*
1871                  * Remove the global breakpoints.  This is only done
1872                  * once from the initial processor on initial entry.
1873                  */
1874                 kdb_bp_remove_global();
1875
1876                 /*
1877                  * If SMP, stop other processors.  The other processors
1878                  * will enter kdb() with KDB_REASON_SWITCH and spin in
1879                  * kdb_main_loop().
1880                  */
1881                 KDB_DEBUG_STATE("kdb 6", reason);
1882                 if (NR_CPUS > 1) {
1883                         int i;
1884                         for (i = 0; i < NR_CPUS; ++i) {
1885                                 if (!cpu_online(i))
1886                                         continue;
1887                                 if (i != kdb_initial_cpu) {
1888                                         KDB_STATE_SET_CPU(HOLD_CPU, i);
1889                                         KDB_STATE_SET_CPU(WAIT_IPI, i);
1890                                 }
1891                         }
1892                         KDB_DEBUG_STATE("kdb 7", reason);
1893                         smp_kdb_stop();
1894                         KDB_DEBUG_STATE("kdb 8", reason);
1895                 }
1896         }
1897
1898         if (KDB_STATE(GO1)) {
1899                 kdb_bp_remove_global();         /* They were set for single-step purposes */
1900                 KDB_STATE_CLEAR(GO1);
1901                 reason = KDB_REASON_SILENT;     /* Now silently go */
1902         }
1903
1904         /* Set up a consistent set of process stacks before talking to the user */
1905         KDB_DEBUG_STATE("kdb 9", result);
1906         result = kdba_main_loop(reason, reason2, error, db_result, regs);
1907
1908         KDB_DEBUG_STATE("kdb 10", result);
1909         kdba_adjust_ip(reason, error, regs);
1910         KDB_STATE_CLEAR(LONGJMP);
1911         KDB_DEBUG_STATE("kdb 11", result);
1912         /* go which requires single-step over a breakpoint must only release
1913          * one cpu.
1914          */
1915         if (result == KDB_CMD_GO && KDB_STATE(SSBPT))
1916                 KDB_STATE_SET(GO1);
1917
1918         if (smp_processor_id() == kdb_initial_cpu &&
1919           !KDB_STATE(DOING_SS) &&
1920           !KDB_STATE(RECURSE)) {
1921                 /*
1922                  * (Re)install the global breakpoints.  This is only done
1923                  * once from the initial processor on go.
1924                  */
1925                 KDB_DEBUG_STATE("kdb 12", reason);
1926                 kdb_bp_install_global(regs);
1927                 if (!KDB_STATE(GO1)) {
1928                         /*
1929                          * Release all other cpus which will see KDB_STATE(LEAVING) is set.
1930                          */
1931                         int i;
1932                         for (i = 0; i < NR_CPUS; ++i) {
1933                                 if (KDB_STATE_CPU(KDB, i))
1934                                         KDB_STATE_SET_CPU(LEAVING, i);
1935                                 KDB_STATE_CLEAR_CPU(WAIT_IPI, i);
1936                                 KDB_STATE_CLEAR_CPU(HOLD_CPU, i);
1937                         }
1938                         /* Wait until all the other processors leave kdb */
1939                         while (kdb_previous_event() != 1)
1940                                 ;
1941                         notifier_call_chain(&kdb_notifier_list, 0, NULL);
1942                         kdb_initial_cpu = -1;   /* release kdb control */
1943                         KDB_DEBUG_STATE("kdb 13", reason);
1944                 }
1945         }
1946
1947         KDB_DEBUG_STATE("kdb 14", result);
1948         kdba_restoreint(&int_state);
1949 #ifdef  CONFIG_CPU_XSCALE
1950         if ( smp_processor_id() == kdb_initial_cpu &&
1951              ( KDB_STATE(SSBPT) | KDB_STATE(DOING_SS) )
1952               ) {
1953                 kdba_setsinglestep(regs);
1954                 // disable IRQ in stack frame
1955                 KDB_STATE_SET(A_XSC_ICH);
1956                 if ( kdba_disable_retirq(regs) ) {
1957                         KDB_STATE_SET(A_XSC_IRQ);
1958                 }
1959                 else {
1960                         KDB_STATE_CLEAR(A_XSC_IRQ);
1961                 }
1962         }
1963 #endif
1964
1965         /* Only do this work if we are really leaving kdb */
1966         if (!(KDB_STATE(DOING_SS) || KDB_STATE(SSBPT) || KDB_STATE(RECURSE))) {
1967                 KDB_DEBUG_STATE("kdb 15", result);
1968                 kdb_bp_install_local(regs);
1969                 kdba_enable_lbr();
1970                 __local_bh_enable();
1971                 KDB_STATE_CLEAR(KDB_CONTROL);
1972         }
1973
1974         KDB_DEBUG_STATE("kdb 16", result);
1975         KDB_FLAG_CLEAR(CATASTROPHIC);
1976         KDB_STATE_CLEAR(IP_ADJUSTED);   /* Re-adjust ip next time in */
1977         KDB_STATE_CLEAR(KEYBOARD);
1978         KDB_STATE_CLEAR(KDB);           /* Main kdb state has been cleared */
1979         KDB_STATE_CLEAR(RECURSE);
1980         KDB_STATE_CLEAR(LEAVING);       /* No more kdb work after this */
1981         KDB_DEBUG_STATE("kdb 17", reason);
1982 out:
1983         atomic_dec(&kdb_event);
1984         return result != 0;
1985 }
1986
1987 /*
1988  * kdb_mdr
1989  *
1990  *      This function implements the guts of the 'mdr' command.
1991  *
1992  *      mdr  <addr arg>,<byte count>
1993  *
1994  * Inputs:
1995  *      addr    Start address
1996  *      count   Number of bytes
1997  * Outputs:
1998  *      None.
1999  * Returns:
2000  *      Always 0.  Any errors are detected and printed by kdb_getarea.
2001  * Locking:
2002  *      none.
2003  * Remarks:
2004  */
2005
2006 static int
2007 kdb_mdr(kdb_machreg_t addr, unsigned int count)
2008 {
2009         unsigned char c;
2010         while (count--) {
2011                 if (kdb_getarea(c, addr))
2012                         return(0);
2013                 kdb_printf("%02x", c);
2014                 addr++;
2015         }
2016         kdb_printf("\n");
2017         return(0);
2018 }
2019
2020 /*
2021  * kdb_md
2022  *
2023  *      This function implements the 'md', 'md1', 'md2', 'md4', 'md8'
2024  *      'mdr' and 'mds' commands.
2025  *
2026  *      md|mds  [<addr arg> [<line count> [<radix>]]]
2027  *      mdWcN   [<addr arg> [<line count> [<radix>]]]
2028  *              where W = is the width (1, 2, 4 or 8) and N is the count.
2029  *              for eg., md1c20 reads 20 bytes, 1 at a time.
2030  *      mdr  <addr arg>,<byte count>
2031  *
2032  * Inputs:
2033  *      argc    argument count
2034  *      argv    argument vector
2035  *      envp    environment vector
2036  *      regs    registers at time kdb was entered.
2037  * Outputs:
2038  *      None.
2039  * Returns:
2040  *      zero for success, a kdb diagnostic if error
2041  * Locking:
2042  *      none.
2043  * Remarks:
2044  */
2045
2046 static void
2047 kdb_md_line(const char *fmtstr, kdb_machreg_t addr,
2048             int symbolic, int nosect, int bytesperword,
2049             int num, int repeat, int phys)
2050 {
2051         /* print just one line of data */
2052         kdb_symtab_t symtab;
2053         char cbuf[32];
2054         char *c = cbuf;
2055         int i;
2056         unsigned long word;
2057
2058         memset(cbuf, '\0', sizeof(cbuf));
2059         if (phys)
2060                 kdb_printf("phys " kdb_machreg_fmt0 " ", addr);
2061         else
2062                 kdb_printf(kdb_machreg_fmt0 " ", addr);
2063
2064         for (i = 0; i < num && repeat--; i++) {
2065                 if (phys) {
2066                         if (kdb_getphysword(&word, addr, bytesperword))
2067                                 break;
2068                 } else if (kdb_getword(&word, addr, bytesperword))
2069                         break;
2070                 kdb_printf(fmtstr, word);
2071                 if (symbolic)
2072                         kdbnearsym(word, &symtab);
2073                 else
2074                         memset(&symtab, 0, sizeof(symtab));
2075                 if (symtab.sym_name) {
2076                         kdb_symbol_print(word, &symtab, 0);
2077                         if (!nosect) {
2078                                 kdb_printf("\n");
2079                                 kdb_printf("                       %s %s "
2080                                            kdb_machreg_fmt " " kdb_machreg_fmt " " kdb_machreg_fmt,
2081                                         symtab.mod_name,
2082                                         symtab.sec_name,
2083                                         symtab.sec_start,
2084                                         symtab.sym_start,
2085                                         symtab.sym_end);
2086                         }
2087                         addr += bytesperword;
2088                 } else {
2089                         union {
2090                                 u64 word;
2091                                 unsigned char c[8];
2092                         } wc;
2093                         unsigned char *cp;
2094 #ifdef  __BIG_ENDIAN
2095                         cp = wc.c + 8 - bytesperword;
2096 #else
2097                         cp = wc.c;
2098 #endif
2099                         wc.word = word;
2100 #define printable_char(c) ({unsigned char __c = c; isprint(__c) ? __c : '.';})
2101                         switch (bytesperword) {
2102                         case 8:
2103                                 *c++ = printable_char(*cp++);
2104                                 *c++ = printable_char(*cp++);
2105                                 *c++ = printable_char(*cp++);
2106                                 *c++ = printable_char(*cp++);
2107                                 addr += 4;
2108                         case 4:
2109                                 *c++ = printable_char(*cp++);
2110                                 *c++ = printable_char(*cp++);
2111                                 addr += 2;
2112                         case 2:
2113                                 *c++ = printable_char(*cp++);
2114                                 addr++;
2115                         case 1:
2116                                 *c++ = printable_char(*cp++);
2117                                 addr++;
2118                                 break;
2119                         }
2120 #undef printable_char
2121                 }
2122         }
2123         kdb_printf("%*s %s\n", (int)((num-i)*(2*bytesperword + 1)+1), " ", cbuf);
2124 }
2125
2126 static int
2127 kdb_md(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2128 {
2129         static kdb_machreg_t last_addr;
2130         static int last_radix, last_bytesperword, last_repeat;
2131         int radix = 16, mdcount = 8, bytesperword = sizeof(kdb_machreg_t), repeat;
2132         int nosect = 0;
2133         char fmtchar, fmtstr[64];
2134         kdb_machreg_t addr;
2135         unsigned long word;
2136         long offset = 0;
2137         int symbolic = 0;
2138         int valid = 0;
2139         int phys = 0;
2140
2141         kdbgetintenv("MDCOUNT", &mdcount);
2142         kdbgetintenv("RADIX", &radix);
2143         kdbgetintenv("BYTESPERWORD", &bytesperword);
2144
2145         /* Assume 'md <addr>' and start with environment values */
2146         repeat = mdcount * 16 / bytesperword;
2147
2148         if (strcmp(argv[0], "mdr") == 0) {
2149                 if (argc != 2)
2150                         return KDB_ARGCOUNT;
2151                 valid = 1;
2152         } else if (isdigit(argv[0][2])) {
2153                 bytesperword = (int)(argv[0][2] - '0');
2154                 if (bytesperword == 0) {
2155                         bytesperword = last_bytesperword;
2156                         if (bytesperword == 0) {
2157                                 bytesperword = 4;
2158                         }
2159                 }
2160                 last_bytesperword = bytesperword;
2161                 repeat = mdcount * 16 / bytesperword;
2162                 if (!argv[0][3])
2163                         valid = 1;
2164                 else if (argv[0][3] == 'c' && argv[0][4]) {
2165                         char *p;
2166                         repeat = simple_strtoul(argv[0]+4, &p, 10);
2167                         mdcount = ((repeat * bytesperword) + 15) / 16;
2168                         valid = !*p;
2169                 }
2170                 last_repeat = repeat;
2171         } else if (strcmp(argv[0], "md") == 0)
2172                 valid = 1;
2173         else if (strcmp(argv[0], "mds") == 0)
2174                 valid = 1;
2175         else if (strcmp(argv[0], "mdp") == 0) {
2176                 phys = valid = 1;
2177         }
2178         if (!valid)
2179                 return KDB_NOTFOUND;
2180
2181         if (argc == 0) {
2182                 if (last_addr == 0)
2183                         return KDB_ARGCOUNT;
2184                 addr = last_addr;
2185                 radix = last_radix;
2186                 bytesperword = last_bytesperword;
2187                 repeat = last_repeat;
2188                 mdcount = ((repeat * bytesperword) + 15) / 16;
2189         }
2190
2191         if (argc) {
2192                 kdb_machreg_t val;
2193                 int diag, nextarg = 1;
2194                 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL, regs);
2195                 if (diag)
2196                         return diag;
2197                 if (argc > nextarg+2)
2198                         return KDB_ARGCOUNT;
2199
2200                 if (argc >= nextarg) {
2201                         diag = kdbgetularg(argv[nextarg], &val);
2202                         if (!diag) {
2203                                 mdcount = (int) val;
2204                                 repeat = mdcount * 16 / bytesperword;
2205                         }
2206                 }
2207                 if (argc >= nextarg+1) {
2208                         diag = kdbgetularg(argv[nextarg+1], &val);
2209                         if (!diag)
2210                                 radix = (int) val;
2211                 }
2212         }
2213
2214         if (strcmp(argv[0], "mdr") == 0) {
2215                 return(kdb_mdr(addr, mdcount));
2216         }
2217
2218         switch (radix) {
2219         case 10:
2220                 fmtchar = 'd';
2221                 break;
2222         case 16:
2223                 fmtchar = 'x';
2224                 break;
2225         case 8:
2226                 fmtchar = 'o';
2227                 break;
2228         default:
2229                 return KDB_BADRADIX;
2230         }
2231
2232         last_radix = radix;
2233
2234         if (bytesperword > sizeof(kdb_machreg_t))
2235                 return KDB_BADWIDTH;
2236
2237         switch (bytesperword) {
2238         case 8:
2239                 sprintf(fmtstr, "%%16.16l%c ", fmtchar);
2240                 break;
2241         case 4:
2242                 sprintf(fmtstr, "%%8.8l%c ", fmtchar);
2243                 break;
2244         case 2:
2245                 sprintf(fmtstr, "%%4.4l%c ", fmtchar);
2246                 break;
2247         case 1:
2248                 sprintf(fmtstr, "%%2.2l%c ", fmtchar);
2249                 break;
2250         default:
2251                 return KDB_BADWIDTH;
2252         }
2253
2254         last_repeat = repeat;
2255         last_bytesperword = bytesperword;
2256
2257         if (strcmp(argv[0], "mds") == 0) {
2258                 symbolic = 1;
2259                 /* Do not save these changes as last_*, they are temporary mds
2260                  * overrides.
2261                  */
2262                 bytesperword = sizeof(kdb_machreg_t);
2263                 repeat = mdcount;
2264                 kdbgetintenv("NOSECT", &nosect);
2265         }
2266
2267         /* Round address down modulo BYTESPERWORD */
2268
2269         addr &= ~(bytesperword-1);
2270
2271         while (repeat > 0) {
2272                 unsigned long a;
2273                 int n, z, num = (symbolic ? 1 : (16 / bytesperword));
2274
2275                 for (a = addr, z = 0; z < repeat; a += bytesperword, ++z) {
2276                         if (phys) {
2277                                 if (kdb_getphysword(&word, a, bytesperword) 
2278                                                 || word)
2279                                         break;
2280                         } else if (kdb_getword(&word, a, bytesperword) || word)
2281                                 break;
2282                 }
2283                 n = min(num, repeat);
2284                 kdb_md_line(fmtstr, addr, symbolic, nosect, bytesperword, num, repeat, phys);
2285                 addr += bytesperword * n;
2286                 repeat -= n;
2287                 z = (z + num - 1) / num;
2288                 if (z > 2) {
2289                         int s = num * (z-2);
2290                         kdb_printf(kdb_machreg_fmt0 "-" kdb_machreg_fmt0 " zero suppressed\n",
2291                                 addr, addr + bytesperword * s - 1);
2292                         addr += bytesperword * s;
2293                         repeat -= s;
2294                 }
2295         }
2296         last_addr = addr;
2297
2298         return 0;
2299 }
2300
2301 /*
2302  * kdb_mm
2303  *
2304  *      This function implements the 'mm' command.
2305  *
2306  *      mm address-expression new-value
2307  *
2308  * Inputs:
2309  *      argc    argument count
2310  *      argv    argument vector
2311  *      envp    environment vector
2312  *      regs    registers at time kdb was entered.
2313  * Outputs:
2314  *      None.
2315  * Returns:
2316  *      zero for success, a kdb diagnostic if error
2317  * Locking:
2318  *      none.
2319  * Remarks:
2320  *      mm works on machine words, mmW works on bytes.
2321  */
2322
2323 static int
2324 kdb_mm(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2325 {
2326         int diag;
2327         kdb_machreg_t addr;
2328         long offset = 0;
2329         unsigned long contents;
2330         int nextarg;
2331         int width;
2332
2333         if (argv[0][2] && !isdigit(argv[0][2]))
2334                 return KDB_NOTFOUND;
2335
2336         if (argc < 2) {
2337                 return KDB_ARGCOUNT;
2338         }
2339
2340         nextarg = 1;
2341         if ((diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL, regs)))
2342                 return diag;
2343
2344         if (nextarg > argc)
2345                 return KDB_ARGCOUNT;
2346
2347         if ((diag = kdbgetaddrarg(argc, argv, &nextarg, &contents, NULL, NULL, regs)))
2348                 return diag;
2349
2350         if (nextarg != argc + 1)
2351                 return KDB_ARGCOUNT;
2352
2353         width = argv[0][2] ? (argv[0][2] - '0') : (sizeof(kdb_machreg_t));
2354         if ((diag = kdb_putword(addr, contents, width)))
2355                 return(diag);
2356
2357         kdb_printf(kdb_machreg_fmt " = " kdb_machreg_fmt "\n", addr, contents);
2358
2359         return 0;
2360 }
2361
2362 /*
2363  * kdb_go
2364  *
2365  *      This function implements the 'go' command.
2366  *
2367  *      go [address-expression]
2368  *
2369  * Inputs:
2370  *      argc    argument count
2371  *      argv    argument vector
2372  *      envp    environment vector
2373  *      regs    registers at time kdb was entered.
2374  * Outputs:
2375  *      None.
2376  * Returns:
2377  *      KDB_CMD_GO for success, a kdb diagnostic if error
2378  * Locking:
2379  *      none.
2380  * Remarks:
2381  */
2382
2383 static int
2384 kdb_go(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2385 {
2386         kdb_machreg_t addr;
2387         int diag;
2388         int nextarg;
2389         long offset;
2390
2391         if (argc == 1) {
2392                 if (smp_processor_id() != kdb_initial_cpu) {
2393                         kdb_printf("go <address> must be issued from the initial cpu, do cpu %d first\n", kdb_initial_cpu);
2394                         return KDB_ARGCOUNT;
2395                 }
2396                 nextarg = 1;
2397                 diag = kdbgetaddrarg(argc, argv, &nextarg,
2398                                      &addr, &offset, NULL, regs);
2399                 if (diag)
2400                         return diag;
2401
2402                 kdba_setpc(regs, addr);
2403         } else if (argc)
2404                 return KDB_ARGCOUNT;
2405
2406         diag = KDB_CMD_GO;
2407         if (KDB_FLAG(CATASTROPHIC)) {
2408                 kdb_printf("Catastrophic error detected\n");
2409                 kdb_printf("kdb_continue_catastrophic=%d, ",
2410                         kdb_continue_catastrophic);
2411                 if (kdb_continue_catastrophic == 0 && kdb_go_count++ == 0) {
2412                         kdb_printf("type go a second time if you really want to continue\n");
2413                         return 0;
2414                 }
2415                 if (kdb_continue_catastrophic == 2) {
2416                         kdb_do_dump(regs);
2417                         kdb_printf("forcing reboot\n");
2418                         kdb_reboot(0, NULL, NULL, regs);
2419                 }
2420                 kdb_printf("attempting to continue\n");
2421         }
2422         if (smp_processor_id() != kdb_initial_cpu) {
2423                 char buf[80];
2424                 kdb_printf("go was not issued from initial cpu, switching back to cpu %d\n", kdb_initial_cpu);
2425                 sprintf(buf, "cpu %d\n", kdb_initial_cpu);
2426                 /* Recursive use of kdb_parse, do not use argv after this point */
2427                 argv = NULL;
2428                 diag = kdb_parse(buf, regs);
2429                 if (diag == KDB_CMD_CPU)
2430                         KDB_STATE_SET_CPU(GO_SWITCH, kdb_initial_cpu);
2431         }
2432         return diag;
2433 }
2434
2435 /*
2436  * kdb_rd
2437  *
2438  *      This function implements the 'rd' command.
2439  *
2440  *      rd              display all general registers.
2441  *      rd  c           display all control registers.
2442  *      rd  d           display all debug registers.
2443  *
2444  * Inputs:
2445  *      argc    argument count
2446  *      argv    argument vector
2447  *      envp    environment vector
2448  *      regs    registers at time kdb was entered.
2449  * Outputs:
2450  *      None.
2451  * Returns:
2452  *      zero for success, a kdb diagnostic if error
2453  * Locking:
2454  *      none.
2455  * Remarks:
2456  */
2457
2458 static int
2459 kdb_rd(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2460 {
2461         if (argc == 0) {
2462                 return kdba_dumpregs(regs, NULL, NULL);
2463         }
2464
2465         if (argc > 2) {
2466                 return KDB_ARGCOUNT;
2467         }
2468
2469         return kdba_dumpregs(regs, argv[1], argc==2 ? argv[2]: NULL);
2470 }
2471
2472 /*
2473  * kdb_rm
2474  *
2475  *      This function implements the 'rm' (register modify)  command.
2476  *
2477  *      rm register-name new-contents
2478  *
2479  * Inputs:
2480  *      argc    argument count
2481  *      argv    argument vector
2482  *      envp    environment vector
2483  *      regs    registers at time kdb was entered.
2484  * Outputs:
2485  *      None.
2486  * Returns:
2487  *      zero for success, a kdb diagnostic if error
2488  * Locking:
2489  *      none.
2490  * Remarks:
2491  *      Currently doesn't allow modification of control or
2492  *      debug registers, nor does it allow modification
2493  *      of model-specific registers (MSR).
2494  */
2495
2496 static int
2497 kdb_rm(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2498 {
2499         int diag;
2500         int ind = 0;
2501         kdb_machreg_t contents;
2502
2503         if (argc != 2) {
2504                 return KDB_ARGCOUNT;
2505         }
2506
2507         /*
2508          * Allow presence or absence of leading '%' symbol.
2509          */
2510
2511         if (argv[1][0] == '%')
2512                 ind = 1;
2513
2514         diag = kdbgetularg(argv[2], &contents);
2515         if (diag)
2516                 return diag;
2517
2518         diag = kdba_setregcontents(&argv[1][ind], regs, contents);
2519         if (diag)
2520                 return diag;
2521
2522         return 0;
2523 }
2524
2525 #if defined(CONFIG_MAGIC_SYSRQ)
2526 /*
2527  * kdb_sr
2528  *
2529  *      This function implements the 'sr' (SYSRQ key) command which
2530  *      interfaces to the soi-disant MAGIC SYSRQ functionality.
2531  *
2532  *      sr <magic-sysrq-code>
2533  *
2534  * Inputs:
2535  *      argc    argument count
2536  *      argv    argument vector
2537  *      envp    environment vector
2538  *      regs    registers at time kdb was entered.
2539  * Outputs:
2540  *      None.
2541  * Returns:
2542  *      zero for success, a kdb diagnostic if error
2543  * Locking:
2544  *      none.
2545  * Remarks:
2546  *      None.
2547  */
2548 static int
2549 kdb_sr(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2550 {
2551         extern int sysrq_enabled;
2552         if (argc != 1) {
2553                 return KDB_ARGCOUNT;
2554         }
2555         if (!sysrq_enabled) {
2556                 kdb_printf("Auto activating sysrq\n");
2557                 sysrq_enabled = 1;
2558         }
2559
2560         handle_sysrq(*argv[1], regs, 0);
2561
2562         return 0;
2563 }
2564 #endif  /* CONFIG_MAGIC_SYSRQ */
2565
2566 /*
2567  * kdb_ef
2568  *
2569  *      This function implements the 'regs' (display exception frame)
2570  *      command.  This command takes an address and expects to find
2571  *      an exception frame at that address, formats and prints it.
2572  *
2573  *      regs address-expression
2574  *
2575  * Inputs:
2576  *      argc    argument count
2577  *      argv    argument vector
2578  *      envp    environment vector
2579  *      regs    registers at time kdb was entered.
2580  * Outputs:
2581  *      None.
2582  * Returns:
2583  *      zero for success, a kdb diagnostic if error
2584  * Locking:
2585  *      none.
2586  * Remarks:
2587  *      Not done yet.
2588  */
2589
2590 static int
2591 kdb_ef(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2592 {
2593         int diag;
2594         kdb_machreg_t addr;
2595         long offset;
2596         int nextarg;
2597
2598         if (argc == 1) {
2599                 nextarg = 1;
2600                 diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL, regs);
2601                 if (diag)
2602                         return diag;
2603
2604                 return kdba_dumpregs((struct pt_regs *)addr, NULL, NULL);
2605         }
2606
2607         return KDB_ARGCOUNT;
2608 }
2609
2610 #if defined(CONFIG_MODULES)
2611 extern struct list_head *kdb_modules;
2612 extern void free_module(struct module *);
2613
2614 /* modules using other modules */
2615 struct module_use
2616 {
2617         struct list_head list;
2618         struct module *module_which_uses;
2619 };
2620
2621 /*
2622  * kdb_lsmod
2623  *
2624  *      This function implements the 'lsmod' command.  Lists currently
2625  *      loaded kernel modules.
2626  *
2627  *      Mostly taken from userland lsmod.
2628  *
2629  * Inputs:
2630  *      argc    argument count
2631  *      argv    argument vector
2632  *      envp    environment vector
2633  *      regs    registers at time kdb was entered.
2634  * Outputs:
2635  *      None.
2636  * Returns:
2637  *      zero for success, a kdb diagnostic if error
2638  * Locking:
2639  *      none.
2640  * Remarks:
2641  *
2642  */
2643
2644 static int
2645 kdb_lsmod(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2646 {
2647         struct module *mod;
2648
2649         if (argc != 0)
2650                 return KDB_ARGCOUNT;
2651
2652         kdb_printf("Module                  Size  modstruct     Used by\n");
2653         list_for_each_entry(mod, kdb_modules, list) {
2654
2655                 kdb_printf("%-20s%8lu  0x%p ", mod->name,
2656                            mod->core_size, (void *)mod);
2657 #ifdef CONFIG_MODULE_UNLOAD
2658                 kdb_printf("%4d ", module_refcount(mod));
2659 #endif
2660                 if (mod->state == MODULE_STATE_GOING)
2661                         kdb_printf(" (Unloading)");
2662                 else if (mod->state == MODULE_STATE_COMING)
2663                         kdb_printf(" (Loading)");
2664                 else
2665                         kdb_printf(" (Live)");
2666
2667 #ifdef CONFIG_MODULE_UNLOAD
2668                 {
2669                         struct module_use *use;
2670                         kdb_printf(" [ ");
2671                         list_for_each_entry(use, &mod->modules_which_use_me, list)
2672                                 kdb_printf("%s ", use->module_which_uses->name);
2673                         kdb_printf("]\n");
2674                 }
2675 #endif
2676         }
2677
2678         return 0;
2679 }
2680
2681 #endif  /* CONFIG_MODULES */
2682
2683 /*
2684  * kdb_env
2685  *
2686  *      This function implements the 'env' command.  Display the current
2687  *      environment variables.
2688  *
2689  * Inputs:
2690  *      argc    argument count
2691  *      argv    argument vector
2692  *      envp    environment vector
2693  *      regs    registers at time kdb was entered.
2694  * Outputs:
2695  *      None.
2696  * Returns:
2697  *      zero for success, a kdb diagnostic if error
2698  * Locking:
2699  *      none.
2700  * Remarks:
2701  */
2702
2703 static int
2704 kdb_env(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2705 {
2706         int i;
2707
2708         for(i=0; i<__nenv; i++) {
2709                 if (__env[i]) {
2710                         kdb_printf("%s\n", __env[i]);
2711                 }
2712         }
2713
2714         if (KDB_DEBUG(MASK))
2715                 kdb_printf("KDBFLAGS=0x%x\n", kdb_flags);
2716
2717         return 0;
2718 }
2719
2720 /*
2721  * kdb_dmesg
2722  *
2723  *      This function implements the 'dmesg' command to display the contents
2724  *      of the syslog buffer.
2725  *
2726  *      dmesg [lines] [adjust]
2727  *
2728  * Inputs:
2729  *      argc    argument count
2730  *      argv    argument vector
2731  *      envp    environment vector
2732  *      regs    registers at time kdb was entered.
2733  * Outputs:
2734  *      None.
2735  * Returns:
2736  *      zero for success, a kdb diagnostic if error
2737  * Locking:
2738  *      none.
2739  * Remarks:
2740  *      None.
2741  */
2742
2743 static int
2744 kdb_dmesg(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2745 {
2746         char *syslog_data[4], *start, *end, c = '\0', *p;
2747         int diag, logging, logsize, lines = 0, adjust = 0, n;
2748
2749         if (argc > 2)
2750                 return KDB_ARGCOUNT;
2751         if (argc) {
2752                 char *cp;
2753                 lines = simple_strtol(argv[1], &cp, 0);
2754                 if (*cp)
2755                         lines = 0;
2756                 if (argc > 1) {
2757                         adjust = simple_strtoul(argv[2], &cp, 0);
2758                         if (*cp || adjust < 0)
2759                                 adjust = 0;
2760                 }
2761         }
2762
2763         /* disable LOGGING if set */
2764         diag = kdbgetintenv("LOGGING", &logging);
2765         if (!diag && logging) {
2766                 const char *setargs[] = { "set", "LOGGING", "0" };
2767                 kdb_set(2, setargs, envp, regs);
2768         }
2769
2770         /* syslog_data[0,1] physical start, end+1.  syslog_data[2,3] logical start, end+1. */
2771         kdb_syslog_data(syslog_data);
2772         if (syslog_data[2] == syslog_data[3])
2773                 return 0;
2774         logsize = syslog_data[1] - syslog_data[0];
2775         start = syslog_data[2];
2776         end = syslog_data[3];
2777 #define KDB_WRAP(p) (((p - syslog_data[0]) % logsize) + syslog_data[0])
2778         for (n = 0, p = start; p < end; ++p) {
2779                 if ((c = *KDB_WRAP(p)) == '\n')
2780                         ++n;
2781         }
2782         if (c != '\n')
2783                 ++n;
2784         if (lines < 0) {
2785                 if (adjust >= n)
2786                         kdb_printf("buffer only contains %d lines, nothing printed\n", n);
2787                 else if (adjust - lines >= n)
2788                         kdb_printf("buffer only contains %d lines, last %d lines printed\n",
2789                                 n, n - adjust);
2790                 if (adjust) {
2791                         for (; start < end && adjust; ++start) {
2792                                 if (*KDB_WRAP(start) == '\n')
2793                                         --adjust;
2794                         }
2795                         if (start < end)
2796                                 ++start;
2797                 }
2798                 for (p = start; p < end && lines; ++p) {
2799                         if (*KDB_WRAP(p) == '\n')
2800                                 ++lines;
2801                 }
2802                 end = p;
2803         } else if (lines > 0) {
2804                 int skip = n - (adjust + lines);
2805                 if (adjust >= n) {
2806                         kdb_printf("buffer only contains %d lines, nothing printed\n", n);
2807                         skip = n;
2808                 } else if (skip < 0) {
2809                         lines += skip;
2810                         skip = 0;
2811                         kdb_printf("buffer only contains %d lines, first %d lines printed\n",
2812                                 n, lines);
2813                 }
2814                 for (; start < end && skip; ++start) {
2815                         if (*KDB_WRAP(start) == '\n')
2816                                 --skip;
2817                 }
2818                 for (p = start; p < end && lines; ++p) {
2819                         if (*KDB_WRAP(p) == '\n')
2820                                 --lines;
2821                 }
2822                 end = p;
2823         }
2824         /* Do a line at a time (max 200 chars) to reduce protocol overhead */
2825         c = '\n';
2826         while (start != end) {
2827                 char buf[201], *p = buf;
2828                 while (start < end && (c = *KDB_WRAP(start)) && (p - buf) < sizeof(buf)-1) {
2829                         ++start;
2830                         *p++ = c;
2831                         if (c == '\n')
2832                                 break;
2833                 }
2834                 *p = '\0';
2835                 kdb_printf("%s", buf);
2836         }
2837         if (c != '\n')
2838                 kdb_printf("\n");
2839
2840         return 0;
2841 }
2842
2843 /*
2844  * kdb_cpu
2845  *
2846  *      This function implements the 'cpu' command.
2847  *
2848  *      cpu     [<cpunum>]
2849  *
2850  * Inputs:
2851  *      argc    argument count
2852  *      argv    argument vector
2853  *      envp    environment vector
2854  *      regs    registers at time kdb was entered.
2855  * Outputs:
2856  *      None.
2857  * Returns:
2858  *      KDB_CMD_CPU for success, a kdb diagnostic if error
2859  * Locking:
2860  *      none.
2861  * Remarks:
2862  *      All cpu's should be spinning in kdb().  However just in case
2863  *      a cpu did not take the smp_kdb_stop NMI, check that a cpu
2864  *      entered kdb() before passing control to it.
2865  */
2866
2867 static void
2868 kdb_cpu_status(void)
2869 {
2870         int i, start_cpu, first_print = 1;
2871         char state, prev_state = '?';
2872
2873         kdb_printf("Currently on cpu %d\n", smp_processor_id());
2874         kdb_printf("Available cpus: ");
2875         for (start_cpu = -1, i = 0; i < NR_CPUS; i++) {
2876                 if (!cpu_online(i))
2877                         state = 'F';    /* cpu is offline */
2878                 else {
2879                         struct kdb_running_process *krp = kdb_running_process+i;
2880                         if (KDB_STATE_CPU(KDB, i)) {
2881                                 state = ' ';    /* cpu is responding to kdb */
2882                                 if (kdb_task_state_char(krp->p) == 'I')
2883                                         state = 'I';    /* running the idle task */
2884                         } else if (krp->seqno && krp->p && krp->seqno >= kdb_seqno - 1)
2885                                 state = '+';    /* some kdb data, but not responding */
2886                         else
2887                                 state = '*';    /* no kdb data */
2888                 }
2889                 if (state != prev_state) {
2890                         if (prev_state != '?') {
2891                                 if (!first_print)
2892                                         kdb_printf(", ");
2893                                 first_print = 0;
2894                                 kdb_printf("%d", start_cpu);
2895                                 if (start_cpu < i-1)
2896                                         kdb_printf("-%d", i-1);
2897                                 if (prev_state != ' ')
2898                                         kdb_printf("(%c)", prev_state);
2899                         }
2900                         prev_state = state;
2901                         start_cpu = i;
2902                 }
2903         }
2904         /* print the trailing cpus, ignoring them if they are all offline */
2905         if (prev_state != 'F') {
2906                 if (!first_print)
2907                         kdb_printf(", ");
2908                 kdb_printf("%d", start_cpu);
2909                 if (start_cpu < i-1)
2910                         kdb_printf("-%d", i-1);
2911                 if (prev_state != ' ')
2912                         kdb_printf("(%c)", prev_state);
2913         }
2914         kdb_printf("\n");
2915 }
2916
2917 static int
2918 kdb_cpu(int argc, const char **argv, const char **envp, struct pt_regs *regs)
2919 {
2920         unsigned long cpunum;
2921         int diag, i;
2922
2923         /* ask the other cpus if they are still active */
2924         for (i=0; i<NR_CPUS; i++) {
2925                 if (cpu_online(i))
2926                         KDB_STATE_CLEAR_CPU(KDB, i);
2927         }
2928         KDB_STATE_SET(KDB);
2929         barrier();
2930         /* wait for the other cpus to notice and set state KDB again,
2931          * see kdb_main_loop
2932          */
2933         udelay(1000);
2934
2935         if (argc == 0) {
2936                 kdb_cpu_status();
2937                 return 0;
2938         }
2939
2940         if (argc != 1)
2941                 return KDB_ARGCOUNT;
2942
2943         diag = kdbgetularg(argv[1], &cpunum);
2944         if (diag)
2945                 return diag;
2946
2947         /*
2948          * Validate cpunum
2949          */
2950         if ((cpunum > NR_CPUS)
2951          || !cpu_online(cpunum)
2952          || !KDB_STATE_CPU(KDB, cpunum))
2953                 return KDB_BADCPUNUM;
2954
2955         kdb_new_cpu = cpunum;
2956
2957         /*
2958          * Switch to other cpu
2959          */
2960         return KDB_CMD_CPU;
2961 }
2962
2963 /* The user may not realize that ps/bta with no parameters does not print idle
2964  * or sleeping system daemon processes, so tell them how many were suppressed.
2965  */
2966 void
2967 kdb_ps_suppressed(void)
2968 {
2969         int idle = 0, daemon = 0;
2970         unsigned long mask_I = kdb_task_state_string("I"),
2971                       mask_M = kdb_task_state_string("M");
2972         unsigned long cpu;
2973         const struct task_struct *p, *g;
2974         for (cpu = 0; cpu < NR_CPUS; ++cpu) {
2975                 if (!cpu_online(cpu))
2976                         continue;
2977                 p = kdb_cpu_curr(cpu);
2978                 if (kdb_task_state(p, mask_I))
2979                         ++idle;
2980         }
2981         kdb_do_each_thread(g, p) {
2982                 if (kdb_task_state(p, mask_M))
2983                         ++daemon;
2984         } kdb_while_each_thread(g, p);
2985         if (idle || daemon) {
2986                 if (idle)
2987                         kdb_printf("%d idle process%s (state I)%s",
2988                                    idle, idle == 1 ? "" : "es",
2989                                    daemon ? " and " : "");
2990                 if (daemon)
2991                         kdb_printf("%d sleeping system daemon (state M) process%s",
2992                                    daemon, daemon == 1 ? "" : "es");
2993                 kdb_printf(" suppressed\n");
2994         }
2995 }
2996
2997 /*
2998  * kdb_ps
2999  *
3000  *      This function implements the 'ps' command which shows
3001  *      a list of the active processes.
3002  *
3003  *      ps [DRSTCZEUIMA]                All processes, optionally filtered by state
3004  *
3005  * Inputs:
3006  *      argc    argument count
3007  *      argv    argument vector
3008  *      envp    environment vector
3009  *      regs    registers at time kdb was entered.
3010  * Outputs:
3011  *      None.
3012  * Returns:
3013  *      zero for success, a kdb diagnostic if error
3014  * Locking:
3015  *      none.
3016  * Remarks:
3017  */
3018
3019 void
3020 kdb_ps1(struct task_struct *p)
3021 {
3022         kdb_printf("0x%p %8d %8d  %d %4d   %c  0x%p %c%s\n",
3023                    (void *)p, p->pid, p->parent->pid,
3024                    kdb_task_has_cpu(p), kdb_process_cpu(p),
3025                    kdb_task_state_char(p),
3026                    (void *)(&p->thread),
3027                    (p == current) ? '*': ' ',
3028                    p->comm);
3029         if (kdb_task_has_cpu(p)) {
3030                 struct kdb_running_process *krp = kdb_running_process + kdb_process_cpu(p);
3031                 if (!krp->seqno || !krp->p)
3032                         kdb_printf("  Error: no saved data for this cpu\n");
3033                 else {
3034                         if (krp->seqno < kdb_seqno - 1)
3035                                 kdb_printf("  Warning: process state is stale\n");
3036                         if (krp->p != p)
3037                                 kdb_printf("  Error: does not match running process table (0x%p)\n", krp->p);
3038                 }
3039         }
3040 }
3041
3042 static int
3043 kdb_ps(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3044 {
3045         struct task_struct *g, *p;
3046         unsigned long mask, cpu;
3047
3048         if (argc == 0)
3049                 kdb_ps_suppressed();
3050         kdb_printf("%-*s      Pid   Parent [*] cpu State %-*s Command\n",
3051                 (int)(2*sizeof(void *))+2, "Task Addr",
3052                 (int)(2*sizeof(void *))+2, "Thread");
3053         mask = kdb_task_state_string(argc ? argv[1] : NULL);
3054         /* Run the active tasks first */
3055         for (cpu = 0; cpu < NR_CPUS; ++cpu) {
3056                 if (!cpu_online(cpu))
3057                         continue;
3058                 p = kdb_cpu_curr(cpu);
3059                 if (kdb_task_state(p, mask))
3060                         kdb_ps1(p);
3061         }
3062         kdb_printf("\n");
3063         /* Now the real tasks */
3064         kdb_do_each_thread(g, p) {
3065                 if (kdb_task_state(p, mask))
3066                         kdb_ps1(p);
3067         } kdb_while_each_thread(g, p);
3068
3069         return 0;
3070 }
3071
3072 /*
3073  * kdb_pid
3074  *
3075  *      This function implements the 'pid' command which switches
3076  *      the currently active process.
3077  *
3078  *      pid [<pid>]
3079  *
3080  * Inputs:
3081  *      argc    argument count
3082  *      argv    argument vector
3083  *      envp    environment vector
3084  *      regs    registers at time kdb was entered.
3085  * Outputs:
3086  *      None.
3087  * Returns:
3088  *      zero for success, a kdb diagnostic if error
3089  * Locking:
3090  *      none.
3091  * Remarks:
3092  */
3093
3094
3095 static int
3096 kdb_pid(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3097 {
3098         struct task_struct *p;
3099         unsigned long val;
3100         int diag;
3101
3102         if (argc > 1)
3103                 return KDB_ARGCOUNT;
3104
3105         if (argc) {
3106                 diag = kdbgetularg(argv[1], &val);
3107                 if (diag)
3108                         return KDB_BADINT;
3109
3110                 p = find_task_by_pid((pid_t)val);
3111                 if (!p) {
3112                         kdb_printf("No task with pid=%d\n", (pid_t)val);
3113                         return 0;
3114                 }
3115
3116                 kdb_current_task = p;
3117         }
3118
3119         kdb_printf("KDB current process is %s(pid=%d)\n", kdb_current_task->comm,
3120                    kdb_current_task->pid);
3121
3122         return 0;
3123 }
3124
3125 /*
3126  * kdb_ll
3127  *
3128  *      This function implements the 'll' command which follows a linked
3129  *      list and executes an arbitrary command for each element.
3130  *
3131  * Inputs:
3132  *      argc    argument count
3133  *      argv    argument vector
3134  *      envp    environment vector
3135  *      regs    registers at time kdb was entered.
3136  * Outputs:
3137  *      None.
3138  * Returns:
3139  *      zero for success, a kdb diagnostic if error
3140  * Locking:
3141  *      none.
3142  * Remarks:
3143  */
3144
3145 static int
3146 kdb_ll(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3147 {
3148         int diag;
3149         kdb_machreg_t addr;
3150         long offset = 0;
3151         kdb_machreg_t va;
3152         unsigned long linkoffset;
3153         int nextarg;
3154         const char *command;
3155
3156         if (argc != 3) {
3157                 return KDB_ARGCOUNT;
3158         }
3159
3160         nextarg = 1;
3161         diag = kdbgetaddrarg(argc, argv, &nextarg, &addr, &offset, NULL, regs);
3162         if (diag)
3163                 return diag;
3164
3165         diag = kdbgetularg(argv[2], &linkoffset);
3166         if (diag)
3167                 return diag;
3168
3169         /*
3170          * Using the starting address as
3171          * the first element in the list, and assuming that
3172          * the list ends with a null pointer.
3173          */
3174
3175         va = addr;
3176         if (!(command = kdb_strdup(argv[3], GFP_KDB))) {
3177                 kdb_printf("%s: cannot duplicate command\n", __FUNCTION__);
3178                 return 0;
3179         }
3180         /* Recursive use of kdb_parse, do not use argv after this point */
3181         argv = NULL;
3182
3183         while (va) {
3184                 char buf[80];
3185
3186                 sprintf(buf, "%s " kdb_machreg_fmt "\n", command, va);
3187                 diag = kdb_parse(buf, regs);
3188                 if (diag)
3189                         return diag;
3190
3191                 addr = va + linkoffset;
3192                 if (kdb_getword(&va, addr, sizeof(va)))
3193                         return(0);
3194         }
3195         kfree(command);
3196
3197         return 0;
3198 }
3199
3200 /*
3201  * kdb_help
3202  *
3203  *      This function implements the 'help' and '?' commands.
3204  *
3205  * Inputs:
3206  *      argc    argument count
3207  *      argv    argument vector
3208  *      envp    environment vector
3209  *      regs    registers at time kdb was entered.
3210  * Outputs:
3211  *      None.
3212  * Returns:
3213  *      zero for success, a kdb diagnostic if error
3214  * Locking:
3215  *      none.
3216  * Remarks:
3217  */
3218
3219 static int
3220 kdb_help(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3221 {
3222         kdbtab_t *kt;
3223
3224         kdb_printf("%-15.15s %-20.20s %s\n", "Command", "Usage", "Description");
3225         kdb_printf("----------------------------------------------------------\n");
3226         for(kt=kdb_commands; kt->cmd_name; kt++) {
3227                 kdb_printf("%-15.15s %-20.20s %s\n", kt->cmd_name,
3228                         kt->cmd_usage, kt->cmd_help);
3229         }
3230         return 0;
3231 }
3232
3233 extern int kdb_wake_up_process(struct task_struct * p);
3234
3235 /*
3236  * kdb_kill
3237  *
3238  *      This function implements the 'kill' commands.
3239  *
3240  * Inputs:
3241  *      argc    argument count
3242  *      argv    argument vector
3243  *      envp    environment vector
3244  *      regs    registers at time kdb was entered.
3245  * Outputs:
3246  *      None.
3247  * Returns:
3248  *      zero for success, a kdb diagnostic if error
3249  * Locking:
3250  *      none.
3251  * Remarks:
3252  */
3253
3254 static int
3255 kdb_kill(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3256 {
3257         long sig, pid;
3258         char *endp;
3259         struct task_struct *p;
3260         struct siginfo info;
3261
3262         if (argc!=2)
3263                 return KDB_ARGCOUNT;
3264
3265         sig = simple_strtol(argv[1], &endp, 0);
3266         if (*endp)
3267                 return KDB_BADINT;
3268         if (sig >= 0 ) {
3269                 kdb_printf("Invalid signal parameter.<-signal>\n");
3270                 return 0;
3271         }
3272         sig=-sig;
3273
3274         pid = simple_strtol(argv[2], &endp, 0);
3275         if (*endp)
3276                 return KDB_BADINT;
3277         if (pid <=0 ) {
3278                 kdb_printf("Process ID must be large than 0.\n");
3279                 return 0;
3280         }
3281
3282         /* Find the process. */
3283         if (!(p = find_task_by_pid(pid))) {
3284                 kdb_printf("The specified process isn't found.\n");
3285                 return 0;
3286         }
3287         p = p->group_leader;
3288         info.si_signo = sig;
3289         info.si_errno = 0;
3290         info.si_code = SI_USER;
3291         info.si_pid = pid;      /* use same capabilities as process being signalled */
3292         info.si_uid = 0;        /* kdb has root authority */
3293         kdb_send_sig_info(p, &info, kdb_seqno);
3294         return 0;
3295 }
3296
3297 struct kdb_tm {
3298         int tm_sec;     /* seconds */
3299         int tm_min;     /* minutes */
3300         int tm_hour;    /* hours */
3301         int tm_mday;    /* day of the month */
3302         int tm_mon;     /* month */
3303         int tm_year;    /* year */
3304 };
3305
3306 static void
3307 kdb_gmtime(struct timespec *tv, struct kdb_tm *tm)
3308 {
3309         /* This will work from 1970-2099, 2100 is not a leap year */
3310         static int mon_day[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
3311         memset(tm, 0, sizeof(*tm));
3312         tm->tm_sec  = tv->tv_sec % (24 * 60 * 60);
3313         tm->tm_mday = tv->tv_sec / (24 * 60 * 60) + (2 * 365 + 1); /* shift base from 1970 to 1968 */
3314         tm->tm_min =  tm->tm_sec / 60 % 60;
3315         tm->tm_hour = tm->tm_sec / 60 / 60;
3316         tm->tm_sec =  tm->tm_sec % 60;
3317         tm->tm_year = 68 + 4*(tm->tm_mday / (4*365+1));
3318         tm->tm_mday %= (4*365+1);
3319         mon_day[1] = 29;
3320         while (tm->tm_mday >= mon_day[tm->tm_mon]) {
3321                 tm->tm_mday -= mon_day[tm->tm_mon];
3322                 if (++tm->tm_mon == 12) {
3323                         tm->tm_mon = 0;
3324                         ++tm->tm_year;
3325                         mon_day[1] = 28;
3326                 }
3327         }
3328         ++tm->tm_mday;
3329 }
3330
3331 /*
3332  * Most of this code has been lifted from kernel/timer.c::sys_sysinfo().
3333  * I cannot call that code directly from kdb, it has an unconditional
3334  * cli()/sti() and calls routines that take locks which can stop the debugger.
3335  */
3336
3337 static void
3338 kdb_sysinfo(struct sysinfo *val)
3339 {
3340         struct timespec uptime;
3341         do_posix_clock_monotonic_gettime(&uptime);
3342         memset(val, 0, sizeof(*val));
3343         val->uptime = uptime.tv_sec;
3344         val->loads[0] = avenrun[0];
3345         val->loads[1] = avenrun[1];
3346         val->loads[2] = avenrun[2];
3347         val->procs = nr_threads-1;
3348         si_meminfo(val);
3349         kdb_si_swapinfo(val);
3350
3351         return;
3352 }
3353
3354 /*
3355  * kdb_summary
3356  *
3357  *      This function implements the 'summary' command.
3358  *
3359  * Inputs:
3360  *      argc    argument count
3361  *      argv    argument vector
3362  *      envp    environment vector
3363  *      regs    registers at time kdb was entered.
3364  * Outputs:
3365  *      None.
3366  * Returns:
3367  *      zero for success, a kdb diagnostic if error
3368  * Locking:
3369  *      none.
3370  * Remarks:
3371  */
3372
3373 static int
3374 kdb_summary(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3375 {
3376         extern struct timespec xtime;
3377         extern struct timezone sys_tz;
3378         struct kdb_tm tm;
3379         struct sysinfo val;
3380
3381         if (argc)
3382                 return KDB_ARGCOUNT;
3383
3384         kdb_printf("sysname    %s\n", system_utsname.sysname);
3385         kdb_printf("release    %s\n", system_utsname.release);
3386         kdb_printf("version    %s\n", system_utsname.version);
3387         kdb_printf("machine    %s\n", system_utsname.machine);
3388         kdb_printf("nodename   %s\n", system_utsname.nodename);
3389         kdb_printf("domainname %s\n", system_utsname.domainname);
3390
3391         kdb_gmtime(&xtime, &tm);
3392         kdb_printf("date       %04d-%02d-%02d %02d:%02d:%02d tz_minuteswest %d\n",
3393                 1900+tm.tm_year, tm.tm_mon+1, tm.tm_mday,
3394                 tm.tm_hour, tm.tm_min, tm.tm_sec,
3395                 sys_tz.tz_minuteswest);
3396
3397         kdb_sysinfo(&val);
3398         kdb_printf("uptime     ");
3399         if (val.uptime > (24*60*60)) {
3400                 int days = val.uptime / (24*60*60);
3401                 val.uptime %= (24*60*60);
3402                 kdb_printf("%d day%s ", days, days == 1 ? "" : "s");
3403         }
3404         kdb_printf("%02ld:%02ld\n", val.uptime/(60*60), (val.uptime/60)%60);
3405
3406         /* lifted from fs/proc/proc_misc.c::loadavg_read_proc() */
3407
3408 #define LOAD_INT(x) ((x) >> FSHIFT)
3409 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
3410         kdb_printf("load avg   %ld.%02ld %ld.%02ld %ld.%02ld\n",
3411                 LOAD_INT(val.loads[0]), LOAD_FRAC(val.loads[0]),
3412                 LOAD_INT(val.loads[1]), LOAD_FRAC(val.loads[1]),
3413                 LOAD_INT(val.loads[2]), LOAD_FRAC(val.loads[2]));
3414         kdb_printf("\n");
3415 #undef LOAD_INT
3416 #undef LOAD_FRAC
3417
3418         kdb_meminfo_read_proc();        /* in fs/proc/proc_misc.c */
3419
3420         return 0;
3421 }
3422
3423 /*
3424  * kdb_per_cpu
3425  *
3426  *      This function implements the 'per_cpu' command.
3427  *
3428  * Inputs:
3429  *      argc    argument count
3430  *      argv    argument vector
3431  *      envp    environment vector
3432  *      regs    registers at time kdb was entered.
3433  * Outputs:
3434  *      None.
3435  * Returns:
3436  *      zero for success, a kdb diagnostic if error
3437  * Locking:
3438  *      none.
3439  * Remarks:
3440  */
3441
3442 static int
3443 kdb_per_cpu(int argc, const char **argv, const char **envp, struct pt_regs *regs)
3444 {
3445         char buf[256], fmtstr[64];
3446         kdb_symtab_t symtab;
3447         cpumask_t suppress = CPU_MASK_NONE;
3448         int cpu, diag;
3449         unsigned long addr, val, bytesperword = 0, whichcpu = ~0UL;
3450
3451         if (argc < 1 || argc > 3)
3452                 return KDB_ARGCOUNT;
3453
3454         snprintf(buf, sizeof(buf), "per_cpu__%s", argv[1]);
3455         if (!kdbgetsymval(buf, &symtab)) {
3456                 kdb_printf("%s is not a per_cpu variable\n", argv[1]);
3457                 return KDB_BADADDR;
3458         }
3459         if (argc >=2 && (diag = kdbgetularg(argv[2], &bytesperword)))
3460                 return diag;
3461         if (!bytesperword)
3462                 bytesperword = sizeof(kdb_machreg_t);
3463         else if (bytesperword > sizeof(kdb_machreg_t))
3464                 return KDB_BADWIDTH;
3465         sprintf(fmtstr, "%%0%dlx ", (int)(2*bytesperword));
3466         if (argc >= 3) {
3467                 if ((diag = kdbgetularg(argv[3], &whichcpu)))
3468                         return diag;
3469                 if (!cpu_online(whichcpu)) {
3470                         kdb_printf("cpu %ld is not online\n", whichcpu);
3471                         return KDB_BADCPUNUM;
3472                 }
3473         }
3474
3475         /* Most architectures use __per_cpu_offset[cpu], some use
3476          * __per_cpu_offset(cpu), smp has no __per_cpu_offset.
3477          */
3478 #ifdef  __per_cpu_offset
3479 #define KDB_PCU(cpu) __per_cpu_offset(cpu)
3480 #else
3481 #ifdef  CONFIG_SMP
3482 #define KDB_PCU(cpu) __per_cpu_offset[cpu]
3483 #else
3484 #define KDB_PCU(cpu) 0
3485 #endif
3486 #endif
3487
3488         for_each_online_cpu(cpu) {
3489                 if (whichcpu != ~0UL && whichcpu != cpu)
3490                         continue;
3491                 addr = symtab.sym_start + KDB_PCU(cpu);
3492                 if ((diag = kdb_getword(&val, addr, bytesperword))) {
3493                         kdb_printf("%5d " kdb_bfd_vma_fmt0 " - unable to read, diag=%d\n",
3494                                 cpu, addr, diag);
3495                         continue;
3496                 }
3497 #ifdef  CONFIG_SMP
3498                 if (!val) {
3499                         cpu_set(cpu, suppress);
3500                         continue;
3501                 }
3502 #endif  /* CONFIG_SMP */
3503                 kdb_printf("%5d ", cpu);
3504                 kdb_md_line(fmtstr, addr,
3505                         bytesperword == sizeof(kdb_machreg_t),
3506                         1, bytesperword, 1, 1, 0);
3507         }
3508         if (cpus_weight(suppress) == 0)
3509                 return 0;
3510         kdb_printf("Zero suppressed cpu(s):");
3511         for (cpu = first_cpu(suppress); cpu < NR_CPUS; cpu = next_cpu(cpu, suppress)) {
3512                 kdb_printf(" %d", cpu);
3513                 if (cpu == NR_CPUS-1 || next_cpu(cpu, suppress) != cpu + 1)
3514                         continue;
3515                 while (cpu < NR_CPUS && next_cpu(cpu, suppress) == cpu + 1)
3516                         ++cpu;
3517                 kdb_printf("-%d", cpu);
3518         }
3519         kdb_printf("\n");
3520
3521 #undef KDB_PCU
3522
3523         return 0;
3524 }
3525
3526
3527 /*
3528  * kdb_register_repeat
3529  *
3530  *      This function is used to register a kernel debugger command.
3531  *
3532  * Inputs:
3533  *      cmd     Command name
3534  *      func    Function to execute the command
3535  *      usage   A simple usage string showing arguments
3536  *      help    A simple help string describing command
3537  *      repeat  Does the command auto repeat on enter?
3538  * Outputs:
3539  *      None.
3540  * Returns:
3541  *      zero for success, one if a duplicate command.
3542  * Locking:
3543  *      none.
3544  * Remarks:
3545  *
3546  */
3547
3548 #define kdb_command_extend 50   /* arbitrary */
3549 int
3550 kdb_register_repeat(char *cmd,
3551                     kdb_func_t func,
3552                     char *usage,
3553                     char *help,
3554                     short minlen,
3555                     kdb_repeat_t repeat)
3556 {
3557         int i;
3558         kdbtab_t *kp;
3559
3560         /*
3561          *  Brute force method to determine duplicates
3562          */
3563         for (i=0, kp=kdb_commands; i<kdb_max_commands; i++, kp++) {
3564                 if (kp->cmd_name && (strcmp(kp->cmd_name, cmd)==0)) {
3565                         kdb_printf("Duplicate kdb command registered: '%s'\n",
3566                                    cmd);
3567                         return 1;
3568                 }
3569         }
3570
3571         /*
3572          * Insert command into first available location in table
3573          */
3574         for (i=0, kp=kdb_commands; i<kdb_max_commands; i++, kp++) {
3575                 if (kp->cmd_name == NULL) {
3576                         break;
3577                 }
3578         }
3579
3580         if (i >= kdb_max_commands) {
3581                 kdbtab_t *new = kmalloc((kdb_max_commands + kdb_command_extend) * sizeof(*new), GFP_KDB);
3582                 if (!new) {
3583                         kdb_printf("Could not allocate new kdb_command table\n");
3584                         return 1;
3585                 }
3586                 if (kdb_commands) {
3587                         memcpy(new, kdb_commands, kdb_max_commands * sizeof(*new));
3588                         kfree(kdb_commands);
3589                 }
3590                 memset(new + kdb_max_commands, 0, kdb_command_extend * sizeof(*new));
3591                 kdb_commands = new;
3592                 kp = kdb_commands + kdb_max_commands;
3593                 kdb_max_commands += kdb_command_extend;
3594         }
3595
3596         kp->cmd_name   = cmd;
3597         kp->cmd_func   = func;
3598         kp->cmd_usage  = usage;
3599         kp->cmd_help   = help;
3600         kp->cmd_flags  = 0;
3601         kp->cmd_minlen = minlen;
3602         kp->cmd_repeat = repeat;
3603
3604         return 0;
3605 }
3606
3607 /*
3608  * kdb_register
3609  *
3610  *      Compatibility register function for commands that do not need to
3611  *      specify a repeat state.  Equivalent to kdb_register_repeat with
3612  *      KDB_REPEAT_NONE.
3613  *
3614  * Inputs:
3615  *      cmd     Command name
3616  *      func    Function to execute the command
3617  *      usage   A simple usage string showing arguments
3618  *      help    A simple help string describing command
3619  * Outputs:
3620  *      None.
3621  * Returns:
3622  *      zero for success, one if a duplicate command.
3623  * Locking:
3624  *      none.
3625  * Remarks:
3626  *
3627  */
3628
3629 int
3630 kdb_register(char *cmd,
3631              kdb_func_t func,
3632              char *usage,
3633              char *help,
3634              short minlen)
3635 {
3636         return kdb_register_repeat(cmd, func, usage, help, minlen, KDB_REPEAT_NONE);
3637 }
3638
3639 /*
3640  * kdb_unregister
3641  *
3642  *      This function is used to unregister a kernel debugger command.
3643  *      It is generally called when a module which implements kdb
3644  *      commands is unloaded.
3645  *
3646  * Inputs:
3647  *      cmd     Command name
3648  * Outputs:
3649  *      None.
3650  * Returns:
3651  *      zero for success, one command not registered.
3652  * Locking:
3653  *      none.
3654  * Remarks:
3655  *
3656  */
3657
3658 int
3659 kdb_unregister(char *cmd)
3660 {
3661         int i;
3662         kdbtab_t *kp;
3663
3664         /*
3665          *  find the command.
3666          */
3667         for (i=0, kp=kdb_commands; i<kdb_max_commands; i++, kp++) {
3668                 if (kp->cmd_name && (strcmp(kp->cmd_name, cmd)==0)) {
3669                         kp->cmd_name = NULL;
3670                         return 0;
3671                 }
3672         }
3673
3674         /*
3675          * Couldn't find it.
3676          */
3677         return 1;
3678 }
3679
3680 /*
3681  * kdb_inittab
3682  *
3683  *      This function is called by the kdb_init function to initialize
3684  *      the kdb command table.   It must be called prior to any other
3685  *      call to kdb_register_repeat.
3686  *
3687  * Inputs:
3688  *      None.
3689  * Outputs:
3690  *      None.
3691  * Returns:
3692  *      None.
3693  * Locking:
3694  *      None.
3695  * Remarks:
3696  *
3697  */
3698
3699 static void __init
3700 kdb_inittab(void)
3701 {
3702         int i;
3703         kdbtab_t *kp;
3704         initcall_t *call;
3705
3706         for(i=0, kp=kdb_commands; i < kdb_max_commands; i++,kp++) {
3707                 kp->cmd_name = NULL;
3708         }
3709
3710         kdb_register_repeat("md", kdb_md, "<vaddr>",   "Display Memory Contents, also mdWcN, e.g. md8c1", 1, KDB_REPEAT_NO_ARGS);
3711         kdb_register_repeat("mdr", kdb_md, "<vaddr> <bytes>",   "Display Raw Memory", 0, KDB_REPEAT_NO_ARGS);
3712         kdb_register_repeat("mdp", kdb_md, "<paddr> <bytes>",   "Display Physical Memory", 0, KDB_REPEAT_NO_ARGS);
3713         kdb_register_repeat("mds", kdb_md, "<vaddr>",   "Display Memory Symbolically", 0, KDB_REPEAT_NO_ARGS);
3714         kdb_register_repeat("mm", kdb_mm, "<vaddr> <contents>",   "Modify Memory Contents", 0, KDB_REPEAT_NO_ARGS);
3715         kdb_register_repeat("id", kdb_id, "<vaddr>",   "Display Instructions", 1, KDB_REPEAT_NO_ARGS);
3716         kdb_register_repeat("go", kdb_go, "[<vaddr>]", "Continue Execution", 1, KDB_REPEAT_NONE);
3717         kdb_register_repeat("rd", kdb_rd, "",           "Display Registers", 1, KDB_REPEAT_NONE);
3718         kdb_register_repeat("rm", kdb_rm, "<reg> <contents>", "Modify Registers", 0, KDB_REPEAT_NONE);
3719         kdb_register_repeat("ef", kdb_ef, "<vaddr>",   "Display exception frame", 0, KDB_REPEAT_NONE);
3720         kdb_register_repeat("bt", kdb_bt, "[<vaddr>]", "Stack traceback", 1, KDB_REPEAT_NONE);
3721         kdb_register_repeat("btp", kdb_bt, "<pid>",     "Display stack for process <pid>", 0, KDB_REPEAT_NONE);
3722         kdb_register_repeat("bta", kdb_bt, "[DRSTCZEUIMA]",     "Display stack all processes", 0, KDB_REPEAT_NONE);
3723         kdb_register_repeat("btc", kdb_bt, "",  "Backtrace current process on each cpu", 0, KDB_REPEAT_NONE);
3724         kdb_register_repeat("btt", kdb_bt, "<vaddr>",   "Backtrace process given its struct task address", 0, KDB_REPEAT_NONE);
3725         kdb_register_repeat("ll", kdb_ll, "<first-element> <linkoffset> <cmd>", "Execute cmd for each element in linked list", 0, KDB_REPEAT_NONE);
3726         kdb_register_repeat("env", kdb_env, "",         "Show environment variables", 0, KDB_REPEAT_NONE);
3727         kdb_register_repeat("set", kdb_set, "",         "Set environment variables", 0, KDB_REPEAT_NONE);
3728         kdb_register_repeat("help", kdb_help, "",       "Display Help Message", 1, KDB_REPEAT_NONE);
3729         kdb_register_repeat("?", kdb_help, "",         "Display Help Message", 0, KDB_REPEAT_NONE);
3730         kdb_register_repeat("cpu", kdb_cpu, "<cpunum>","Switch to new cpu", 0, KDB_REPEAT_NONE);
3731         kdb_register_repeat("ps", kdb_ps, "",           "Display active task list", 0, KDB_REPEAT_NONE);
3732         kdb_register_repeat("pid", kdb_pid, "<pidnum>", "Switch to another task", 0, KDB_REPEAT_NONE);
3733         kdb_register_repeat("reboot", kdb_reboot, "",  "Reboot the machine immediately", 0, KDB_REPEAT_NONE);
3734 #if defined(CONFIG_MODULES)
3735         kdb_register_repeat("lsmod", kdb_lsmod, "",     "List loaded kernel modules", 0, KDB_REPEAT_NONE);
3736 #endif
3737 #if defined(CONFIG_MAGIC_SYSRQ)
3738         kdb_register_repeat("sr", kdb_sr, "<key>",      "Magic SysRq key", 0, KDB_REPEAT_NONE);
3739 #endif
3740         kdb_register_repeat("dmesg", kdb_dmesg, "[lines]",      "Display syslog buffer", 0, KDB_REPEAT_NONE);
3741         kdb_register_repeat("defcmd", kdb_defcmd, "name \"usage\" \"help\"", "Define a set of commands, down to endefcmd", 0, KDB_REPEAT_NONE);
3742         kdb_register_repeat("kill", kdb_kill, "<-signal> <pid>", "Send a signal to a process", 0, KDB_REPEAT_NONE);
3743         kdb_register_repeat("summary", kdb_summary, "", "Summarize the system", 4, KDB_REPEAT_NONE);
3744         kdb_register_repeat("per_cpu", kdb_per_cpu, "", "Display per_cpu variables", 3, KDB_REPEAT_NONE);
3745
3746         /* Any kdb commands that are not in the base code but are required
3747          * earlier than normal initcall processing.
3748          */
3749         call = &__kdb_initcall_start;
3750         while (call < &__kdb_initcall_end) {
3751                 (*call)();
3752                 call++;
3753         };
3754 }
3755
3756 /*
3757  * kdb_cmd_init
3758  *
3759  *      This function is called by the kdb_init function to execute any
3760  *      commands defined in kdb_cmds.
3761  *
3762  * Inputs:
3763  *      Commands in *kdb_cmds[];
3764  * Outputs:
3765  *      None.
3766  * Returns:
3767  *      None.
3768  * Locking:
3769  *      None.
3770  * Remarks:
3771  *
3772  */
3773
3774 static void __init
3775 kdb_cmd_init(void)
3776 {
3777         int i, diag;
3778         for (i = 0; kdb_cmds[i]; ++i) {
3779                 if (!defcmd_in_progress)
3780                         kdb_printf("kdb_cmd[%d]: %s", i, kdb_cmds[i]);
3781                 diag = kdb_parse(kdb_cmds[i], NULL);
3782                 if (diag)
3783                         kdb_printf("command failed, kdb diag %d\n", diag);
3784         }
3785         if (defcmd_in_progress) {
3786                 kdb_printf("Incomplete 'defcmd' set, forcing endefcmd\n");
3787                 kdb_parse("endefcmd", NULL);
3788         }
3789 }
3790
3791 /*
3792  * kdb_panic
3793  *
3794  *      Invoked via the panic_notifier_list.
3795  *
3796  * Inputs:
3797  *      None.
3798  * Outputs:
3799  *      None.
3800  * Returns:
3801  *      Zero.
3802  * Locking:
3803  *      None.
3804  * Remarks:
3805  *      When this function is called from panic(), the other cpus have already
3806  *      been stopped.
3807  *
3808  */
3809
3810 static int
3811 kdb_panic(struct notifier_block *self, unsigned long command, void *ptr)
3812 {
3813         KDB_FLAG_SET(CATASTROPHIC);     /* kernel state is dubious now */
3814         KDB_ENTER();
3815         return(0);
3816 }
3817
3818 static struct notifier_block kdb_block = { kdb_panic, NULL, 0 };
3819
3820 /*
3821  * kdb_init
3822  *
3823  *      Initialize the kernel debugger environment.
3824  *
3825  * Parameters:
3826  *      None.
3827  * Returns:
3828  *      None.
3829  * Locking:
3830  *      None.
3831  * Remarks:
3832  *      None.
3833  */
3834
3835 void __init
3836 kdb_init(void)
3837 {
3838         kdb_initial_cpu = smp_processor_id();
3839         /*
3840          * This must be called before any calls to kdb_printf.
3841          */
3842         kdb_io_init();
3843
3844         kdb_inittab();          /* Initialize Command Table */
3845         kdb_initbptab();        /* Initialize Breakpoint Table */
3846         kdb_id_init();          /* Initialize Disassembler */
3847         kdba_init();            /* Architecture Dependent Initialization */
3848
3849         /*
3850          * Use printk() to get message in log_buf[];
3851          */
3852         printk("kdb version %d.%d%s by Keith Owens, Scott Lurndal. "\
3853                "Copyright SGI, All Rights Reserved\n",
3854                 KDB_MAJOR_VERSION, KDB_MINOR_VERSION, KDB_TEST_VERSION);
3855
3856         kdb_cmd_init();         /* Preset commands from kdb_cmds */
3857         kdb_initial_cpu = -1;   /* Avoid recursion problems */
3858         kdb(KDB_REASON_SILENT, 0, 0);   /* Activate any preset breakpoints on boot cpu */
3859         kdb_initial_cpu = smp_processor_id();
3860         notifier_chain_register(&panic_notifier_list, &kdb_block);
3861
3862 #ifdef KDB_HAVE_LONGJMP
3863         kdbjmpbuf = vmalloc(NR_CPUS * sizeof(*kdbjmpbuf));
3864         if (!kdbjmpbuf)
3865                 printk(KERN_ERR "Cannot allocate kdbjmpbuf, no kdb recovery will be possible\n");
3866 #endif  /* KDB_HAVE_LONGJMP */
3867
3868         kdb_initial_cpu = -1;
3869 }
3870
3871 EXPORT_SYMBOL(kdb_register);
3872 EXPORT_SYMBOL(kdb_register_repeat);
3873 EXPORT_SYMBOL(kdb_unregister);
3874 EXPORT_SYMBOL(kdb_getarea_size);
3875 EXPORT_SYMBOL(kdb_putarea_size);
3876 EXPORT_SYMBOL(kdb_getuserarea_size);
3877 EXPORT_SYMBOL(kdb_putuserarea_size);
3878 EXPORT_SYMBOL(kdb_getword);
3879 EXPORT_SYMBOL(kdb_putword);
3880 EXPORT_SYMBOL(kdbgetularg);
3881 EXPORT_SYMBOL(kdbgetenv);
3882 EXPORT_SYMBOL(kdbgetintenv);
3883 EXPORT_SYMBOL(kdbgetaddrarg);
3884 EXPORT_SYMBOL(kdb);
3885 EXPORT_SYMBOL(kdb_on);
3886 EXPORT_SYMBOL(kdb_seqno);
3887 EXPORT_SYMBOL(kdb_initial_cpu);
3888 EXPORT_SYMBOL(kdbgetsymval);
3889 EXPORT_SYMBOL(kdbnearsym);
3890 EXPORT_SYMBOL(kdb_printf);
3891 EXPORT_SYMBOL(kdb_symbol_print);
3892 EXPORT_SYMBOL(kdb_notifier_list);
3893 EXPORT_SYMBOL(kdb_current_task);