ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / arch / mips / kernel / gdb-stub.c
1 /*
2  *  arch/mips/kernel/gdb-stub.c
3  *
4  *  Originally written by Glenn Engel, Lake Stevens Instrument Division
5  *
6  *  Contributed by HP Systems
7  *
8  *  Modified for SPARC by Stu Grossman, Cygnus Support.
9  *
10  *  Modified for Linux/MIPS (and MIPS in general) by Andreas Busse
11  *  Send complaints, suggestions etc. to <andy@waldorf-gmbh.de>
12  *
13  *  Copyright (C) 1995 Andreas Busse
14  *
15  *  Copyright (C) 2003 MontaVista Software Inc.
16  *  Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
17  */
18
19 /*
20  *  To enable debugger support, two things need to happen.  One, a
21  *  call to set_debug_traps() is necessary in order to allow any breakpoints
22  *  or error conditions to be properly intercepted and reported to gdb.
23  *  Two, a breakpoint needs to be generated to begin communication.  This
24  *  is most easily accomplished by a call to breakpoint().  Breakpoint()
25  *  simulates a breakpoint by executing a BREAK instruction.
26  *
27  *
28  *    The following gdb commands are supported:
29  *
30  * command          function                               Return value
31  *
32  *    g             return the value of the CPU registers  hex data or ENN
33  *    G             set the value of the CPU registers     OK or ENN
34  *
35  *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
36  *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
37  *
38  *    c             Resume at current address              SNN   ( signal NN)
39  *    cAA..AA       Continue at address AA..AA             SNN
40  *
41  *    s             Step one instruction                   SNN
42  *    sAA..AA       Step one instruction from AA..AA       SNN
43  *
44  *    k             kill
45  *
46  *    ?             What was the last sigval ?             SNN   (signal NN)
47  *
48  *    bBB..BB       Set baud rate to BB..BB                OK or BNN, then sets
49  *                                                         baud rate
50  *
51  * All commands and responses are sent with a packet which includes a
52  * checksum.  A packet consists of
53  *
54  * $<packet info>#<checksum>.
55  *
56  * where
57  * <packet info> :: <characters representing the command or response>
58  * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
59  *
60  * When a packet is received, it is first acknowledged with either '+' or '-'.
61  * '+' indicates a successful transfer.  '-' indicates a failed transfer.
62  *
63  * Example:
64  *
65  * Host:                  Reply:
66  * $m0,10#2a               +$00010203040506070809101112131415#42
67  *
68  *
69  *  ==============
70  *  MORE EXAMPLES:
71  *  ==============
72  *
73  *  For reference -- the following are the steps that one
74  *  company took (RidgeRun Inc) to get remote gdb debugging
75  *  going. In this scenario the host machine was a PC and the
76  *  target platform was a Galileo EVB64120A MIPS evaluation
77  *  board.
78  *
79  *  Step 1:
80  *  First download gdb-5.0.tar.gz from the internet.
81  *  and then build/install the package.
82  *
83  *  Example:
84  *    $ tar zxf gdb-5.0.tar.gz
85  *    $ cd gdb-5.0
86  *    $ ./configure --target=mips-linux-elf
87  *    $ make
88  *    $ install
89  *    $ which mips-linux-elf-gdb
90  *    /usr/local/bin/mips-linux-elf-gdb
91  *
92  *  Step 2:
93  *  Configure linux for remote debugging and build it.
94  *
95  *  Example:
96  *    $ cd ~/linux
97  *    $ make menuconfig <go to "Kernel Hacking" and turn on remote debugging>
98  *    $ make
99  *
100  *  Step 3:
101  *  Download the kernel to the remote target and start
102  *  the kernel running. It will promptly halt and wait
103  *  for the host gdb session to connect. It does this
104  *  since the "Kernel Hacking" option has defined
105  *  CONFIG_KGDB which in turn enables your calls
106  *  to:
107  *     set_debug_traps();
108  *     breakpoint();
109  *
110  *  Step 4:
111  *  Start the gdb session on the host.
112  *
113  *  Example:
114  *    $ mips-linux-elf-gdb vmlinux
115  *    (gdb) set remotebaud 115200
116  *    (gdb) target remote /dev/ttyS1
117  *    ...at this point you are connected to
118  *       the remote target and can use gdb
119  *       in the normal fasion. Setting
120  *       breakpoints, single stepping,
121  *       printing variables, etc.
122  */
123 #include <linux/config.h>
124 #include <linux/string.h>
125 #include <linux/kernel.h>
126 #include <linux/signal.h>
127 #include <linux/sched.h>
128 #include <linux/mm.h>
129 #include <linux/console.h>
130 #include <linux/init.h>
131 #include <linux/smp.h>
132 #include <linux/spinlock.h>
133 #include <linux/slab.h>
134 #include <linux/reboot.h>
135
136 #include <asm/asm.h>
137 #include <asm/cacheflush.h>
138 #include <asm/mipsregs.h>
139 #include <asm/pgtable.h>
140 #include <asm/system.h>
141 #include <asm/gdb-stub.h>
142 #include <asm/inst.h>
143
144 /*
145  * external low-level support routines
146  */
147
148 extern int putDebugChar(char c);    /* write a single character      */
149 extern char getDebugChar(void);     /* read and return a single char */
150 extern void trap_low(void);
151
152 /*
153  * breakpoint and test functions
154  */
155 extern void breakpoint(void);
156 extern void breakinst(void);
157 extern void async_breakpoint(void);
158 extern void async_breakinst(void);
159 extern void adel(void);
160
161 /*
162  * local prototypes
163  */
164
165 static void getpacket(char *buffer);
166 static void putpacket(char *buffer);
167 static int computeSignal(int tt);
168 static int hex(unsigned char ch);
169 static int hexToInt(char **ptr, int *intValue);
170 static int hexToLong(char **ptr, long *longValue);
171 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault);
172 void handle_exception(struct gdb_regs *regs);
173
174 /*
175  * spin locks for smp case
176  */
177 static spinlock_t kgdb_lock = SPIN_LOCK_UNLOCKED;
178 static spinlock_t kgdb_cpulock[NR_CPUS] = { [0 ... NR_CPUS-1] = SPIN_LOCK_UNLOCKED};
179
180 /*
181  * BUFMAX defines the maximum number of characters in inbound/outbound buffers
182  * at least NUMREGBYTES*2 are needed for register packets
183  */
184 #define BUFMAX 2048
185
186 static char input_buffer[BUFMAX];
187 static char output_buffer[BUFMAX];
188 static int initialized; /* !0 means we've been initialized */
189 static int kgdb_started;
190 static const char hexchars[]="0123456789abcdef";
191
192 /* Used to prevent crashes in memory access.  Note that they'll crash anyway if
193    we haven't set up fault handlers yet... */
194 int kgdb_read_byte(unsigned char *address, unsigned char *dest);
195 int kgdb_write_byte(unsigned char val, unsigned char *dest);
196
197 /*
198  * Convert ch from a hex digit to an int
199  */
200 static int hex(unsigned char ch)
201 {
202         if (ch >= 'a' && ch <= 'f')
203                 return ch-'a'+10;
204         if (ch >= '0' && ch <= '9')
205                 return ch-'0';
206         if (ch >= 'A' && ch <= 'F')
207                 return ch-'A'+10;
208         return -1;
209 }
210
211 /*
212  * scan for the sequence $<data>#<checksum>
213  */
214 static void getpacket(char *buffer)
215 {
216         unsigned char checksum;
217         unsigned char xmitcsum;
218         int i;
219         int count;
220         unsigned char ch;
221
222         do {
223                 /*
224                  * wait around for the start character,
225                  * ignore all other characters
226                  */
227                 while ((ch = (getDebugChar() & 0x7f)) != '$') ;
228
229                 checksum = 0;
230                 xmitcsum = -1;
231                 count = 0;
232
233                 /*
234                  * now, read until a # or end of buffer is found
235                  */
236                 while (count < BUFMAX) {
237                         ch = getDebugChar();
238                         if (ch == '#')
239                                 break;
240                         checksum = checksum + ch;
241                         buffer[count] = ch;
242                         count = count + 1;
243                 }
244
245                 if (count >= BUFMAX)
246                         continue;
247
248                 buffer[count] = 0;
249
250                 if (ch == '#') {
251                         xmitcsum = hex(getDebugChar() & 0x7f) << 4;
252                         xmitcsum |= hex(getDebugChar() & 0x7f);
253
254                         if (checksum != xmitcsum)
255                                 putDebugChar('-');      /* failed checksum */
256                         else {
257                                 putDebugChar('+'); /* successful transfer */
258
259                                 /*
260                                  * if a sequence char is present,
261                                  * reply the sequence ID
262                                  */
263                                 if (buffer[2] == ':') {
264                                         putDebugChar(buffer[0]);
265                                         putDebugChar(buffer[1]);
266
267                                         /*
268                                          * remove sequence chars from buffer
269                                          */
270                                         count = strlen(buffer);
271                                         for (i=3; i <= count; i++)
272                                                 buffer[i-3] = buffer[i];
273                                 }
274                         }
275                 }
276         }
277         while (checksum != xmitcsum);
278 }
279
280 /*
281  * send the packet in buffer.
282  */
283 static void putpacket(char *buffer)
284 {
285         unsigned char checksum;
286         int count;
287         unsigned char ch;
288
289         /*
290          * $<packet info>#<checksum>.
291          */
292
293         do {
294                 putDebugChar('$');
295                 checksum = 0;
296                 count = 0;
297
298                 while ((ch = buffer[count]) != 0) {
299                         if (!(putDebugChar(ch)))
300                                 return;
301                         checksum += ch;
302                         count += 1;
303                 }
304
305                 putDebugChar('#');
306                 putDebugChar(hexchars[checksum >> 4]);
307                 putDebugChar(hexchars[checksum & 0xf]);
308
309         }
310         while ((getDebugChar() & 0x7f) != '+');
311 }
312
313
314 /*
315  * Convert the memory pointed to by mem into hex, placing result in buf.
316  * Return a pointer to the last char put in buf (null), in case of mem fault,
317  * return 0.
318  * may_fault is non-zero if we are reading from arbitrary memory, but is currently
319  * not used.
320  */
321 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault)
322 {
323         unsigned char ch;
324
325         while (count-- > 0) {
326                 if (kgdb_read_byte(mem++, &ch) != 0)
327                         return 0;
328                 *buf++ = hexchars[ch >> 4];
329                 *buf++ = hexchars[ch & 0xf];
330         }
331
332         *buf = 0;
333
334         return buf;
335 }
336
337 /*
338  * convert the hex array pointed to by buf into binary to be placed in mem
339  * return a pointer to the character AFTER the last byte written
340  * may_fault is non-zero if we are reading from arbitrary memory, but is currently
341  * not used.
342  */
343 static char *hex2mem(char *buf, char *mem, int count, int binary, int may_fault)
344 {
345         int i;
346         unsigned char ch;
347
348         for (i=0; i<count; i++)
349         {
350                 if (binary) {
351                         ch = *buf++;
352                         if (ch == 0x7d)
353                                 ch = 0x20 ^ *buf++;
354                 }
355                 else {
356                         ch = hex(*buf++) << 4;
357                         ch |= hex(*buf++);
358                 }
359                 if (kgdb_write_byte(ch, mem++) != 0)
360                         return 0;
361         }
362
363         return mem;
364 }
365
366 /*
367  * This table contains the mapping between SPARC hardware trap types, and
368  * signals, which are primarily what GDB understands.  It also indicates
369  * which hardware traps we need to commandeer when initializing the stub.
370  */
371 static struct hard_trap_info {
372         unsigned char tt;               /* Trap type code for MIPS R3xxx and R4xxx */
373         unsigned char signo;            /* Signal that we map this trap into */
374 } hard_trap_info[] = {
375         { 6, SIGBUS },                  /* instruction bus error */
376         { 7, SIGBUS },                  /* data bus error */
377         { 9, SIGTRAP },                 /* break */
378         { 10, SIGILL },                 /* reserved instruction */
379 /*      { 11, SIGILL },         */      /* CPU unusable */
380         { 12, SIGFPE },                 /* overflow */
381         { 13, SIGTRAP },                /* trap */
382         { 14, SIGSEGV },                /* virtual instruction cache coherency */
383         { 15, SIGFPE },                 /* floating point exception */
384         { 23, SIGSEGV },                /* watch */
385         { 31, SIGSEGV },                /* virtual data cache coherency */
386         { 0, 0}                         /* Must be last */
387 };
388
389 /* Save the normal trap handlers for user-mode traps. */
390 void *saved_vectors[32];
391
392 /*
393  * Set up exception handlers for tracing and breakpoints
394  */
395 void set_debug_traps(void)
396 {
397         struct hard_trap_info *ht;
398         unsigned long flags;
399         unsigned char c;
400
401         local_irq_save(flags);
402         for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
403                 saved_vectors[ht->tt] = set_except_vector(ht->tt, trap_low);
404
405         putDebugChar('+'); /* 'hello world' */
406         /*
407          * In case GDB is started before us, ack any packets
408          * (presumably "$?#xx") sitting there.
409          */
410         while((c = getDebugChar()) != '$');
411         while((c = getDebugChar()) != '#');
412         c = getDebugChar(); /* eat first csum byte */
413         c = getDebugChar(); /* eat second csum byte */
414         putDebugChar('+'); /* ack it */
415
416         initialized = 1;
417         local_irq_restore(flags);
418 }
419
420 void restore_debug_traps(void)
421 {
422         struct hard_trap_info *ht;
423         unsigned long flags;
424
425         local_irq_save(flags);
426         for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
427                 set_except_vector(ht->tt, saved_vectors[ht->tt]);
428         local_irq_restore(flags);
429 }
430
431 /*
432  * Convert the MIPS hardware trap type code to a Unix signal number.
433  */
434 static int computeSignal(int tt)
435 {
436         struct hard_trap_info *ht;
437
438         for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
439                 if (ht->tt == tt)
440                         return ht->signo;
441
442         return SIGHUP;          /* default for things we don't know about */
443 }
444
445 /*
446  * While we find nice hex chars, build an int.
447  * Return number of chars processed.
448  */
449 static int hexToInt(char **ptr, int *intValue)
450 {
451         int numChars = 0;
452         int hexValue;
453
454         *intValue = 0;
455
456         while (**ptr) {
457                 hexValue = hex(**ptr);
458                 if (hexValue < 0)
459                         break;
460
461                 *intValue = (*intValue << 4) | hexValue;
462                 numChars ++;
463
464                 (*ptr)++;
465         }
466
467         return (numChars);
468 }
469
470 static int hexToLong(char **ptr, long *longValue)
471 {
472         int numChars = 0;
473         int hexValue;
474
475         *longValue = 0;
476
477         while (**ptr) {
478                 hexValue = hex(**ptr);
479                 if (hexValue < 0)
480                         break;
481
482                 *longValue = (*longValue << 4) | hexValue;
483                 numChars ++;
484
485                 (*ptr)++;
486         }
487
488         return numChars;
489 }
490
491
492 #if 0
493 /*
494  * Print registers (on target console)
495  * Used only to debug the stub...
496  */
497 void show_gdbregs(struct gdb_regs * regs)
498 {
499         /*
500          * Saved main processor registers
501          */
502         printk("$0 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
503                regs->reg0, regs->reg1, regs->reg2, regs->reg3,
504                regs->reg4, regs->reg5, regs->reg6, regs->reg7);
505         printk("$8 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
506                regs->reg8, regs->reg9, regs->reg10, regs->reg11,
507                regs->reg12, regs->reg13, regs->reg14, regs->reg15);
508         printk("$16: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
509                regs->reg16, regs->reg17, regs->reg18, regs->reg19,
510                regs->reg20, regs->reg21, regs->reg22, regs->reg23);
511         printk("$24: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
512                regs->reg24, regs->reg25, regs->reg26, regs->reg27,
513                regs->reg28, regs->reg29, regs->reg30, regs->reg31);
514
515         /*
516          * Saved cp0 registers
517          */
518         printk("epc  : %08lx\nStatus: %08lx\nCause : %08lx\n",
519                regs->cp0_epc, regs->cp0_status, regs->cp0_cause);
520 }
521 #endif /* dead code */
522
523 /*
524  * We single-step by setting breakpoints. When an exception
525  * is handled, we need to restore the instructions hoisted
526  * when the breakpoints were set.
527  *
528  * This is where we save the original instructions.
529  */
530 static struct gdb_bp_save {
531         unsigned long addr;
532         unsigned int val;
533 } step_bp[2];
534
535 #define BP 0x0000000d  /* break opcode */
536
537 /*
538  * Set breakpoint instructions for single stepping.
539  */
540 static void single_step(struct gdb_regs *regs)
541 {
542         union mips_instruction insn;
543         unsigned long targ;
544         int is_branch, is_cond, i;
545
546         targ = regs->cp0_epc;
547         insn.word = *(unsigned int *)targ;
548         is_branch = is_cond = 0;
549
550         switch (insn.i_format.opcode) {
551         /*
552          * jr and jalr are in r_format format.
553          */
554         case spec_op:
555                 switch (insn.r_format.func) {
556                 case jalr_op:
557                 case jr_op:
558                         targ = *(&regs->reg0 + insn.r_format.rs);
559                         is_branch = 1;
560                         break;
561                 }
562                 break;
563
564         /*
565          * This group contains:
566          * bltz_op, bgez_op, bltzl_op, bgezl_op,
567          * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
568          */
569         case bcond_op:
570                 is_branch = is_cond = 1;
571                 targ += 4 + (insn.i_format.simmediate << 2);
572                 break;
573
574         /*
575          * These are unconditional and in j_format.
576          */
577         case jal_op:
578         case j_op:
579                 is_branch = 1;
580                 targ += 4;
581                 targ >>= 28;
582                 targ <<= 28;
583                 targ |= (insn.j_format.target << 2);
584                 break;
585
586         /*
587          * These are conditional.
588          */
589         case beq_op:
590         case beql_op:
591         case bne_op:
592         case bnel_op:
593         case blez_op:
594         case blezl_op:
595         case bgtz_op:
596         case bgtzl_op:
597         case cop0_op:
598         case cop1_op:
599         case cop2_op:
600         case cop1x_op:
601                 is_branch = is_cond = 1;
602                 targ += 4 + (insn.i_format.simmediate << 2);
603                 break;
604         }
605
606         if (is_branch) {
607                 i = 0;
608                 if (is_cond && targ != (regs->cp0_epc + 8)) {
609                         step_bp[i].addr = regs->cp0_epc + 8;
610                         step_bp[i++].val = *(unsigned *)(regs->cp0_epc + 8);
611                         *(unsigned *)(regs->cp0_epc + 8) = BP;
612                 }
613                 step_bp[i].addr = targ;
614                 step_bp[i].val  = *(unsigned *)targ;
615                 *(unsigned *)targ = BP;
616         } else {
617                 step_bp[0].addr = regs->cp0_epc + 4;
618                 step_bp[0].val  = *(unsigned *)(regs->cp0_epc + 4);
619                 *(unsigned *)(regs->cp0_epc + 4) = BP;
620         }
621 }
622
623 /*
624  *  If asynchronously interrupted by gdb, then we need to set a breakpoint
625  *  at the interrupted instruction so that we wind up stopped with a
626  *  reasonable stack frame.
627  */
628 static struct gdb_bp_save async_bp;
629
630 /*
631  * Swap the interrupted EPC with our asynchronous breakpoint routine.
632  * This is safer than stuffing the breakpoint in-place, since no cache
633  * flushes (or resulting smp_call_functions) are required.  The
634  * assumption is that only one CPU will be handling asynchronous bp's,
635  * and only one can be active at a time.
636  */
637 extern spinlock_t smp_call_lock;
638 void set_async_breakpoint(unsigned long *epc)
639 {
640         /* skip breaking into userland */
641         if ((*epc & 0x80000000) == 0)
642                 return;
643
644         /* avoid deadlock if someone is make IPC */
645         if (spin_is_locked(&smp_call_lock))
646                 return;
647
648         async_bp.addr = *epc;
649         *epc = (unsigned long)async_breakpoint;
650 }
651
652 void kgdb_wait(void *arg)
653 {
654         unsigned flags;
655         int cpu = smp_processor_id();
656
657         local_irq_save(flags);
658
659         spin_lock(&kgdb_cpulock[cpu]);
660         spin_unlock(&kgdb_cpulock[cpu]);
661
662         local_irq_restore(flags);
663 }
664
665
666 /*
667  * This function does all command processing for interfacing to gdb.  It
668  * returns 1 if you should skip the instruction at the trap address, 0
669  * otherwise.
670  */
671 void handle_exception (struct gdb_regs *regs)
672 {
673         int trap;                       /* Trap type */
674         int sigval;
675         long addr;
676         int length;
677         char *ptr;
678         unsigned long *stack;
679         int i;
680         int bflag = 0;
681
682         kgdb_started = 1;
683
684         /*
685          * acquire the big kgdb spinlock
686          */
687         if (!spin_trylock(&kgdb_lock)) {
688                 /* 
689                  * some other CPU has the lock, we should go back to 
690                  * receive the gdb_wait IPC
691                  */
692                 return;
693         }
694
695         /*
696          * If we're in async_breakpoint(), restore the real EPC from
697          * the breakpoint.
698          */
699         if (regs->cp0_epc == (unsigned long)async_breakinst) {
700                 regs->cp0_epc = async_bp.addr;
701                 async_bp.addr = 0;
702         }
703
704         /* 
705          * acquire the CPU spinlocks
706          */
707         for (i = num_online_cpus()-1; i >= 0; i--)
708                 if (spin_trylock(&kgdb_cpulock[i]) == 0)
709                         panic("kgdb: couldn't get cpulock %d\n", i);
710
711         /*
712          * force other cpus to enter kgdb
713          */
714         smp_call_function(kgdb_wait, NULL, 0, 0);
715
716         /*
717          * If we're in breakpoint() increment the PC
718          */
719         trap = (regs->cp0_cause & 0x7c) >> 2;
720         if (trap == 9 && regs->cp0_epc == (unsigned long)breakinst)
721                 regs->cp0_epc += 4;
722
723         /*
724          * If we were single_stepping, restore the opcodes hoisted
725          * for the breakpoint[s].
726          */
727         if (step_bp[0].addr) {
728                 *(unsigned *)step_bp[0].addr = step_bp[0].val;
729                 step_bp[0].addr = 0;
730
731                 if (step_bp[1].addr) {
732                         *(unsigned *)step_bp[1].addr = step_bp[1].val;
733                         step_bp[1].addr = 0;
734                 }
735         }
736
737         stack = (long *)regs->reg29;                    /* stack ptr */
738         sigval = computeSignal(trap);
739
740         /*
741          * reply to host that an exception has occurred
742          */
743         ptr = output_buffer;
744
745         /*
746          * Send trap type (converted to signal)
747          */
748         *ptr++ = 'T';
749         *ptr++ = hexchars[sigval >> 4];
750         *ptr++ = hexchars[sigval & 0xf];
751
752         /*
753          * Send Error PC
754          */
755         *ptr++ = hexchars[REG_EPC >> 4];
756         *ptr++ = hexchars[REG_EPC & 0xf];
757         *ptr++ = ':';
758         ptr = mem2hex((char *)&regs->cp0_epc, ptr, sizeof(long), 0);
759         *ptr++ = ';';
760
761         /*
762          * Send frame pointer
763          */
764         *ptr++ = hexchars[REG_FP >> 4];
765         *ptr++ = hexchars[REG_FP & 0xf];
766         *ptr++ = ':';
767         ptr = mem2hex((char *)&regs->reg30, ptr, sizeof(long), 0);
768         *ptr++ = ';';
769
770         /*
771          * Send stack pointer
772          */
773         *ptr++ = hexchars[REG_SP >> 4];
774         *ptr++ = hexchars[REG_SP & 0xf];
775         *ptr++ = ':';
776         ptr = mem2hex((char *)&regs->reg29, ptr, sizeof(long), 0);
777         *ptr++ = ';';
778
779         *ptr++ = 0;
780         putpacket(output_buffer);       /* send it off... */
781
782         /*
783          * Wait for input from remote GDB
784          */
785         while (1) {
786                 output_buffer[0] = 0;
787                 getpacket(input_buffer);
788
789                 switch (input_buffer[0])
790                 {
791                 case '?':
792                         output_buffer[0] = 'S';
793                         output_buffer[1] = hexchars[sigval >> 4];
794                         output_buffer[2] = hexchars[sigval & 0xf];
795                         output_buffer[3] = 0;
796                         break;
797
798                 /*
799                  * Detach debugger; let CPU run
800                  */
801                 case 'D':
802                         putpacket(output_buffer);
803                         goto finish_kgdb;
804                         break;
805
806                 case 'd':
807                         /* toggle debug flag */
808                         break;
809
810                 /*
811                  * Return the value of the CPU registers
812                  */
813                 case 'g':
814                         ptr = output_buffer;
815                         ptr = mem2hex((char *)&regs->reg0, ptr, 32*sizeof(long), 0); /* r0...r31 */
816                         ptr = mem2hex((char *)&regs->cp0_status, ptr, 6*sizeof(long), 0); /* cp0 */
817                         ptr = mem2hex((char *)&regs->fpr0, ptr, 32*sizeof(long), 0); /* f0...31 */
818                         ptr = mem2hex((char *)&regs->cp1_fsr, ptr, 2*sizeof(long), 0); /* cp1 */
819                         ptr = mem2hex((char *)&regs->frame_ptr, ptr, 2*sizeof(long), 0); /* frp */
820                         ptr = mem2hex((char *)&regs->cp0_index, ptr, 16*sizeof(long), 0); /* cp0 */
821                         break;
822
823                 /*
824                  * set the value of the CPU registers - return OK
825                  */
826                 case 'G':
827                 {
828                         ptr = &input_buffer[1];
829                         hex2mem(ptr, (char *)&regs->reg0, 32*sizeof(long), 0, 0);
830                         ptr += 32*(2*sizeof(long));
831                         hex2mem(ptr, (char *)&regs->cp0_status, 6*sizeof(long), 0, 0);
832                         ptr += 6*(2*sizeof(long));
833                         hex2mem(ptr, (char *)&regs->fpr0, 32*sizeof(long), 0, 0);
834                         ptr += 32*(2*sizeof(long));
835                         hex2mem(ptr, (char *)&regs->cp1_fsr, 2*sizeof(long), 0, 0);
836                         ptr += 2*(2*sizeof(long));
837                         hex2mem(ptr, (char *)&regs->frame_ptr, 2*sizeof(long), 0, 0);
838                         ptr += 2*(2*sizeof(long));
839                         hex2mem(ptr, (char *)&regs->cp0_index, 16*sizeof(long), 0, 0);
840                         strcpy(output_buffer,"OK");
841                  }
842                 break;
843
844                 /*
845                  * mAA..AA,LLLL  Read LLLL bytes at address AA..AA
846                  */
847                 case 'm':
848                         ptr = &input_buffer[1];
849
850                         if (hexToLong(&ptr, &addr)
851                                 && *ptr++ == ','
852                                 && hexToInt(&ptr, &length)) {
853                                 if (mem2hex((char *)addr, output_buffer, length, 1))
854                                         break;
855                                 strcpy (output_buffer, "E03");
856                         } else
857                                 strcpy(output_buffer,"E01");
858                         break;
859
860                 /*
861                  * XAA..AA,LLLL: Write LLLL escaped binary bytes at address AA.AA
862                  */
863                 case 'X':
864                         bflag = 1;
865                         /* fall through */
866
867                 /*
868                  * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
869                  */
870                 case 'M':
871                         ptr = &input_buffer[1];
872
873                         if (hexToLong(&ptr, &addr)
874                                 && *ptr++ == ','
875                                 && hexToInt(&ptr, &length)
876                                 && *ptr++ == ':') {
877                                 if (hex2mem(ptr, (char *)addr, length, bflag, 1))
878                                         strcpy(output_buffer, "OK");
879                                 else
880                                         strcpy(output_buffer, "E03");
881                         }
882                         else
883                                 strcpy(output_buffer, "E02");
884                         break;
885
886                 /*
887                  * cAA..AA    Continue at address AA..AA(optional)
888                  */
889                 case 'c':
890                         /* try to read optional parameter, pc unchanged if no parm */
891
892                         ptr = &input_buffer[1];
893                         if (hexToLong(&ptr, &addr))
894                                 regs->cp0_epc = addr;
895           
896                         goto exit_kgdb_exception;
897                         break;
898
899                 /*
900                  * kill the program; let us try to restart the machine
901                  * Reset the whole machine.
902                  */
903                 case 'k':
904                 case 'r':
905                         machine_restart("kgdb restarts machine");
906                         break;
907
908                 /*
909                  * Step to next instruction
910                  */
911                 case 's':
912                         /*
913                          * There is no single step insn in the MIPS ISA, so we
914                          * use breakpoints and continue, instead.
915                          */
916                         single_step(regs);
917                         goto exit_kgdb_exception;
918                         /* NOTREACHED */
919                         break;
920
921                 /*
922                  * Set baud rate (bBB)
923                  * FIXME: Needs to be written
924                  */
925                 case 'b':
926                 {
927 #if 0
928                         int baudrate;
929                         extern void set_timer_3();
930
931                         ptr = &input_buffer[1];
932                         if (!hexToInt(&ptr, &baudrate))
933                         {
934                                 strcpy(output_buffer,"B01");
935                                 break;
936                         }
937
938                         /* Convert baud rate to uart clock divider */
939
940                         switch (baudrate)
941                         {
942                                 case 38400:
943                                         baudrate = 16;
944                                         break;
945                                 case 19200:
946                                         baudrate = 33;
947                                         break;
948                                 case 9600:
949                                         baudrate = 65;
950                                         break;
951                                 default:
952                                         baudrate = 0;
953                                         strcpy(output_buffer,"B02");
954                                         goto x1;
955                         }
956
957                         if (baudrate) {
958                                 putpacket("OK");        /* Ack before changing speed */
959                                 set_timer_3(baudrate); /* Set it */
960                         }
961 #endif
962                 }
963                 break;
964
965                 }                       /* switch */
966
967                 /*
968                  * reply to the request
969                  */
970
971                 putpacket(output_buffer);
972
973         } /* while */
974
975         return;
976
977 finish_kgdb:
978         restore_debug_traps();
979
980 exit_kgdb_exception:
981         /* release locks so other CPUs can go */
982         for (i = num_online_cpus()-1; i >= 0; i--)
983                 spin_unlock(&kgdb_cpulock[i]);
984         spin_unlock(&kgdb_lock);
985
986         __flush_cache_all();
987         return;
988 }
989
990 /*
991  * This function will generate a breakpoint exception.  It is used at the
992  * beginning of a program to sync up with a debugger and can be used
993  * otherwise as a quick means to stop program execution and "break" into
994  * the debugger.
995  */
996 void breakpoint(void)
997 {
998         if (!initialized)
999                 return;
1000
1001         __asm__ __volatile__(
1002                         ".globl breakinst\n\t" 
1003                         ".set\tnoreorder\n\t"
1004                         "nop\n"
1005                         "breakinst:\tbreak\n\t"
1006                         "nop\n\t"
1007                         ".set\treorder"
1008                         );
1009 }
1010
1011 /* Nothing but the break; don't pollute any registers */
1012 void async_breakpoint(void)
1013 {
1014         __asm__ __volatile__(
1015                         ".globl async_breakinst\n\t" 
1016                         ".set\tnoreorder\n\t"
1017                         "nop\n"
1018                         "async_breakinst:\tbreak\n\t"
1019                         "nop\n\t"
1020                         ".set\treorder"
1021                         );
1022 }
1023
1024 void adel(void)
1025 {
1026         __asm__ __volatile__(
1027                         ".globl\tadel\n\t"
1028                         "lui\t$8,0x8000\n\t"
1029                         "lw\t$9,1($8)\n\t"
1030                         );
1031 }
1032
1033 /*
1034  * malloc is needed by gdb client in "call func()", even a private one
1035  * will make gdb happy
1036  */
1037 static void *malloc(size_t size)
1038 {
1039         return kmalloc(size, GFP_ATOMIC);
1040 }
1041
1042 static void free(void *where)
1043 {
1044         kfree(where);
1045 }
1046
1047 #ifdef CONFIG_GDB_CONSOLE
1048
1049 void gdb_putsn(const char *str, int l)
1050 {
1051         char outbuf[18];
1052
1053         if (!kgdb_started)
1054                 return;
1055
1056         outbuf[0]='O';
1057
1058         while(l) {
1059                 int i = (l>8)?8:l;
1060                 mem2hex((char *)str, &outbuf[1], i, 0);
1061                 outbuf[(i*2)+1]=0;
1062                 putpacket(outbuf);
1063                 str += i;
1064                 l -= i;
1065         }
1066 }
1067
1068 static void gdb_console_write(struct console *con, const char *s, unsigned n)
1069 {
1070         gdb_putsn(s, n);
1071 }
1072
1073 static struct console gdb_console = {
1074         .name   = "gdb",
1075         .write  = gdb_console_write,
1076         .flags  = CON_PRINTBUFFER,
1077         .index  = -1
1078 };
1079
1080 static int __init register_gdb_console(void)
1081 {
1082         register_console(&gdb_console);
1083
1084         return 0;
1085 }
1086
1087 console_initcall(register_gdb_console);
1088
1089 #endif