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;
640 void set_async_breakpoint(unsigned long *epc)
642 /* skip breaking into userland */
643 if ((*epc & 0x80000000) == 0)
646 /* avoid deadlock if someone is make IPC */
647 if (spin_is_locked(&smp_call_lock))
650 async_bp.addr = *epc;
651 *epc = (unsigned long)async_breakpoint;
654 void kgdb_wait(void *arg)
657 int cpu = smp_processor_id();
659 local_irq_save(flags);
661 spin_lock(&kgdb_cpulock[cpu]);
662 spin_unlock(&kgdb_cpulock[cpu]);
664 local_irq_restore(flags);
669 * This function does all command processing for interfacing to gdb. It
670 * returns 1 if you should skip the instruction at the trap address, 0
673 void handle_exception (struct gdb_regs *regs)
675 int trap; /* Trap type */
680 unsigned long *stack;
687 * acquire the big kgdb spinlock
689 if (!spin_trylock(&kgdb_lock)) {
691 * some other CPU has the lock, we should go back to
692 * receive the gdb_wait IPC
698 * If we're in async_breakpoint(), restore the real EPC from
701 if (regs->cp0_epc == (unsigned long)async_breakinst) {
702 regs->cp0_epc = async_bp.addr;
707 * acquire the CPU spinlocks
709 for (i = num_online_cpus()-1; i >= 0; i--)
710 if (spin_trylock(&kgdb_cpulock[i]) == 0)
711 panic("kgdb: couldn't get cpulock %d\n", i);
714 * force other cpus to enter kgdb
716 smp_call_function(kgdb_wait, NULL, 0, 0);
719 * If we're in breakpoint() increment the PC
721 trap = (regs->cp0_cause & 0x7c) >> 2;
722 if (trap == 9 && regs->cp0_epc == (unsigned long)breakinst)
726 * If we were single_stepping, restore the opcodes hoisted
727 * for the breakpoint[s].
729 if (step_bp[0].addr) {
730 *(unsigned *)step_bp[0].addr = step_bp[0].val;
733 if (step_bp[1].addr) {
734 *(unsigned *)step_bp[1].addr = step_bp[1].val;
739 stack = (long *)regs->reg29; /* stack ptr */
740 sigval = computeSignal(trap);
743 * reply to host that an exception has occurred
748 * Send trap type (converted to signal)
751 *ptr++ = hexchars[sigval >> 4];
752 *ptr++ = hexchars[sigval & 0xf];
757 *ptr++ = hexchars[REG_EPC >> 4];
758 *ptr++ = hexchars[REG_EPC & 0xf];
760 ptr = mem2hex((char *)®s->cp0_epc, ptr, sizeof(long), 0);
766 *ptr++ = hexchars[REG_FP >> 4];
767 *ptr++ = hexchars[REG_FP & 0xf];
769 ptr = mem2hex((char *)®s->reg30, ptr, sizeof(long), 0);
775 *ptr++ = hexchars[REG_SP >> 4];
776 *ptr++ = hexchars[REG_SP & 0xf];
778 ptr = mem2hex((char *)®s->reg29, ptr, sizeof(long), 0);
782 putpacket(output_buffer); /* send it off... */
785 * Wait for input from remote GDB
788 output_buffer[0] = 0;
789 getpacket(input_buffer);
791 switch (input_buffer[0])
794 output_buffer[0] = 'S';
795 output_buffer[1] = hexchars[sigval >> 4];
796 output_buffer[2] = hexchars[sigval & 0xf];
797 output_buffer[3] = 0;
801 * Detach debugger; let CPU run
804 putpacket(output_buffer);
809 /* toggle debug flag */
813 * Return the value of the CPU registers
817 ptr = mem2hex((char *)®s->reg0, ptr, 32*sizeof(long), 0); /* r0...r31 */
818 ptr = mem2hex((char *)®s->cp0_status, ptr, 6*sizeof(long), 0); /* cp0 */
819 ptr = mem2hex((char *)®s->fpr0, ptr, 32*sizeof(long), 0); /* f0...31 */
820 ptr = mem2hex((char *)®s->cp1_fsr, ptr, 2*sizeof(long), 0); /* cp1 */
821 ptr = mem2hex((char *)®s->frame_ptr, ptr, 2*sizeof(long), 0); /* frp */
822 ptr = mem2hex((char *)®s->cp0_index, ptr, 16*sizeof(long), 0); /* cp0 */
826 * set the value of the CPU registers - return OK
830 ptr = &input_buffer[1];
831 hex2mem(ptr, (char *)®s->reg0, 32*sizeof(long), 0, 0);
832 ptr += 32*(2*sizeof(long));
833 hex2mem(ptr, (char *)®s->cp0_status, 6*sizeof(long), 0, 0);
834 ptr += 6*(2*sizeof(long));
835 hex2mem(ptr, (char *)®s->fpr0, 32*sizeof(long), 0, 0);
836 ptr += 32*(2*sizeof(long));
837 hex2mem(ptr, (char *)®s->cp1_fsr, 2*sizeof(long), 0, 0);
838 ptr += 2*(2*sizeof(long));
839 hex2mem(ptr, (char *)®s->frame_ptr, 2*sizeof(long), 0, 0);
840 ptr += 2*(2*sizeof(long));
841 hex2mem(ptr, (char *)®s->cp0_index, 16*sizeof(long), 0, 0);
842 strcpy(output_buffer,"OK");
847 * mAA..AA,LLLL Read LLLL bytes at address AA..AA
850 ptr = &input_buffer[1];
852 if (hexToLong(&ptr, &addr)
854 && hexToInt(&ptr, &length)) {
855 if (mem2hex((char *)addr, output_buffer, length, 1))
857 strcpy (output_buffer, "E03");
859 strcpy(output_buffer,"E01");
863 * XAA..AA,LLLL: Write LLLL escaped binary bytes at address AA.AA
870 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
873 ptr = &input_buffer[1];
875 if (hexToLong(&ptr, &addr)
877 && hexToInt(&ptr, &length)
879 if (hex2mem(ptr, (char *)addr, length, bflag, 1))
880 strcpy(output_buffer, "OK");
882 strcpy(output_buffer, "E03");
885 strcpy(output_buffer, "E02");
889 * cAA..AA Continue at address AA..AA(optional)
892 /* try to read optional parameter, pc unchanged if no parm */
894 ptr = &input_buffer[1];
895 if (hexToLong(&ptr, &addr))
896 regs->cp0_epc = addr;
898 goto exit_kgdb_exception;
902 * kill the program; let us try to restart the machine
903 * Reset the whole machine.
907 machine_restart("kgdb restarts machine");
911 * Step to next instruction
915 * There is no single step insn in the MIPS ISA, so we
916 * use breakpoints and continue, instead.
919 goto exit_kgdb_exception;
924 * Set baud rate (bBB)
925 * FIXME: Needs to be written
931 extern void set_timer_3();
933 ptr = &input_buffer[1];
934 if (!hexToInt(&ptr, &baudrate))
936 strcpy(output_buffer,"B01");
940 /* Convert baud rate to uart clock divider */
955 strcpy(output_buffer,"B02");
960 putpacket("OK"); /* Ack before changing speed */
961 set_timer_3(baudrate); /* Set it */
970 * reply to the request
973 putpacket(output_buffer);
980 restore_debug_traps();
983 /* release locks so other CPUs can go */
984 for (i = num_online_cpus()-1; i >= 0; i--)
985 spin_unlock(&kgdb_cpulock[i]);
986 spin_unlock(&kgdb_lock);
993 * This function will generate a breakpoint exception. It is used at the
994 * beginning of a program to sync up with a debugger and can be used
995 * otherwise as a quick means to stop program execution and "break" into
998 void breakpoint(void)
1003 __asm__ __volatile__(
1004 ".globl breakinst\n\t"
1005 ".set\tnoreorder\n\t"
1007 "breakinst:\tbreak\n\t"
1013 /* Nothing but the break; don't pollute any registers */
1014 void async_breakpoint(void)
1016 __asm__ __volatile__(
1017 ".globl async_breakinst\n\t"
1018 ".set\tnoreorder\n\t"
1020 "async_breakinst:\tbreak\n\t"
1028 __asm__ __volatile__(
1030 "lui\t$8,0x8000\n\t"
1036 * malloc is needed by gdb client in "call func()", even a private one
1037 * will make gdb happy
1039 static void *malloc(size_t size)
1041 return kmalloc(size, GFP_ATOMIC);
1044 static void free(void *where)
1049 #ifdef CONFIG_GDB_CONSOLE
1051 void gdb_putsn(const char *str, int l)
1062 mem2hex((char *)str, &outbuf[1], i, 0);
1070 static void gdb_console_write(struct console *con, const char *s, unsigned n)
1075 static struct console gdb_console = {
1077 .write = gdb_console_write,
1078 .flags = CON_PRINTBUFFER,
1082 static int __init register_gdb_console(void)
1084 register_console(&gdb_console);
1089 console_initcall(register_gdb_console);