1/*!**************************************************************************
2*!
3*! FILE NAME  : kgdb.c
4*!
5*! DESCRIPTION: Implementation of the gdb stub with respect to ETRAX 100.
6*!              It is a mix of arch/m68k/kernel/kgdb.c and cris_stub.c.
7*!
8*!---------------------------------------------------------------------------
9*! HISTORY
10*!
11*! DATE         NAME            CHANGES
12*! ----         ----            -------
13*! Apr 26 1999  Hendrik Ruijter Initial version.
14*! May  6 1999  Hendrik Ruijter Removed call to strlen in libc and removed
15*!                              struct assignment as it generates calls to
16*!                              memcpy in libc.
17*! Jun 17 1999  Hendrik Ruijter Added gdb 4.18 support. 'X', 'qC' and 'qL'.
18*! Jul 21 1999  Bjorn Wesen     eLinux port
19*!
20*! $Log: not supported by cvs2svn $
21*! Revision 1.6  2005/01/14 10:12:17  starvik
22*! KGDB on separate port.
23*! Console fixes from 2.4.
24*!
25*! Revision 1.5  2004/10/07 13:59:08  starvik
26*! Corrected call to set_int_vector
27*!
28*! Revision 1.4  2003/04/09 05:20:44  starvik
29*! Merge of Linux 2.5.67
30*!
31*! Revision 1.3  2003/01/21 19:11:08  starvik
32*! Modified include path for new dir layout
33*!
34*! Revision 1.2  2002/11/19 14:35:24  starvik
35*! Changes from linux 2.4
36*! Changed struct initializer syntax to the currently preferred notation
37*!
38*! Revision 1.1  2001/12/17 13:59:27  bjornw
39*! Initial revision
40*!
41*! Revision 1.6  2001/10/09 13:10:03  matsfg
42*! Added $ on registers and removed some underscores
43*!
44*! Revision 1.5  2001/04/17 13:58:39  orjanf
45*! * Renamed CONFIG_KGDB to CONFIG_ETRAX_KGDB.
46*!
47*! Revision 1.4  2001/02/23 13:45:19  bjornw
48*! config.h check
49*!
50*! Revision 1.3  2001/01/31 18:08:23  orjanf
51*! Removed kgdb_handle_breakpoint from being the break 8 handler.
52*!
53*! Revision 1.2  2001/01/12 14:22:25  orjanf
54*! Updated kernel debugging support to work with ETRAX 100LX.
55*!
56*! Revision 1.1  2000/07/10 16:25:21  bjornw
57*! Initial revision
58*!
59*! Revision 1.1.1.1  1999/12/03 14:57:31  bjornw
60*! * Initial version of arch/cris, the latest CRIS architecture with an MMU.
61*!   Mostly copied from arch/etrax100 with appropriate renames of files.
62*!   The mm/ subdir is copied from arch/i386.
63*!   This does not compile yet at all.
64*!
65*!
66*! Revision 1.4  1999/07/22 17:25:25  bjornw
67*! Dont wait for + in putpacket if we havent hit the initial breakpoint yet. Added a kgdb_init function which sets up the break and irq vectors.
68*!
69*! Revision 1.3  1999/07/21 19:51:18  bjornw
70*! Check if the interrupting char is a ctrl-C, ignore otherwise.
71*!
72*! Revision 1.2  1999/07/21 18:09:39  bjornw
73*! Ported to eLinux architecture, and added some kgdb documentation.
74*!
75*!
76*!---------------------------------------------------------------------------
77*!
78*! $Id: kgdb.c,v 1.1.1.1 2007-08-03 18:51:41 $
79*!
80*! (C) Copyright 1999, Axis Communications AB, LUND, SWEDEN
81*!
82*!**************************************************************************/
83/* @(#) cris_stub.c 1.3 06/17/99 */
84
85
86/*
87 *  To enable debugger support, two things need to happen.  One, a
88 *  call to kgdb_init() is necessary in order to allow any breakpoints
89 *  or error conditions to be properly intercepted and reported to gdb.
90 *  Two, a breakpoint needs to be generated to begin communication.  This
91 *  is most easily accomplished by a call to breakpoint().
92 *
93 *    The following gdb commands are supported:
94 *
95 * command          function                               Return value
96 *
97 *    g             return the value of the CPU registers  hex data or ENN
98 *    G             set the value of the CPU registers     OK or ENN
99 *
100 *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
101 *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
102 *
103 *    c             Resume at current address              SNN   ( signal NN)
104 *    cAA..AA       Continue at address AA..AA             SNN
105 *
106 *    s             Step one instruction                   SNN
107 *    sAA..AA       Step one instruction from AA..AA       SNN
108 *
109 *    k             kill
110 *
111 *    ?             What was the last sigval ?             SNN   (signal NN)
112 *
113 *    bBB..BB	    Set baud rate to BB..BB		   OK or BNN, then sets
114 *							   baud rate
115 *
116 * All commands and responses are sent with a packet which includes a
117 * checksum.  A packet consists of
118 *
119 * $<packet info>#<checksum>.
120 *
121 * where
122 * <packet info> :: <characters representing the command or response>
123 * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
124 *
125 * When a packet is received, it is first acknowledged with either '+' or '-'.
126 * '+' indicates a successful transfer.  '-' indicates a failed transfer.
127 *
128 * Example:
129 *
130 * Host:                  Reply:
131 * $m0,10#2a               +$00010203040506070809101112131415#42
132 *
133 */
134
135
136#include <linux/string.h>
137#include <linux/signal.h>
138#include <linux/kernel.h>
139#include <linux/delay.h>
140#include <linux/linkage.h>
141#include <linux/reboot.h>
142
143#include <asm/setup.h>
144#include <asm/ptrace.h>
145
146#include <asm/arch/svinto.h>
147#include <asm/irq.h>
148
149static int kgdb_started = 0;
150
151/********************************* Register image ****************************/
152/* Use the order of registers as defined in "AXIS ETRAX CRIS Programmer's
153   Reference", p. 1-1, with the additional register definitions of the
154   ETRAX 100LX in cris-opc.h.
155   There are 16 general 32-bit registers, R0-R15, where R14 is the stack
156   pointer, SP, and R15 is the program counter, PC.
157   There are 16 special registers, P0-P15, where three of the unimplemented
158   registers, P0, P4 and P8, are reserved as zero-registers. A read from
159   any of these registers returns zero and a write has no effect. */
160
161typedef
162struct register_image
163{
164	/* Offset */
165	unsigned int     r0;   /* 0x00 */
166	unsigned int     r1;   /* 0x04 */
167	unsigned int     r2;   /* 0x08 */
168	unsigned int     r3;   /* 0x0C */
169	unsigned int     r4;   /* 0x10 */
170	unsigned int     r5;   /* 0x14 */
171	unsigned int     r6;   /* 0x18 */
172	unsigned int     r7;   /* 0x1C */
173	unsigned int     r8;   /* 0x20 Frame pointer */
174	unsigned int     r9;   /* 0x24 */
175	unsigned int    r10;   /* 0x28 */
176	unsigned int    r11;   /* 0x2C */
177	unsigned int    r12;   /* 0x30 */
178	unsigned int    r13;   /* 0x34 */
179	unsigned int     sp;   /* 0x38 Stack pointer */
180	unsigned int     pc;   /* 0x3C Program counter */
181
182        unsigned char    p0;   /* 0x40 8-bit zero-register */
183	unsigned char    vr;   /* 0x41 Version register */
184
185        unsigned short   p4;   /* 0x42 16-bit zero-register */
186	unsigned short  ccr;   /* 0x44 Condition code register */
187
188	unsigned int    mof;   /* 0x46 Multiply overflow register */
189
190        unsigned int     p8;   /* 0x4A 32-bit zero-register */
191	unsigned int    ibr;   /* 0x4E Interrupt base register */
192	unsigned int    irp;   /* 0x52 Interrupt return pointer */
193	unsigned int    srp;   /* 0x56 Subroutine return pointer */
194	unsigned int    bar;   /* 0x5A Breakpoint address register */
195	unsigned int   dccr;   /* 0x5E Double condition code register */
196	unsigned int    brp;   /* 0x62 Breakpoint return pointer (pc in caller) */
197	unsigned int    usp;   /* 0x66 User mode stack pointer */
198} registers;
199
200/************** Prototypes for local library functions ***********************/
201
202/* Copy of strcpy from libc. */
203static char *gdb_cris_strcpy (char *s1, const char *s2);
204
205/* Copy of strlen from libc. */
206static int gdb_cris_strlen (const char *s);
207
208/* Copy of memchr from libc. */
209static void *gdb_cris_memchr (const void *s, int c, int n);
210
211/* Copy of strtol from libc. Does only support base 16. */
212static int gdb_cris_strtol (const char *s, char **endptr, int base);
213
214/********************** Prototypes for local functions. **********************/
215/* Copy the content of a register image into another. The size n is
216   the size of the register image. Due to struct assignment generation of
217   memcpy in libc. */
218static void copy_registers (registers *dptr, registers *sptr, int n);
219
220/* Copy the stored registers from the stack. Put the register contents
221   of thread thread_id in the struct reg. */
222static void copy_registers_from_stack (int thread_id, registers *reg);
223
224/* Copy the registers to the stack. Put the register contents of thread
225   thread_id from struct reg to the stack. */
226static void copy_registers_to_stack (int thread_id, registers *reg);
227
228/* Write a value to a specified register regno in the register image
229   of the current thread. */
230static int write_register (int regno, char *val);
231
232/* Write a value to a specified register in the stack of a thread other
233   than the current thread. */
234static write_stack_register (int thread_id, int regno, char *valptr);
235
236/* Read a value from a specified register in the register image. Returns the
237   status of the read operation. The register value is returned in valptr. */
238static int read_register (char regno, unsigned int *valptr);
239
240/* Serial port, reads one character. ETRAX 100 specific. from debugport.c */
241int getDebugChar (void);
242
243/* Serial port, writes one character. ETRAX 100 specific. from debugport.c */
244void putDebugChar (int val);
245
246void enableDebugIRQ (void);
247
248/* Returns the character equivalent of a nibble, bit 7, 6, 5, and 4 of a byte,
249   represented by int x. */
250static char highhex (int x);
251
252/* Returns the character equivalent of a nibble, bit 3, 2, 1, and 0 of a byte,
253   represented by int x. */
254static char lowhex (int x);
255
256/* Returns the integer equivalent of a hexadecimal character. */
257static int hex (char ch);
258
259/* Convert the memory, pointed to by mem into hexadecimal representation.
260   Put the result in buf, and return a pointer to the last character
261   in buf (null). */
262static char *mem2hex (char *buf, unsigned char *mem, int count);
263
264/* Convert the array, in hexadecimal representation, pointed to by buf into
265   binary representation. Put the result in mem, and return a pointer to
266   the character after the last byte written. */
267static unsigned char *hex2mem (unsigned char *mem, char *buf, int count);
268
269/* Put the content of the array, in binary representation, pointed to by buf
270   into memory pointed to by mem, and return a pointer to
271   the character after the last byte written. */
272static unsigned char *bin2mem (unsigned char *mem, unsigned char *buf, int count);
273
274/* Await the sequence $<data>#<checksum> and store <data> in the array buffer
275   returned. */
276static void getpacket (char *buffer);
277
278/* Send $<data>#<checksum> from the <data> in the array buffer. */
279static void putpacket (char *buffer);
280
281/* Build and send a response packet in order to inform the host the
282   stub is stopped. */
283static void stub_is_stopped (int sigval);
284
285/* All expected commands are sent from remote.c. Send a response according
286   to the description in remote.c. */
287static void handle_exception (int sigval);
288
289/* Performs a complete re-start from scratch. ETRAX specific. */
290static void kill_restart (void);
291
292/******************** Prototypes for global functions. ***********************/
293
294/* The string str is prepended with the GDB printout token and sent. */
295void putDebugString (const unsigned char *str, int length); /* used by etrax100ser.c */
296
297/* The hook for both static (compiled) and dynamic breakpoints set by GDB.
298   ETRAX 100 specific. */
299void handle_breakpoint (void);                          /* used by irq.c */
300
301/* The hook for an interrupt generated by GDB. ETRAX 100 specific. */
302void handle_interrupt (void);                           /* used by irq.c */
303
304/* A static breakpoint to be used at startup. */
305void breakpoint (void);                                 /* called by init/main.c */
306
307/* From osys_int.c, executing_task contains the number of the current
308   executing task in osys. Does not know of object-oriented threads. */
309extern unsigned char executing_task;
310
311/* The number of characters used for a 64 bit thread identifier. */
312#define HEXCHARS_IN_THREAD_ID 16
313
314/* Avoid warning as the internal_stack is not used in the C-code. */
315#define USEDVAR(name)    { if (name) { ; } }
316#define USEDFUN(name) { void (*pf)(void) = (void *)name; USEDVAR(pf) }
317
318/********************************** Packet I/O ******************************/
319/* BUFMAX defines the maximum number of characters in
320   inbound/outbound buffers */
321#define BUFMAX 512
322
323/* Run-length encoding maximum length. Send 64 at most. */
324#define RUNLENMAX 64
325
326/* Definition of all valid hexadecimal characters */
327static const char hexchars[] = "0123456789abcdef";
328
329/* The inbound/outbound buffers used in packet I/O */
330static char remcomInBuffer[BUFMAX];
331static char remcomOutBuffer[BUFMAX];
332
333/* Error and warning messages. */
334enum error_type
335{
336	SUCCESS, E01, E02, E03, E04, E05, E06, E07
337};
338static char *error_message[] =
339{
340	"",
341	"E01 Set current or general thread - H[c,g] - internal error.",
342	"E02 Change register content - P - cannot change read-only register.",
343	"E03 Thread is not alive.", /* T, not used. */
344	"E04 The command is not supported - [s,C,S,!,R,d,r] - internal error.",
345	"E05 Change register content - P - the register is not implemented..",
346	"E06 Change memory content - M - internal error.",
347	"E07 Change register content - P - the register is not stored on the stack"
348};
349/********************************* Register image ****************************/
350/* Use the order of registers as defined in "AXIS ETRAX CRIS Programmer's
351   Reference", p. 1-1, with the additional register definitions of the
352   ETRAX 100LX in cris-opc.h.
353   There are 16 general 32-bit registers, R0-R15, where R14 is the stack
354   pointer, SP, and R15 is the program counter, PC.
355   There are 16 special registers, P0-P15, where three of the unimplemented
356   registers, P0, P4 and P8, are reserved as zero-registers. A read from
357   any of these registers returns zero and a write has no effect. */
358enum register_name
359{
360	R0,  R1,   R2,  R3,
361	R4,  R5,   R6,  R7,
362	R8,  R9,   R10, R11,
363	R12, R13,  SP,  PC,
364	P0,  VR,   P2,  P3,
365	P4,  CCR,  P6,  MOF,
366	P8,  IBR,  IRP, SRP,
367	BAR, DCCR, BRP, USP
368};
369
370/* The register sizes of the registers in register_name. An unimplemented register
371   is designated by size 0 in this array. */
372static int register_size[] =
373{
374	4, 4, 4, 4,
375	4, 4, 4, 4,
376	4, 4, 4, 4,
377	4, 4, 4, 4,
378	1, 1, 0, 0,
379	2, 2, 0, 4,
380	4, 4, 4, 4,
381	4, 4, 4, 4
382};
383
384/* Contains the register image of the executing thread in the assembler
385   part of the code in order to avoid horrible addressing modes. */
386static registers reg;
387
388/* Contains the assumed consistency state of the register image. Uses the
389   enum error_type for state information. */
390static int consistency_status = SUCCESS;
391
392/********************************** Handle exceptions ************************/
393/* The variable reg contains the register image associated with the
394   current_thread_c variable. It is a complete register image created at
395   entry. The reg_g contains a register image of a task where the general
396   registers are taken from the stack and all special registers are taken
397   from the executing task. It is associated with current_thread_g and used
398   in order to provide access mainly for 'g', 'G' and 'P'.
399*/
400
401/* Need two task id pointers in order to handle Hct and Hgt commands. */
402static int current_thread_c = 0;
403static int current_thread_g = 0;
404
405/* Need two register images in order to handle Hct and Hgt commands. The
406   variable reg_g is in addition to reg above. */
407static registers reg_g;
408
409/********************************** Breakpoint *******************************/
410/* Use an internal stack in the breakpoint and interrupt response routines */
411#define INTERNAL_STACK_SIZE 1024
412static char internal_stack[INTERNAL_STACK_SIZE];
413
414/* Due to the breakpoint return pointer, a state variable is needed to keep
415   track of whether it is a static (compiled) or dynamic (gdb-invoked)
416   breakpoint to be handled. A static breakpoint uses the content of register
417   BRP as it is whereas a dynamic breakpoint requires subtraction with 2
418   in order to execute the instruction. The first breakpoint is static. */
419static unsigned char is_dyn_brkp = 0;
420
421/********************************* String library ****************************/
422/* Single-step over library functions creates trap loops. */
423
424/* Copy char s2[] to s1[]. */
425static char*
426gdb_cris_strcpy (char *s1, const char *s2)
427{
428	char *s = s1;
429
430	for (s = s1; (*s++ = *s2++) != '\0'; )
431		;
432	return (s1);
433}
434
435/* Find length of s[]. */
436static int
437gdb_cris_strlen (const char *s)
438{
439	const char *sc;
440
441	for (sc = s; *sc != '\0'; sc++)
442		;
443	return (sc - s);
444}
445
446/* Find first occurrence of c in s[n]. */
447static void*
448gdb_cris_memchr (const void *s, int c, int n)
449{
450	const unsigned char uc = c;
451	const unsigned char *su;
452
453	for (su = s; 0 < n; ++su, --n)
454		if (*su == uc)
455			return ((void *)su);
456	return (NULL);
457}
458/******************************* Standard library ****************************/
459/* Single-step over library functions creates trap loops. */
460/* Convert string to long. */
461static int
462gdb_cris_strtol (const char *s, char **endptr, int base)
463{
464	char *s1;
465	char *sd;
466	int x = 0;
467
468	for (s1 = (char*)s; (sd = gdb_cris_memchr(hexchars, *s1, base)) != NULL; ++s1)
469		x = x * base + (sd - hexchars);
470
471        if (endptr)
472        {
473                /* Unconverted suffix is stored in endptr unless endptr is NULL. */
474                *endptr = s1;
475        }
476
477	return x;
478}
479
480/********************************* Register image ****************************/
481/* Copy the content of a register image into another. The size n is
482   the size of the register image. Due to struct assignment generation of
483   memcpy in libc. */
484static void
485copy_registers (registers *dptr, registers *sptr, int n)
486{
487	unsigned char *dreg;
488	unsigned char *sreg;
489
490	for (dreg = (unsigned char*)dptr, sreg = (unsigned char*)sptr; n > 0; n--)
491		*dreg++ = *sreg++;
492}
493
494#ifdef PROCESS_SUPPORT
495/* Copy the stored registers from the stack. Put the register contents
496   of thread thread_id in the struct reg. */
497static void
498copy_registers_from_stack (int thread_id, registers *regptr)
499{
500	int j;
501	stack_registers *s = (stack_registers *)stack_list[thread_id];
502	unsigned int *d = (unsigned int *)regptr;
503
504	for (j = 13; j >= 0; j--)
505		*d++ = s->r[j];
506	regptr->sp = (unsigned int)stack_list[thread_id];
507	regptr->pc = s->pc;
508	regptr->dccr = s->dccr;
509	regptr->srp = s->srp;
510}
511
512/* Copy the registers to the stack. Put the register contents of thread
513   thread_id from struct reg to the stack. */
514static void
515copy_registers_to_stack (int thread_id, registers *regptr)
516{
517	int i;
518	stack_registers *d = (stack_registers *)stack_list[thread_id];
519	unsigned int *s = (unsigned int *)regptr;
520
521	for (i = 0; i < 14; i++) {
522		d->r[i] = *s++;
523	}
524	d->pc = regptr->pc;
525	d->dccr = regptr->dccr;
526	d->srp = regptr->srp;
527}
528#endif
529
530/* Write a value to a specified register in the register image of the current
531   thread. Returns status code SUCCESS, E02 or E05. */
532static int
533write_register (int regno, char *val)
534{
535	int status = SUCCESS;
536	registers *current_reg = &reg;
537
538        if (regno >= R0 && regno <= PC) {
539		/* 32-bit register with simple offset. */
540		hex2mem ((unsigned char *)current_reg + regno * sizeof(unsigned int),
541			 val, sizeof(unsigned int));
542	}
543        else if (regno == P0 || regno == VR || regno == P4 || regno == P8) {
544		/* Do not support read-only registers. */
545		status = E02;
546	}
547        else if (regno == CCR) {
548		/* 16 bit register with complex offset. (P4 is read-only, P6 is not implemented,
549                   and P7 (MOF) is 32 bits in ETRAX 100LX. */
550		hex2mem ((unsigned char *)&(current_reg->ccr) + (regno-CCR) * sizeof(unsigned short),
551			 val, sizeof(unsigned short));
552	}
553	else if (regno >= MOF && regno <= USP) {
554		/* 32 bit register with complex offset.  (P8 has been taken care of.) */
555		hex2mem ((unsigned char *)&(current_reg->ibr) + (regno-IBR) * sizeof(unsigned int),
556			 val, sizeof(unsigned int));
557	}
558        else {
559		/* Do not support nonexisting or unimplemented registers (P2, P3, and P6). */
560		status = E05;
561	}
562	return status;
563}
564
565#ifdef PROCESS_SUPPORT
566/* Write a value to a specified register in the stack of a thread other
567   than the current thread. Returns status code SUCCESS or E07. */
568static int
569write_stack_register (int thread_id, int regno, char *valptr)
570{
571	int status = SUCCESS;
572	stack_registers *d = (stack_registers *)stack_list[thread_id];
573	unsigned int val;
574
575	hex2mem ((unsigned char *)&val, valptr, sizeof(unsigned int));
576	if (regno >= R0 && regno < SP) {
577		d->r[regno] = val;
578	}
579	else if (regno == SP) {
580		stack_list[thread_id] = val;
581	}
582	else if (regno == PC) {
583		d->pc = val;
584	}
585	else if (regno == SRP) {
586		d->srp = val;
587	}
588	else if (regno == DCCR) {
589		d->dccr = val;
590	}
591	else {
592		/* Do not support registers in the current thread. */
593		status = E07;
594	}
595	return status;
596}
597#endif
598
599/* Read a value from a specified register in the register image. Returns the
600   value in the register or -1 for non-implemented registers.
601   Should check consistency_status after a call which may be E05 after changes
602   in the implementation. */
603static int
604read_register (char regno, unsigned int *valptr)
605{
606	registers *current_reg = &reg;
607
608	if (regno >= R0 && regno <= PC) {
609		/* 32-bit register with simple offset. */
610		*valptr = *(unsigned int *)((char *)current_reg + regno * sizeof(unsigned int));
611                return SUCCESS;
612	}
613	else if (regno == P0 || regno == VR) {
614		/* 8 bit register with complex offset. */
615		*valptr = (unsigned int)(*(unsigned char *)
616                                         ((char *)&(current_reg->p0) + (regno-P0) * sizeof(char)));
617                return SUCCESS;
618	}
619	else if (regno == P4 || regno == CCR) {
620		/* 16 bit register with complex offset. */
621		*valptr = (unsigned int)(*(unsigned short *)
622                                         ((char *)&(current_reg->p4) + (regno-P4) * sizeof(unsigned short)));
623                return SUCCESS;
624	}
625	else if (regno >= MOF && regno <= USP) {
626		/* 32 bit register with complex offset. */
627		*valptr = *(unsigned int *)((char *)&(current_reg->p8)
628                                            + (regno-P8) * sizeof(unsigned int));
629                return SUCCESS;
630	}
631	else {
632		/* Do not support nonexisting or unimplemented registers (P2, P3, and P6). */
633		consistency_status = E05;
634		return E05;
635	}
636}
637
638/********************************** Packet I/O ******************************/
639/* Returns the character equivalent of a nibble, bit 7, 6, 5, and 4 of a byte,
640   represented by int x. */
641static inline char
642highhex(int x)
643{
644	return hexchars[(x >> 4) & 0xf];
645}
646
647/* Returns the character equivalent of a nibble, bit 3, 2, 1, and 0 of a byte,
648   represented by int x. */
649static inline char
650lowhex(int x)
651{
652	return hexchars[x & 0xf];
653}
654
655/* Returns the integer equivalent of a hexadecimal character. */
656static int
657hex (char ch)
658{
659	if ((ch >= 'a') && (ch <= 'f'))
660		return (ch - 'a' + 10);
661	if ((ch >= '0') && (ch <= '9'))
662		return (ch - '0');
663	if ((ch >= 'A') && (ch <= 'F'))
664		return (ch - 'A' + 10);
665	return (-1);
666}
667
668/* Convert the memory, pointed to by mem into hexadecimal representation.
669   Put the result in buf, and return a pointer to the last character
670   in buf (null). */
671
672static int do_printk = 0;
673
674static char *
675mem2hex(char *buf, unsigned char *mem, int count)
676{
677	int i;
678	int ch;
679
680        if (mem == NULL) {
681                for (i = 0; i < count; i++) {
682                        *buf++ = '0';
683                        *buf++ = '0';
684                }
685        } else {
686                /* Valid mem address. */
687                for (i = 0; i < count; i++) {
688                        ch = *mem++;
689                        *buf++ = highhex (ch);
690                        *buf++ = lowhex (ch);
691                }
692        }
693
694        /* Terminate properly. */
695	*buf = '\0';
696	return (buf);
697}
698
699/* Convert the array, in hexadecimal representation, pointed to by buf into
700   binary representation. Put the result in mem, and return a pointer to
701   the character after the last byte written. */
702static unsigned char*
703hex2mem (unsigned char *mem, char *buf, int count)
704{
705	int i;
706	unsigned char ch;
707	for (i = 0; i < count; i++) {
708		ch = hex (*buf++) << 4;
709		ch = ch + hex (*buf++);
710		*mem++ = ch;
711	}
712	return (mem);
713}
714
715/* Put the content of the array, in binary representation, pointed to by buf
716   into memory pointed to by mem, and return a pointer to the character after
717   the last byte written.
718   Gdb will escape $, #, and the escape char (0x7d). */
719static unsigned char*
720bin2mem (unsigned char *mem, unsigned char *buf, int count)
721{
722	int i;
723	unsigned char *next;
724	for (i = 0; i < count; i++) {
725		/* Check for any escaped characters. Be paranoid and
726		   only unescape chars that should be escaped. */
727		if (*buf == 0x7d) {
728			next = buf + 1;
729			if (*next == 0x3 || *next == 0x4 || *next == 0x5D) /* #, $, ESC */
730				{
731					buf++;
732					*buf += 0x20;
733				}
734		}
735		*mem++ = *buf++;
736	}
737	return (mem);
738}
739
740/* Await the sequence $<data>#<checksum> and store <data> in the array buffer
741   returned. */
742static void
743getpacket (char *buffer)
744{
745	unsigned char checksum;
746	unsigned char xmitcsum;
747	int i;
748	int count;
749	char ch;
750	do {
751		while ((ch = getDebugChar ()) != '$')
752			/* Wait for the start character $ and ignore all other characters */;
753		checksum = 0;
754		xmitcsum = -1;
755		count = 0;
756		/* Read until a # or the end of the buffer is reached */
757		while (count < BUFMAX) {
758			ch = getDebugChar ();
759			if (ch == '#')
760				break;
761			checksum = checksum + ch;
762			buffer[count] = ch;
763			count = count + 1;
764		}
765		buffer[count] = '\0';
766
767		if (ch == '#') {
768			xmitcsum = hex (getDebugChar ()) << 4;
769			xmitcsum += hex (getDebugChar ());
770			if (checksum != xmitcsum) {
771				/* Wrong checksum */
772				putDebugChar ('-');
773			}
774			else {
775				/* Correct checksum */
776				putDebugChar ('+');
777				/* If sequence characters are received, reply with them */
778				if (buffer[2] == ':') {
779					putDebugChar (buffer[0]);
780					putDebugChar (buffer[1]);
781					/* Remove the sequence characters from the buffer */
782					count = gdb_cris_strlen (buffer);
783					for (i = 3; i <= count; i++)
784						buffer[i - 3] = buffer[i];
785				}
786			}
787		}
788	} while (checksum != xmitcsum);
789}
790
791/* Send $<data>#<checksum> from the <data> in the array buffer. */
792
793static void
794putpacket(char *buffer)
795{
796	int checksum;
797	int runlen;
798	int encode;
799
800	do {
801		char *src = buffer;
802		putDebugChar ('$');
803		checksum = 0;
804		while (*src) {
805			/* Do run length encoding */
806			putDebugChar (*src);
807			checksum += *src;
808			runlen = 0;
809			while (runlen < RUNLENMAX && *src == src[runlen]) {
810				runlen++;
811			}
812			if (runlen > 3) {
813				/* Got a useful amount */
814				putDebugChar ('*');
815				checksum += '*';
816				encode = runlen + ' ' - 4;
817				putDebugChar (encode);
818				checksum += encode;
819				src += runlen;
820			}
821			else {
822				src++;
823			}
824		}
825		putDebugChar ('#');
826		putDebugChar (highhex (checksum));
827		putDebugChar (lowhex (checksum));
828	} while(kgdb_started && (getDebugChar() != '+'));
829}
830
831/* The string str is prepended with the GDB printout token and sent. Required
832   in traditional implementations. */
833void
834putDebugString (const unsigned char *str, int length)
835{
836        remcomOutBuffer[0] = 'O';
837        mem2hex(&remcomOutBuffer[1], (unsigned char *)str, length);
838        putpacket(remcomOutBuffer);
839}
840
841/********************************** Handle exceptions ************************/
842/* Build and send a response packet in order to inform the host the
843   stub is stopped. TAAn...:r...;n...:r...;n...:r...;
844                    AA = signal number
845                    n... = register number (hex)
846                    r... = register contents
847                    n... = `thread'
848                    r... = thread process ID.  This is a hex integer.
849                    n... = other string not starting with valid hex digit.
850                    gdb should ignore this n,r pair and go on to the next.
851                    This way we can extend the protocol. */
852static void
853stub_is_stopped(int sigval)
854{
855	char *ptr = remcomOutBuffer;
856	int regno;
857
858	unsigned int reg_cont;
859	int status;
860
861	/* Send trap type (converted to signal) */
862
863	*ptr++ = 'T';
864	*ptr++ = highhex (sigval);
865	*ptr++ = lowhex (sigval);
866
867	/* Send register contents. We probably only need to send the
868	 * PC, frame pointer and stack pointer here. Other registers will be
869	 * explicitely asked for. But for now, send all.
870	 */
871
872	for (regno = R0; regno <= USP; regno++) {
873		/* Store n...:r...; for the registers in the buffer. */
874
875                status = read_register (regno, &reg_cont);
876
877		if (status == SUCCESS) {
878
879                        *ptr++ = highhex (regno);
880                        *ptr++ = lowhex (regno);
881                        *ptr++ = ':';
882
883                        ptr = mem2hex(ptr, (unsigned char *)&reg_cont,
884                                      register_size[regno]);
885                        *ptr++ = ';';
886                }
887
888	}
889
890#ifdef PROCESS_SUPPORT
891	/* Store the registers of the executing thread. Assume that both step,
892	   continue, and register content requests are with respect to this
893	   thread. The executing task is from the operating system scheduler. */
894
895	current_thread_c = executing_task;
896	current_thread_g = executing_task;
897
898	/* A struct assignment translates into a libc memcpy call. Avoid
899	   all libc functions in order to prevent recursive break points. */
900	copy_registers (&reg_g, &reg, sizeof(registers));
901
902	/* Store thread:r...; with the executing task TID. */
903	gdb_cris_strcpy (&remcomOutBuffer[pos], "thread:");
904	pos += gdb_cris_strlen ("thread:");
905	remcomOutBuffer[pos++] = highhex (executing_task);
906	remcomOutBuffer[pos++] = lowhex (executing_task);
907	gdb_cris_strcpy (&remcomOutBuffer[pos], ";");
908#endif
909
910	/* null-terminate and send it off */
911
912	*ptr = 0;
913
914	putpacket (remcomOutBuffer);
915}
916
917/* All expected commands are sent from remote.c. Send a response according
918   to the description in remote.c. */
919static void
920handle_exception (int sigval)
921{
922	/* Avoid warning of not used. */
923
924	USEDFUN(handle_exception);
925	USEDVAR(internal_stack[0]);
926
927	/* Send response. */
928
929	stub_is_stopped (sigval);
930
931	for (;;) {
932		remcomOutBuffer[0] = '\0';
933		getpacket (remcomInBuffer);
934		switch (remcomInBuffer[0]) {
935			case 'g':
936				/* Read registers: g
937				   Success: Each byte of register data is described by two hex digits.
938				   Registers are in the internal order for GDB, and the bytes
939				   in a register  are in the same order the machine uses.
940				   Failure: void. */
941
942				{
943#ifdef PROCESS_SUPPORT
944					/* Use the special register content in the executing thread. */
945					copy_registers (&reg_g, &reg, sizeof(registers));
946					/* Replace the content available on the stack. */
947					if (current_thread_g != executing_task) {
948						copy_registers_from_stack (current_thread_g, &reg_g);
949					}
950					mem2hex ((unsigned char *)remcomOutBuffer, (unsigned char *)&reg_g, sizeof(registers));
951#else
952					mem2hex(remcomOutBuffer, (char *)&reg, sizeof(registers));
953#endif
954				}
955				break;
956
957			case 'G':
958				/* Write registers. GXX..XX
959				   Each byte of register data  is described by two hex digits.
960				   Success: OK
961				   Failure: void. */
962#ifdef PROCESS_SUPPORT
963				hex2mem ((unsigned char *)&reg_g, &remcomInBuffer[1], sizeof(registers));
964				if (current_thread_g == executing_task) {
965					copy_registers (&reg, &reg_g, sizeof(registers));
966				}
967				else {
968					copy_registers_to_stack(current_thread_g, &reg_g);
969				}
970#else
971				hex2mem((char *)&reg, &remcomInBuffer[1], sizeof(registers));
972#endif
973				gdb_cris_strcpy (remcomOutBuffer, "OK");
974				break;
975
976			case 'P':
977				/* Write register. Pn...=r...
978				   Write register n..., hex value without 0x, with value r...,
979				   which contains a hex value without 0x and two hex digits
980				   for each byte in the register (target byte order). P1f=11223344 means
981				   set register 31 to 44332211.
982				   Success: OK
983				   Failure: E02, E05 */
984				{
985					char *suffix;
986					int regno = gdb_cris_strtol (&remcomInBuffer[1], &suffix, 16);
987					int status;
988#ifdef PROCESS_SUPPORT
989					if (current_thread_g != executing_task)
990						status = write_stack_register (current_thread_g, regno, suffix+1);
991					else
992#endif
993						status = write_register (regno, suffix+1);
994
995					switch (status) {
996						case E02:
997							/* Do not support read-only registers. */
998							gdb_cris_strcpy (remcomOutBuffer, error_message[E02]);
999							break;
1000						case E05:
1001							/* Do not support non-existing registers. */
1002							gdb_cris_strcpy (remcomOutBuffer, error_message[E05]);
1003							break;
1004						case E07:
1005							/* Do not support non-existing registers on the stack. */
1006							gdb_cris_strcpy (remcomOutBuffer, error_message[E07]);
1007							break;
1008						default:
1009							/* Valid register number. */
1010							gdb_cris_strcpy (remcomOutBuffer, "OK");
1011							break;
1012					}
1013				}
1014				break;
1015
1016			case 'm':
1017				/* Read from memory. mAA..AA,LLLL
1018				   AA..AA is the address and LLLL is the length.
1019				   Success: XX..XX is the memory content.  Can be fewer bytes than
1020				   requested if only part of the data may be read. m6000120a,6c means
1021				   retrieve 108 byte from base address 6000120a.
1022				   Failure: void. */
1023				{
1024                                        char *suffix;
1025					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
1026                                                                                               &suffix, 16);                                        int length = gdb_cris_strtol(suffix+1, 0, 16);
1027
1028                                        mem2hex(remcomOutBuffer, addr, length);
1029                                }
1030				break;
1031
1032			case 'X':
1033				/* Write to memory. XAA..AA,LLLL:XX..XX
1034				   AA..AA is the start address,  LLLL is the number of bytes, and
1035				   XX..XX is the binary data.
1036				   Success: OK
1037				   Failure: void. */
1038			case 'M':
1039				/* Write to memory. MAA..AA,LLLL:XX..XX
1040				   AA..AA is the start address,  LLLL is the number of bytes, and
1041				   XX..XX is the hexadecimal data.
1042				   Success: OK
1043				   Failure: void. */
1044				{
1045					char *lenptr;
1046					char *dataptr;
1047					unsigned char *addr = (unsigned char *)gdb_cris_strtol(&remcomInBuffer[1],
1048										      &lenptr, 16);
1049					int length = gdb_cris_strtol(lenptr+1, &dataptr, 16);
1050					if (*lenptr == ',' && *dataptr == ':') {
1051						if (remcomInBuffer[0] == 'M') {
1052							hex2mem(addr, dataptr + 1, length);
1053						}
1054						else /* X */ {
1055							bin2mem(addr, dataptr + 1, length);
1056						}
1057						gdb_cris_strcpy (remcomOutBuffer, "OK");
1058					}
1059					else {
1060						gdb_cris_strcpy (remcomOutBuffer, error_message[E06]);
1061					}
1062				}
1063				break;
1064
1065			case 'c':
1066				/* Continue execution. cAA..AA
1067				   AA..AA is the address where execution is resumed. If AA..AA is
1068				   omitted, resume at the present address.
1069				   Success: return to the executing thread.
1070				   Failure: will never know. */
1071				if (remcomInBuffer[1] != '\0') {
1072					reg.pc = gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
1073				}
1074				enableDebugIRQ();
1075				return;
1076
1077			case 's':
1078				/* Step. sAA..AA
1079				   AA..AA is the address where execution is resumed. If AA..AA is
1080				   omitted, resume at the present address. Success: return to the
1081				   executing thread. Failure: will never know.
1082
1083				   Should never be invoked. The single-step is implemented on
1084				   the host side. If ever invoked, it is an internal error E04. */
1085				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
1086				putpacket (remcomOutBuffer);
1087				return;
1088
1089			case '?':
1090				/* The last signal which caused a stop. ?
1091				   Success: SAA, where AA is the signal number.
1092				   Failure: void. */
1093				remcomOutBuffer[0] = 'S';
1094				remcomOutBuffer[1] = highhex (sigval);
1095				remcomOutBuffer[2] = lowhex (sigval);
1096				remcomOutBuffer[3] = 0;
1097				break;
1098
1099			case 'D':
1100				/* Detach from host. D
1101				   Success: OK, and return to the executing thread.
1102				   Failure: will never know */
1103				putpacket ("OK");
1104				return;
1105
1106			case 'k':
1107			case 'r':
1108				/* kill request or reset request.
1109				   Success: restart of target.
1110				   Failure: will never know. */
1111				kill_restart ();
1112				break;
1113
1114			case 'C':
1115			case 'S':
1116			case '!':
1117			case 'R':
1118			case 'd':
1119				/* Continue with signal sig. Csig;AA..AA
1120				   Step with signal sig. Ssig;AA..AA
1121				   Use the extended remote protocol. !
1122				   Restart the target system. R0
1123				   Toggle debug flag. d
1124				   Search backwards. tAA:PP,MM
1125				   Not supported: E04 */
1126				gdb_cris_strcpy (remcomOutBuffer, error_message[E04]);
1127				break;
1128#ifdef PROCESS_SUPPORT
1129
1130			case 'T':
1131				/* Thread alive. TXX
1132				   Is thread XX alive?
1133				   Success: OK, thread XX is alive.
1134				   Failure: E03, thread XX is dead. */
1135				{
1136					int thread_id = (int)gdb_cris_strtol (&remcomInBuffer[1], 0, 16);
1137					/* Cannot tell whether it is alive or not. */
1138					if (thread_id >= 0 && thread_id < number_of_tasks)
1139						gdb_cris_strcpy (remcomOutBuffer, "OK");
1140				}
1141				break;
1142
1143			case 'H':
1144				/* Set thread for subsequent operations: Hct
1145				   c = 'c' for thread used in step and continue;
1146				   t can be -1 for all threads.
1147				   c = 'g' for thread used in other  operations.
1148				   t = 0 means pick any thread.
1149				   Success: OK
1150				   Failure: E01 */
1151				{
1152					int thread_id = gdb_cris_strtol (&remcomInBuffer[2], 0, 16);
1153					if (remcomInBuffer[1] == 'c') {
1154						/* c = 'c' for thread used in step and continue */
1155						/* Do not change current_thread_c here. It would create a mess in
1156						   the scheduler. */
1157						gdb_cris_strcpy (remcomOutBuffer, "OK");
1158					}
1159					else if (remcomInBuffer[1] == 'g') {
1160						/* c = 'g' for thread used in other  operations.
1161						   t = 0 means pick any thread. Impossible since the scheduler does
1162						   not allow that. */
1163						if (thread_id >= 0 && thread_id < number_of_tasks) {
1164							current_thread_g = thread_id;
1165							gdb_cris_strcpy (remcomOutBuffer, "OK");
1166						}
1167						else {
1168							/* Not expected - send an error message. */
1169							gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
1170						}
1171					}
1172					else {
1173						/* Not expected - send an error message. */
1174						gdb_cris_strcpy (remcomOutBuffer, error_message[E01]);
1175					}
1176				}
1177				break;
1178
1179			case 'q':
1180			case 'Q':
1181				{
1182					int pos;
1183					int nextpos;
1184					int thread_id;
1185
1186					switch (remcomInBuffer[1]) {
1187						case 'C':
1188							/* Identify the remote current thread. */
1189							gdb_cris_strcpy (&remcomOutBuffer[0], "QC");
1190							remcomOutBuffer[2] = highhex (current_thread_c);
1191							remcomOutBuffer[3] = lowhex (current_thread_c);
1192							remcomOutBuffer[4] = '\0';
1193							break;
1194						case 'L':
1195							gdb_cris_strcpy (&remcomOutBuffer[0], "QM");
1196							/* Reply with number of threads. */
1197							if (os_is_started()) {
1198								remcomOutBuffer[2] = highhex (number_of_tasks);
1199								remcomOutBuffer[3] = lowhex (number_of_tasks);
1200							}
1201							else {
1202								remcomOutBuffer[2] = highhex (0);
1203								remcomOutBuffer[3] = lowhex (1);
1204							}
1205							/* Done with the reply. */
1206							remcomOutBuffer[4] = lowhex (1);
1207							pos = 5;
1208							/* Expects the argument thread id. */
1209							for (; pos < (5 + HEXCHARS_IN_THREAD_ID); pos++)
1210								remcomOutBuffer[pos] = remcomInBuffer[pos];
1211							/* Reply with the thread identifiers. */
1212							if (os_is_started()) {
1213								/* Store the thread identifiers of all tasks. */
1214								for (thread_id = 0; thread_id < number_of_tasks; thread_id++) {
1215									nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
1216									for (; pos < nextpos; pos ++)
1217										remcomOutBuffer[pos] = lowhex (0);
1218									remcomOutBuffer[pos++] = lowhex (thread_id);
1219								}
1220							}
1221							else {
1222								/* Store the thread identifier of the boot task. */
1223								nextpos = pos + HEXCHARS_IN_THREAD_ID - 1;
1224								for (; pos < nextpos; pos ++)
1225									remcomOutBuffer[pos] = lowhex (0);
1226								remcomOutBuffer[pos++] = lowhex (current_thread_c);
1227							}
1228							remcomOutBuffer[pos] = '\0';
1229							break;
1230						default:
1231							/* Not supported: "" */
1232							/* Request information about section offsets: qOffsets. */
1233							remcomOutBuffer[0] = 0;
1234							break;
1235					}
1236				}
1237				break;
1238#endif /* PROCESS_SUPPORT */
1239
1240			default:
1241				/* The stub should ignore other request and send an empty
1242				   response ($#<checksum>). This way we can extend the protocol and GDB
1243				   can tell whether the stub it is talking to uses the old or the new. */
1244				remcomOutBuffer[0] = 0;
1245				break;
1246		}
1247		putpacket(remcomOutBuffer);
1248	}
1249}
1250
1251/* Performs a complete re-start from scratch. */
1252static void
1253kill_restart ()
1254{
1255	machine_restart("");
1256}
1257
1258/********************************** Breakpoint *******************************/
1259/* The hook for both a static (compiled) and a dynamic breakpoint set by GDB.
1260   An internal stack is used by the stub. The register image of the caller is
1261   stored in the structure register_image.
1262   Interactive communication with the host is handled by handle_exception and
1263   finally the register image is restored. */
1264
1265void kgdb_handle_breakpoint(void);
1266
1267asm ("
1268  .global kgdb_handle_breakpoint
1269kgdb_handle_breakpoint:
1270;;
1271;; Response to the break-instruction
1272;;
1273;; Create a register image of the caller
1274;;
1275  move     $dccr,[reg+0x5E] ; Save the flags in DCCR before disable interrupts
1276  di                        ; Disable interrupts
1277  move.d   $r0,[reg]        ; Save R0
1278  move.d   $r1,[reg+0x04]   ; Save R1
1279  move.d   $r2,[reg+0x08]   ; Save R2
1280  move.d   $r3,[reg+0x0C]   ; Save R3
1281  move.d   $r4,[reg+0x10]   ; Save R4
1282  move.d   $r5,[reg+0x14]   ; Save R5
1283  move.d   $r6,[reg+0x18]   ; Save R6
1284  move.d   $r7,[reg+0x1C]   ; Save R7
1285  move.d   $r8,[reg+0x20]   ; Save R8
1286  move.d   $r9,[reg+0x24]   ; Save R9
1287  move.d   $r10,[reg+0x28]  ; Save R10
1288  move.d   $r11,[reg+0x2C]  ; Save R11
1289  move.d   $r12,[reg+0x30]  ; Save R12
1290  move.d   $r13,[reg+0x34]  ; Save R13
1291  move.d   $sp,[reg+0x38]   ; Save SP (R14)
1292;; Due to the old assembler-versions BRP might not be recognized
1293  .word 0xE670              ; move brp,$r0
1294  subq     2,$r0             ; Set to address of previous instruction.
1295  move.d   $r0,[reg+0x3c]   ; Save the address in PC (R15)
1296  clear.b  [reg+0x40]      ; Clear P0
1297  move     $vr,[reg+0x41]   ; Save special register P1
1298  clear.w  [reg+0x42]      ; Clear P4
1299  move     $ccr,[reg+0x44]  ; Save special register CCR
1300  move     $mof,[reg+0x46]  ; P7
1301  clear.d  [reg+0x4A]      ; Clear P8
1302  move     $ibr,[reg+0x4E]  ; P9,
1303  move     $irp,[reg+0x52]  ; P10,
1304  move     $srp,[reg+0x56]  ; P11,
1305  move     $dtp0,[reg+0x5A] ; P12, register BAR, assembler might not know BAR
1306                            ; P13, register DCCR already saved
1307;; Due to the old assembler-versions BRP might not be recognized
1308  .word 0xE670              ; move brp,r0
1309;; Static (compiled) breakpoints must return to the next instruction in order
1310;; to avoid infinite loops. Dynamic (gdb-invoked) must restore the instruction
1311;; in order to execute it when execution is continued.
1312  test.b   [is_dyn_brkp]    ; Is this a dynamic breakpoint?
1313  beq      is_static         ; No, a static breakpoint
1314  nop
1315  subq     2,$r0              ; rerun the instruction the break replaced
1316is_static:
1317  moveq    1,$r1
1318  move.b   $r1,[is_dyn_brkp] ; Set the state variable to dynamic breakpoint
1319  move.d   $r0,[reg+0x62]    ; Save the return address in BRP
1320  move     $usp,[reg+0x66]   ; USP
1321;;
1322;; Handle the communication
1323;;
1324  move.d   internal_stack+1020,$sp ; Use the internal stack which grows upward
1325  moveq    5,$r10                   ; SIGTRAP
1326  jsr      handle_exception       ; Interactive routine
1327;;
1328;; Return to the caller
1329;;
1330   move.d  [reg],$r0         ; Restore R0
1331   move.d  [reg+0x04],$r1    ; Restore R1
1332   move.d  [reg+0x08],$r2    ; Restore R2
1333   move.d  [reg+0x0C],$r3    ; Restore R3
1334   move.d  [reg+0x10],$r4    ; Restore R4
1335   move.d  [reg+0x14],$r5    ; Restore R5
1336   move.d  [reg+0x18],$r6    ; Restore R6
1337   move.d  [reg+0x1C],$r7    ; Restore R7
1338   move.d  [reg+0x20],$r8    ; Restore R8
1339   move.d  [reg+0x24],$r9    ; Restore R9
1340   move.d  [reg+0x28],$r10   ; Restore R10
1341   move.d  [reg+0x2C],$r11   ; Restore R11
1342   move.d  [reg+0x30],$r12   ; Restore R12
1343   move.d  [reg+0x34],$r13   ; Restore R13
1344;;
1345;; FIXME: Which registers should be restored?
1346;;
1347   move.d  [reg+0x38],$sp    ; Restore SP (R14)
1348   move    [reg+0x56],$srp   ; Restore the subroutine return pointer.
1349   move    [reg+0x5E],$dccr  ; Restore DCCR
1350   move    [reg+0x66],$usp   ; Restore USP
1351   jump    [reg+0x62]       ; A jump to the content in register BRP works.
1352   nop                       ;
1353");
1354
1355/* The hook for an interrupt generated by GDB. An internal stack is used
1356   by the stub. The register image of the caller is stored in the structure
1357   register_image. Interactive communication with the host is handled by
1358   handle_exception and finally the register image is restored. Due to the
1359   old assembler which does not recognise the break instruction and the
1360   breakpoint return pointer hex-code is used. */
1361
1362void kgdb_handle_serial(void);
1363
1364asm ("
1365  .global kgdb_handle_serial
1366kgdb_handle_serial:
1367;;
1368;; Response to a serial interrupt
1369;;
1370
1371  move     $dccr,[reg+0x5E] ; Save the flags in DCCR
1372  di                        ; Disable interrupts
1373  move.d   $r0,[reg]        ; Save R0
1374  move.d   $r1,[reg+0x04]   ; Save R1
1375  move.d   $r2,[reg+0x08]   ; Save R2
1376  move.d   $r3,[reg+0x0C]   ; Save R3
1377  move.d   $r4,[reg+0x10]   ; Save R4
1378  move.d   $r5,[reg+0x14]   ; Save R5
1379  move.d   $r6,[reg+0x18]   ; Save R6
1380  move.d   $r7,[reg+0x1C]   ; Save R7
1381  move.d   $r8,[reg+0x20]   ; Save R8
1382  move.d   $r9,[reg+0x24]   ; Save R9
1383  move.d   $r10,[reg+0x28]  ; Save R10
1384  move.d   $r11,[reg+0x2C]  ; Save R11
1385  move.d   $r12,[reg+0x30]  ; Save R12
1386  move.d   $r13,[reg+0x34]  ; Save R13
1387  move.d   $sp,[reg+0x38]   ; Save SP (R14)
1388  move     $irp,[reg+0x3c]  ; Save the address in PC (R15)
1389  clear.b  [reg+0x40]      ; Clear P0
1390  move     $vr,[reg+0x41]   ; Save special register P1,
1391  clear.w  [reg+0x42]      ; Clear P4
1392  move     $ccr,[reg+0x44]  ; Save special register CCR
1393  move     $mof,[reg+0x46]  ; P7
1394  clear.d  [reg+0x4A]      ; Clear P8
1395  move     $ibr,[reg+0x4E]  ; P9,
1396  move     $irp,[reg+0x52]  ; P10,
1397  move     $srp,[reg+0x56]  ; P11,
1398  move     $dtp0,[reg+0x5A] ; P12, register BAR, assembler might not know BAR
1399                            ; P13, register DCCR already saved
1400;; Due to the old assembler-versions BRP might not be recognized
1401  .word 0xE670              ; move brp,r0
1402  move.d   $r0,[reg+0x62]   ; Save the return address in BRP
1403  move     $usp,[reg+0x66]  ; USP
1404
1405;; get the serial character (from debugport.c) and check if it is a ctrl-c
1406
1407  jsr getDebugChar
1408  cmp.b 3, $r10
1409  bne goback
1410  nop
1411
1412  move.d  [reg+0x5E], $r10		; Get DCCR
1413  btstq	   8, $r10			; Test the U-flag.
1414  bmi	   goback
1415  nop
1416
1417;;
1418;; Handle the communication
1419;;
1420  move.d   internal_stack+1020,$sp ; Use the internal stack
1421  moveq    2,$r10                   ; SIGINT
1422  jsr      handle_exception       ; Interactive routine
1423
1424goback:
1425;;
1426;; Return to the caller
1427;;
1428   move.d  [reg],$r0         ; Restore R0
1429   move.d  [reg+0x04],$r1    ; Restore R1
1430   move.d  [reg+0x08],$r2    ; Restore R2
1431   move.d  [reg+0x0C],$r3    ; Restore R3
1432   move.d  [reg+0x10],$r4    ; Restore R4
1433   move.d  [reg+0x14],$r5    ; Restore R5
1434   move.d  [reg+0x18],$r6    ; Restore R6
1435   move.d  [reg+0x1C],$r7    ; Restore R7
1436   move.d  [reg+0x20],$r8    ; Restore R8
1437   move.d  [reg+0x24],$r9    ; Restore R9
1438   move.d  [reg+0x28],$r10   ; Restore R10
1439   move.d  [reg+0x2C],$r11   ; Restore R11
1440   move.d  [reg+0x30],$r12   ; Restore R12
1441   move.d  [reg+0x34],$r13   ; Restore R13
1442;;
1443;; FIXME: Which registers should be restored?
1444;;
1445   move.d  [reg+0x38],$sp    ; Restore SP (R14)
1446   move    [reg+0x56],$srp   ; Restore the subroutine return pointer.
1447   move    [reg+0x5E],$dccr  ; Restore DCCR
1448   move    [reg+0x66],$usp   ; Restore USP
1449   reti                      ; Return from the interrupt routine
1450   nop
1451");
1452
1453/* Use this static breakpoint in the start-up only. */
1454
1455void
1456breakpoint(void)
1457{
1458	kgdb_started = 1;
1459	is_dyn_brkp = 0;     /* This is a static, not a dynamic breakpoint. */
1460	__asm__ volatile ("break 8"); /* Jump to handle_breakpoint. */
1461}
1462
1463/* initialize kgdb. doesn't break into the debugger, but sets up irq and ports */
1464
1465void
1466kgdb_init(void)
1467{
1468	/* could initialize debug port as well but it's done in head.S already... */
1469
1470        /* breakpoint handler is now set in irq.c */
1471	set_int_vector(8, kgdb_handle_serial);
1472
1473	enableDebugIRQ();
1474}
1475
1476/****************************** End of file **********************************/
1477