2 * arch/mips/kernel/gdb-stub.c
4 * Originally written by Glenn Engel, Lake Stevens Instrument Division
6 * Contributed by HP Systems
8 * Modified for SPARC by Stu Grossman, Cygnus Support.
10 * Modified for Linux/MIPS (and MIPS in general) by Andreas Busse
11 * Send complaints, suggestions etc. to <andy@waldorf-gmbh.de>
13 * Copyright (C) 1995 Andreas Busse
17 * To enable debugger support, two things need to happen. One, a
18 * call to set_debug_traps() is necessary in order to allow any breakpoints
19 * or error conditions to be properly intercepted and reported to gdb.
20 * Two, a breakpoint needs to be generated to begin communication. This
21 * is most easily accomplished by a call to breakpoint(). Breakpoint()
22 * simulates a breakpoint by executing a BREAK instruction.
25 * The following gdb commands are supported:
27 * command function Return value
29 * g return the value of the CPU registers hex data or ENN
30 * G set the value of the CPU registers OK or ENN
32 * mAA..AA,LLLL Read LLLL bytes at address AA..AA hex data or ENN
33 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA OK or ENN
35 * c Resume at current address SNN ( signal NN)
36 * cAA..AA Continue at address AA..AA SNN
38 * s Step one instruction SNN
39 * sAA..AA Step one instruction from AA..AA SNN
43 * ? What was the last sigval ? SNN (signal NN)
45 * bBB..BB Set baud rate to BB..BB OK or BNN, then sets
48 * All commands and responses are sent with a packet which includes a
49 * checksum. A packet consists of
51 * $<packet info>#<checksum>.
54 * <packet info> :: <characters representing the command or response>
55 * <checksum> :: < two hex digits computed as modulo 256 sum of <packetinfo>>
57 * When a packet is received, it is first acknowledged with either '+' or '-'.
58 * '+' indicates a successful transfer. '-' indicates a failed transfer.
63 * $m0,10#2a +$00010203040506070809101112131415#42
70 * For reference -- the following are the steps that one
71 * company took (RidgeRun Inc) to get remote gdb debugging
72 * going. In this scenario the host machine was a PC and the
73 * target platform was a Galileo EVB64120A MIPS evaluation
77 * First download gdb-5.0.tar.gz from the internet.
78 * and then build/install the package.
81 * $ tar zxf gdb-5.0.tar.gz
83 * $ ./configure --target=mips-linux-elf
86 * $ which mips-linux-elf-gdb
87 * /usr/local/bin/mips-linux-elf-gdb
90 * Configure linux for remote debugging and build it.
94 * $ make menuconfig <go to "Kernel Hacking" and turn on remote debugging>
95 * $ make dep; make vmlinux
98 * Download the kernel to the remote target and start
99 * the kernel running. It will promptly halt and wait
100 * for the host gdb session to connect. It does this
101 * since the "Kernel Hacking" option has defined
102 * CONFIG_KGDB which in turn enables your calls
108 * Start the gdb session on the host.
111 * $ mips-linux-elf-gdb vmlinux
112 * (gdb) set remotebaud 115200
113 * (gdb) target remote /dev/ttyS1
114 * ...at this point you are connected to
115 * the remote target and can use gdb
116 * in the normal fasion. Setting
117 * breakpoints, single stepping,
118 * printing variables, etc.
120 #include <linux/config.h>
121 #include <linux/string.h>
122 #include <linux/kernel.h>
123 #include <linux/signal.h>
124 #include <linux/sched.h>
125 #include <linux/mm.h>
126 #include <linux/console.h>
127 #include <linux/init.h>
128 #include <linux/slab.h>
129 #include <linux/reboot.h>
132 #include <asm/mipsregs.h>
133 #include <asm/pgtable.h>
134 #include <asm/system.h>
135 #include <asm/gdb-stub.h>
136 #include <asm/inst.h>
139 * external low-level support routines
142 extern int putDebugChar(char c); /* write a single character */
143 extern char getDebugChar(void); /* read and return a single char */
144 extern void trap_low(void);
147 * breakpoint and test functions
149 extern void breakpoint(void);
150 extern void breakinst(void);
151 extern void adel(void);
157 static void getpacket(char *buffer);
158 static void putpacket(char *buffer);
159 static int computeSignal(int tt);
160 static int hex(unsigned char ch);
161 static int hexToInt(char **ptr, int *intValue);
162 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault);
163 void handle_exception(struct gdb_regs *regs);
166 * BUFMAX defines the maximum number of characters in inbound/outbound buffers
167 * at least NUMREGBYTES*2 are needed for register packets
171 static char input_buffer[BUFMAX];
172 static char output_buffer[BUFMAX];
173 static int initialized; /* !0 means we've been initialized */
174 static const char hexchars[]="0123456789abcdef";
176 /* Used to prevent crashes in memory access. Note that they'll crash anyway if
177 we haven't set up fault handlers yet... */
178 int kgdb_read_byte(unsigned char *address, unsigned char *dest);
179 int kgdb_write_byte(unsigned char val, unsigned char *dest);
182 * Convert ch from a hex digit to an int
184 static int hex(unsigned char ch)
186 if (ch >= 'a' && ch <= 'f')
188 if (ch >= '0' && ch <= '9')
190 if (ch >= 'A' && ch <= 'F')
196 * scan for the sequence $<data>#<checksum>
198 static void getpacket(char *buffer)
200 unsigned char checksum;
201 unsigned char xmitcsum;
208 * wait around for the start character,
209 * ignore all other characters
211 while ((ch = (getDebugChar() & 0x7f)) != '$') ;
218 * now, read until a # or end of buffer is found
220 while (count < BUFMAX) {
221 ch = getDebugChar() & 0x7f;
224 checksum = checksum + ch;
235 xmitcsum = hex(getDebugChar() & 0x7f) << 4;
236 xmitcsum |= hex(getDebugChar() & 0x7f);
238 if (checksum != xmitcsum)
239 putDebugChar('-'); /* failed checksum */
241 putDebugChar('+'); /* successful transfer */
244 * if a sequence char is present,
245 * reply the sequence ID
247 if (buffer[2] == ':') {
248 putDebugChar(buffer[0]);
249 putDebugChar(buffer[1]);
252 * remove sequence chars from buffer
254 count = strlen(buffer);
255 for (i=3; i <= count; i++)
256 buffer[i-3] = buffer[i];
261 while (checksum != xmitcsum);
265 * send the packet in buffer.
267 static void putpacket(char *buffer)
269 unsigned char checksum;
274 * $<packet info>#<checksum>.
282 while ((ch = buffer[count]) != 0) {
283 if (!(putDebugChar(ch)))
290 putDebugChar(hexchars[checksum >> 4]);
291 putDebugChar(hexchars[checksum & 0xf]);
294 while ((getDebugChar() & 0x7f) != '+');
299 * Convert the memory pointed to by mem into hex, placing result in buf.
300 * Return a pointer to the last char put in buf (null), in case of mem fault,
302 * may_fault is non-zero if we are reading from arbitrary memory, but is currently
305 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault)
309 while (count-- > 0) {
310 if (kgdb_read_byte(mem++, &ch) != 0)
312 *buf++ = hexchars[ch >> 4];
313 *buf++ = hexchars[ch & 0xf];
322 * convert the hex array pointed to by buf into binary to be placed in mem
323 * return a pointer to the character AFTER the last byte written
324 * may_fault is non-zero if we are reading from arbitrary memory, but is currently
327 static char *hex2mem(char *buf, char *mem, int count, int may_fault)
332 for (i=0; i<count; i++)
334 ch = hex(*buf++) << 4;
336 if (kgdb_write_byte(ch, mem++) != 0)
344 * This table contains the mapping between SPARC hardware trap types, and
345 * signals, which are primarily what GDB understands. It also indicates
346 * which hardware traps we need to commandeer when initializing the stub.
348 static struct hard_trap_info {
349 unsigned char tt; /* Trap type code for MIPS R3xxx and R4xxx */
350 unsigned char signo; /* Signal that we map this trap into */
351 } hard_trap_info[] = {
352 { 6, SIGBUS }, /* instruction bus error */
353 { 7, SIGBUS }, /* data bus error */
354 { 9, SIGTRAP }, /* break */
355 { 10, SIGILL }, /* reserved instruction */
356 /* { 11, SIGILL }, */ /* CPU unusable */
357 { 12, SIGFPE }, /* overflow */
358 { 13, SIGTRAP }, /* trap */
359 { 14, SIGSEGV }, /* virtual instruction cache coherency */
360 { 15, SIGFPE }, /* floating point exception */
361 { 23, SIGSEGV }, /* watch */
362 { 31, SIGSEGV }, /* virtual data cache coherency */
363 { 0, 0} /* Must be last */
366 /* Save the normal trap handlers for user-mode traps. */
367 void *saved_vectors[32];
370 * Set up exception handlers for tracing and breakpoints
372 void set_debug_traps(void)
374 struct hard_trap_info *ht;
378 local_irq_save(flags);
379 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
380 saved_vectors[ht->tt] = set_except_vector(ht->tt, trap_low);
382 putDebugChar('+'); /* 'hello world' */
384 * In case GDB is started before us, ack any packets
385 * (presumably "$?#xx") sitting there.
387 while((c = getDebugChar()) != '$');
388 while((c = getDebugChar()) != '#');
389 c = getDebugChar(); /* eat first csum byte */
390 c = getDebugChar(); /* eat second csum byte */
391 putDebugChar('+'); /* ack it */
394 local_irq_restore(flags);
398 * Convert the MIPS hardware trap type code to a Unix signal number.
400 static int computeSignal(int tt)
402 struct hard_trap_info *ht;
404 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
408 return SIGHUP; /* default for things we don't know about */
412 * While we find nice hex chars, build an int.
413 * Return number of chars processed.
415 static int hexToInt(char **ptr, int *intValue)
423 hexValue = hex(**ptr);
427 *intValue = (*intValue << 4) | hexValue;
439 * Print registers (on target console)
440 * Used only to debug the stub...
442 void show_gdbregs(struct gdb_regs * regs)
445 * Saved main processor registers
447 printk("$0 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
448 regs->reg0, regs->reg1, regs->reg2, regs->reg3,
449 regs->reg4, regs->reg5, regs->reg6, regs->reg7);
450 printk("$8 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
451 regs->reg8, regs->reg9, regs->reg10, regs->reg11,
452 regs->reg12, regs->reg13, regs->reg14, regs->reg15);
453 printk("$16: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
454 regs->reg16, regs->reg17, regs->reg18, regs->reg19,
455 regs->reg20, regs->reg21, regs->reg22, regs->reg23);
456 printk("$24: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
457 regs->reg24, regs->reg25, regs->reg26, regs->reg27,
458 regs->reg28, regs->reg29, regs->reg30, regs->reg31);
461 * Saved cp0 registers
463 printk("epc : %08lx\nStatus: %08lx\nCause : %08lx\n",
464 regs->cp0_epc, regs->cp0_status, regs->cp0_cause);
466 #endif /* dead code */
469 * We single-step by setting breakpoints. When an exception
470 * is handled, we need to restore the instructions hoisted
471 * when the breakpoints were set.
473 * This is where we save the original instructions.
475 static struct gdb_bp_save {
480 #define BP 0x0000000d /* break opcode */
483 * Set breakpoint instructions for single stepping.
485 static void single_step(struct gdb_regs *regs)
487 union mips_instruction insn;
489 int is_branch, is_cond, i;
491 targ = regs->cp0_epc;
492 insn.word = *(unsigned int *)targ;
493 is_branch = is_cond = 0;
495 switch (insn.i_format.opcode) {
497 * jr and jalr are in r_format format.
500 switch (insn.r_format.func) {
503 targ = *(®s->reg0 + insn.r_format.rs);
510 * This group contains:
511 * bltz_op, bgez_op, bltzl_op, bgezl_op,
512 * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
515 is_branch = is_cond = 1;
516 targ += 4 + (insn.i_format.simmediate << 2);
520 * These are unconditional and in j_format.
528 targ |= (insn.j_format.target << 2);
532 * These are conditional.
546 is_branch = is_cond = 1;
547 targ += 4 + (insn.i_format.simmediate << 2);
553 if (is_cond && targ != (regs->cp0_epc + 8)) {
554 step_bp[i].addr = regs->cp0_epc + 8;
555 step_bp[i++].val = *(unsigned *)(regs->cp0_epc + 8);
556 *(unsigned *)(regs->cp0_epc + 8) = BP;
558 step_bp[i].addr = targ;
559 step_bp[i].val = *(unsigned *)targ;
560 *(unsigned *)targ = BP;
562 step_bp[0].addr = regs->cp0_epc + 4;
563 step_bp[0].val = *(unsigned *)(regs->cp0_epc + 4);
564 *(unsigned *)(regs->cp0_epc + 4) = BP;
569 * If asynchronously interrupted by gdb, then we need to set a breakpoint
570 * at the interrupted instruction so that we wind up stopped with a
571 * reasonable stack frame.
573 static struct gdb_bp_save async_bp;
575 void set_async_breakpoint(unsigned int epc)
578 async_bp.val = *(unsigned *)epc;
579 *(unsigned *)epc = BP;
585 * This function does all command processing for interfacing to gdb. It
586 * returns 1 if you should skip the instruction at the trap address, 0
589 void handle_exception (struct gdb_regs *regs)
591 int trap; /* Trap type */
596 unsigned long *stack;
599 * If we're in breakpoint() increment the PC
601 trap = (regs->cp0_cause & 0x7c) >> 2;
602 if (trap == 9 && regs->cp0_epc == (unsigned long)breakinst)
606 * If we were single_stepping, restore the opcodes hoisted
607 * for the breakpoint[s].
609 if (step_bp[0].addr) {
610 *(unsigned *)step_bp[0].addr = step_bp[0].val;
613 if (step_bp[1].addr) {
614 *(unsigned *)step_bp[1].addr = step_bp[1].val;
620 * If we were interrupted asynchronously by gdb, then a
621 * breakpoint was set at the EPC of the interrupt so
622 * that we'd wind up here with an interesting stack frame.
625 *(unsigned *)async_bp.addr = async_bp.val;
629 stack = (long *)regs->reg29; /* stack ptr */
630 sigval = computeSignal(trap);
633 * reply to host that an exception has occurred
638 * Send trap type (converted to signal)
641 *ptr++ = hexchars[sigval >> 4];
642 *ptr++ = hexchars[sigval & 0xf];
647 *ptr++ = hexchars[REG_EPC >> 4];
648 *ptr++ = hexchars[REG_EPC & 0xf];
650 ptr = mem2hex((char *)®s->cp0_epc, ptr, 4, 0);
656 *ptr++ = hexchars[REG_FP >> 4];
657 *ptr++ = hexchars[REG_FP & 0xf];
659 ptr = mem2hex((char *)®s->reg30, ptr, 4, 0);
665 *ptr++ = hexchars[REG_SP >> 4];
666 *ptr++ = hexchars[REG_SP & 0xf];
668 ptr = mem2hex((char *)®s->reg29, ptr, 4, 0);
672 putpacket(output_buffer); /* send it off... */
675 * Wait for input from remote GDB
678 output_buffer[0] = 0;
679 getpacket(input_buffer);
681 switch (input_buffer[0])
684 output_buffer[0] = 'S';
685 output_buffer[1] = hexchars[sigval >> 4];
686 output_buffer[2] = hexchars[sigval & 0xf];
687 output_buffer[3] = 0;
691 /* detach; let CPU run */
692 putpacket(output_buffer);
696 /* toggle debug flag */
700 * Return the value of the CPU registers
704 ptr = mem2hex((char *)®s->reg0, ptr, 32*4, 0); /* r0...r31 */
705 ptr = mem2hex((char *)®s->cp0_status, ptr, 6*4, 0); /* cp0 */
706 ptr = mem2hex((char *)®s->fpr0, ptr, 32*4, 0); /* f0...31 */
707 ptr = mem2hex((char *)®s->cp1_fsr, ptr, 2*4, 0); /* cp1 */
708 ptr = mem2hex((char *)®s->frame_ptr, ptr, 2*4, 0); /* frp */
709 ptr = mem2hex((char *)®s->cp0_index, ptr, 16*4, 0); /* cp0 */
713 * set the value of the CPU registers - return OK
717 ptr = &input_buffer[1];
718 hex2mem(ptr, (char *)®s->reg0, 32*4, 0);
720 hex2mem(ptr, (char *)®s->cp0_status, 6*4, 0);
722 hex2mem(ptr, (char *)®s->fpr0, 32*4, 0);
724 hex2mem(ptr, (char *)®s->cp1_fsr, 2*4, 0);
726 hex2mem(ptr, (char *)®s->frame_ptr, 2*4, 0);
728 hex2mem(ptr, (char *)®s->cp0_index, 16*4, 0);
729 strcpy(output_buffer,"OK");
734 * mAA..AA,LLLL Read LLLL bytes at address AA..AA
737 ptr = &input_buffer[1];
739 if (hexToInt(&ptr, &addr)
741 && hexToInt(&ptr, &length)) {
742 if (mem2hex((char *)addr, output_buffer, length, 1))
744 strcpy (output_buffer, "E03");
746 strcpy(output_buffer,"E01");
750 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
753 ptr = &input_buffer[1];
755 if (hexToInt(&ptr, &addr)
757 && hexToInt(&ptr, &length)
759 if (hex2mem(ptr, (char *)addr, length, 1))
760 strcpy(output_buffer, "OK");
762 strcpy(output_buffer, "E03");
765 strcpy(output_buffer, "E02");
769 * cAA..AA Continue at address AA..AA(optional)
772 /* try to read optional parameter, pc unchanged if no parm */
774 ptr = &input_buffer[1];
775 if (hexToInt(&ptr, &addr))
776 regs->cp0_epc = addr;
779 * Need to flush the instruction cache here, as we may
780 * have deposited a breakpoint, and the icache probably
781 * has no way of knowing that a data ref to some location
782 * may have changed something that is in the instruction
784 * NB: We flush both caches, just to be sure...
794 * kill the program; let us try to restart the machine
795 * Reset the whole machine.
799 machine_restart("kgdb restarts machine");
803 * Step to next instruction
807 * There is no single step insn in the MIPS ISA, so we
808 * use breakpoints and continue, instead.
816 * Set baud rate (bBB)
817 * FIXME: Needs to be written
823 extern void set_timer_3();
825 ptr = &input_buffer[1];
826 if (!hexToInt(&ptr, &baudrate))
828 strcpy(output_buffer,"B01");
832 /* Convert baud rate to uart clock divider */
847 strcpy(output_buffer,"B02");
852 putpacket("OK"); /* Ack before changing speed */
853 set_timer_3(baudrate); /* Set it */
862 * reply to the request
865 putpacket(output_buffer);
871 * This function will generate a breakpoint exception. It is used at the
872 * beginning of a program to sync up with a debugger and can be used
873 * otherwise as a quick means to stop program execution and "break" into
876 void breakpoint(void)
881 __asm__ __volatile__(
882 ".globl breakinst\n\t"
883 ".set\tnoreorder\n\t"
885 "breakinst:\tbreak\n\t"
893 __asm__ __volatile__(
895 "la\t$8,0x80000001\n\t"
901 * malloc is needed by gdb client in "call func()", even a private one
902 * will make gdb happy
904 static void *malloc(size_t size)
906 return kmalloc(size, GFP_ATOMIC);
909 static void free(void *where)
914 #ifdef CONFIG_GDB_CONSOLE
916 void gdb_putsn(const char *str, int l)
924 mem2hex((char *)str, &outbuf[1], i, 0);
932 static void gdb_console_write(struct console *con, const char *s, unsigned n)
937 static struct console gdb_console = {
939 .write = gdb_console_write,
940 .flags = CON_PRINTBUFFER,
944 __init void register_gdb_console(void)
946 register_console(&gdb_console);