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
15 * Copyright (C) 2003 MontaVista Software Inc.
16 * Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
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.
28 * The following gdb commands are supported:
30 * command function Return value
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
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
38 * c Resume at current address SNN ( signal NN)
39 * cAA..AA Continue at address AA..AA SNN
41 * s Step one instruction SNN
42 * sAA..AA Step one instruction from AA..AA SNN
46 * ? What was the last sigval ? SNN (signal NN)
48 * bBB..BB Set baud rate to BB..BB OK or BNN, then sets
51 * All commands and responses are sent with a packet which includes a
52 * checksum. A packet consists of
54 * $<packet info>#<checksum>.
57 * <packet info> :: <characters representing the command or response>
58 * <checksum> :: < two hex digits computed as modulo 256 sum of <packetinfo>>
60 * When a packet is received, it is first acknowledged with either '+' or '-'.
61 * '+' indicates a successful transfer. '-' indicates a failed transfer.
66 * $m0,10#2a +$00010203040506070809101112131415#42
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
80 * First download gdb-5.0.tar.gz from the internet.
81 * and then build/install the package.
84 * $ tar zxf gdb-5.0.tar.gz
86 * $ ./configure --target=mips-linux-elf
89 * $ which mips-linux-elf-gdb
90 * /usr/local/bin/mips-linux-elf-gdb
93 * Configure linux for remote debugging and build it.
97 * $ make menuconfig <go to "Kernel Hacking" and turn on remote debugging>
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
111 * Start the gdb session on the host.
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.
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>
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>
145 * external low-level support routines
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);
153 * breakpoint and test functions
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);
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);
177 * spin locks for smp case
179 static spinlock_t kgdb_lock = SPIN_LOCK_UNLOCKED;
180 static spinlock_t kgdb_cpulock[NR_CPUS] = { [0 ... NR_CPUS-1] = SPIN_LOCK_UNLOCKED};
183 * BUFMAX defines the maximum number of characters in inbound/outbound buffers
184 * at least NUMREGBYTES*2 are needed for register packets
188 static char input_buffer[BUFMAX];
189 static char output_buffer[BUFMAX];
190 static int initialized; /* !0 means we've been initialized */
191 static int kgdb_started;
192 static const char hexchars[]="0123456789abcdef";
194 /* Used to prevent crashes in memory access. Note that they'll crash anyway if
195 we haven't set up fault handlers yet... */
196 int kgdb_read_byte(unsigned char *address, unsigned char *dest);
197 int kgdb_write_byte(unsigned char val, unsigned char *dest);
200 * Convert ch from a hex digit to an int
202 static int hex(unsigned char ch)
204 if (ch >= 'a' && ch <= 'f')
206 if (ch >= '0' && ch <= '9')
208 if (ch >= 'A' && ch <= 'F')
214 * scan for the sequence $<data>#<checksum>
216 static void getpacket(char *buffer)
218 unsigned char checksum;
219 unsigned char xmitcsum;
226 * wait around for the start character,
227 * ignore all other characters
229 while ((ch = (getDebugChar() & 0x7f)) != '$') ;
236 * now, read until a # or end of buffer is found
238 while (count < BUFMAX) {
242 checksum = checksum + ch;
253 xmitcsum = hex(getDebugChar() & 0x7f) << 4;
254 xmitcsum |= hex(getDebugChar() & 0x7f);
256 if (checksum != xmitcsum)
257 putDebugChar('-'); /* failed checksum */
259 putDebugChar('+'); /* successful transfer */
262 * if a sequence char is present,
263 * reply the sequence ID
265 if (buffer[2] == ':') {
266 putDebugChar(buffer[0]);
267 putDebugChar(buffer[1]);
270 * remove sequence chars from buffer
272 count = strlen(buffer);
273 for (i=3; i <= count; i++)
274 buffer[i-3] = buffer[i];
279 while (checksum != xmitcsum);
283 * send the packet in buffer.
285 static void putpacket(char *buffer)
287 unsigned char checksum;
292 * $<packet info>#<checksum>.
300 while ((ch = buffer[count]) != 0) {
301 if (!(putDebugChar(ch)))
308 putDebugChar(hexchars[checksum >> 4]);
309 putDebugChar(hexchars[checksum & 0xf]);
312 while ((getDebugChar() & 0x7f) != '+');
317 * Convert the memory pointed to by mem into hex, placing result in buf.
318 * Return a pointer to the last char put in buf (null), in case of mem fault,
320 * may_fault is non-zero if we are reading from arbitrary memory, but is currently
323 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault)
327 while (count-- > 0) {
328 if (kgdb_read_byte(mem++, &ch) != 0)
330 *buf++ = hexchars[ch >> 4];
331 *buf++ = hexchars[ch & 0xf];
340 * convert the hex array pointed to by buf into binary to be placed in mem
341 * return a pointer to the character AFTER the last byte written
342 * may_fault is non-zero if we are reading from arbitrary memory, but is currently
345 static char *hex2mem(char *buf, char *mem, int count, int binary, int may_fault)
350 for (i=0; i<count; i++)
358 ch = hex(*buf++) << 4;
361 if (kgdb_write_byte(ch, mem++) != 0)
369 * This table contains the mapping between SPARC hardware trap types, and
370 * signals, which are primarily what GDB understands. It also indicates
371 * which hardware traps we need to commandeer when initializing the stub.
373 static struct hard_trap_info {
374 unsigned char tt; /* Trap type code for MIPS R3xxx and R4xxx */
375 unsigned char signo; /* Signal that we map this trap into */
376 } hard_trap_info[] = {
377 { 6, SIGBUS }, /* instruction bus error */
378 { 7, SIGBUS }, /* data bus error */
379 { 9, SIGTRAP }, /* break */
380 { 10, SIGILL }, /* reserved instruction */
381 /* { 11, SIGILL }, */ /* CPU unusable */
382 { 12, SIGFPE }, /* overflow */
383 { 13, SIGTRAP }, /* trap */
384 { 14, SIGSEGV }, /* virtual instruction cache coherency */
385 { 15, SIGFPE }, /* floating point exception */
386 { 23, SIGSEGV }, /* watch */
387 { 31, SIGSEGV }, /* virtual data cache coherency */
388 { 0, 0} /* Must be last */
391 /* Save the normal trap handlers for user-mode traps. */
392 void *saved_vectors[32];
395 * Set up exception handlers for tracing and breakpoints
397 void set_debug_traps(void)
399 struct hard_trap_info *ht;
403 local_irq_save(flags);
404 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
405 saved_vectors[ht->tt] = set_except_vector(ht->tt, trap_low);
407 putDebugChar('+'); /* 'hello world' */
409 * In case GDB is started before us, ack any packets
410 * (presumably "$?#xx") sitting there.
412 while((c = getDebugChar()) != '$');
413 while((c = getDebugChar()) != '#');
414 c = getDebugChar(); /* eat first csum byte */
415 c = getDebugChar(); /* eat second csum byte */
416 putDebugChar('+'); /* ack it */
419 local_irq_restore(flags);
422 void restore_debug_traps(void)
424 struct hard_trap_info *ht;
427 local_irq_save(flags);
428 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
429 set_except_vector(ht->tt, saved_vectors[ht->tt]);
430 local_irq_restore(flags);
434 * Convert the MIPS hardware trap type code to a Unix signal number.
436 static int computeSignal(int tt)
438 struct hard_trap_info *ht;
440 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
444 return SIGHUP; /* default for things we don't know about */
448 * While we find nice hex chars, build an int.
449 * Return number of chars processed.
451 static int hexToInt(char **ptr, int *intValue)
459 hexValue = hex(**ptr);
463 *intValue = (*intValue << 4) | hexValue;
472 static int hexToLong(char **ptr, long *longValue)
480 hexValue = hex(**ptr);
484 *longValue = (*longValue << 4) | hexValue;
496 * Print registers (on target console)
497 * Used only to debug the stub...
499 void show_gdbregs(struct gdb_regs * regs)
502 * Saved main processor registers
504 printk("$0 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
505 regs->reg0, regs->reg1, regs->reg2, regs->reg3,
506 regs->reg4, regs->reg5, regs->reg6, regs->reg7);
507 printk("$8 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
508 regs->reg8, regs->reg9, regs->reg10, regs->reg11,
509 regs->reg12, regs->reg13, regs->reg14, regs->reg15);
510 printk("$16: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
511 regs->reg16, regs->reg17, regs->reg18, regs->reg19,
512 regs->reg20, regs->reg21, regs->reg22, regs->reg23);
513 printk("$24: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
514 regs->reg24, regs->reg25, regs->reg26, regs->reg27,
515 regs->reg28, regs->reg29, regs->reg30, regs->reg31);
518 * Saved cp0 registers
520 printk("epc : %08lx\nStatus: %08lx\nCause : %08lx\n",
521 regs->cp0_epc, regs->cp0_status, regs->cp0_cause);
523 #endif /* dead code */
526 * We single-step by setting breakpoints. When an exception
527 * is handled, we need to restore the instructions hoisted
528 * when the breakpoints were set.
530 * This is where we save the original instructions.
532 static struct gdb_bp_save {
537 #define BP 0x0000000d /* break opcode */
540 * Set breakpoint instructions for single stepping.
542 static void single_step(struct gdb_regs *regs)
544 union mips_instruction insn;
546 int is_branch, is_cond, i;
548 targ = regs->cp0_epc;
549 insn.word = *(unsigned int *)targ;
550 is_branch = is_cond = 0;
552 switch (insn.i_format.opcode) {
554 * jr and jalr are in r_format format.
557 switch (insn.r_format.func) {
560 targ = *(®s->reg0 + insn.r_format.rs);
567 * This group contains:
568 * bltz_op, bgez_op, bltzl_op, bgezl_op,
569 * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
572 is_branch = is_cond = 1;
573 targ += 4 + (insn.i_format.simmediate << 2);
577 * These are unconditional and in j_format.
585 targ |= (insn.j_format.target << 2);
589 * These are conditional.
603 is_branch = is_cond = 1;
604 targ += 4 + (insn.i_format.simmediate << 2);
610 if (is_cond && targ != (regs->cp0_epc + 8)) {
611 step_bp[i].addr = regs->cp0_epc + 8;
612 step_bp[i++].val = *(unsigned *)(regs->cp0_epc + 8);
613 *(unsigned *)(regs->cp0_epc + 8) = BP;
615 step_bp[i].addr = targ;
616 step_bp[i].val = *(unsigned *)targ;
617 *(unsigned *)targ = BP;
619 step_bp[0].addr = regs->cp0_epc + 4;
620 step_bp[0].val = *(unsigned *)(regs->cp0_epc + 4);
621 *(unsigned *)(regs->cp0_epc + 4) = BP;
626 * If asynchronously interrupted by gdb, then we need to set a breakpoint
627 * at the interrupted instruction so that we wind up stopped with a
628 * reasonable stack frame.
630 static struct gdb_bp_save async_bp;
633 * Swap the interrupted EPC with our asynchronous breakpoint routine.
634 * This is safer than stuffing the breakpoint in-place, since no cache
635 * flushes (or resulting smp_call_functions) are required. The
636 * assumption is that only one CPU will be handling asynchronous bp's,
637 * and only one can be active at a time.
639 extern spinlock_t smp_call_lock;
641 void set_async_breakpoint(unsigned long *epc)
643 /* skip breaking into userland */
644 if ((*epc & 0x80000000) == 0)
648 /* avoid deadlock if someone is make IPC */
649 if (spin_is_locked(&smp_call_lock))
653 async_bp.addr = *epc;
654 *epc = (unsigned long)async_breakpoint;
657 void kgdb_wait(void *arg)
660 int cpu = smp_processor_id();
662 local_irq_save(flags);
664 spin_lock(&kgdb_cpulock[cpu]);
665 spin_unlock(&kgdb_cpulock[cpu]);
667 local_irq_restore(flags);
672 * This function does all command processing for interfacing to gdb. It
673 * returns 1 if you should skip the instruction at the trap address, 0
676 void handle_exception (struct gdb_regs *regs)
678 int trap; /* Trap type */
683 unsigned long *stack;
690 * acquire the big kgdb spinlock
692 if (!spin_trylock(&kgdb_lock)) {
694 * some other CPU has the lock, we should go back to
695 * receive the gdb_wait IPC
701 * If we're in async_breakpoint(), restore the real EPC from
704 if (regs->cp0_epc == (unsigned long)async_breakinst) {
705 regs->cp0_epc = async_bp.addr;
710 * acquire the CPU spinlocks
712 for (i = num_online_cpus()-1; i >= 0; i--)
713 if (spin_trylock(&kgdb_cpulock[i]) == 0)
714 panic("kgdb: couldn't get cpulock %d\n", i);
717 * force other cpus to enter kgdb
719 smp_call_function(kgdb_wait, NULL, 0, 0);
722 * If we're in breakpoint() increment the PC
724 trap = (regs->cp0_cause & 0x7c) >> 2;
725 if (trap == 9 && regs->cp0_epc == (unsigned long)breakinst)
729 * If we were single_stepping, restore the opcodes hoisted
730 * for the breakpoint[s].
732 if (step_bp[0].addr) {
733 *(unsigned *)step_bp[0].addr = step_bp[0].val;
736 if (step_bp[1].addr) {
737 *(unsigned *)step_bp[1].addr = step_bp[1].val;
742 stack = (long *)regs->reg29; /* stack ptr */
743 sigval = computeSignal(trap);
746 * reply to host that an exception has occurred
751 * Send trap type (converted to signal)
754 *ptr++ = hexchars[sigval >> 4];
755 *ptr++ = hexchars[sigval & 0xf];
760 *ptr++ = hexchars[REG_EPC >> 4];
761 *ptr++ = hexchars[REG_EPC & 0xf];
763 ptr = mem2hex((char *)®s->cp0_epc, ptr, sizeof(long), 0);
769 *ptr++ = hexchars[REG_FP >> 4];
770 *ptr++ = hexchars[REG_FP & 0xf];
772 ptr = mem2hex((char *)®s->reg30, ptr, sizeof(long), 0);
778 *ptr++ = hexchars[REG_SP >> 4];
779 *ptr++ = hexchars[REG_SP & 0xf];
781 ptr = mem2hex((char *)®s->reg29, ptr, sizeof(long), 0);
785 putpacket(output_buffer); /* send it off... */
788 * Wait for input from remote GDB
791 output_buffer[0] = 0;
792 getpacket(input_buffer);
794 switch (input_buffer[0])
797 output_buffer[0] = 'S';
798 output_buffer[1] = hexchars[sigval >> 4];
799 output_buffer[2] = hexchars[sigval & 0xf];
800 output_buffer[3] = 0;
804 * Detach debugger; let CPU run
807 putpacket(output_buffer);
812 /* toggle debug flag */
816 * Return the value of the CPU registers
820 ptr = mem2hex((char *)®s->reg0, ptr, 32*sizeof(long), 0); /* r0...r31 */
821 ptr = mem2hex((char *)®s->cp0_status, ptr, 6*sizeof(long), 0); /* cp0 */
822 ptr = mem2hex((char *)®s->fpr0, ptr, 32*sizeof(long), 0); /* f0...31 */
823 ptr = mem2hex((char *)®s->cp1_fsr, ptr, 2*sizeof(long), 0); /* cp1 */
824 ptr = mem2hex((char *)®s->frame_ptr, ptr, 2*sizeof(long), 0); /* frp */
825 ptr = mem2hex((char *)®s->cp0_index, ptr, 16*sizeof(long), 0); /* cp0 */
829 * set the value of the CPU registers - return OK
833 ptr = &input_buffer[1];
834 hex2mem(ptr, (char *)®s->reg0, 32*sizeof(long), 0, 0);
835 ptr += 32*(2*sizeof(long));
836 hex2mem(ptr, (char *)®s->cp0_status, 6*sizeof(long), 0, 0);
837 ptr += 6*(2*sizeof(long));
838 hex2mem(ptr, (char *)®s->fpr0, 32*sizeof(long), 0, 0);
839 ptr += 32*(2*sizeof(long));
840 hex2mem(ptr, (char *)®s->cp1_fsr, 2*sizeof(long), 0, 0);
841 ptr += 2*(2*sizeof(long));
842 hex2mem(ptr, (char *)®s->frame_ptr, 2*sizeof(long), 0, 0);
843 ptr += 2*(2*sizeof(long));
844 hex2mem(ptr, (char *)®s->cp0_index, 16*sizeof(long), 0, 0);
845 strcpy(output_buffer,"OK");
850 * mAA..AA,LLLL Read LLLL bytes at address AA..AA
853 ptr = &input_buffer[1];
855 if (hexToLong(&ptr, &addr)
857 && hexToInt(&ptr, &length)) {
858 if (mem2hex((char *)addr, output_buffer, length, 1))
860 strcpy (output_buffer, "E03");
862 strcpy(output_buffer,"E01");
866 * XAA..AA,LLLL: Write LLLL escaped binary bytes at address AA.AA
873 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
876 ptr = &input_buffer[1];
878 if (hexToLong(&ptr, &addr)
880 && hexToInt(&ptr, &length)
882 if (hex2mem(ptr, (char *)addr, length, bflag, 1))
883 strcpy(output_buffer, "OK");
885 strcpy(output_buffer, "E03");
888 strcpy(output_buffer, "E02");
892 * cAA..AA Continue at address AA..AA(optional)
895 /* try to read optional parameter, pc unchanged if no parm */
897 ptr = &input_buffer[1];
898 if (hexToLong(&ptr, &addr))
899 regs->cp0_epc = addr;
901 goto exit_kgdb_exception;
905 * kill the program; let us try to restart the machine
906 * Reset the whole machine.
910 machine_restart("kgdb restarts machine");
914 * Step to next instruction
918 * There is no single step insn in the MIPS ISA, so we
919 * use breakpoints and continue, instead.
922 goto exit_kgdb_exception;
927 * Set baud rate (bBB)
928 * FIXME: Needs to be written
934 extern void set_timer_3();
936 ptr = &input_buffer[1];
937 if (!hexToInt(&ptr, &baudrate))
939 strcpy(output_buffer,"B01");
943 /* Convert baud rate to uart clock divider */
958 strcpy(output_buffer,"B02");
963 putpacket("OK"); /* Ack before changing speed */
964 set_timer_3(baudrate); /* Set it */
973 * reply to the request
976 putpacket(output_buffer);
983 restore_debug_traps();
986 /* release locks so other CPUs can go */
987 for (i = num_online_cpus()-1; i >= 0; i--)
988 spin_unlock(&kgdb_cpulock[i]);
989 spin_unlock(&kgdb_lock);
996 * This function will generate a breakpoint exception. It is used at the
997 * beginning of a program to sync up with a debugger and can be used
998 * otherwise as a quick means to stop program execution and "break" into
1001 void breakpoint(void)
1006 __asm__ __volatile__(
1007 ".globl breakinst\n\t"
1008 ".set\tnoreorder\n\t"
1010 "breakinst:\tbreak\n\t"
1016 /* Nothing but the break; don't pollute any registers */
1017 void async_breakpoint(void)
1019 __asm__ __volatile__(
1020 ".globl async_breakinst\n\t"
1021 ".set\tnoreorder\n\t"
1023 "async_breakinst:\tbreak\n\t"
1031 __asm__ __volatile__(
1033 "lui\t$8,0x8000\n\t"
1039 * malloc is needed by gdb client in "call func()", even a private one
1040 * will make gdb happy
1042 static void * __attribute_used__ malloc(size_t size)
1044 return kmalloc(size, GFP_ATOMIC);
1047 static void __attribute_used__ free (void *where)
1052 #ifdef CONFIG_GDB_CONSOLE
1054 void gdb_putsn(const char *str, int l)
1065 mem2hex((char *)str, &outbuf[1], i, 0);
1073 static void gdb_console_write(struct console *con, const char *s, unsigned n)
1078 static struct console gdb_console = {
1080 .write = gdb_console_write,
1081 .flags = CON_PRINTBUFFER,
1085 static int __init register_gdb_console(void)
1087 register_console(&gdb_console);
1092 console_initcall(register_gdb_console);