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