OSDN Git Service

Initial revision
[pf3gnuchains/pf3gnuchains3x.git] / gdb / sh-stub.c
1 /* sh-stub.c -- debugging stub for the Hitachi-SH. 
2
3  NOTE!! This code has to be compiled with optimization, otherwise the 
4  function inlining which generates the exception handlers won't work.
5  
6 */
7
8 /*   This is originally based on an m68k software stub written by Glenn
9      Engel at HP, but has changed quite a bit. 
10
11      Modifications for the SH by Ben Lee and Steve Chamberlain
12
13 */
14
15 /****************************************************************************
16
17                 THIS SOFTWARE IS NOT COPYRIGHTED
18
19    HP offers the following for use in the public domain.  HP makes no
20    warranty with regard to the software or it's performance and the
21    user accepts the software "AS IS" with all faults.
22
23    HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
24    TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
25    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26
27 ****************************************************************************/
28
29
30 /* Remote communication protocol.
31
32    A debug packet whose contents are <data>
33    is encapsulated for transmission in the form:
34
35         $ <data> # CSUM1 CSUM2
36
37         <data> must be ASCII alphanumeric and cannot include characters
38         '$' or '#'.  If <data> starts with two characters followed by
39         ':', then the existing stubs interpret this as a sequence number.
40
41         CSUM1 and CSUM2 are ascii hex representation of an 8-bit 
42         checksum of <data>, the most significant nibble is sent first.
43         the hex digits 0-9,a-f are used.
44
45    Receiver responds with:
46
47         +       - if CSUM is correct and ready for next packet
48         -       - if CSUM is incorrect
49
50    <data> is as follows:
51    All values are encoded in ascii hex digits.
52
53         Request         Packet
54
55         read registers  g
56         reply           XX....X         Each byte of register data
57                                         is described by two hex digits.
58                                         Registers are in the internal order
59                                         for GDB, and the bytes in a register
60                                         are in the same order the machine uses.
61                         or ENN          for an error.
62
63         write regs      GXX..XX         Each byte of register data
64                                         is described by two hex digits.
65         reply           OK              for success
66                         ENN             for an error
67
68         write reg       Pn...=r...      Write register n... with value r...,
69                                         which contains two hex digits for each
70                                         byte in the register (target byte
71                                         order).
72         reply           OK              for success
73                         ENN             for an error
74         (not supported by all stubs).
75
76         read mem        mAA..AA,LLLL    AA..AA is address, LLLL is length.
77         reply           XX..XX          XX..XX is mem contents
78                                         Can be fewer bytes than requested
79                                         if able to read only part of the data.
80                         or ENN          NN is errno
81
82         write mem       MAA..AA,LLLL:XX..XX
83                                         AA..AA is address,
84                                         LLLL is number of bytes,
85                                         XX..XX is data
86         reply           OK              for success
87                         ENN             for an error (this includes the case
88                                         where only part of the data was
89                                         written).
90
91         cont            cAA..AA         AA..AA is address to resume
92                                         If AA..AA is omitted,
93                                         resume at same address.
94
95         step            sAA..AA         AA..AA is address to resume
96                                         If AA..AA is omitted,
97                                         resume at same address.
98
99         last signal     ?               Reply the current reason for stopping.
100                                         This is the same reply as is generated
101                                         for step or cont : SAA where AA is the
102                                         signal number.
103
104         There is no immediate reply to step or cont.
105         The reply comes when the machine stops.
106         It is           SAA             AA is the "signal number"
107
108         or...           TAAn...:r...;n:r...;n...:r...;
109                                         AA = signal number
110                                         n... = register number
111                                         r... = register contents
112         or...           WAA             The process exited, and AA is
113                                         the exit status.  This is only
114                                         applicable for certains sorts of
115                                         targets.
116         kill request    k
117
118         toggle debug    d               toggle debug flag (see 386 & 68k stubs)
119         reset           r               reset -- see sparc stub.
120         reserved        <other>         On other requests, the stub should
121                                         ignore the request and send an empty
122                                         response ($#<checksum>).  This way
123                                         we can extend the protocol and GDB
124                                         can tell whether the stub it is
125                                         talking to uses the old or the new.
126         search          tAA:PP,MM       Search backwards starting at address
127                                         AA for a match with pattern PP and
128                                         mask MM.  PP and MM are 4 bytes.
129                                         Not supported by all stubs.
130
131         general query   qXXXX           Request info about XXXX.
132         general set     QXXXX=yyyy      Set value of XXXX to yyyy.
133         query sect offs qOffsets        Get section offsets.  Reply is
134                                         Text=xxx;Data=yyy;Bss=zzz
135         console output  Otext           Send text to stdout.  Only comes from
136                                         remote target.
137
138         Responses can be run-length encoded to save space.  A '*' means that
139         the next character is an ASCII encoding giving a repeat count which
140         stands for that many repititions of the character preceding the '*'.
141         The encoding is n+29, yielding a printable character where n >=3 
142         (which is where rle starts to win).  Don't use an n > 126. 
143
144         So 
145         "0* " means the same as "0000".  */
146
147 #include <string.h>
148 #include <setjmp.h>
149
150
151
152 #define COND_BR_MASK    0xff00
153 #define UCOND_DBR_MASK  0xe000
154 #define UCOND_RBR_MASK  0xf0df
155 #define TRAPA_MASK              0xff00
156
157 #define COND_DISP               0x00ff
158 #define UCOND_DISP              0x0fff
159 #define UCOND_REG               0x0f00
160
161 #define BF_INSTR                0x8b00
162 #define BT_INSTR                0x8900
163 #define BRA_INSTR               0xa000
164 #define BSR_INSTR               0xb000
165 #define JMP_INSTR               0x402b
166 #define JSR_INSTR               0x400b
167 #define RTS_INSTR               0x000b
168 #define RTE_INSTR               0x002b
169 #define TRAPA_INSTR             0xc300
170
171 #define SSTEP_INSTR             0xc3ff
172
173 #define T_BIT_MASK              0x0001
174 /*
175  * BUFMAX defines the maximum number of characters in inbound/outbound
176  * buffers at least NUMREGBYTES*2 are needed for register packets
177  */
178 #define BUFMAX 1024
179
180 /*
181  * Number of bytes for registers
182  */
183 #define NUMREGBYTES 112         /* 92 */
184
185 /*
186  * typedef
187  */
188 typedef void (*Function) ();
189
190 /*
191  * Forward declarations
192  */
193
194 static int hex (char);
195 static char *mem2hex (char *, char *, int);
196 static char *hex2mem (char *, char *, int);
197 static int hexToInt (char **, int *);
198 static void getpacket (char *);
199 static void putpacket (char *);
200 static void handle_buserror (void);
201 static int computeSignal (int exceptionVector);
202 static void handle_exception (int exceptionVector);
203 void init_serial();
204
205 void putDebugChar (char);
206 char getDebugChar (void);
207
208 /* These are in the file but in asm statements so the compiler can't see them */
209 void catch_exception_4 (void);
210 void catch_exception_6 (void);
211 void catch_exception_9 (void);
212 void catch_exception_10 (void);
213 void catch_exception_11 (void);
214 void catch_exception_32 (void);
215 void catch_exception_33 (void);
216 void catch_exception_255 (void);
217
218
219
220 #define catch_exception_random catch_exception_255 /* Treat all odd ones like 255 */
221
222 void breakpoint (void);
223
224
225 #define init_stack_size 8*1024  /* if you change this you should also modify BINIT */
226 #define stub_stack_size 8*1024
227
228 int init_stack[init_stack_size] __attribute__ ((section ("stack"))) = {0};
229 int stub_stack[stub_stack_size] __attribute__ ((section ("stack"))) = {0};
230
231 typedef struct
232   {
233     void (*func_cold) ();
234     int *stack_cold;
235     void (*func_warm) ();
236     int *stack_warm;
237     void (*(handler[256 - 4])) ();
238   }
239 vec_type;
240
241
242 void INIT ();
243 void BINIT ();
244
245 /* When you link take care that this is at address 0 -
246    or wherever your vbr points */
247
248 #define CPU_BUS_ERROR_VEC  9
249 #define DMA_BUS_ERROR_VEC 10
250 #define NMI_VEC           11
251 #define INVALID_INSN_VEC   4
252 #define INVALID_SLOT_VEC   6
253 #define TRAP_VEC          32
254 #define IO_VEC            33
255 #define USER_VEC         255
256
257
258 #define BCR  (*(volatile short *)(0x05FFFFA0)) /* Bus control register */
259 #define BAS  (0x800)                            /* Byte access select */
260 #define WCR1 (*(volatile short *)(0x05ffffA2)) /* Wait state control register */
261
262 const vec_type vectable =
263
264   &BINIT,                       /* 0: Power-on reset PC */
265   init_stack + init_stack_size, /* 1: Power-on reset SP */
266   &BINIT,                       /* 2: Manual reset PC */
267   init_stack + init_stack_size, /* 3: Manual reset SP */
268 {
269   &catch_exception_4,           /* 4: General invalid instruction */
270   &catch_exception_random,      /* 5: Reserved for system */
271   &catch_exception_6,           /* 6: Invalid slot instruction */
272   &catch_exception_random,      /* 7: Reserved for system */
273   &catch_exception_random,      /* 8: Reserved for system */
274   &catch_exception_9,           /* 9: CPU bus error */
275   &catch_exception_10,          /* 10: DMA bus error */
276   &catch_exception_11,          /* 11: NMI */
277   &catch_exception_random,      /* 12: User break */
278   &catch_exception_random,      /* 13: Reserved for system */
279   &catch_exception_random,      /* 14: Reserved for system */
280   &catch_exception_random,      /* 15: Reserved for system */
281   &catch_exception_random,      /* 16: Reserved for system */
282   &catch_exception_random,      /* 17: Reserved for system */
283   &catch_exception_random,      /* 18: Reserved for system */
284   &catch_exception_random,      /* 19: Reserved for system */
285   &catch_exception_random,      /* 20: Reserved for system */
286   &catch_exception_random,      /* 21: Reserved for system */
287   &catch_exception_random,      /* 22: Reserved for system */
288   &catch_exception_random,      /* 23: Reserved for system */
289   &catch_exception_random,      /* 24: Reserved for system */
290   &catch_exception_random,      /* 25: Reserved for system */
291   &catch_exception_random,      /* 26: Reserved for system */
292   &catch_exception_random,      /* 27: Reserved for system */
293   &catch_exception_random,      /* 28: Reserved for system */
294   &catch_exception_random,      /* 29: Reserved for system */
295   &catch_exception_random,      /* 30: Reserved for system */
296   &catch_exception_random,      /* 31: Reserved for system */
297   &catch_exception_32,          /* 32: Trap instr (user vectors) */
298   &catch_exception_33,          /* 33: Trap instr (user vectors) */
299   &catch_exception_random,      /* 34: Trap instr (user vectors) */
300   &catch_exception_random,      /* 35: Trap instr (user vectors) */
301   &catch_exception_random,      /* 36: Trap instr (user vectors) */
302   &catch_exception_random,      /* 37: Trap instr (user vectors) */
303   &catch_exception_random,      /* 38: Trap instr (user vectors) */
304   &catch_exception_random,      /* 39: Trap instr (user vectors) */
305   &catch_exception_random,      /* 40: Trap instr (user vectors) */
306   &catch_exception_random,      /* 41: Trap instr (user vectors) */
307   &catch_exception_random,      /* 42: Trap instr (user vectors) */
308   &catch_exception_random,      /* 43: Trap instr (user vectors) */
309   &catch_exception_random,      /* 44: Trap instr (user vectors) */
310   &catch_exception_random,      /* 45: Trap instr (user vectors) */
311   &catch_exception_random,      /* 46: Trap instr (user vectors) */
312   &catch_exception_random,      /* 47: Trap instr (user vectors) */
313   &catch_exception_random,      /* 48: Trap instr (user vectors) */
314   &catch_exception_random,      /* 49: Trap instr (user vectors) */
315   &catch_exception_random,      /* 50: Trap instr (user vectors) */
316   &catch_exception_random,      /* 51: Trap instr (user vectors) */
317   &catch_exception_random,      /* 52: Trap instr (user vectors) */
318   &catch_exception_random,      /* 53: Trap instr (user vectors) */
319   &catch_exception_random,      /* 54: Trap instr (user vectors) */
320   &catch_exception_random,      /* 55: Trap instr (user vectors) */
321   &catch_exception_random,      /* 56: Trap instr (user vectors) */
322   &catch_exception_random,      /* 57: Trap instr (user vectors) */
323   &catch_exception_random,      /* 58: Trap instr (user vectors) */
324   &catch_exception_random,      /* 59: Trap instr (user vectors) */
325   &catch_exception_random,      /* 60: Trap instr (user vectors) */
326   &catch_exception_random,      /* 61: Trap instr (user vectors) */
327   &catch_exception_random,      /* 62: Trap instr (user vectors) */
328   &catch_exception_random,      /* 63: Trap instr (user vectors) */
329   &catch_exception_random,      /* 64: IRQ0 */
330   &catch_exception_random,      /* 65: IRQ1 */
331   &catch_exception_random,      /* 66: IRQ2 */
332   &catch_exception_random,      /* 67: IRQ3 */
333   &catch_exception_random,      /* 68: IRQ4 */
334   &catch_exception_random,      /* 69: IRQ5 */
335   &catch_exception_random,      /* 70: IRQ6 */
336   &catch_exception_random,      /* 71: IRQ7 */
337   &catch_exception_random,
338   &catch_exception_random,
339   &catch_exception_random,
340   &catch_exception_random,
341   &catch_exception_random,
342   &catch_exception_random,
343   &catch_exception_random,
344   &catch_exception_random,
345   &catch_exception_random,
346      &catch_exception_random,
347      &catch_exception_random,
348      &catch_exception_random,
349      &catch_exception_random,
350      &catch_exception_random,
351      &catch_exception_random,
352      &catch_exception_random,
353      &catch_exception_random,
354      &catch_exception_random,
355      &catch_exception_random,
356      &catch_exception_random,
357      &catch_exception_random,
358      &catch_exception_random,
359      &catch_exception_random,
360      &catch_exception_random,
361      &catch_exception_random,
362      &catch_exception_random,
363      &catch_exception_random,
364      &catch_exception_random,
365      &catch_exception_random,
366      &catch_exception_random,
367      &catch_exception_random,
368      &catch_exception_random,
369      &catch_exception_random,
370      &catch_exception_random,
371      &catch_exception_random,
372      &catch_exception_random,
373      &catch_exception_random,
374      &catch_exception_random,
375      &catch_exception_random,
376      &catch_exception_random,
377      &catch_exception_random,
378      &catch_exception_random,
379      &catch_exception_random,
380      &catch_exception_random,
381      &catch_exception_random,
382      &catch_exception_random,
383      &catch_exception_random,
384      &catch_exception_random,
385      &catch_exception_random,
386      &catch_exception_random,
387      &catch_exception_random,
388      &catch_exception_random,
389      &catch_exception_random,
390      &catch_exception_random,
391      &catch_exception_random,
392      &catch_exception_random,
393      &catch_exception_random,
394      &catch_exception_random,
395      &catch_exception_random,
396      &catch_exception_random,
397      &catch_exception_random,
398      &catch_exception_random,
399      &catch_exception_random,
400      &catch_exception_random,
401      &catch_exception_random,
402      &catch_exception_random,
403      &catch_exception_random,
404      &catch_exception_random,
405      &catch_exception_random,
406      &catch_exception_random,
407      &catch_exception_random,
408      &catch_exception_random,
409      &catch_exception_random,
410      &catch_exception_random,
411      &catch_exception_random,
412      &catch_exception_random,
413      &catch_exception_random,
414      &catch_exception_random,
415      &catch_exception_random,
416      &catch_exception_random,
417      &catch_exception_random,
418      &catch_exception_random,
419      &catch_exception_random,
420      &catch_exception_random,
421      &catch_exception_random,
422      &catch_exception_random,
423      &catch_exception_random,
424      &catch_exception_random,
425      &catch_exception_random,
426      &catch_exception_random,
427      &catch_exception_random,
428      &catch_exception_random,
429      &catch_exception_random,
430      &catch_exception_random,
431      &catch_exception_random,
432      &catch_exception_random,
433      &catch_exception_random,
434      &catch_exception_random,
435      &catch_exception_random,
436      &catch_exception_random,
437      &catch_exception_random,
438      &catch_exception_random,
439      &catch_exception_random,
440      &catch_exception_random,
441      &catch_exception_random,
442      &catch_exception_random,
443      &catch_exception_random,
444      &catch_exception_random,
445      &catch_exception_random,
446      &catch_exception_random,
447      &catch_exception_random,
448      &catch_exception_random,
449      &catch_exception_random,
450      &catch_exception_random,
451      &catch_exception_random,
452      &catch_exception_random,
453      &catch_exception_random,
454      &catch_exception_random,
455      &catch_exception_random,
456      &catch_exception_random,
457      &catch_exception_random,
458      &catch_exception_random,
459      &catch_exception_random,
460      &catch_exception_random,
461      &catch_exception_random,
462      &catch_exception_random,
463      &catch_exception_random,
464      &catch_exception_random,
465      &catch_exception_random,
466      &catch_exception_random,
467      &catch_exception_random,
468      &catch_exception_random,
469      &catch_exception_random,
470      &catch_exception_random,
471      &catch_exception_random,
472      &catch_exception_random,
473      &catch_exception_random,
474      &catch_exception_random,
475      &catch_exception_random,
476      &catch_exception_random,
477      &catch_exception_random,
478      &catch_exception_random,
479      &catch_exception_random,
480      &catch_exception_random,
481      &catch_exception_random,
482      &catch_exception_random,
483      &catch_exception_random,
484      &catch_exception_random,
485      &catch_exception_random,
486      &catch_exception_random,
487      &catch_exception_random,
488      &catch_exception_random,
489      &catch_exception_random,
490      &catch_exception_random,
491      &catch_exception_random,
492      &catch_exception_random,
493      &catch_exception_random,
494      &catch_exception_random,
495      &catch_exception_random,
496      &catch_exception_random,
497      &catch_exception_random,
498      &catch_exception_random,
499      &catch_exception_random,
500      &catch_exception_random,
501      &catch_exception_random,
502      &catch_exception_random,
503      &catch_exception_random,
504      &catch_exception_random,
505      &catch_exception_random,
506      &catch_exception_random,
507      &catch_exception_random,
508      &catch_exception_random,
509      &catch_exception_random,
510      &catch_exception_random,
511      &catch_exception_random,
512      &catch_exception_random,
513      &catch_exception_random,
514      &catch_exception_random,
515      &catch_exception_random,
516      &catch_exception_random,
517      &catch_exception_random,
518      &catch_exception_random,
519      &catch_exception_random,
520      &catch_exception_255}};
521
522
523 char in_nmi;   /* Set when handling an NMI, so we don't reenter */
524 int dofault;  /* Non zero, bus errors will raise exception */
525
526 int *stub_sp;
527
528 /* debug > 0 prints ill-formed commands in valid packets & checksum errors */
529 int remote_debug;
530
531 /* jump buffer used for setjmp/longjmp */
532 jmp_buf remcomEnv;
533
534 enum regnames
535   {
536     R0, R1, R2, R3, R4, R5, R6, R7,
537     R8, R9, R10, R11, R12, R13, R14,
538     R15, PC, PR, GBR, VBR, MACH, MACL, SR,
539     TICKS, STALLS, CYCLES, INSTS, PLR
540   };
541
542 typedef struct
543   {
544     short *memAddr;
545     short oldInstr;
546   }
547 stepData;
548
549 int registers[NUMREGBYTES / 4];
550 stepData instrBuffer;
551 char stepped;
552 static const char hexchars[] = "0123456789abcdef";
553 char remcomInBuffer[BUFMAX];
554 char remcomOutBuffer[BUFMAX];
555
556 char highhex(int  x)
557 {
558   return hexchars[(x >> 4) & 0xf];
559 }
560
561 char lowhex(int  x)
562 {
563   return hexchars[x & 0xf];
564 }
565
566 /*
567  * Assembly macros
568  */
569
570 #define BREAKPOINT()   asm("trapa       #0x20"::);
571
572
573 /*
574  * Routines to handle hex data
575  */
576
577 static int
578 hex (char ch)
579 {
580   if ((ch >= 'a') && (ch <= 'f'))
581     return (ch - 'a' + 10);
582   if ((ch >= '0') && (ch <= '9'))
583     return (ch - '0');
584   if ((ch >= 'A') && (ch <= 'F'))
585     return (ch - 'A' + 10);
586   return (-1);
587 }
588
589 /* convert the memory, pointed to by mem into hex, placing result in buf */
590 /* return a pointer to the last char put in buf (null) */
591 static char *
592 mem2hex (char *mem, char *buf, int count)
593 {
594   int i;
595   int ch;
596   for (i = 0; i < count; i++)
597     {
598       ch = *mem++;
599       *buf++ = highhex (ch);
600       *buf++ = lowhex (ch);
601     }
602   *buf = 0;
603   return (buf);
604 }
605
606 /* convert the hex array pointed to by buf into binary, to be placed in mem */
607 /* return a pointer to the character after the last byte written */
608
609 static char *
610 hex2mem (char *buf, char *mem, int count)
611 {
612   int i;
613   unsigned char ch;
614   for (i = 0; i < count; i++)
615     {
616       ch = hex (*buf++) << 4;
617       ch = ch + hex (*buf++);
618       *mem++ = ch;
619     }
620   return (mem);
621 }
622
623 /**********************************************/
624 /* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
625 /* RETURN NUMBER OF CHARS PROCESSED           */
626 /**********************************************/
627 static int
628 hexToInt (char **ptr, int *intValue)
629 {
630   int numChars = 0;
631   int hexValue;
632
633   *intValue = 0;
634
635   while (**ptr)
636     {
637       hexValue = hex (**ptr);
638       if (hexValue >= 0)
639         {
640           *intValue = (*intValue << 4) | hexValue;
641           numChars++;
642         }
643       else
644         break;
645
646       (*ptr)++;
647     }
648
649   return (numChars);
650 }
651
652 /*
653  * Routines to get and put packets
654  */
655
656 /* scan for the sequence $<data>#<checksum>     */
657
658 static
659 void
660 getpacket (char *buffer)
661 {
662   unsigned char checksum;
663   unsigned char xmitcsum;
664   int i;
665   int count;
666   char ch;
667   do
668     {
669       /* wait around for the start character, ignore all other characters */
670       while ((ch = getDebugChar ()) != '$');
671       checksum = 0;
672       xmitcsum = -1;
673
674       count = 0;
675
676       /* now, read until a # or end of buffer is found */
677       while (count < BUFMAX)
678         {
679           ch = getDebugChar ();
680           if (ch == '#')
681             break;
682           checksum = checksum + ch;
683           buffer[count] = ch;
684           count = count + 1;
685         }
686       buffer[count] = 0;
687
688       if (ch == '#')
689         {
690           xmitcsum = hex (getDebugChar ()) << 4;
691           xmitcsum += hex (getDebugChar ());
692           if (checksum != xmitcsum)
693             putDebugChar ('-'); /* failed checksum */
694           else
695             {
696               putDebugChar ('+');       /* successful transfer */
697               /* if a sequence char is present, reply the sequence ID */
698               if (buffer[2] == ':')
699                 {
700                   putDebugChar (buffer[0]);
701                   putDebugChar (buffer[1]);
702                   /* remove sequence chars from buffer */
703                   count = strlen (buffer);
704                   for (i = 3; i <= count; i++)
705                     buffer[i - 3] = buffer[i];
706                 }
707             }
708         }
709     }
710   while (checksum != xmitcsum);
711
712 }
713
714
715 /* send the packet in buffer.  The host get's one chance to read it.
716    This routine does not wait for a positive acknowledge.  */
717
718 static void
719 putpacket (register char *buffer)
720 {
721   register  int checksum;
722   register  int count;
723
724   /*  $<packet info>#<checksum>. */
725   do
726     {
727       char *src = buffer;
728       putDebugChar ('$');
729       checksum = 0;
730
731       while (*src)
732         {
733           int runlen;
734
735           /* Do run length encoding */
736           for (runlen = 0; runlen < 100; runlen ++) 
737             {
738               if (src[0] != src[runlen]) 
739                 {
740                   if (runlen > 3) 
741                     {
742                       int encode;
743                       /* Got a useful amount */
744                       putDebugChar (*src);
745                       checksum += *src;
746                       putDebugChar ('*');
747                       checksum += '*';
748                       checksum += (encode = runlen + ' ' - 4);
749                       putDebugChar (encode);
750                       src += runlen;
751                     }
752                   else
753                     {
754                       putDebugChar (*src);
755                       checksum += *src;
756                       src++;
757                     }
758                   break;
759                 }
760             }
761         }
762
763
764       putDebugChar ('#');
765       putDebugChar (highhex(checksum));
766       putDebugChar (lowhex(checksum));
767     }
768   while  (getDebugChar() != '+');
769
770 }
771
772
773 /* a bus error has occurred, perform a longjmp
774    to return execution and allow handling of the error */
775
776 void
777 handle_buserror (void)
778 {
779   longjmp (remcomEnv, 1);
780 }
781
782 /*
783  * this function takes the SH-1 exception number and attempts to
784  * translate this number into a unix compatible signal value
785  */
786 static int
787 computeSignal (int exceptionVector)
788 {
789   int sigval;
790   switch (exceptionVector)
791     {
792     case INVALID_INSN_VEC:
793       sigval = 4;
794       break;                    
795     case INVALID_SLOT_VEC:
796       sigval = 4;
797       break;                    
798     case CPU_BUS_ERROR_VEC:
799       sigval = 10;
800       break;                    
801     case DMA_BUS_ERROR_VEC:
802       sigval = 10;
803       break;    
804     case NMI_VEC:
805       sigval = 2;
806       break;    
807
808     case TRAP_VEC:
809     case USER_VEC:
810       sigval = 5;
811       break;
812
813     default:
814       sigval = 7;               /* "software generated"*/
815       break;
816     }
817   return (sigval);
818 }
819
820 void
821 doSStep (void)
822 {
823   short *instrMem;
824   int displacement;
825   int reg;
826   unsigned short opcode;
827
828   instrMem = (short *) registers[PC];
829
830   opcode = *instrMem;
831   stepped = 1;
832
833   if ((opcode & COND_BR_MASK) == BT_INSTR)
834     {
835       if (registers[SR] & T_BIT_MASK)
836         {
837           displacement = (opcode & COND_DISP) << 1;
838           if (displacement & 0x80)
839             displacement |= 0xffffff00;
840           /*
841                    * Remember PC points to second instr.
842                    * after PC of branch ... so add 4
843                    */
844           instrMem = (short *) (registers[PC] + displacement + 4);
845         }
846       else
847         instrMem += 1;
848     }
849   else if ((opcode & COND_BR_MASK) == BF_INSTR)
850     {
851       if (registers[SR] & T_BIT_MASK)
852         instrMem += 1;
853       else
854         {
855           displacement = (opcode & COND_DISP) << 1;
856           if (displacement & 0x80)
857             displacement |= 0xffffff00;
858           /*
859                    * Remember PC points to second instr.
860                    * after PC of branch ... so add 4
861                    */
862           instrMem = (short *) (registers[PC] + displacement + 4);
863         }
864     }
865   else if ((opcode & UCOND_DBR_MASK) == BRA_INSTR)
866     {
867       displacement = (opcode & UCOND_DISP) << 1;
868       if (displacement & 0x0800)
869         displacement |= 0xfffff000;
870
871       /*
872            * Remember PC points to second instr.
873            * after PC of branch ... so add 4
874            */
875       instrMem = (short *) (registers[PC] + displacement + 4);
876     }
877   else if ((opcode & UCOND_RBR_MASK) == JSR_INSTR)
878     {
879       reg = (char) ((opcode & UCOND_REG) >> 8);
880
881       instrMem = (short *) registers[reg];
882     }
883   else if (opcode == RTS_INSTR)
884     instrMem = (short *) registers[PR];
885   else if (opcode == RTE_INSTR)
886     instrMem = (short *) registers[15];
887   else if ((opcode & TRAPA_MASK) == TRAPA_INSTR)
888     instrMem = (short *) ((opcode & ~TRAPA_MASK) << 2);
889   else
890     instrMem += 1;
891
892   instrBuffer.memAddr = instrMem;
893   instrBuffer.oldInstr = *instrMem;
894   *instrMem = SSTEP_INSTR;
895 }
896
897
898 /* Undo the effect of a previous doSStep.  If we single stepped,
899    restore the old instruction. */
900
901 void
902 undoSStep (void)
903 {
904   if (stepped)
905     {  short *instrMem;
906       instrMem = instrBuffer.memAddr;
907       *instrMem = instrBuffer.oldInstr;
908     }
909   stepped = 0;
910 }
911
912 /*
913 This function does all exception handling.  It only does two things -
914 it figures out why it was called and tells gdb, and then it reacts
915 to gdb's requests.
916
917 When in the monitor mode we talk a human on the serial line rather than gdb.
918
919 */
920
921
922 void
923 gdb_handle_exception (int exceptionVector)
924 {
925   int sigval;
926   int addr, length;
927   char *ptr;
928
929   /* reply to host that an exception has occurred */
930   sigval = computeSignal (exceptionVector);
931   remcomOutBuffer[0] = 'S';
932   remcomOutBuffer[1] = highhex(sigval);
933   remcomOutBuffer[2] = lowhex (sigval);
934   remcomOutBuffer[3] = 0;
935
936   putpacket (remcomOutBuffer);
937
938   /*
939    * exception 255 indicates a software trap
940    * inserted in place of code ... so back up
941    * PC by one instruction, since this instruction
942    * will later be replaced by its original one!
943    */
944   if (exceptionVector == 0xff
945       || exceptionVector == 0x20)
946     registers[PC] -= 2;
947
948   /*
949    * Do the thangs needed to undo
950    * any stepping we may have done!
951    */
952   undoSStep ();
953
954   while (1)
955     {
956       remcomOutBuffer[0] = 0;
957       getpacket (remcomInBuffer);
958
959       switch (remcomInBuffer[0])
960         {
961         case '?':
962           remcomOutBuffer[0] = 'S';
963           remcomOutBuffer[1] = highhex (sigval);
964           remcomOutBuffer[2] = lowhex (sigval);
965           remcomOutBuffer[3] = 0;
966           break;
967         case 'd':
968           remote_debug = !(remote_debug);       /* toggle debug flag */
969           break;
970         case 'g':               /* return the value of the CPU registers */
971           mem2hex ((char *) registers, remcomOutBuffer, NUMREGBYTES);
972           break;
973         case 'G':               /* set the value of the CPU registers - return OK */
974           hex2mem (&remcomInBuffer[1], (char *) registers, NUMREGBYTES);
975           strcpy (remcomOutBuffer, "OK");
976           break;
977
978           /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
979         case 'm':
980           if (setjmp (remcomEnv) == 0)
981             {
982               dofault = 0;
983               /* TRY, TO READ %x,%x.  IF SUCCEED, SET PTR = 0 */
984               ptr = &remcomInBuffer[1];
985               if (hexToInt (&ptr, &addr))
986                 if (*(ptr++) == ',')
987                   if (hexToInt (&ptr, &length))
988                     {
989                       ptr = 0;
990                       mem2hex ((char *) addr, remcomOutBuffer, length);
991                     }
992               if (ptr)
993                 strcpy (remcomOutBuffer, "E01");
994             }
995           else
996             strcpy (remcomOutBuffer, "E03");
997
998           /* restore handler for bus error */
999           dofault = 1;
1000           break;
1001
1002           /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
1003         case 'M':
1004           if (setjmp (remcomEnv) == 0)
1005             {
1006               dofault = 0;
1007
1008               /* TRY, TO READ '%x,%x:'.  IF SUCCEED, SET PTR = 0 */
1009               ptr = &remcomInBuffer[1];
1010               if (hexToInt (&ptr, &addr))
1011                 if (*(ptr++) == ',')
1012                   if (hexToInt (&ptr, &length))
1013                     if (*(ptr++) == ':')
1014                       {
1015                         hex2mem (ptr, (char *) addr, length);
1016                         ptr = 0;
1017                         strcpy (remcomOutBuffer, "OK");
1018                       }
1019               if (ptr)
1020                 strcpy (remcomOutBuffer, "E02");
1021             }
1022           else
1023             strcpy (remcomOutBuffer, "E03");
1024
1025           /* restore handler for bus error */
1026           dofault = 1;
1027           break;
1028
1029           /* cAA..AA    Continue at address AA..AA(optional) */
1030           /* sAA..AA   Step one instruction from AA..AA(optional) */
1031         case 'c':
1032         case 's':
1033           {
1034             /* tRY, to read optional parameter, pc unchanged if no parm */
1035             ptr = &remcomInBuffer[1];
1036             if (hexToInt (&ptr, &addr))
1037               registers[PC] = addr;
1038
1039             if (remcomInBuffer[0] == 's')
1040               doSStep ();
1041           }
1042           return;
1043           break;
1044
1045           /* kill the program */
1046         case 'k':               /* do nothing */
1047           break;
1048         }                       /* switch */
1049
1050       /* reply to the request */
1051       putpacket (remcomOutBuffer);
1052     }
1053 }
1054
1055
1056 #define GDBCOOKIE 0x5ac 
1057 static int ingdbmode;
1058 /* We've had an exception - choose to go into the monitor or
1059    the gdb stub */
1060 void handle_exception(int exceptionVector)
1061 {
1062 #ifdef MONITOR
1063     if (ingdbmode != GDBCOOKIE)
1064       monitor_handle_exception (exceptionVector);
1065     else 
1066 #endif
1067       gdb_handle_exception (exceptionVector);
1068
1069 }
1070
1071 void
1072 gdb_mode()
1073 {
1074   ingdbmode = GDBCOOKIE;
1075   breakpoint();
1076 }
1077 /* This function will generate a breakpoint exception.  It is used at the
1078    beginning of a program to sync up with a debugger and can be used
1079    otherwise as a quick means to stop program execution and "break" into
1080    the debugger. */
1081
1082 void
1083 breakpoint (void)
1084 {
1085       BREAKPOINT ();
1086 }
1087
1088 asm ("_BINIT: mov.l  L1,r15");
1089 asm ("bra _INIT");
1090 asm ("nop");
1091 asm ("L1: .long _init_stack + 8*1024*4");
1092 void
1093 INIT (void)
1094 {
1095   /* First turn on the ram */
1096   WCR1  = 0;    /* Never sample wait */
1097   BCR = BAS;    /* use lowbyte/high byte */
1098
1099   init_serial();
1100
1101 #ifdef MONITOR
1102   reset_hook ();
1103 #endif
1104
1105
1106   in_nmi = 0;
1107   dofault = 1;
1108   stepped = 0;
1109
1110   stub_sp = stub_stack + stub_stack_size;
1111   breakpoint ();
1112
1113   while (1)
1114     ;
1115 }
1116
1117
1118 static void sr()
1119 {
1120
1121
1122   /* Calling Reset does the same as pressing the button */
1123   asm (".global _Reset
1124         .global _WarmReset
1125 _Reset:
1126 _WarmReset:
1127          mov.l L_sp,r15
1128          bra   _INIT
1129          nop
1130          .align 2
1131 L_sp:    .long _init_stack + 8000");
1132
1133   asm("saveRegisters:
1134         mov.l   @(L_reg, pc), r0
1135         mov.l   @r15+, r1                               ! pop R0
1136         mov.l   r2, @(0x08, r0)                         ! save R2
1137         mov.l   r1, @r0                                 ! save R0
1138         mov.l   @r15+, r1                               ! pop R1
1139         mov.l   r3, @(0x0c, r0)                         ! save R3
1140         mov.l   r1, @(0x04, r0)                         ! save R1
1141         mov.l   r4, @(0x10, r0)                         ! save R4
1142         mov.l   r5, @(0x14, r0)                         ! save R5
1143         mov.l   r6, @(0x18, r0)                         ! save R6
1144         mov.l   r7, @(0x1c, r0)                         ! save R7
1145         mov.l   r8, @(0x20, r0)                         ! save R8
1146         mov.l   r9, @(0x24, r0)                         ! save R9
1147         mov.l   r10, @(0x28, r0)                        ! save R10
1148         mov.l   r11, @(0x2c, r0)                        ! save R11
1149         mov.l   r12, @(0x30, r0)                        ! save R12
1150         mov.l   r13, @(0x34, r0)                        ! save R13
1151         mov.l   r14, @(0x38, r0)                        ! save R14
1152         mov.l   @r15+, r4                               ! save arg to handleException
1153         add     #8, r15                                 ! hide PC/SR values on stack
1154         mov.l   r15, @(0x3c, r0)                        ! save R15
1155         add     #-8, r15                                ! save still needs old SP value
1156         add     #92, r0                                 ! readjust register pointer
1157         mov     r15, r2
1158         add     #4, r2
1159         mov.l   @r2, r2                                 ! R2 has SR
1160         mov.l   @r15, r1                                ! R1 has PC
1161         mov.l   r2, @-r0                                ! save SR
1162         sts.l   macl, @-r0                              ! save MACL
1163         sts.l   mach, @-r0                              ! save MACH
1164         stc.l   vbr, @-r0                               ! save VBR
1165         stc.l   gbr, @-r0                               ! save GBR
1166         sts.l   pr, @-r0                                ! save PR
1167         mov.l   @(L_stubstack, pc), r2
1168         mov.l   @(L_hdl_except, pc), r3
1169         mov.l   @r2, r15
1170         jsr     @r3
1171         mov.l   r1, @-r0                                ! save PC
1172         mov.l   @(L_stubstack, pc), r0
1173         mov.l   @(L_reg, pc), r1
1174         bra     restoreRegisters
1175         mov.l   r15, @r0                                ! save __stub_stack
1176         
1177         .align 2
1178 L_reg:
1179         .long   _registers
1180 L_stubstack:
1181         .long   _stub_sp
1182 L_hdl_except:
1183         .long   _handle_exception");
1184
1185 }
1186
1187 static void rr()
1188 {
1189 asm("
1190         .align 2        
1191         .global _resume
1192 _resume:
1193         mov     r4,r1
1194 restoreRegisters:
1195         add     #8, r1                                          ! skip to R2
1196         mov.l   @r1+, r2                                        ! restore R2
1197         mov.l   @r1+, r3                                        ! restore R3
1198         mov.l   @r1+, r4                                        ! restore R4
1199         mov.l   @r1+, r5                                        ! restore R5
1200         mov.l   @r1+, r6                                        ! restore R6
1201         mov.l   @r1+, r7                                        ! restore R7
1202         mov.l   @r1+, r8                                        ! restore R8
1203         mov.l   @r1+, r9                                        ! restore R9
1204         mov.l   @r1+, r10                                       ! restore R10
1205         mov.l   @r1+, r11                                       ! restore R11
1206         mov.l   @r1+, r12                                       ! restore R12
1207         mov.l   @r1+, r13                                       ! restore R13
1208         mov.l   @r1+, r14                                       ! restore R14
1209         mov.l   @r1+, r15                                       ! restore programs stack
1210         mov.l   @r1+, r0
1211         add     #-8, r15                                        ! uncover PC/SR on stack 
1212         mov.l   r0, @r15                                        ! restore PC onto stack
1213         lds.l   @r1+, pr                                        ! restore PR
1214         ldc.l   @r1+, gbr                                       ! restore GBR           
1215         ldc.l   @r1+, vbr                                       ! restore VBR
1216         lds.l   @r1+, mach                                      ! restore MACH
1217         lds.l   @r1+, macl                                      ! restore MACL
1218         mov.l   @r1, r0 
1219         add     #-88, r1                                        ! readjust reg pointer to R1
1220         mov.l   r0, @(4, r15)                                   ! restore SR onto stack+4
1221         mov.l   r2, @-r15
1222         mov.l   L_in_nmi, r0
1223         mov             #0, r2
1224         mov.b   r2, @r0
1225         mov.l   @r15+, r2
1226         mov.l   @r1+, r0                                        ! restore R0
1227         rte
1228         mov.l   @r1, r1                                         ! restore R1
1229
1230 ");
1231 }
1232
1233
1234 static __inline__ void code_for_catch_exception(int n) 
1235 {
1236   asm("         .globl  _catch_exception_%O0" : : "i" (n)                               ); 
1237   asm(" _catch_exception_%O0:" :: "i" (n)                                               );
1238
1239   asm("         add     #-4, r15                                ! reserve spot on stack ");
1240   asm("         mov.l   r1, @-r15                               ! push R1               ");
1241
1242   if (n == NMI_VEC) 
1243     {
1244       /* Special case for NMI - make sure that they don't nest */
1245       asm("     mov.l   r0, @-r15                                       ! push R0");
1246       asm("     mov.l   L_in_nmi, r0");
1247       asm("     tas.b   @r0                                             ! Fend off against addtnl NMIs");
1248       asm("     bt              noNMI");
1249       asm("     mov.l   @r15+, r0");
1250       asm("     mov.l   @r15+, r1");
1251       asm("     add             #4, r15");
1252       asm("     rte");
1253       asm("     nop");
1254       asm(".align 2");
1255       asm("L_in_nmi: .long      _in_nmi");
1256       asm("noNMI:");
1257     }
1258   else
1259     {
1260
1261       if (n == CPU_BUS_ERROR_VEC)
1262         {
1263           /* Exception 9 (bus errors) are disasbleable - so that you
1264              can probe memory and get zero instead of a fault.
1265              Because the vector table may be in ROM we don't revector
1266              the interrupt like all the other stubs, we check in here
1267              */
1268           asm("mov.l    L_dofault,r1");
1269           asm("mov.l    @r1,r1");
1270           asm("tst      r1,r1");
1271           asm("bf       faultaway");
1272           asm("bsr      _handle_buserror");
1273           asm(".align   2");
1274           asm("L_dofault: .long _dofault");
1275           asm("faultaway:");
1276         }
1277       asm("             mov     #15<<4, r1                                                      ");
1278       asm("             ldc     r1, sr                                  ! disable interrupts    ");
1279       asm("             mov.l   r0, @-r15                               ! push R0               ");
1280     }
1281
1282   /* Prepare for saving context, we've already pushed r0 and r1, stick exception number
1283      into the frame */
1284   asm("         mov     r15, r0                                                         ");
1285   asm("         add     #8, r0                                                          ");
1286   asm("         mov     %0,r1" :: "i" (n)                                               );
1287   asm("         extu.b  r1,r1                                                           ");
1288   asm("         bra     saveRegisters                           ! save register values  ");
1289   asm("         mov.l   r1, @r0                                 ! save exception #      ");
1290 }
1291
1292
1293 static  void
1294 exceptions()
1295 {
1296   code_for_catch_exception (CPU_BUS_ERROR_VEC);
1297   code_for_catch_exception (DMA_BUS_ERROR_VEC);
1298   code_for_catch_exception (INVALID_INSN_VEC);
1299   code_for_catch_exception (INVALID_SLOT_VEC);
1300   code_for_catch_exception (NMI_VEC);
1301   code_for_catch_exception (TRAP_VEC);
1302   code_for_catch_exception (USER_VEC);
1303   code_for_catch_exception (IO_VEC);
1304 }
1305
1306
1307
1308
1309
1310
1311 /* Support for Serial I/O using on chip uart */
1312
1313 #define SMR0 (*(volatile char *)(0x05FFFEC0)) /* Channel 0  serial mode register */
1314 #define BRR0 (*(volatile char *)(0x05FFFEC1)) /* Channel 0  bit rate register */
1315 #define SCR0 (*(volatile char *)(0x05FFFEC2)) /* Channel 0  serial control register */
1316 #define TDR0 (*(volatile char *)(0x05FFFEC3)) /* Channel 0  transmit data register */
1317 #define SSR0 (*(volatile char *)(0x05FFFEC4)) /* Channel 0  serial status register */
1318 #define RDR0 (*(volatile char *)(0x05FFFEC5)) /* Channel 0  receive data register */
1319
1320 #define SMR1 (*(volatile char *)(0x05FFFEC8)) /* Channel 1  serial mode register */
1321 #define BRR1 (*(volatile char *)(0x05FFFEC9)) /* Channel 1  bit rate register */
1322 #define SCR1 (*(volatile char *)(0x05FFFECA)) /* Channel 1  serial control register */
1323 #define TDR1 (*(volatile char *)(0x05FFFECB)) /* Channel 1  transmit data register */
1324 #define SSR1 (*(volatile char *)(0x05FFFECC)) /* Channel 1  serial status register */
1325 #define RDR1 (*(volatile char *)(0x05FFFECD)) /* Channel 1  receive data register */
1326
1327 /*
1328  * Serial mode register bits
1329  */
1330
1331 #define SYNC_MODE               0x80
1332 #define SEVEN_BIT_DATA          0x40
1333 #define PARITY_ON               0x20
1334 #define ODD_PARITY              0x10
1335 #define STOP_BITS_2             0x08
1336 #define ENABLE_MULTIP           0x04
1337 #define PHI_64                  0x03
1338 #define PHI_16                  0x02
1339 #define PHI_4                   0x01
1340
1341 /*
1342  * Serial control register bits
1343  */
1344 #define SCI_TIE                         0x80    /* Transmit interrupt enable */
1345 #define SCI_RIE                         0x40    /* Receive interrupt enable */
1346 #define SCI_TE                          0x20    /* Transmit enable */
1347 #define SCI_RE                          0x10    /* Receive enable */
1348 #define SCI_MPIE                        0x08    /* Multiprocessor interrupt enable */
1349 #define SCI_TEIE                        0x04    /* Transmit end interrupt enable */
1350 #define SCI_CKE1                        0x02    /* Clock enable 1 */
1351 #define SCI_CKE0                        0x01    /* Clock enable 0 */
1352
1353 /*
1354  * Serial status register bits
1355  */
1356 #define SCI_TDRE                        0x80    /* Transmit data register empty */
1357 #define SCI_RDRF                        0x40    /* Receive data register full */
1358 #define SCI_ORER                        0x20    /* Overrun error */
1359 #define SCI_FER                         0x10    /* Framing error */
1360 #define SCI_PER                         0x08    /* Parity error */
1361 #define SCI_TEND                        0x04    /* Transmit end */
1362 #define SCI_MPB                         0x02    /* Multiprocessor bit */
1363 #define SCI_MPBT                        0x01    /* Multiprocessor bit transfer */
1364
1365
1366 /*
1367  * Port B IO Register (PBIOR)
1368  */
1369 #define PBIOR           (*(volatile char *)(0x05FFFFC6))
1370 #define PB15IOR         0x8000
1371 #define PB14IOR         0x4000
1372 #define PB13IOR         0x2000
1373 #define PB12IOR         0x1000
1374 #define PB11IOR         0x0800
1375 #define PB10IOR         0x0400
1376 #define PB9IOR          0x0200
1377 #define PB8IOR          0x0100
1378 #define PB7IOR          0x0080
1379 #define PB6IOR          0x0040
1380 #define PB5IOR          0x0020
1381 #define PB4IOR          0x0010
1382 #define PB3IOR          0x0008
1383 #define PB2IOR          0x0004
1384 #define PB1IOR          0x0002
1385 #define PB0IOR          0x0001
1386
1387 /*
1388  * Port B Control Register (PBCR1)
1389  */
1390 #define PBCR1           (*(volatile short *)(0x05FFFFCC))
1391 #define PB15MD1         0x8000
1392 #define PB15MD0         0x4000
1393 #define PB14MD1         0x2000
1394 #define PB14MD0         0x1000
1395 #define PB13MD1         0x0800
1396 #define PB13MD0         0x0400
1397 #define PB12MD1         0x0200
1398 #define PB12MD0         0x0100
1399 #define PB11MD1         0x0080
1400 #define PB11MD0         0x0040
1401 #define PB10MD1         0x0020
1402 #define PB10MD0         0x0010
1403 #define PB9MD1          0x0008
1404 #define PB9MD0          0x0004
1405 #define PB8MD1          0x0002
1406 #define PB8MD0          0x0001
1407
1408 #define PB15MD          PB15MD1|PB14MD0
1409 #define PB14MD          PB14MD1|PB14MD0
1410 #define PB13MD          PB13MD1|PB13MD0
1411 #define PB12MD          PB12MD1|PB12MD0
1412 #define PB11MD          PB11MD1|PB11MD0
1413 #define PB10MD          PB10MD1|PB10MD0
1414 #define PB9MD           PB9MD1|PB9MD0
1415 #define PB8MD           PB8MD1|PB8MD0
1416
1417 #define PB_TXD1         PB11MD1
1418 #define PB_RXD1         PB10MD1
1419 #define PB_TXD0         PB9MD1
1420 #define PB_RXD0         PB8MD1
1421
1422 /*
1423  * Port B Control Register (PBCR2)
1424  */
1425 #define PBCR2   0x05FFFFCE
1426 #define PB7MD1  0x8000
1427 #define PB7MD0  0x4000
1428 #define PB6MD1  0x2000
1429 #define PB6MD0  0x1000
1430 #define PB5MD1  0x0800
1431 #define PB5MD0  0x0400
1432 #define PB4MD1  0x0200
1433 #define PB4MD0  0x0100
1434 #define PB3MD1  0x0080
1435 #define PB3MD0  0x0040
1436 #define PB2MD1  0x0020
1437 #define PB2MD0  0x0010
1438 #define PB1MD1  0x0008
1439 #define PB1MD0  0x0004
1440 #define PB0MD1  0x0002
1441 #define PB0MD0  0x0001
1442         
1443 #define PB7MD   PB7MD1|PB7MD0
1444 #define PB6MD   PB6MD1|PB6MD0
1445 #define PB5MD   PB5MD1|PB5MD0
1446 #define PB4MD   PB4MD1|PB4MD0
1447 #define PB3MD   PB3MD1|PB3MD0
1448 #define PB2MD   PB2MD1|PB2MD0
1449 #define PB1MD   PB1MD1|PB1MD0
1450 #define PB0MD   PB0MD1|PB0MD0
1451
1452
1453 #ifdef MHZ
1454 #define BPS                     32 * 9600 * MHZ / ( BAUD * 10)
1455 #else
1456 #define BPS                     32      /* 9600 for 10 Mhz */
1457 #endif
1458
1459 void handleError (char theSSR);
1460
1461 void
1462 nop ()
1463 {
1464
1465 }
1466 void 
1467 init_serial()
1468 {
1469   int i;
1470
1471   /* Clear TE and RE in Channel 1's SCR   */
1472   SCR1 &= ~(SCI_TE | SCI_RE);
1473
1474   /* Set communication to be async, 8-bit data, no parity, 1 stop bit and use internal clock */
1475
1476   SMR1 = 0;
1477   BRR1 = BPS;
1478
1479   SCR1 &= ~(SCI_CKE1 | SCI_CKE0);
1480
1481   /* let the hardware settle */
1482
1483   for (i = 0; i < 1000; i++)
1484     nop ();
1485
1486   /* Turn on in and out */
1487   SCR1 |= SCI_RE | SCI_TE;
1488
1489   /* Set the PFC to make RXD1 (pin PB8) an input pin and TXD1 (pin PB9) an output pin */
1490   PBCR1 &= ~(PB_TXD1 | PB_RXD1);
1491   PBCR1 |= PB_TXD1 | PB_RXD1;
1492 }
1493
1494
1495 int
1496 getDebugCharReady (void)
1497 {
1498   char mySSR;
1499   mySSR = SSR1 & ( SCI_PER | SCI_FER | SCI_ORER );
1500   if ( mySSR )
1501     handleError ( mySSR );
1502   return SSR1 & SCI_RDRF ;
1503 }
1504
1505 char 
1506 getDebugChar (void)
1507 {
1508   char ch;
1509   char mySSR;
1510
1511   while ( ! getDebugCharReady())
1512     ;
1513
1514   ch = RDR1;
1515   SSR1 &= ~SCI_RDRF;
1516
1517   mySSR = SSR1 & (SCI_PER | SCI_FER | SCI_ORER);
1518
1519   if (mySSR)
1520     handleError (mySSR);
1521
1522   return ch;
1523 }
1524
1525 int 
1526 putDebugCharReady()
1527 {
1528   return (SSR1 & SCI_TDRE);
1529 }
1530
1531 void
1532 putDebugChar (char ch)
1533 {
1534   while (!putDebugCharReady())
1535     ;
1536
1537   /*
1538    * Write data into TDR and clear TDRE
1539    */
1540   TDR1 = ch;
1541   SSR1 &= ~SCI_TDRE;
1542 }
1543
1544 void 
1545 handleError (char theSSR)
1546 {
1547   SSR1 &= ~(SCI_ORER | SCI_PER | SCI_FER);
1548 }
1549