/* rtl-stub.c for Alpha, originally taken from alpha-gdbstub.c and modified to
 * work with RTLinux debugger.  See comments below.
 *
 * RTLinux Debugger modifications are written by Nathan Paul Simons and are
 * (C) Finite State Machine Labs Inc. 2000 business@fsmlabs.com
 *
 * Released under the terms of GPL 2.
 * Open RTLinux makes use of a patented process described in
 * US Patent 5,995,745. Use of this process is governed
 * by the Open RTLinux Patent License which can be obtained from
 * www.fsmlabs.com/PATENT or by sending email to
 * licensequestions@fsmlabs.com
 */

/****************************************************************************

		THIS SOFTWARE IS NOT COPYRIGHTED

   HP offers the following for use in the public domain.  HP makes no
   warranty with regard to the software or its performance and the
   user accepts the software "AS IS" with all faults.

   HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
   TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

****************************************************************************/

/****************************************************************************
 *  Header: remcom.c,v 1.34 91/03/09 12:29:49 glenne Exp $
 *
 *  Module name: remcom.c $
 *  Revision: 1.34 $
 *  Date: 91/03/09 12:29:49 $
 *  Contributor:     Lake Stevens Instrument Division$
 *
 *  Description:     low level support for gdb debugger. $
 *
 *  Considerations:  only works on target hardware $
 *
 *  Written by:      Glenn Engel $
 *  ModuleState:     Experimental $
 *
 *  NOTES:           See Below $
 *
 *  Modified for FreeBSD by Stu Grossman.
 *
 *  To enable debugger support, two things need to happen.  One, a
 *  call to set_debug_traps() is necessary in order to allow any breakpoints
 *  or error conditions to be properly intercepted and reported to gdb.
 *  Two, a breakpoint needs to be generated to begin communication.  This
 *  is most easily accomplished by a call to breakpoint().  Breakpoint()
 *  simulates a breakpoint by executing a trap #1.
 *
 *  The external function exceptionHandler() is
 *  used to attach a specific handler to a specific 386 vector number.
 *  It should use the same privilege level it runs at.  It should
 *  install it as an interrupt gate so that interrupts are masked
 *  while the handler runs.
 *  Also, need to assign exceptionHook and oldExceptionHook.
 *
 *  Because gdb will sometimes write to the stack area to execute function
 *  calls, this program cannot rely on using the supervisor stack so it
 *  uses its own stack area reserved in the int array remcomStack.
 *
 *************
 *
 *    The following gdb commands are supported:
 *
 * command          function                               Return value
 *
 *    g             return the value of the CPU registers  hex data or ENN
 *    G             set the value of the CPU registers     OK or ENN
 *
 *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
 *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
 *
 *    c             Resume at current address              SNN   ( signal NN)
 *    cAA..AA       Continue at address AA..AA             SNN
 *
 *    s             Step one instruction                   SNN
 *    sAA..AA       Step one instruction from AA..AA       SNN
 *
 *    k             kill
 *
 *    ?             What was the last sigval ?             SNN   (signal NN)
 *
 *    D             detach                                 OK
 *
 * All commands and responses are sent with a packet which includes a
 * checksum.  A packet consists of
 *
 * $<packet info>#<checksum>.
 *
 * where
 * <packet info> :: <characters representing the command or response>
 * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
 *
 * When a packet is received, it is first acknowledged with either '+' or '-'.
 * '+' indicates a successful transfer.  '-' indicates a failed transfer.
 *
 * Example:
 *
 * Host:                  Reply:
 * $m0,10#2a               +$00010203040506070809101112131415#42
 *
 ****************************************************************************/

#include <linux/string.h>
#include <asm/system.h>
#include <asm/ptrace.h>		/* for linux pt_regs struct */
#include <asm/reg.h>		/* for EF_* reg num defines */
#include <asm/gentrap.h>	/* for GEN_* trap num defines */
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/signal.h>

/* RTLinux support */
#define __NO_VERSION__

#include <linux/module.h>
#include <rtl_sync.h>
#include <rtl_sched.h>
#include <psc.h>
#include "rtl_ex.c"

#define strtoul simple_strtoul
#define rtl_running_linux() (pthread_self() == &LOCAL_SCHED->rtl_linux_task)

int rtl_debug_initialized = 0;
/* end of RTLinux support */

/* Indicate to caller of mem2hex or hex2mem that there has been an
   error.  */
static volatile int real_mem_err[NR_CPUS];
static volatile int real_mem_err_expected[NR_CPUS];

#define mem_err (real_mem_err[rtl_getcpuid()])
#define mem_err_expected (real_mem_err_expected[rtl_getcpuid()])

/* external low-level support routines */
typedef void (*Function) (void);	/* pointer to a function */
extern int putDebugChar(int);	/* write a single character      */
extern int getDebugChar(void);	/* read and return a single char */
extern int rtl_request_traps(int (*rtl_exception_intercept)
			      (int vector, struct pt_regs * regs));

/* ripped from arch/alpha/kernel/process.c 
 * XXX we should probably just export show_regs and use the pre-exisiting 
 * one to cut down on code size -Nathan */
void show_regs(struct pt_regs *regs)
{
	printk("\nps: %04lx pc: [<%016lx>]\n", regs->ps, regs->pc);
	printk("rp: [<%016lx>] sp: %p\n", regs->r26, regs + 1);
	printk(" r0: %016lx  r1: %016lx  r2: %016lx  r3: %016lx\n",
	       regs->r0, regs->r1, regs->r2, regs->r3);
	printk(" r4: %016lx  r5: %016lx  r6: %016lx  r7: %016lx\n",
	       regs->r4, regs->r5, regs->r6, regs->r7);
	printk(" r8: %016lx r16: %016lx r17: %016lx r18: %016lx\n",
	       regs->r8, regs->r16, regs->r17, regs->r18);
	printk("r19: %016lx r20: %016lx r21: %016lx r22: %016lx\n",
	       regs->r19, regs->r20, regs->r21, regs->r22);
	printk("r23: %016lx r24: %016lx r25: %016lx r26: %016lx\n",
	       regs->r23, regs->r24, regs->r25, regs->r26);
	printk("r27: %016lx r28: %016lx r29: %016lx hae: %016lx\n",
	       regs->r27, regs->r28, regs->gp, regs->hae);
}

/* BUFMAX defines the maximum number of characters in inbound/outbound buffers
 * at least NUMREGBYTES*2 are needed for register packets */
#define BUFMAX 1500

int remote_debug = 0;

static const char hexchars[] = "0123456789abcdef";

static int hex(char ch)
{
	if ((ch >= 'a') && (ch <= 'f'))
		return (ch - 'a' + 10);
	if ((ch >= '0') && (ch <= '9'))
		return (ch - '0');
	if ((ch >= 'A') && (ch <= 'F'))
		return (ch - 'A' + 10);
	return (-1);
}

/* scan for the sequence $<data>#<checksum>     */
static void getpacket(char *buffer)
{
	unsigned char checksum;
	unsigned char xmitcsum;
	int i;
	int count;
	unsigned char ch;

	do {
		/* wait around for the start character, ignore all other 
		 * characters */
		while ((ch = (getDebugChar() & 0x7f)) != '$');

		checksum = 0;
		xmitcsum = -1;

		count = 0;

		/* now, read until a # or end of buffer is found */
		while (count < BUFMAX) {
			ch = getDebugChar() & 0x7f;
			if (ch == '#')
				break;
			checksum = checksum + ch;
			buffer[count] = ch;
			count = count + 1;
		}
		buffer[count] = 0;

		if (ch == '#') {
			xmitcsum = hex(getDebugChar() & 0x7f) << 4;
			xmitcsum += hex(getDebugChar() & 0x7f);

			if (checksum != xmitcsum)
				putDebugChar('-');	/* failed checksum */
			else {
				putDebugChar('+');	/* successful xfer */

				/* if a sequence char is present, reply the 
				 * sequence ID */
				if (buffer[2] == ':') {
					putDebugChar(buffer[0]);
					putDebugChar(buffer[1]);

					/* remove sequence chars from buffer */
					count = strlen(buffer);
					for (i = 3; i <= count; i++)
						buffer[i - 3] = buffer[i];
				}
			}
		}
	} while (checksum != xmitcsum);

	if (strlen(buffer) >= BUFMAX)
		panic("kgdb: buffer overflow");
}				/* static void getpacket(char *buffer) */

/* send the packet in buffer.  */
static void putpacket(char *buffer)
{
	unsigned char checksum;
	int count;
	unsigned char ch;

	if (strlen(buffer) >= BUFMAX)
		panic("kgdb: buffer overflow");

	/*  $<packet info>#<checksum>. */
	do {
		putDebugChar('$');
		checksum = 0;
		count = 0;

		while ((ch = buffer[count])) {
			if (!putDebugChar(ch))
				return;
			checksum += ch;
			count += 1;
		}

		putDebugChar('#');
		putDebugChar(hexchars[checksum >> 4]);
		putDebugChar(hexchars[checksum % 16]);
	} while ((getDebugChar() & 0x7f) != '+');
}				/* static void putpacket(char *buffer) */

int get_char(char *addr)
{
	return *addr;
}

void set_char(char *addr, int val)
{
	*addr = val;
}

/* convert the memory pointed to by mem into hex, placing result in buf */
/* return a pointer to the last char put in buf (null) */
static char *mem2hex(char *mem, char *buf, int count)
{
	unsigned char ch;
	int may_fault = 1;

	if (mem == 0) {
		strcpy(buf, "E03");
		return buf;
	}

	if (may_fault) {
		mem_err_expected = 1;
		mem_err = 0;
	}

	while (count-- > 0) {
		ch = *mem++;

		if (may_fault && mem_err) {
			if (remote_debug)
				printk
				    ("Mem fault fetching from addr %lx\n",
				     (long) (mem - 1));
			*buf = 0;	/* truncate buffer */
			return 0;
		}

		*buf++ = hexchars[ch >> 4];
		*buf++ = hexchars[ch & 0xf];
	}
	*buf = 0;
	if (may_fault)
		mem_err_expected = 0;

	return buf;
}

/* convert the hex array pointed to by buf into binary to be placed in mem */
/* return a pointer to the character AFTER the last byte written */
static char *hex2mem(char *buf, char *mem, int count)
{
	unsigned char ch;

	while (count-- > 0) {
		ch = hex(*buf++) << 4;
		ch = ch + hex(*buf++);
		set_char(mem++, ch);
	}
	return mem;
}

/*
 * While we find nice hex chars, build an int.
 * Return number of chars processed.
 */
static long hexToInt(char **ptr, long *intValue)
{
	long numChars = 0;
	long hexValue;

	*intValue = 0;

	while (**ptr) {
		hexValue = hex(**ptr);
		if (hexValue >= 0) {
			*intValue = (*intValue << 4) | hexValue;
			numChars++;
		} else
			break;

		(*ptr)++;
	}

	return (numChars);
}

/* more RTLinux support */
static spinlock_t bp_lock = SPIN_LOCK_UNLOCKED;

#define RTL_MAX_BP 1024
static struct bp_cache_entry {
	char *mem;
	unsigned char val;
	struct bp_cache_entry *next;
} bp_cache[RTL_MAX_BP];

static struct bp_cache_entry *cache_start = 0;

int insert_bp(char *mem)
{
	int i;
	struct bp_cache_entry *e;
	int old;
	char buf[3];

	if (!mem2hex(mem, buf, 1)) {
		return EINVAL;	/* memory error */
	}

	old = strtoul(buf, 0, 16);

	for (e = cache_start; e; e = e->next) {
		if (e->mem == mem) {
			return EINVAL;	/* already there */
		}
	}
	for (i = 0; i < RTL_MAX_BP; i++) {
		if (bp_cache[i].mem == 0) {
			break;
		}
	}
	if (i == RTL_MAX_BP) {
		return EINVAL;	/* no space */
	}
	bp_cache[i].val = old;
	bp_cache[i].mem = mem;
	bp_cache[i].next = cache_start;
	cache_start = &bp_cache[i];

	set_char(mem, 0xcc);
	return 0;
}

#define CONFIG_RTL_DEBUGGER_THREADS
#define CONFIG_RTL_DEBUGGER_Z_PROTOCOL

static int send_exception_info = 0;

static char remcomInBuffer[BUFMAX];
static char remcomOutBuffer[BUFMAX];
static short error;

void debug_error(char *format, char *parm)
{
	if (remote_debug)
		printk(format, parm);
}

/* Alpha registers are 64 bit wide, so 8 bytes to a register, times 66
 * registers we need to keep track of */
#define NUMREGS	66
#define BYTESPERREG	8
#define NUMREGBYTES	(BYTESPERREG * NUMREGS)

int remove_bp(char *mem)
{
	struct bp_cache_entry *e = cache_start;
	struct bp_cache_entry *f = 0;
	if (!e) {
		return EINVAL;
	}
	if (e->mem == mem) {
		cache_start = e->next;
		f = e;
	} else {
		for (; e->next; e = e->next) {
			if (e->next->mem == mem) {
				f = e->next;
				e->next = f->next;
				break;
			}
		}
	}
	if (!f) {
		return EINVAL;
	}

	mem_err_expected = 1;
	set_char(f->mem, f->val);
	if (mem_err) {
		return EINVAL;
	}
	mem_err_expected = 0;
	return 0;
}				/* int remove_bp(char *mem) */

/* for some reason, the mappings in reg.h are not *completely* correct.  That
 * is, they don't match up with the mappings in GDB.  For instance, EF_PC is
 * supposed to be the 64th integer in the gdb_regs array, not the 28th.  i
 * don't know how gdb possibly works with normal core files, but to get things
 * to work here, we are going to *ignore* asm-alpha/regs.h and go with what
 * gdb says. -Nathan */
static void regs_to_gdb_regs(unsigned long *gdb_regs, struct pt_regs *regs)
{
	gdb_regs[EF_V0] = regs->r0;	/* return value */
	gdb_regs[EF_T0] = regs->r1;	/* temporary registers 1-8 */
	gdb_regs[EF_T1] = regs->r2;
	gdb_regs[EF_T2] = regs->r3;
	gdb_regs[EF_T3] = regs->r4;
	gdb_regs[EF_T4] = regs->r5;
	gdb_regs[EF_T5] = regs->r6;
	gdb_regs[EF_T6] = regs->r7;
	gdb_regs[EF_T7] = regs->r8;
	gdb_regs[EF_S0] = 0;	/* saved regs 9-15; we don't deal */
	/* with these */
	gdb_regs[EF_S1] = 0;
	gdb_regs[EF_S2] = 0;
	gdb_regs[EF_S3] = 0;
	gdb_regs[EF_S4] = 0;
	gdb_regs[EF_S5] = 0;
	gdb_regs[EF_S6] = 0;
	gdb_regs[16] = regs->r16;	/* argument regs 16-21 */
	gdb_regs[17] = regs->r17;
	gdb_regs[18] = regs->r18;
	gdb_regs[19] = regs->r19;
	gdb_regs[20] = regs->r20;
	gdb_regs[21] = regs->r21;
	gdb_regs[22] = regs->r22;	/* temporary regs 22-25 */
	gdb_regs[23] = regs->r23;
	gdb_regs[24] = regs->r24;
	gdb_regs[25] = regs->r25;
	gdb_regs[26] = regs->r26;	/* return address */
	gdb_regs[27] = regs->r27;	/* procedure value */
	gdb_regs[28] = regs->r28;	/* assembler temp */
	gdb_regs[30] = rdusp();	/* stack pointer */
	gdb_regs[65] = regs->ps;	/* processor status */
	gdb_regs[64] = regs->pc;	/* processor counter */
	gdb_regs[EF_GP] = regs->gp;	/* global pointer */
}				/* static void regs_to_gdb_regs(int *gdb_regs, struct pt_regs *regs) */

static void gdb_regs_to_regs(unsigned long *gdb_regs, struct pt_regs *regs)
{
	regs->r0 = gdb_regs[EF_V0];
	regs->r1 = gdb_regs[EF_T0];
	regs->r2 = gdb_regs[EF_T1];
	regs->r3 = gdb_regs[EF_T2];
	regs->r4 = gdb_regs[EF_T3];
	regs->r5 = gdb_regs[EF_T4];
	regs->r6 = gdb_regs[EF_T5];
	regs->r7 = gdb_regs[EF_T6];
	regs->r8 = gdb_regs[EF_T7];
	regs->r16 = gdb_regs[EF_A0];
	regs->r17 = gdb_regs[EF_A1];
	regs->r18 = gdb_regs[EF_A2];
	regs->r19 = gdb_regs[EF_A3];
	regs->r20 = gdb_regs[EF_A4];
	regs->r21 = gdb_regs[EF_A5];
	regs->r22 = gdb_regs[EF_T8];
	regs->r23 = gdb_regs[EF_T9];
	regs->r24 = gdb_regs[EF_T10];
	regs->r25 = gdb_regs[EF_T11];
	regs->r26 = gdb_regs[EF_RA];
	regs->r27 = gdb_regs[EF_T12];
	regs->r28 = gdb_regs[EF_AT];
	regs->ps = gdb_regs[EF_PS];
	regs->pc = gdb_regs[EF_PC];
	regs->gp = gdb_regs[EF_GP];
}				/* static void gdb_regs_to_regs(int *gdb_regs, struct pt_regs *regs) */

static int handle_exception(int exceptionVector,
			    int signo, struct pt_regs *regs)
{
	long addr, length, newPC;
	unsigned long flags;
	char *ptr;
	unsigned long gdb_regs[NUMREGS];

#ifdef CONFIG_RTL_DEBUGGER_THREADS
	pthread_t current_thread = pthread_self();
#endif				/* CONFIG_RTL_DEBUGGER_THREADS */

	rtl_hard_savef_and_cli(flags);

	if (user_mode(regs) && !(rtl_is_psc_active())) {
		rtl_printf("rtl_debug: got a user-mode exception\n");
		return 0;
	}

	memset(gdb_regs, 0, NUMREGBYTES);

	if (remote_debug)
		show_regs(regs);

	if ((exceptionVector == 6) && (mem_err_expected == 1)) {
		mem_err = 1;	/* set mem error flag */
		mem_err_expected = 0;
		conpr("mem2hex() croaked\n");
		if (remote_debug)
			conpr("Return after memory error\n");
		if (remote_debug)
			show_regs(regs);
		rtl_hard_restore_flags(flags);
		return (1);
	}

	if (rtl_running_linux()) {
		rtl_hard_restore_flags(flags);
		rtl_printf("rtl_debug: not our fault; Linux's\n");
		return 0;	/* let Linux handle it's own faults */
	}

	/* ok, here we know pthread_self() is an RT-thread */
	pthread_cleanup_push(&rtl_exit_debugger, 0);
	rtl_enter_debugger(exceptionVector, (void *) regs->pc);

	/* reply to host that an exception has occurred */
	set_bit(0, &send_exception_info);

	while (1) {
		error = 0;
		remcomOutBuffer[0] = 0;
		if (test_and_clear_bit(0, &send_exception_info)) {
			strcpy(remcomInBuffer, "?");
		} else {
			getpacket(remcomInBuffer);
/*conpr("getpacket: ");conpr(remcomInBuffer);conpr("\n");*/
		}
		switch (remcomInBuffer[0]) {
		case 'q':
			if (!strcmp(remcomInBuffer, "qOffsets") && text
			    && data && bss) {
				sprintf(remcomOutBuffer,
					"Text=%x;Data=%x;Bss=%x",
					(unsigned) text, (unsigned) data,
					(unsigned) bss);
			}
#ifdef CONFIG_RTL_DEBUGGER_THREADS
			if (!strcmp(remcomInBuffer, "qC")) {
				sprintf(remcomOutBuffer, "QC%x",
					(unsigned long) (pthread_self()));
			} else if (!strncmp(remcomInBuffer, "qL", 2)) {
				/* we assume we have a limit of 31 threads -- 
				 * to fit in one packet */
				char packethead[17];
				pthread_t task;
				int ntasks = 0;
				int i;

				strcpy(remcomOutBuffer, remcomInBuffer);

				for (i = 0; i < rtl_num_cpus(); i++) {
					int cpu_id = cpu_logical_map(i);
					schedule_t *s = &rtl_sched[cpu_id];

					spin_lock(&s->rtl_tasks_lock);
					task = s->rtl_tasks;
					while (task != &s->rtl_linux_task
					       && ntasks < 31) {
						sprintf((remcomOutBuffer) +
							strlen
							(remcomOutBuffer),
							"00000000%08x",
							(unsigned long)
							task);
						task = task->next;
						ntasks++;
					}
					spin_unlock(&s->rtl_tasks_lock);
				}
				sprintf(packethead, "qM%02x%01x", ntasks,
					1 /* done */ );
				memcpy(remcomOutBuffer, packethead,
				       strlen(packethead));
			}
#endif				/* CONFIG_RTL_DEBUGGER_THREADS */
			break;
#ifdef CONFIG_RTL_DEBUGGER_THREADS
		case 'H':
			if (	/* remcomInBuffer[1] == 'c' || */
				   remcomInBuffer[1] == 'g') {
				if (remcomInBuffer[2] == '-') {
					current_thread =
					    (pthread_t) -
					    strtoul(remcomInBuffer + 3, 0,
						    16);
				} else {
					current_thread = (pthread_t)
					    strtoul(remcomInBuffer + 2, 0,
						    16);
				}
				debugpr("Hc/g: %x",
					(unsigned long) current_thread);
				strcpy(remcomOutBuffer, "OK");
			}
			break;

		case 'T':{
				pthread_t thread;
				if (remcomInBuffer[1] == '-') {
					thread =
					    (pthread_t) -
					    strtoul(remcomInBuffer + 2, 0,
						    16);
				} else {
					thread = (pthread_t)
					    strtoul(remcomInBuffer + 1, 0,
						    16);
				}
				if (!pthread_kill(thread, 0)) {
					strcpy(remcomOutBuffer, "OK");
				} else {
					strcpy(remcomOutBuffer, "ERROR");
				}

			}
			break;
#endif				/* CONFIG_RTL_DEBUGGER_THREADS */
#ifdef CONFIG_RTL_DEBUGGER_Z_PROTOCOL
		case 'Z':
		case 'z':
			{
				int type = remcomInBuffer[1] - '0';
				long address =
				    strtoul(remcomInBuffer + 3, 0, 16);
				int res;
				if (type != 0) {
					strcpy(remcomOutBuffer, "ERROR");
					break;
				}
				spin_lock(&bp_lock);
				if (remcomInBuffer[0] == 'Z') {
					res = insert_bp((char *) address);
				} else {
					remove_bp((char *) address);
					res = 0;
				}
				spin_unlock(&bp_lock);
				if (res) {
					strcpy(remcomOutBuffer, "ERROR");
				} else {
					strcpy(remcomOutBuffer, "OK");
				}

			}
			break;
#endif				/* CONFIG_RTL_DEBUGGER_Z_PROTOCOL */
		case '?':
#ifdef CONFIG_RTL_DEBUGGER_THREADS
			sprintf(remcomOutBuffer, "T%02xthread:%x;", signo,
				(unsigned long) pthread_self());

#else
			remcomOutBuffer[0] = 'S';
			remcomOutBuffer[1] = hexchars[signo >> 4];
			remcomOutBuffer[2] = hexchars[signo % 16];
			remcomOutBuffer[3] = 0;
#endif				/* CONFIG_RTL_DEBUGGER_THREADS */
			break;
		case 'd':
			remote_debug = !(remote_debug);	/* toggle debug flag */
			printk("Remote debug %s\n",
			       remote_debug ? "on" : "off");
			break;
		case 'g':	/* return the value of the CPU registers */
			regs_to_gdb_regs(gdb_regs, regs);
#ifdef CONFIG_RTL_DEBUGGER_THREADS
			if (current_thread != pthread_self()) {
				gdb_regs[EF_SP] =
				    (long) current_thread->stack;
				gdb_regs[EF_PC] = *(current_thread->stack);
				rtl_printf("*(current_thread->stack: %x\n",
					   (current_thread->stack));
				debugpr("reg read for %x",
					(unsigned long) current_thread);

			}
#endif				/* CONFIG_RTL_DEBUGGER_THREADS */
			mem2hex((char *) gdb_regs, remcomOutBuffer,
				NUMREGBYTES);
			break;
		case 'G':	/* set the value of the CPU registers - return OK */
			hex2mem(&remcomInBuffer[1], (char *) gdb_regs,
				NUMREGBYTES);
			gdb_regs_to_regs(gdb_regs, regs);
			strcpy(remcomOutBuffer, "OK");
			break;

			/* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
		case 'm':
			/* TRY TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
			ptr = &remcomInBuffer[1];
			if (hexToInt(&ptr, &addr))
				if (*(ptr++) == ',')
					if (hexToInt(&ptr, &length)) {
						ptr = 0;
						if (!mem2hex
						    ((char *) addr,
						     remcomOutBuffer,
						     length)) {
							strcpy
							    (remcomOutBuffer,
							     "E03");
							debug_error
							    ("memory fault\n",
							     NULL);
						}
					}

			if (ptr) {
				strcpy(remcomOutBuffer, "E01");
				debug_error
				    ("malformed read memory command: %s\n",
				     remcomInBuffer);
			}
			break;

			/* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
		case 'M':
			/* TRY TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
			ptr = &remcomInBuffer[1];
			if (hexToInt(&ptr, &addr))
				if (*(ptr++) == ',')
					if (hexToInt(&ptr, &length))
						if (*(ptr++) == ':') {
							if (!hex2mem
							    (ptr,
							     (char *) addr,
							     length)) {
								strcpy
								    (remcomOutBuffer,
								     "E03");
								debug_error
								    ("memory fault\n",
								     NULL);
							} else {
								strcpy
								    (remcomOutBuffer,
								     "OK");
							}

							ptr = 0;
						}
			if (ptr) {
				strcpy(remcomOutBuffer, "E02");
				debug_error
				    ("malformed write memory command: %s\n",
				     remcomInBuffer);
			}
			break;

			/* cAA..AA    Continue at address AA..AA(optional) */
			/* sAA..AA   Step one instruction from AA..AA(optional) */
		case 'c':
		case 's':
			/* try to read optional parameter, pc unchanged if no 
			 * parm */
			ptr = &remcomInBuffer[1];
			if (hexToInt(&ptr, &addr)) {
				if (remote_debug)
					printk("Changing EF_PC to 0x%x\n",
					       addr);

				regs->pc = addr;
			}

			newPC = regs->pc;

			/* clear the trace bit */
#if 0
			/* XXX don't know how to do these yet. -Nathan
			   regs->ps &= 0xfffffeff; */

			/* set the trace bit if we're stepping */
			if (remcomInBuffer[0] == 's')
				regs.eflags |= 0x100;
#endif				/* 0 */
			if (remote_debug) {
				printk("Resuming execution\n");
				show_regs(regs);
			}
			debugpr("cont\n");
			goto cleanup;

			/* kill the program */
		case 'k':
			goto cleanup;
		}		/* switch */
/*conpr("putpacket: ");conpr(remcomOutBuffer);conpr("\n");*/
		/* reply to the request */
		putpacket(remcomOutBuffer);
	}			/* while (1) */

      cleanup:pthread_cleanup_pop(1);
	rtl_hard_restore_flags(flags);
	return (1);
#undef regs
}

/* we don't have a hard_trap_info struct and we have to use this gigantic
 * switch statement because of the special case of generic traps.  This also
 * means that we have to pass across the registers so that we can get the
 * value from r16 to determine which generic trap it is. */
static int computeSignal(unsigned int tt, struct pt_regs *regs)
{
	switch (tt) {
	case 0:		/* breakpoint */
	case 1:		/* bugcheck */
		return SIGTRAP;

	case 2:		/* gentrap */
		switch ((long) regs->r16) {
		case GEN_INTOVF:
		case GEN_INTDIV:
		case GEN_FLTOVF:
		case GEN_FLTDIV:
		case GEN_FLTUND:
		case GEN_FLTINV:
		case GEN_FLTINE:
		case GEN_ROPRAND:
			return SIGFPE;

		case GEN_DECOVF:
		case GEN_DECDIV:
		case GEN_DECINV:
		case GEN_ASSERTERR:
		case GEN_NULPTRERR:
		case GEN_STKOVF:
		case GEN_STRLENERR:
		case GEN_SUBSTRERR:
		case GEN_RANGERR:
		case GEN_SUBRNG:
		case GEN_SUBRNG1:
		case GEN_SUBRNG2:
		case GEN_SUBRNG3:
		case GEN_SUBRNG4:
		case GEN_SUBRNG5:
		case GEN_SUBRNG6:
		case GEN_SUBRNG7:
			return SIGTRAP;
		}		/* switch ((long) regs->r16) */

	case 3:		/* FEN fault */
		return SIGILL;

	case 4:		/* opDEC */
		return SIGILL;
	}			/* switch (tt) */

	/* don't know what signal to return?  SIGHUP to the rescue! */
	return SIGHUP;
}

int rtl_debug_exception(int vector, struct pt_regs *regs)
{
	int signo = computeSignal(vector, regs);
	return handle_exception(vector, signo, regs);
}

int set_debug_traps(void)
{
	if (rtl_debug_initialized) {
		printk("rtl_debug: already loaded\n");
		return -1;
	}

	rtl_request_traps(&rtl_debug_exception);

	rtl_debug_initialized = 1;
	return 0;
}

void unset_debug_traps(void)
{
	/*
	   int i;
	   for (i = 0; i < nbreak; i++) {
	   debugpr ("unpatching leftover breakpoints\n");
	   set_char(bp_cache[i].mem, bp_cache[i].val);
	   }
	 */

	rtl_request_traps(0);
	rtl_debug_initialized = 0;
}
