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);
175 * spin locks for smp case
177 static spinlock_t kgdb_lock = SPIN_LOCK_UNLOCKED;
178 static spinlock_t kgdb_cpulock[NR_CPUS] = { [0 ... NR_CPUS-1] = SPIN_LOCK_UNLOCKED};
181 * BUFMAX defines the maximum number of characters in inbound/outbound buffers
182 * at least NUMREGBYTES*2 are needed for register packets
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";
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);
198 * Convert ch from a hex digit to an int
200 static int hex(unsigned char ch)
202 if (ch >= 'a' && ch <= 'f')
204 if (ch >= '0' && ch <= '9')
206 if (ch >= 'A' && ch <= 'F')
212 * scan for the sequence $<data>#<checksum>
214 static void getpacket(char *buffer)
216 unsigned char checksum;
217 unsigned char xmitcsum;
224 * wait around for the start character,
225 * ignore all other characters
227 while ((ch = (getDebugChar() & 0x7f)) != '$') ;
234 * now, read until a # or end of buffer is found
236 while (count < BUFMAX) {
240 checksum = checksum + ch;
251 xmitcsum = hex(getDebugChar() & 0x7f) << 4;
252 xmitcsum |= hex(getDebugChar() & 0x7f);
254 if (checksum != xmitcsum)
255 putDebugChar('-'); /* failed checksum */
257 putDebugChar('+'); /* successful transfer */
260 * if a sequence char is present,
261 * reply the sequence ID
263 if (buffer[2] == ':') {
264 putDebugChar(buffer[0]);
265 putDebugChar(buffer[1]);
268 * remove sequence chars from buffer
270 count = strlen(buffer);
271 for (i=3; i <= count; i++)
272 buffer[i-3] = buffer[i];
277 while (checksum != xmitcsum);
281 * send the packet in buffer.
283 static void putpacket(char *buffer)
285 unsigned char checksum;
290 * $<packet info>#<checksum>.
298 while ((ch = buffer[count]) != 0) {
299 if (!(putDebugChar(ch)))
306 putDebugChar(hexchars[checksum >> 4]);
307 putDebugChar(hexchars[checksum & 0xf]);
310 while ((getDebugChar() & 0x7f) != '+');
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,
318 * may_fault is non-zero if we are reading from arbitrary memory, but is currently
321 static unsigned char *mem2hex(char *mem, char *buf, int count, int may_fault)
325 while (count-- > 0) {
326 if (kgdb_read_byte(mem++, &ch) != 0)
328 *buf++ = hexchars[ch >> 4];
329 *buf++ = hexchars[ch & 0xf];
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
343 static char *hex2mem(char *buf, char *mem, int count, int binary, int may_fault)
348 for (i=0; i<count; i++)
356 ch = hex(*buf++) << 4;
359 if (kgdb_write_byte(ch, mem++) != 0)
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.
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 */
389 /* Save the normal trap handlers for user-mode traps. */
390 void *saved_vectors[32];
393 * Set up exception handlers for tracing and breakpoints
395 void set_debug_traps(void)
397 struct hard_trap_info *ht;
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);
405 putDebugChar('+'); /* 'hello world' */
407 * In case GDB is started before us, ack any packets
408 * (presumably "$?#xx") sitting there.
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 */
417 local_irq_restore(flags);
420 void restore_debug_traps(void)
422 struct hard_trap_info *ht;
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);
432 * Convert the MIPS hardware trap type code to a Unix signal number.
434 static int computeSignal(int tt)
436 struct hard_trap_info *ht;
438 for (ht = hard_trap_info; ht->tt && ht->signo; ht++)
442 return SIGHUP; /* default for things we don't know about */
446 * While we find nice hex chars, build an int.
447 * Return number of chars processed.
449 static int hexToInt(char **ptr, int *intValue)
457 hexValue = hex(**ptr);
461 *intValue = (*intValue << 4) | hexValue;
470 static int hexToLong(char **ptr, long *longValue)
478 hexValue = hex(**ptr);
482 *longValue = (*longValue << 4) | hexValue;
494 * Print registers (on target console)
495 * Used only to debug the stub...
497 void show_gdbregs(struct gdb_regs * regs)
500 * Saved main processor registers
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);
516 * Saved cp0 registers
518 printk("epc : %08lx\nStatus: %08lx\nCause : %08lx\n",
519 regs->cp0_epc, regs->cp0_status, regs->cp0_cause);
521 #endif /* dead code */
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.
528 * This is where we save the original instructions.
530 static struct gdb_bp_save {
535 #define BP 0x0000000d /* break opcode */
538 * Set breakpoint instructions for single stepping.
540 static void single_step(struct gdb_regs *regs)
542 union mips_instruction insn;
544 int is_branch, is_cond, i;
546 targ = regs->cp0_epc;
547 insn.word = *(unsigned int *)targ;
548 is_branch = is_cond = 0;
550 switch (insn.i_format.opcode) {
552 * jr and jalr are in r_format format.
555 switch (insn.r_format.func) {
558 targ = *(®s->reg0 + insn.r_format.rs);
565 * This group contains:
566 * bltz_op, bgez_op, bltzl_op, bgezl_op,
567 * bltzal_op, bgezal_op, bltzall_op, bgezall_op.
570 is_branch = is_cond = 1;
571 targ += 4 + (insn.i_format.simmediate << 2);
575 * These are unconditional and in j_format.
583 targ |= (insn.j_format.target << 2);
587 * These are conditional.
601 is_branch = is_cond = 1;
602 targ += 4 + (insn.i_format.simmediate << 2);
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;
613 step_bp[i].addr = targ;
614 step_bp[i].val = *(unsigned *)targ;
615 *(unsigned *)targ = BP;
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;
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.
628 static struct gdb_bp_save async_bp;
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.
637 extern spinlock_t smp_call_lock;
638 void set_async_breakpoint(unsigned long *epc)
640 /* skip breaking into userland */
641 if ((*epc & 0x80000000) == 0)
644 /* avoid deadlock if someone is make IPC */
645 if (spin_is_locked(&smp_call_lock))
648 async_bp.addr = *epc;
649 *epc = (unsigned long)async_breakpoint;
652 void kgdb_wait(void *arg)
655 int cpu = smp_processor_id();
657 local_irq_save(flags);
659 spin_lock(&kgdb_cpulock[cpu]);
660 spin_unlock(&kgdb_cpulock[cpu]);
662 local_irq_restore(flags);
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
671 void handle_exception (struct gdb_regs *regs)
673 int trap; /* Trap type */
678 unsigned long *stack;
685 * acquire the big kgdb spinlock
687 if (!spin_trylock(&kgdb_lock)) {
689 * some other CPU has the lock, we should go back to
690 * receive the gdb_wait IPC
696 * If we're in async_breakpoint(), restore the real EPC from
699 if (regs->cp0_epc == (unsigned long)async_breakinst) {
700 regs->cp0_epc = async_bp.addr;
705 * acquire the CPU spinlocks
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);
712 * force other cpus to enter kgdb
714 smp_call_function(kgdb_wait, NULL, 0, 0);
717 * If we're in breakpoint() increment the PC
719 trap = (regs->cp0_cause & 0x7c) >> 2;
720 if (trap == 9 && regs->cp0_epc == (unsigned long)breakinst)
724 * If we were single_stepping, restore the opcodes hoisted
725 * for the breakpoint[s].
727 if (step_bp[0].addr) {
728 *(unsigned *)step_bp[0].addr = step_bp[0].val;
731 if (step_bp[1].addr) {
732 *(unsigned *)step_bp[1].addr = step_bp[1].val;
737 stack = (long *)regs->reg29; /* stack ptr */
738 sigval = computeSignal(trap);
741 * reply to host that an exception has occurred
746 * Send trap type (converted to signal)
749 *ptr++ = hexchars[sigval >> 4];
750 *ptr++ = hexchars[sigval & 0xf];
755 *ptr++ = hexchars[REG_EPC >> 4];
756 *ptr++ = hexchars[REG_EPC & 0xf];
758 ptr = mem2hex((char *)®s->cp0_epc, ptr, sizeof(long), 0);
764 *ptr++ = hexchars[REG_FP >> 4];
765 *ptr++ = hexchars[REG_FP & 0xf];
767 ptr = mem2hex((char *)®s->reg30, ptr, sizeof(long), 0);
773 *ptr++ = hexchars[REG_SP >> 4];
774 *ptr++ = hexchars[REG_SP & 0xf];
776 ptr = mem2hex((char *)®s->reg29, ptr, sizeof(long), 0);
780 putpacket(output_buffer); /* send it off... */
783 * Wait for input from remote GDB
786 output_buffer[0] = 0;
787 getpacket(input_buffer);
789 switch (input_buffer[0])
792 output_buffer[0] = 'S';
793 output_buffer[1] = hexchars[sigval >> 4];
794 output_buffer[2] = hexchars[sigval & 0xf];
795 output_buffer[3] = 0;
799 * Detach debugger; let CPU run
802 putpacket(output_buffer);
807 /* toggle debug flag */
811 * Return the value of the CPU registers
815 ptr = mem2hex((char *)®s->reg0, ptr, 32*sizeof(long), 0); /* r0...r31 */
816 ptr = mem2hex((char *)®s->cp0_status, ptr, 6*sizeof(long), 0); /* cp0 */
817 ptr = mem2hex((char *)®s->fpr0, ptr, 32*sizeof(long), 0); /* f0...31 */
818 ptr = mem2hex((char *)®s->cp1_fsr, ptr, 2*sizeof(long), 0); /* cp1 */
819 ptr = mem2hex((char *)®s->frame_ptr, ptr, 2*sizeof(long), 0); /* frp */
820 ptr = mem2hex((char *)®s->cp0_index, ptr, 16*sizeof(long), 0); /* cp0 */
824 * set the value of the CPU registers - return OK
828 ptr = &input_buffer[1];
829 hex2mem(ptr, (char *)®s->reg0, 32*sizeof(long), 0, 0);
830 ptr += 32*(2*sizeof(long));
831 hex2mem(ptr, (char *)®s->cp0_status, 6*sizeof(long), 0, 0);
832 ptr += 6*(2*sizeof(long));
833 hex2mem(ptr, (char *)®s->fpr0, 32*sizeof(long), 0, 0);
834 ptr += 32*(2*sizeof(long));
835 hex2mem(ptr, (char *)®s->cp1_fsr, 2*sizeof(long), 0, 0);
836 ptr += 2*(2*sizeof(long));
837 hex2mem(ptr, (char *)®s->frame_ptr, 2*sizeof(long), 0, 0);
838 ptr += 2*(2*sizeof(long));
839 hex2mem(ptr, (char *)®s->cp0_index, 16*sizeof(long), 0, 0);
840 strcpy(output_buffer,"OK");
845 * mAA..AA,LLLL Read LLLL bytes at address AA..AA
848 ptr = &input_buffer[1];
850 if (hexToLong(&ptr, &addr)
852 && hexToInt(&ptr, &length)) {
853 if (mem2hex((char *)addr, output_buffer, length, 1))
855 strcpy (output_buffer, "E03");
857 strcpy(output_buffer,"E01");
861 * XAA..AA,LLLL: Write LLLL escaped binary bytes at address AA.AA
868 * MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK
871 ptr = &input_buffer[1];
873 if (hexToLong(&ptr, &addr)
875 && hexToInt(&ptr, &length)
877 if (hex2mem(ptr, (char *)addr, length, bflag, 1))
878 strcpy(output_buffer, "OK");
880 strcpy(output_buffer, "E03");
883 strcpy(output_buffer, "E02");
887 * cAA..AA Continue at address AA..AA(optional)
890 /* try to read optional parameter, pc unchanged if no parm */
892 ptr = &input_buffer[1];
893 if (hexToLong(&ptr, &addr))
894 regs->cp0_epc = addr;
896 goto exit_kgdb_exception;
900 * kill the program; let us try to restart the machine
901 * Reset the whole machine.
905 machine_restart("kgdb restarts machine");
909 * Step to next instruction
913 * There is no single step insn in the MIPS ISA, so we
914 * use breakpoints and continue, instead.
917 goto exit_kgdb_exception;
922 * Set baud rate (bBB)
923 * FIXME: Needs to be written
929 extern void set_timer_3();
931 ptr = &input_buffer[1];
932 if (!hexToInt(&ptr, &baudrate))
934 strcpy(output_buffer,"B01");
938 /* Convert baud rate to uart clock divider */
953 strcpy(output_buffer,"B02");
958 putpacket("OK"); /* Ack before changing speed */
959 set_timer_3(baudrate); /* Set it */
968 * reply to the request
971 putpacket(output_buffer);
978 restore_debug_traps();
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);
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
996 void breakpoint(void)
1001 __asm__ __volatile__(
1002 ".globl breakinst\n\t"
1003 ".set\tnoreorder\n\t"
1005 "breakinst:\tbreak\n\t"
1011 /* Nothing but the break; don't pollute any registers */
1012 void async_breakpoint(void)
1014 __asm__ __volatile__(
1015 ".globl async_breakinst\n\t"
1016 ".set\tnoreorder\n\t"
1018 "async_breakinst:\tbreak\n\t"
1026 __asm__ __volatile__(
1028 "lui\t$8,0x8000\n\t"
1034 * malloc is needed by gdb client in "call func()", even a private one
1035 * will make gdb happy
1037 static void *malloc(size_t size)
1039 return kmalloc(size, GFP_ATOMIC);
1042 static void free(void *where)
1047 #ifdef CONFIG_GDB_CONSOLE
1049 void gdb_putsn(const char *str, int l)
1060 mem2hex((char *)str, &outbuf[1], i, 0);
1068 static void gdb_console_write(struct console *con, const char *s, unsigned n)
1073 static struct console gdb_console = {
1075 .write = gdb_console_write,
1076 .flags = CON_PRINTBUFFER,
1080 static int __init register_gdb_console(void)
1082 register_console(&gdb_console);
1087 console_initcall(register_gdb_console);