* remote-mips.c: Remove form feeds (^L) from source.
[platform/upstream/binutils.git] / gdb / remote-mips.c
1 /* Remote debugging interface for MIPS remote debugging protocol.
2    Copyright 1993, 1994, 1995 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.  Written by Ian Lance Taylor
4    <ian@cygnus.com>.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "bfd.h"
25 #include "symfile.h"
26 #include "wait.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include "serial.h"
30 #include "target.h"
31 #include "remote-utils.h"
32 #include "gdb_string.h"
33
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #ifdef ANSI_PROTOTYPES
38 #include <stdarg.h>
39 #else
40 #include <varargs.h>
41 #endif
42
43 /* Microsoft C's stat.h doesn't define all the POSIX file modes.  */
44 #ifndef S_IROTH
45 #define S_IROTH S_IREAD
46 #endif
47
48 extern void mips_set_processor_type_command PARAMS ((char *, int));
49
50
51
52 /* Prototypes for local functions.  */
53
54 static int mips_readchar PARAMS ((int timeout));
55
56 static int mips_receive_header PARAMS ((unsigned char *hdr, int *pgarbage,
57                                         int ch, int timeout));
58
59 static int mips_receive_trailer PARAMS ((unsigned char *trlr, int *pgarbage,
60                                          int *pch, int timeout));
61
62 static int mips_cksum PARAMS ((const unsigned char *hdr,
63                                const unsigned char *data,
64                                int len));
65
66 static void mips_send_packet PARAMS ((const char *s, int get_ack));
67
68 static void mips_send_command PARAMS ((const char *cmd, int prompt));
69
70 static int mips_receive_packet PARAMS ((char *buff, int throw_error,
71                                         int timeout));
72
73 static CORE_ADDR mips_request PARAMS ((int cmd, CORE_ADDR addr,
74                                  CORE_ADDR data, int *perr, int timeout,
75                                  char *buff));
76
77 static void mips_initialize PARAMS ((void));
78
79 static void mips_open PARAMS ((char *name, int from_tty));
80
81 static void pmon_open PARAMS ((char *name, int from_tty));
82
83 static void ddb_open PARAMS ((char *name, int from_tty));
84
85 static void lsi_open PARAMS ((char *name, int from_tty));
86
87 static void mips_close PARAMS ((int quitting));
88
89 static void mips_detach PARAMS ((char *args, int from_tty));
90
91 static void mips_resume PARAMS ((int pid, int step,
92                                  enum target_signal siggnal));
93
94 static int mips_wait PARAMS ((int pid, struct target_waitstatus *status));
95
96 static int pmon_wait PARAMS ((int pid, struct target_waitstatus *status));
97
98 static int mips_map_regno PARAMS ((int regno));
99
100 static void mips_fetch_registers PARAMS ((int regno));
101
102 static void mips_prepare_to_store PARAMS ((void));
103
104 static void mips_store_registers PARAMS ((int regno));
105
106 static unsigned int mips_fetch_word PARAMS ((CORE_ADDR addr));
107
108 static int mips_store_word PARAMS ((CORE_ADDR addr, unsigned int value,
109                                     char *old_contents));
110
111 static int mips_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len,
112                                      int write, struct target_ops *ignore));
113
114 static void mips_files_info PARAMS ((struct target_ops *ignore));
115
116 static void mips_create_inferior PARAMS ((char *execfile, char *args,
117                                           char **env));
118
119 static void mips_mourn_inferior PARAMS ((void));
120
121 static int pmon_makeb64 PARAMS ((unsigned long v, char *p, int n, int *chksum));
122
123 static int pmon_zeroset PARAMS ((int recsize, char **buff, int *amount,
124                                  unsigned int *chksum));
125
126 static int pmon_checkset PARAMS ((int recsize, char **buff, int *value));
127
128 static void pmon_make_fastrec PARAMS ((char **outbuf, unsigned char *inbuf,
129                                        int *inptr, int inamount, int *recsize,
130                                        unsigned int *csum, unsigned int *zerofill));
131
132 static int pmon_check_ack PARAMS ((char *mesg));
133
134 static void pmon_start_download PARAMS ((void));
135
136 static void pmon_end_download PARAMS ((int final, int bintotal));
137
138 static void pmon_download PARAMS ((char *buffer, int length));
139
140 static void pmon_load_fast PARAMS ((char *file));
141
142 static void mips_load PARAMS ((char *file, int from_tty));
143
144 static int mips_make_srec PARAMS ((char *buffer, int type, CORE_ADDR memaddr,
145                                    unsigned char *myaddr, int len));
146
147 static int common_breakpoint PARAMS ((int cmd, CORE_ADDR addr, CORE_ADDR mask,
148                                       char *flags));
149
150 static void common_open PARAMS ((struct target_ops *ops, char *name,
151                                  int from_tty));
152 /* Forward declarations.  */
153 extern struct target_ops mips_ops;
154 extern struct target_ops pmon_ops;
155 extern struct target_ops ddb_ops;
156
157
158 /* The MIPS remote debugging interface is built on top of a simple
159    packet protocol.  Each packet is organized as follows:
160
161    SYN  The first character is always a SYN (ASCII 026, or ^V).  SYN
162         may not appear anywhere else in the packet.  Any time a SYN is
163         seen, a new packet should be assumed to have begun.
164
165    TYPE_LEN
166         This byte contains the upper five bits of the logical length
167         of the data section, plus a single bit indicating whether this
168         is a data packet or an acknowledgement.  The documentation
169         indicates that this bit is 1 for a data packet, but the actual
170         board uses 1 for an acknowledgement.  The value of the byte is
171                 0x40 + (ack ? 0x20 : 0) + (len >> 6)
172         (we always have 0 <= len < 1024).  Acknowledgement packets do
173         not carry data, and must have a data length of 0.
174
175    LEN1 This byte contains the lower six bits of the logical length of
176         the data section.  The value is
177                 0x40 + (len & 0x3f)
178
179    SEQ  This byte contains the six bit sequence number of the packet.
180         The value is
181                 0x40 + seq
182         An acknowlegment packet contains the sequence number of the
183         packet being acknowledged plus 1 modulo 64.  Data packets are
184         transmitted in sequence.  There may only be one outstanding
185         unacknowledged data packet at a time.  The sequence numbers
186         are independent in each direction.  If an acknowledgement for
187         the previous packet is received (i.e., an acknowledgement with
188         the sequence number of the packet just sent) the packet just
189         sent should be retransmitted.  If no acknowledgement is
190         received within a timeout period, the packet should be
191         retransmitted.  This has an unfortunate failure condition on a
192         high-latency line, as a delayed acknowledgement may lead to an
193         endless series of duplicate packets.
194
195    DATA The actual data bytes follow.  The following characters are
196         escaped inline with DLE (ASCII 020, or ^P):
197                 SYN (026)       DLE S
198                 DLE (020)       DLE D
199                 ^C  (003)       DLE C
200                 ^S  (023)       DLE s
201                 ^Q  (021)       DLE q
202         The additional DLE characters are not counted in the logical
203         length stored in the TYPE_LEN and LEN1 bytes.
204
205    CSUM1
206    CSUM2
207    CSUM3
208         These bytes contain an 18 bit checksum of the complete
209         contents of the packet excluding the SEQ byte and the
210         CSUM[123] bytes.  The checksum is simply the twos complement
211         addition of all the bytes treated as unsigned characters.  The
212         values of the checksum bytes are:
213                 CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
214                 CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
215                 CSUM3: 0x40 + (cksum & 0x3f)
216
217    It happens that the MIPS remote debugging protocol always
218    communicates with ASCII strings.  Because of this, this
219    implementation doesn't bother to handle the DLE quoting mechanism,
220    since it will never be required.  */
221
222 /* The SYN character which starts each packet.  */
223 #define SYN '\026'
224
225 /* The 0x40 used to offset each packet (this value ensures that all of
226    the header and trailer bytes, other than SYN, are printable ASCII
227    characters).  */
228 #define HDR_OFFSET 0x40
229
230 /* The indices of the bytes in the packet header.  */
231 #define HDR_INDX_SYN 0
232 #define HDR_INDX_TYPE_LEN 1
233 #define HDR_INDX_LEN1 2
234 #define HDR_INDX_SEQ 3
235 #define HDR_LENGTH 4
236
237 /* The data/ack bit in the TYPE_LEN header byte.  */
238 #define TYPE_LEN_DA_BIT 0x20
239 #define TYPE_LEN_DATA 0
240 #define TYPE_LEN_ACK TYPE_LEN_DA_BIT
241
242 /* How to compute the header bytes.  */
243 #define HDR_SET_SYN(data, len, seq) (SYN)
244 #define HDR_SET_TYPE_LEN(data, len, seq) \
245   (HDR_OFFSET \
246    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
247    + (((len) >> 6) & 0x1f))
248 #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
249 #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))
250
251 /* Check that a header byte is reasonable.  */
252 #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)
253
254 /* Get data from the header.  These macros evaluate their argument
255    multiple times.  */
256 #define HDR_IS_DATA(hdr) \
257   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
258 #define HDR_GET_LEN(hdr) \
259   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
260 #define HDR_GET_SEQ(hdr) ((unsigned int)(hdr)[HDR_INDX_SEQ] & 0x3f)
261
262 /* The maximum data length.  */
263 #define DATA_MAXLEN 1023
264
265 /* The trailer offset.  */
266 #define TRLR_OFFSET HDR_OFFSET
267
268 /* The indices of the bytes in the packet trailer.  */
269 #define TRLR_INDX_CSUM1 0
270 #define TRLR_INDX_CSUM2 1
271 #define TRLR_INDX_CSUM3 2
272 #define TRLR_LENGTH 3
273
274 /* How to compute the trailer bytes.  */
275 #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
276 #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
277 #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))
278
279 /* Check that a trailer byte is reasonable.  */
280 #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)
281
282 /* Get data from the trailer.  This evaluates its argument multiple
283    times.  */
284 #define TRLR_GET_CKSUM(trlr) \
285   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
286    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
287    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))
288
289 /* The sequence number modulos.  */
290 #define SEQ_MODULOS (64)
291
292 /* PMON commands to load from the serial port or UDP socket.  */
293 #define LOAD_CMD        "load -b -s tty0\r"
294 #define LOAD_CMD_UDP    "load -b -s udp\r"
295
296 enum mips_monitor_type {
297   /* IDT/SIM monitor being used: */
298   MON_IDT,
299   /* PMON monitor being used: */
300   MON_PMON, /* 3.0.83 [COGENT,EB,FP,NET] Algorithmics Ltd. Nov  9 1995 17:19:50 */
301   MON_DDB,  /* 2.7.473 [DDBVR4300,EL,FP,NET] Risq Modular Systems,  Thu Jun 6 09:28:40 PDT 1996 */
302   MON_LSI,  /* 4.3.12 [EB,FP], LSI LOGIC Corp. Tue Feb 25 13:22:14 1997 */
303   /* Last and unused value, for sizing vectors, etc. */
304   MON_LAST
305 };
306 static enum mips_monitor_type mips_monitor = MON_LAST;
307
308 /* The default monitor prompt text: */
309 static char *mips_monitor_prompt = TARGET_MONITOR_PROMPT;
310 /* For the Cogent PMON world this is still not ideal. The default
311    prompt is "PMON> ", unfortunately the user can change the prompt
312    and the new prompt will survive over a power-cycle (EEPROM). This
313    means that the code should really force the monitor prompt to a
314    known value as the very first action, and that the
315    "mips_monitor_prompt" support is not needed... since the prompt
316    could be explicitly set to TARGET_MONITOR_PROMPT (even though it
317    may be the prompt for a different monitor). However, this will
318    require changing the mips_initialize reset sequence. (TODO) */
319
320 /* Set to 1 if the target is open.  */
321 static int mips_is_open;
322
323 /* Currently active target description (if mips_is_open == 1) */
324 static struct target_ops *current_ops;
325
326 /* Set to 1 while the connection is being initialized.  */
327 static int mips_initializing;
328
329 /* Set to 1 while the connection is being brought down.  */
330 static int mips_exiting;
331
332 /* The next sequence number to send.  */
333 static unsigned int mips_send_seq;
334
335 /* The next sequence number we expect to receive.  */
336 static unsigned int mips_receive_seq;
337
338 /* The time to wait before retransmitting a packet, in seconds.  */
339 static int mips_retransmit_wait = 3;
340
341 /* The number of times to try retransmitting a packet before giving up.  */
342 static int mips_send_retries = 10;
343
344 /* The number of garbage characters to accept when looking for an
345    SYN for the next packet.  */
346 static int mips_syn_garbage = 1050;
347
348 /* The time to wait for a packet, in seconds.  */
349 static int mips_receive_wait = 5;
350
351 /* Set if we have sent a packet to the board but have not yet received
352    a reply.  */
353 static int mips_need_reply = 0;
354
355 /* Handle used to access serial I/O stream.  */
356 static serial_t mips_desc;
357
358 /* UDP handle used to download files to target.  */
359 static serial_t udp_desc;
360 static int udp_in_use;
361
362 /* TFTP filename used to download files to DDB board, in the form
363    host:filename.  */
364 static char *tftp_name;         /* host:filename */
365 static char *tftp_localname;    /* filename portion of above */
366 static int tftp_in_use;
367 static FILE *tftp_file;
368
369 /* Counts the number of times the user tried to interrupt the target (usually
370    via ^C.  */
371 static int interrupt_count;
372
373 /* If non-zero, means that the target is running. */
374 static int mips_wait_flag = 0;
375
376 /* If non-zero, monitor supports breakpoint commands. */
377 static monitor_supports_breakpoints = 0;
378
379 /* Data cache header.  */
380
381 #if 0   /* not used (yet?) */
382 static DCACHE *mips_dcache;
383 #endif
384
385 /* Non-zero means that we've just hit a read or write watchpoint */
386 static int hit_watchpoint;
387
388 static void
389 close_ports()
390 {
391   mips_is_open = 0;
392   SERIAL_CLOSE (mips_desc);
393
394   if (udp_in_use)
395     {
396       SERIAL_CLOSE (udp_desc);
397       udp_in_use = 0;
398     }
399   tftp_in_use = 0;
400 }
401     
402 /* Handle low-level error that we can't recover from.  Note that just
403    error()ing out from target_wait or some such low-level place will cause
404    all hell to break loose--the rest of GDB will tend to get left in an
405    inconsistent state.  */
406
407 static NORETURN void
408 #ifdef ANSI_PROTOTYPES
409 mips_error (char *string, ...)
410 #else
411 mips_error (va_alist)
412      va_dcl
413 #endif
414 {
415   va_list args;
416
417 #ifdef ANSI_PROTOTYPES
418   va_start (args, string);
419 #else
420   char *string;
421   va_start (args);
422   string = va_arg (args, char *);
423 #endif
424  
425   target_terminal_ours ();
426   wrap_here("");                        /* Force out any buffered output */
427   gdb_flush (gdb_stdout);
428   if (error_pre_print)
429     fprintf_filtered (gdb_stderr, error_pre_print);
430   vfprintf_filtered (gdb_stderr, string, args);
431   fprintf_filtered (gdb_stderr, "\n");
432   va_end (args);
433   gdb_flush (gdb_stderr);
434
435   /* Clean up in such a way that mips_close won't try to talk to the
436      board (it almost surely won't work since we weren't able to talk to
437      it).  */
438   close_ports ();
439
440   printf_unfiltered ("Ending remote MIPS debugging.\n");
441   target_mourn_inferior ();
442
443   return_to_top_level (RETURN_ERROR);
444 }
445
446 /* putc_readable - print a character, displaying non-printable chars in
447    ^x notation or in hex.  */
448
449 static void
450 putc_readable (ch)
451      int ch;
452 {
453   if (ch == '\n')
454     putchar_unfiltered ('\n');
455   else if (ch == '\r')
456     printf_unfiltered ("\\r");
457   else if (ch < 0x20)   /* ASCII control character */
458     printf_unfiltered ("^%c", ch + '@');
459   else if (ch >= 0x7f)  /* non-ASCII characters (rubout or greater) */
460     printf_unfiltered ("[%02x]", ch & 0xff);
461   else
462     putchar_unfiltered (ch);
463 }
464
465
466 /* puts_readable - print a string, displaying non-printable chars in
467    ^x notation or in hex.  */
468
469 static void
470 puts_readable (string)
471      char *string;
472 {
473   int c;
474
475   while ((c = *string++) != '\0')
476     putc_readable (c);
477 }
478
479
480 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
481    timed out.  TIMEOUT specifies timeout value in seconds.
482 */
483
484 int
485 mips_expect_timeout (string, timeout)
486      char *string;
487      int timeout;
488 {
489   char *p = string;
490
491   if (remote_debug)
492     {
493       printf_unfiltered ("Expected \"");
494       puts_readable (string);
495       printf_unfiltered ("\", got \"");
496     }
497
498   immediate_quit = 1;
499   while (1)
500     {
501       int c;
502
503 /* Must use SERIAL_READCHAR here cuz mips_readchar would get confused if we
504    were waiting for the mips_monitor_prompt... */
505
506       c = SERIAL_READCHAR (mips_desc, timeout);
507
508       if (c == SERIAL_TIMEOUT)
509         {
510           if (remote_debug)
511             printf_unfiltered ("\": FAIL\n");
512           return 0;
513         }
514
515       if (remote_debug)
516         putc_readable (c);
517
518       if (c == *p++)
519         {       
520           if (*p == '\0')
521             {
522               immediate_quit = 0;
523               if (remote_debug)
524               printf_unfiltered ("\": OK\n");
525               return 1;
526             }
527         }
528       else
529         {
530           p = string;
531           if (c == *p)
532             p++;
533         }
534     }
535 }
536
537 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
538    timed out.  The timeout value is hard-coded to 2 seconds.  Use
539    mips_expect_timeout if a different timeout value is needed.
540 */
541
542 int
543 mips_expect (string)
544      char *string;
545 {
546     return mips_expect_timeout (string, 2);
547 }
548
549 /* Read the required number of characters into the given buffer (which
550    is assumed to be large enough). The only failure is a timeout. */
551 int
552 mips_getstring (string, n)
553      char *string;
554      int n;
555 {
556   char *p = string;
557   int c;
558
559   immediate_quit = 1;
560   while (n > 0)
561     {
562       c = SERIAL_READCHAR (mips_desc, 2);
563
564       if (c == SERIAL_TIMEOUT) {
565         fprintf_unfiltered (stderr, "Failed to read %d characters from target (TIMEOUT)\n", n);
566         return 0;
567       }
568
569       *p++ = c;
570       n--;
571     }
572
573   return 1;
574 }
575
576 /* Read a character from the remote, aborting on error.  Returns
577    SERIAL_TIMEOUT on timeout (since that's what SERIAL_READCHAR
578    returns).  FIXME: If we see the string mips_monitor_prompt from
579    the board, then we are debugging on the main console port, and we
580    have somehow dropped out of remote debugging mode.  In this case,
581    we automatically go back in to remote debugging mode.  This is a
582    hack, put in because I can't find any way for a program running on
583    the remote board to terminate without also ending remote debugging
584    mode.  I assume users won't have any trouble with this; for one
585    thing, the IDT documentation generally assumes that the remote
586    debugging port is not the console port.  This is, however, very
587    convenient for DejaGnu when you only have one connected serial
588    port.  */
589
590 static int
591 mips_readchar (timeout)
592      int timeout;
593 {
594   int ch;
595   static int state = 0;
596   static int mips_monitor_prompt_len = -1;
597
598   /* NASTY, since we assume that the prompt does not change after the
599      first mips_readchar call: */
600   if (mips_monitor_prompt_len == -1)
601    mips_monitor_prompt_len = strlen(mips_monitor_prompt);
602
603 #ifdef MAINTENANCE_CMDS
604   {
605     int i;
606
607     i = timeout;
608     if (i == -1 && watchdog > 0)
609      i = watchdog;
610   }
611 #endif
612
613   if (state == mips_monitor_prompt_len)
614     timeout = 1;
615   ch = SERIAL_READCHAR (mips_desc, timeout);
616 #ifdef MAINTENANCE_CMDS
617   if (ch == SERIAL_TIMEOUT && timeout == -1) /* Watchdog went off */
618     {
619       target_mourn_inferior ();
620       error ("Watchdog has expired.  Target detached.\n");
621     }
622 #endif
623   if (ch == SERIAL_EOF)
624     mips_error ("End of file from remote");
625   if (ch == SERIAL_ERROR)
626     mips_error ("Error reading from remote: %s", safe_strerror (errno));
627   if (remote_debug > 1)
628     {
629       /* Don't use _filtered; we can't deal with a QUIT out of
630          target_wait, and I think this might be called from there.  */
631       if (ch != SERIAL_TIMEOUT)
632         printf_unfiltered ("Read '%c' %d 0x%x\n", ch, ch, ch);
633       else
634         printf_unfiltered ("Timed out in read\n");
635     }
636
637   /* If we have seen mips_monitor_prompt and we either time out, or
638      we see a @ (which was echoed from a packet we sent), reset the
639      board as described above.  The first character in a packet after
640      the SYN (which is not echoed) is always an @ unless the packet is
641      more than 64 characters long, which ours never are.  */
642   if ((ch == SERIAL_TIMEOUT || ch == '@')
643       && state == mips_monitor_prompt_len
644       && ! mips_initializing
645       && ! mips_exiting)
646     {
647       if (remote_debug > 0)
648         /* Don't use _filtered; we can't deal with a QUIT out of
649            target_wait, and I think this might be called from there.  */
650         printf_unfiltered ("Reinitializing MIPS debugging mode\n");
651
652       mips_need_reply = 0;
653       mips_initialize ();
654
655       state = 0;
656
657       /* At this point, about the only thing we can do is abort the command
658          in progress and get back to command level as quickly as possible. */
659
660       error ("Remote board reset, debug protocol re-initialized.");
661     }
662
663   if (ch == mips_monitor_prompt[state])
664     ++state;
665   else
666     state = 0;
667
668   return ch;
669 }
670
671 /* Get a packet header, putting the data in the supplied buffer.
672    PGARBAGE is a pointer to the number of garbage characters received
673    so far.  CH is the last character received.  Returns 0 for success,
674    or -1 for timeout.  */
675
676 static int
677 mips_receive_header (hdr, pgarbage, ch, timeout)
678      unsigned char *hdr;
679      int *pgarbage;
680      int ch;
681      int timeout;
682 {
683   int i;
684
685   while (1)
686     {
687       /* Wait for a SYN.  mips_syn_garbage is intended to prevent
688          sitting here indefinitely if the board sends us one garbage
689          character per second.  ch may already have a value from the
690          last time through the loop.  */
691       while (ch != SYN)
692         {
693           ch = mips_readchar (timeout);
694           if (ch == SERIAL_TIMEOUT)
695            return -1;
696           if (ch != SYN)
697             {
698               /* Printing the character here lets the user of gdb see
699                  what the program is outputting, if the debugging is
700                  being done on the console port.  Don't use _filtered;
701                  we can't deal with a QUIT out of target_wait.  */
702               if (! mips_initializing || remote_debug > 0)
703                 {
704                   putc_readable (ch);
705                   gdb_flush (gdb_stdout);
706                 }
707
708               ++*pgarbage;
709               if (mips_syn_garbage > 0
710                   && *pgarbage > mips_syn_garbage)
711                 mips_error ("Debug protocol failure:  more than %d characters before a sync.", 
712                             mips_syn_garbage);
713             }
714         }
715
716       /* Get the packet header following the SYN.  */
717       for (i = 1; i < HDR_LENGTH; i++)
718         {
719           ch = mips_readchar (timeout);
720           if (ch == SERIAL_TIMEOUT)
721             return -1;
722           /* Make sure this is a header byte.  */
723           if (ch == SYN || ! HDR_CHECK (ch))
724             break;
725
726           hdr[i] = ch;
727         }
728
729       /* If we got the complete header, we can return.  Otherwise we
730          loop around and keep looking for SYN.  */
731       if (i >= HDR_LENGTH)
732         return 0;
733     }
734 }
735
736 /* Get a packet header, putting the data in the supplied buffer.
737    PGARBAGE is a pointer to the number of garbage characters received
738    so far.  The last character read is returned in *PCH.  Returns 0
739    for success, -1 for timeout, -2 for error.  */
740
741 static int
742 mips_receive_trailer (trlr, pgarbage, pch, timeout)
743      unsigned char *trlr;
744      int *pgarbage;
745      int *pch;
746      int timeout;
747 {
748   int i;
749   int ch;
750
751   for (i = 0; i < TRLR_LENGTH; i++)
752     {
753       ch = mips_readchar (timeout);
754       *pch = ch;
755       if (ch == SERIAL_TIMEOUT)
756         return -1;
757       if (! TRLR_CHECK (ch))
758         return -2;
759       trlr[i] = ch;
760     }
761   return 0;
762 }
763
764 /* Get the checksum of a packet.  HDR points to the packet header.
765    DATA points to the packet data.  LEN is the length of DATA.  */
766
767 static int
768 mips_cksum (hdr, data, len)
769      const unsigned char *hdr;
770      const unsigned char *data;
771      int len;
772 {
773   register const unsigned char *p;
774   register int c;
775   register int cksum;
776
777   cksum = 0;
778
779   /* The initial SYN is not included in the checksum.  */
780   c = HDR_LENGTH - 1;
781   p = hdr + 1;
782   while (c-- != 0)
783     cksum += *p++;
784   
785   c = len;
786   p = data;
787   while (c-- != 0)
788     cksum += *p++;
789
790   return cksum;
791 }
792
793 /* Send a packet containing the given ASCII string.  */
794
795 static void
796 mips_send_packet (s, get_ack)
797      const char *s;
798      int get_ack;
799 {
800   /* unsigned */ int len;
801   unsigned char *packet;
802   register int cksum;
803   int try;
804
805   len = strlen (s);
806   if (len > DATA_MAXLEN)
807     mips_error ("MIPS protocol data packet too long: %s", s);
808
809   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);
810
811   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
812   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
813   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
814   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);
815
816   memcpy (packet + HDR_LENGTH, s, len);
817
818   cksum = mips_cksum (packet, packet + HDR_LENGTH, len);
819   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
820   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
821   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
822
823   /* Increment the sequence number.  This will set mips_send_seq to
824      the sequence number we expect in the acknowledgement.  */
825   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;
826
827   /* We can only have one outstanding data packet, so we just wait for
828      the acknowledgement here.  Keep retransmitting the packet until
829      we get one, or until we've tried too many times.  */
830   for (try = 0; try < mips_send_retries; try++)
831     {
832       int garbage;
833       int ch;
834
835       if (remote_debug > 0)
836         {
837           /* Don't use _filtered; we can't deal with a QUIT out of
838              target_wait, and I think this might be called from there.  */
839           packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
840           printf_unfiltered ("Writing \"%s\"\n", packet + 1);
841         }
842
843       if (SERIAL_WRITE (mips_desc, packet,
844                         HDR_LENGTH + len + TRLR_LENGTH) != 0)
845         mips_error ("write to target failed: %s", safe_strerror (errno));
846
847       if (! get_ack)
848         return;
849
850       garbage = 0;
851       ch = 0;
852       while (1)
853         {
854           unsigned char hdr[HDR_LENGTH + 1];
855           unsigned char trlr[TRLR_LENGTH + 1];
856           int err;
857           unsigned int seq;
858
859           /* Get the packet header.  If we time out, resend the data
860              packet.  */
861           err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
862           if (err != 0)
863             break;
864
865           ch = 0;
866
867           /* If we get a data packet, assume it is a duplicate and
868              ignore it.  FIXME: If the acknowledgement is lost, this
869              data packet may be the packet the remote sends after the
870              acknowledgement.  */
871           if (HDR_IS_DATA (hdr)) {
872             int i;
873
874             /* Ignore any errors raised whilst attempting to ignore
875                packet. */
876
877             len = HDR_GET_LEN (hdr);
878
879             for (i = 0; i < len; i++)
880               {
881                 int rch;
882
883                 rch = mips_readchar (2);
884                 if (rch == SYN)
885                   {
886                     ch = SYN;
887                     break;
888                   }
889                 if (rch == SERIAL_TIMEOUT)
890                   break;
891                 /* ignore the character */
892               }
893
894             if (i == len)
895               (void) mips_receive_trailer (trlr, &garbage, &ch, 2);
896
897             /* We don't bother checking the checksum, or providing an
898                ACK to the packet. */
899             continue;
900           }
901
902           /* If the length is not 0, this is a garbled packet.  */
903           if (HDR_GET_LEN (hdr) != 0)
904             continue;
905
906           /* Get the packet trailer.  */
907           err = mips_receive_trailer (trlr, &garbage, &ch,
908                                       mips_retransmit_wait);
909
910           /* If we timed out, resend the data packet.  */
911           if (err == -1)
912             break;
913
914           /* If we got a bad character, reread the header.  */
915           if (err != 0)
916             continue;
917
918           /* If the checksum does not match the trailer checksum, this
919              is a bad packet; ignore it.  */
920           if (mips_cksum (hdr, (unsigned char *) NULL, 0)
921               != TRLR_GET_CKSUM (trlr))
922             continue;
923
924           if (remote_debug > 0)
925             {
926               hdr[HDR_LENGTH] = '\0';
927               trlr[TRLR_LENGTH] = '\0';
928               /* Don't use _filtered; we can't deal with a QUIT out of
929                  target_wait, and I think this might be called from there.  */
930               printf_unfiltered ("Got ack %d \"%s%s\"\n",
931                                HDR_GET_SEQ (hdr), hdr + 1, trlr);
932             }
933
934           /* If this ack is for the current packet, we're done.  */
935           seq = HDR_GET_SEQ (hdr);
936           if (seq == mips_send_seq)
937             return;
938
939           /* If this ack is for the last packet, resend the current
940              packet.  */
941           if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
942             break;
943
944           /* Otherwise this is a bad ack; ignore it.  Increment the
945              garbage count to ensure that we do not stay in this loop
946              forever.  */
947           ++garbage;
948         }
949     }
950
951   mips_error ("Remote did not acknowledge packet");
952 }
953
954 /* Receive and acknowledge a packet, returning the data in BUFF (which
955    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
956    implies that only the sender retransmits packets, so this code just
957    waits silently for a packet.  It returns the length of the received
958    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
959    don't print an error message and return -1.  */
960
961 static int
962 mips_receive_packet (buff, throw_error, timeout)
963      char *buff;
964      int throw_error;
965      int timeout;
966 {
967   int ch;
968   int garbage;
969   int len;
970   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
971   int cksum;
972
973   ch = 0;
974   garbage = 0;
975   while (1)
976     {
977       unsigned char hdr[HDR_LENGTH];
978       unsigned char trlr[TRLR_LENGTH];
979       int i;
980       int err;
981
982       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
983         {
984           if (throw_error)
985             mips_error ("Timed out waiting for remote packet");
986           else
987             return -1;
988         }
989
990       ch = 0;
991
992       /* An acknowledgement is probably a duplicate; ignore it.  */
993       if (! HDR_IS_DATA (hdr))
994         {
995           len = HDR_GET_LEN (hdr);
996           /* Check if the length is valid for an ACK, we may aswell
997              try and read the remainder of the packet: */
998           if (len == 0)
999             {
1000               /* Ignore the error condition, since we are going to
1001                  ignore the packet anyway. */
1002               (void) mips_receive_trailer (trlr, &garbage, &ch, timeout);
1003             }
1004           /* Don't use _filtered; we can't deal with a QUIT out of
1005              target_wait, and I think this might be called from there.  */
1006           if (remote_debug > 0)
1007             printf_unfiltered ("Ignoring unexpected ACK\n");
1008           continue;
1009         }
1010
1011       len = HDR_GET_LEN (hdr);
1012       for (i = 0; i < len; i++)
1013         {
1014           int rch;
1015
1016           rch = mips_readchar (timeout);
1017           if (rch == SYN)
1018             {
1019               ch = SYN;
1020               break;
1021             }
1022           if (rch == SERIAL_TIMEOUT)
1023             {
1024               if (throw_error)
1025                 mips_error ("Timed out waiting for remote packet");
1026               else
1027                 return -1;
1028             }
1029           buff[i] = rch;
1030         }
1031
1032       if (i < len)
1033         {
1034           /* Don't use _filtered; we can't deal with a QUIT out of
1035              target_wait, and I think this might be called from there.  */
1036           if (remote_debug > 0)
1037             printf_unfiltered ("Got new SYN after %d chars (wanted %d)\n",
1038                              i, len);
1039           continue;
1040         }
1041
1042       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
1043       if (err == -1)
1044         {
1045           if (throw_error)
1046             mips_error ("Timed out waiting for packet");
1047           else
1048             return -1;
1049         }
1050       if (err == -2)
1051         {
1052           /* Don't use _filtered; we can't deal with a QUIT out of
1053              target_wait, and I think this might be called from there.  */
1054           if (remote_debug > 0)
1055             printf_unfiltered ("Got SYN when wanted trailer\n");
1056           continue;
1057         }
1058
1059       /* If this is the wrong sequence number, ignore it.  */
1060       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
1061         {
1062           /* Don't use _filtered; we can't deal with a QUIT out of
1063              target_wait, and I think this might be called from there.  */
1064           if (remote_debug > 0)
1065             printf_unfiltered ("Ignoring sequence number %d (want %d)\n",
1066                              HDR_GET_SEQ (hdr), mips_receive_seq);
1067           continue;
1068         }
1069
1070       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
1071         break;
1072
1073       if (remote_debug > 0)
1074         /* Don't use _filtered; we can't deal with a QUIT out of
1075            target_wait, and I think this might be called from there.  */
1076         printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
1077                          mips_cksum (hdr, buff, len),
1078                          TRLR_GET_CKSUM (trlr));
1079
1080       /* The checksum failed.  Send an acknowledgement for the
1081          previous packet to tell the remote to resend the packet.  */
1082       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1083       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1084       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1085       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1086
1087       cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
1088
1089       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1090       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1091       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1092
1093       if (remote_debug > 0)
1094         {
1095           ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1096           /* Don't use _filtered; we can't deal with a QUIT out of
1097              target_wait, and I think this might be called from there.  */
1098           printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1099                            ack + 1);
1100         }
1101
1102       if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1103         {
1104           if (throw_error)
1105             mips_error ("write to target failed: %s", safe_strerror (errno));
1106           else
1107             return -1;
1108         }
1109     }
1110
1111   if (remote_debug > 0)
1112     {
1113       buff[len] = '\0';
1114       /* Don't use _filtered; we can't deal with a QUIT out of
1115          target_wait, and I think this might be called from there.  */
1116       printf_unfiltered ("Got packet \"%s\"\n", buff);
1117     }
1118
1119   /* We got the packet.  Send an acknowledgement.  */
1120   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;
1121
1122   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1123   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1124   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1125   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1126
1127   cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
1128
1129   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1130   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1131   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1132
1133   if (remote_debug > 0)
1134     {
1135       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1136       /* Don't use _filtered; we can't deal with a QUIT out of
1137          target_wait, and I think this might be called from there.  */
1138       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1139                        ack + 1);
1140     }
1141
1142   if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1143     {
1144       if (throw_error)
1145         mips_error ("write to target failed: %s", safe_strerror (errno));
1146       else
1147         return -1;
1148     }
1149
1150   return len;
1151 }
1152
1153
1154 /* Optionally send a request to the remote system and optionally wait
1155    for the reply.  This implements the remote debugging protocol,
1156    which is built on top of the packet protocol defined above.  Each
1157    request has an ADDR argument and a DATA argument.  The following
1158    requests are defined:
1159
1160    \0   don't send a request; just wait for a reply
1161    i    read word from instruction space at ADDR
1162    d    read word from data space at ADDR
1163    I    write DATA to instruction space at ADDR
1164    D    write DATA to data space at ADDR
1165    r    read register number ADDR
1166    R    set register number ADDR to value DATA
1167    c    continue execution (if ADDR != 1, set pc to ADDR)
1168    s    single step (if ADDR != 1, set pc to ADDR)
1169
1170    The read requests return the value requested.  The write requests
1171    return the previous value in the changed location.  The execution
1172    requests return a UNIX wait value (the approximate signal which
1173    caused execution to stop is in the upper eight bits).
1174
1175    If PERR is not NULL, this function waits for a reply.  If an error
1176    occurs, it sets *PERR to 1 and sets errno according to what the
1177    target board reports.  */
1178
1179 static CORE_ADDR 
1180 mips_request (cmd, addr, data, perr, timeout, buff)
1181      int cmd;
1182      CORE_ADDR addr;
1183      CORE_ADDR data;
1184      int *perr;
1185      int timeout;
1186      char *buff;
1187 {
1188   char myBuff[DATA_MAXLEN + 1];
1189   int len;
1190   int rpid;
1191   char rcmd;
1192   int rerrflg;
1193   int rresponse;
1194
1195   if (buff == (char *) NULL)
1196     buff = myBuff;
1197
1198   if (cmd != '\0')
1199     {
1200       if (mips_need_reply)
1201         fatal ("mips_request: Trying to send command before reply");
1202       sprintf (buff, "0x0 %c 0x%s 0x%s", cmd, paddr_nz (addr), paddr_nz (data));
1203       mips_send_packet (buff, 1);
1204       mips_need_reply = 1;
1205     }
1206
1207   if (perr == (int *) NULL)
1208     return 0;
1209
1210   if (! mips_need_reply)
1211     fatal ("mips_request: Trying to get reply before command");
1212
1213   mips_need_reply = 0;
1214
1215   len = mips_receive_packet (buff, 1, timeout);
1216   buff[len] = '\0';
1217
1218   if (sscanf (buff, "0x%x %c 0x%x 0x%x",
1219               &rpid, &rcmd, &rerrflg, &rresponse) != 4
1220       || (cmd != '\0' && rcmd != cmd))
1221     mips_error ("Bad response from remote board");
1222
1223   if (rerrflg != 0)
1224     {
1225       *perr = 1;
1226
1227       /* FIXME: This will returns MIPS errno numbers, which may or may
1228          not be the same as errno values used on other systems.  If
1229          they stick to common errno values, they will be the same, but
1230          if they don't, they must be translated.  */
1231       errno = rresponse;
1232
1233       return 0;
1234     }
1235
1236   *perr = 0;
1237   return rresponse;
1238 }
1239
1240 static void
1241 mips_initialize_cleanups (arg)
1242      PTR arg;
1243 {
1244   mips_initializing = 0;
1245 }
1246
1247 static void
1248 mips_exit_cleanups (arg)
1249      PTR arg;
1250 {
1251   mips_exiting = 0;
1252 }
1253
1254 static void
1255 mips_send_command (cmd, prompt)
1256      const char *cmd;
1257      int prompt;
1258 {
1259   SERIAL_WRITE (mips_desc, cmd, strlen(cmd));
1260   mips_expect (cmd);
1261   mips_expect ("\n");
1262   if (prompt)
1263     mips_expect (mips_monitor_prompt);
1264 }
1265
1266 /* Enter remote (dbx) debug mode: */
1267 static void
1268 mips_enter_debug ()
1269 {
1270   /* Reset the sequence numbers, ready for the new debug sequence: */
1271   mips_send_seq = 0;
1272   mips_receive_seq = 0;
1273
1274   if (mips_monitor != MON_IDT)
1275     mips_send_command ("debug\r", 0);
1276   else /* assume IDT monitor by default */
1277     mips_send_command ("db tty0\r", 0);
1278
1279   SERIAL_WRITE (mips_desc, "\r", sizeof "\r" - 1);
1280
1281   /* We don't need to absorb any spurious characters here, since the
1282      mips_receive_header will eat up a reasonable number of characters
1283      whilst looking for the SYN, however this avoids the "garbage"
1284      being displayed to the user. */
1285   if (mips_monitor != MON_IDT)
1286     mips_expect ("\r");
1287   
1288   {
1289     char buff[DATA_MAXLEN + 1];
1290     if (mips_receive_packet (buff, 1, 3) < 0)
1291       mips_error ("Failed to initialize (didn't receive packet).");
1292   }
1293 }
1294
1295 /* Exit remote (dbx) debug mode, returning to the monitor prompt: */
1296 static int
1297 mips_exit_debug ()
1298 {
1299   int err;
1300   struct cleanup *old_cleanups = make_cleanup (mips_exit_cleanups, NULL);
1301
1302   mips_exiting = 1;
1303
1304   if (mips_monitor != MON_IDT)
1305     {
1306       /* The DDB (NEC) and MiniRISC (LSI) versions of PMON exit immediately,
1307          so we do not get a reply to this command: */
1308       mips_request ('x', (unsigned int) 0, (unsigned int) 0, NULL,
1309                 mips_receive_wait, NULL);
1310       mips_need_reply = 0;
1311       if (!mips_expect (" break!"))
1312         return -1;
1313     }
1314   else
1315     mips_request ('x', (unsigned int) 0, (unsigned int) 0, &err,
1316                   mips_receive_wait, NULL);
1317
1318   if (mips_monitor == MON_IDT && !mips_expect ("Exiting remote debug mode"))
1319     return -1;
1320     
1321   if (mips_monitor == MON_DDB)
1322     {
1323       if (!mips_expect ("\n"))
1324         return -1;
1325     }
1326   else
1327     if (!mips_expect ("\r\n"))
1328       return -1;
1329
1330   if (!mips_expect (mips_monitor_prompt))
1331     return -1;
1332
1333   do_cleanups (old_cleanups);
1334
1335   return 0;
1336 }
1337
1338 /* Initialize a new connection to the MIPS board, and make sure we are
1339    really connected.  */
1340
1341 static void
1342 mips_initialize ()
1343 {
1344   int err;
1345   struct cleanup *old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);
1346   int j;
1347
1348   /* What is this code doing here?  I don't see any way it can happen, and
1349      it might mean mips_initializing didn't get cleared properly.
1350      So I'll make it a warning.  */
1351
1352   if (mips_initializing)
1353     {
1354       warning ("internal error: mips_initialize called twice");
1355       return;
1356     }
1357
1358   mips_wait_flag = 0;
1359   mips_initializing = 1;
1360
1361   /* At this point, the packit protocol isn't responding.  We'll try getting
1362      into the monitor, and restarting the protocol.  */
1363
1364   /* Force the system into the monitor.  After this we *should* be at
1365      the mips_monitor_prompt.  */
1366   if (mips_monitor != MON_IDT)
1367     j = 0; /* start by checking if we are already at the prompt */
1368   else
1369     j = 1; /* start by sending a break */
1370   for (; j <= 4; j++)
1371     {
1372       switch (j)
1373         {
1374         case 0:                 /* First, try sending a CR */
1375           SERIAL_FLUSH_INPUT (mips_desc);
1376           SERIAL_WRITE (mips_desc, "\r", 1);
1377           break;
1378         case 1:                 /* First, try sending a break */
1379           SERIAL_SEND_BREAK (mips_desc);
1380           break;
1381         case 2:                 /* Then, try a ^C */
1382           SERIAL_WRITE (mips_desc, "\003", 1);
1383           break;
1384         case 3:                 /* Then, try escaping from download */
1385           {
1386             if (mips_monitor != MON_IDT)
1387               {
1388                 char tbuff[7];
1389
1390                 /* We shouldn't need to send multiple termination
1391                    sequences, since the target performs line (or
1392                    block) reads, and then processes those
1393                    packets. In-case we were downloading a large packet
1394                    we flush the output buffer before inserting a
1395                    termination sequence. */
1396                 SERIAL_FLUSH_OUTPUT (mips_desc);
1397                 sprintf (tbuff, "\r/E/E\r");
1398                 SERIAL_WRITE (mips_desc, tbuff, 6);
1399               }
1400             else
1401               {
1402                 char srec[10];
1403                 int i;
1404
1405                 /* We are possibly in binary download mode, having
1406                    aborted in the middle of an S-record.  ^C won't
1407                    work because of binary mode.  The only reliable way
1408                    out is to send enough termination packets (8 bytes)
1409                    to fill up and then overflow the largest size
1410                    S-record (255 bytes in this case).  This amounts to
1411                    256/8 + 1 packets.
1412                    */
1413
1414                 mips_make_srec (srec, '7', 0, NULL, 0);
1415
1416                 for (i = 1; i <= 33; i++)
1417                   {
1418                     SERIAL_WRITE (mips_desc, srec, 8);
1419
1420                     if (SERIAL_READCHAR (mips_desc, 0) >= 0)
1421                       break;    /* Break immediatly if we get something from
1422                                    the board. */
1423                   }
1424               }
1425           }
1426           break;
1427         case 4:
1428           mips_error ("Failed to initialize.");
1429         }
1430
1431       if (mips_expect (mips_monitor_prompt))
1432         break;
1433     }
1434
1435   if (mips_monitor != MON_IDT)
1436     {
1437       /* Ensure the correct target state: */
1438       if (mips_monitor != MON_LSI)
1439         mips_send_command ("set regsize 64\r", -1);
1440       mips_send_command ("set hostport tty0\r", -1);
1441       mips_send_command ("set brkcmd \"\"\r", -1);
1442       /* Delete all the current breakpoints: */
1443       mips_send_command ("db *\r", -1);
1444       /* NOTE: PMON does not have breakpoint support through the
1445          "debug" mode, only at the monitor command-line. */
1446     }
1447
1448   mips_enter_debug ();
1449
1450   /* Clear all breakpoints: */
1451   if (mips_monitor == MON_IDT && common_breakpoint ('b', -1, 0, NULL) == 0)
1452     monitor_supports_breakpoints = 1;
1453   else
1454     monitor_supports_breakpoints = 0;
1455
1456   do_cleanups (old_cleanups);
1457
1458   /* If this doesn't call error, we have connected; we don't care if
1459      the request itself succeeds or fails.  */
1460
1461   mips_request ('r', (unsigned int) 0, (unsigned int) 0, &err,
1462                 mips_receive_wait, NULL);
1463   set_current_frame (create_new_frame (read_fp (), read_pc ()));
1464   select_frame (get_current_frame (), 0);
1465 }
1466
1467 /* Open a connection to the remote board.  */
1468 static void
1469 common_open (ops, name, from_tty)
1470      struct target_ops *ops;
1471      char *name;
1472      int from_tty;
1473 {
1474   char *ptype;
1475   char *serial_port_name;
1476   char *remote_name = 0;
1477   char *local_name = 0;
1478   char **argv;
1479
1480   if (name == 0)
1481     error (
1482 "To open a MIPS remote debugging connection, you need to specify what serial\n\
1483 device is attached to the target board (e.g., /dev/ttya).\n"
1484 "If you want to use TFTP to download to the board, specify the name of a\n"
1485 "temporary file to be used by GDB for downloads as the second argument.\n"
1486 "This filename must be in the form host:filename, where host is the name\n"
1487 "of the host running the TFTP server, and the file must be readable by the\n"
1488 "world.  If the local name of the temporary file differs from the name as\n"
1489 "seen from the board via TFTP, specify that name as the third parameter.\n");
1490
1491   /* Parse the serial port name, the optional TFTP name, and the
1492      optional local TFTP name.  */
1493   if ((argv = buildargv (name)) == NULL)
1494     nomem(0);
1495   make_cleanup (freeargv, (char *) argv);
1496
1497   serial_port_name = strsave (argv[0]);
1498   if (argv[1])                          /* remote TFTP name specified? */
1499     {
1500       remote_name = argv[1];
1501       if (argv[2])                      /* local TFTP filename specified? */
1502         local_name = argv[2];
1503     }
1504
1505   target_preopen (from_tty);
1506
1507   if (mips_is_open)
1508     unpush_target (current_ops);
1509
1510   /* Open and initialize the serial port.  */
1511   mips_desc = SERIAL_OPEN (serial_port_name);
1512   if (mips_desc == (serial_t) NULL)
1513     perror_with_name (serial_port_name);
1514
1515   if (baud_rate != -1)
1516     {
1517       if (SERIAL_SETBAUDRATE (mips_desc, baud_rate))
1518         {
1519           SERIAL_CLOSE (mips_desc);
1520           perror_with_name (serial_port_name);
1521         }
1522     }
1523
1524   SERIAL_RAW (mips_desc);
1525
1526   /* Open and initialize the optional download port.  If it is in the form
1527      hostname#portnumber, it's a UDP socket.  If it is in the form
1528      hostname:filename, assume it's the TFTP filename that must be
1529      passed to the DDB board to tell it where to get the load file.  */
1530   if (remote_name)
1531     {
1532       if (strchr (remote_name, '#'))
1533         {
1534           udp_desc = SERIAL_OPEN (remote_name);
1535           if (!udp_desc)
1536             perror_with_name ("Unable to open UDP port");
1537           udp_in_use = 1;
1538         }
1539       else
1540         {
1541           /* Save the remote and local names of the TFTP temp file.  If
1542              the user didn't specify a local name, assume it's the same
1543              as the part of the remote name after the "host:".  */
1544           if (tftp_name)
1545             free (tftp_name);
1546           if (tftp_localname)
1547             free (tftp_localname);
1548           if (local_name == NULL)
1549               if ((local_name = strchr (remote_name, ':')) != NULL)
1550                 local_name++;           /* skip over the colon */
1551           if (local_name == NULL)
1552             local_name = remote_name;   /* local name same as remote name */
1553           tftp_name = strsave (remote_name);
1554           tftp_localname = strsave (local_name);
1555           tftp_in_use = 1;
1556         }
1557     }
1558
1559   current_ops = ops;
1560   mips_is_open = 1;
1561
1562   mips_initialize ();
1563
1564   if (from_tty)
1565     printf_unfiltered ("Remote MIPS debugging using %s\n", serial_port_name);
1566
1567   /* Switch to using remote target now.  */
1568   push_target (ops);
1569
1570   /* FIXME: Should we call start_remote here?  */
1571
1572   /* Try to figure out the processor model if possible.  */
1573   ptype = mips_read_processor_type ();
1574   if (ptype)
1575     mips_set_processor_type_command (strsave (ptype), 0);
1576
1577 /* This is really the job of start_remote however, that makes an assumption
1578    that the target is about to print out a status message of some sort.  That
1579    doesn't happen here (in fact, it may not be possible to get the monitor to
1580    send the appropriate packet).  */
1581
1582   flush_cached_frames ();
1583   registers_changed ();
1584   stop_pc = read_pc ();
1585   set_current_frame (create_new_frame (read_fp (), stop_pc));
1586   select_frame (get_current_frame (), 0);
1587   print_stack_frame (selected_frame, -1, 1);
1588   free (serial_port_name);
1589 }
1590
1591 static void
1592 mips_open (name, from_tty)
1593      char *name;
1594      int from_tty;
1595 {
1596   mips_monitor = MON_IDT;
1597   common_open (&mips_ops, name, from_tty);
1598 }
1599
1600 static void
1601 pmon_open (name, from_tty)
1602      char *name;
1603      int from_tty;
1604 {
1605   /* The PMON monitor has a prompt different from the default
1606      "TARGET_MONITOR_PROMPT": */
1607   mips_monitor_prompt = "PMON> ";
1608   mips_monitor = MON_PMON;
1609   common_open (&pmon_ops, name, from_tty);
1610 }
1611
1612 static void
1613 ddb_open (name, from_tty)
1614      char *name;
1615      int from_tty;
1616 {
1617   /* The PMON monitor has a prompt different from the default
1618      "TARGET_MONITOR_PROMPT": */
1619   mips_monitor_prompt = "NEC010>";
1620   mips_monitor = MON_DDB;
1621   common_open (&ddb_ops, name, from_tty);
1622 }
1623
1624 static void
1625 lsi_open (name, from_tty)
1626      char *name;
1627      int from_tty;
1628 {
1629   mips_monitor_prompt = "PMON> ";
1630   mips_monitor = MON_LSI;
1631   common_open (&ddb_ops, name, from_tty);
1632 }
1633
1634 /* Close a connection to the remote board.  */
1635
1636 static void
1637 mips_close (quitting)
1638      int quitting;
1639 {
1640   if (mips_is_open)
1641     {
1642       /* Get the board out of remote debugging mode.  */
1643       (void) mips_exit_debug ();
1644
1645       close_ports ();
1646     }
1647 }
1648
1649 /* Detach from the remote board.  */
1650
1651 static void
1652 mips_detach (args, from_tty)
1653      char *args;
1654      int from_tty;
1655 {
1656   if (args)
1657     error ("Argument given to \"detach\" when remotely debugging.");
1658
1659   pop_target ();
1660
1661   mips_close (1);
1662
1663   if (from_tty)
1664     printf_unfiltered ("Ending remote MIPS debugging.\n");
1665 }
1666
1667 /* Tell the target board to resume.  This does not wait for a reply
1668    from the board.  */
1669
1670 static void
1671 mips_resume (pid, step, siggnal)
1672      int pid, step;
1673      enum target_signal siggnal;
1674 {
1675   int err;
1676
1677 /* start-sanitize-gm */
1678 #ifndef GENERAL_MAGIC
1679   if (siggnal != TARGET_SIGNAL_0)
1680     warning
1681       ("Can't send signals to a remote system.  Try `handle %s ignore'.",
1682        target_signal_to_name (siggnal));
1683 #endif /* GENERAL_MAGIC */
1684 /* end-sanitize-gm */
1685
1686   /* LSI PMON requires returns a reply packet "0x1 s 0x0 0x57f" after
1687      a single step, so we wait for that.  */
1688   mips_request (step ? 's' : 'c',
1689                 (unsigned int) 1,
1690                 (unsigned int) siggnal,
1691                 mips_monitor == MON_LSI && step ? &err : (int *) NULL,
1692                 mips_receive_wait, NULL);
1693 }
1694
1695 /* Return the signal corresponding to SIG, where SIG is the number which
1696    the MIPS protocol uses for the signal.  */
1697 enum target_signal
1698 mips_signal_from_protocol (sig)
1699      int sig;
1700 {
1701   /* We allow a few more signals than the IDT board actually returns, on
1702      the theory that there is at least *some* hope that perhaps the numbering
1703      for these signals is widely agreed upon.  */
1704   if (sig <= 0
1705       || sig > 31)
1706     return TARGET_SIGNAL_UNKNOWN;
1707
1708   /* Don't want to use target_signal_from_host because we are converting
1709      from MIPS signal numbers, not host ones.  Our internal numbers
1710      match the MIPS numbers for the signals the board can return, which
1711      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
1712   return (enum target_signal) sig;
1713 }
1714
1715 /* Wait until the remote stops, and return a wait status.  */
1716
1717 static int
1718 mips_wait (pid, status)
1719      int pid;
1720      struct target_waitstatus *status;
1721 {
1722   int rstatus;
1723   int err;
1724   char buff[DATA_MAXLEN];
1725   int rpc, rfp, rsp;
1726   char flags[20];
1727   int nfields;
1728
1729   interrupt_count = 0;
1730   hit_watchpoint = 0;
1731
1732   /* If we have not sent a single step or continue command, then the
1733      board is waiting for us to do something.  Return a status
1734      indicating that it is stopped.  */
1735   if (! mips_need_reply)
1736     {
1737       status->kind = TARGET_WAITKIND_STOPPED;
1738       status->value.sig = TARGET_SIGNAL_TRAP;
1739       return 0;
1740     }
1741
1742   /* No timeout; we sit here as long as the program continues to execute.  */
1743   mips_wait_flag = 1;
1744   rstatus = mips_request ('\000', (unsigned int) 0, (unsigned int) 0, &err, -1,
1745                           buff);
1746   mips_wait_flag = 0;
1747   if (err)
1748     mips_error ("Remote failure: %s", safe_strerror (errno));
1749
1750   nfields = sscanf (buff, "0x%*x %*c 0x%*x 0x%*x 0x%x 0x%x 0x%x 0x%*x %s",
1751                     &rpc, &rfp, &rsp, flags);
1752
1753   /* See if we got back extended status.  If so, pick out the pc, fp, sp, etc... */
1754
1755   if (nfields == 7 || nfields == 9) 
1756     {
1757       char buf[MAX_REGISTER_RAW_SIZE];
1758
1759       store_unsigned_integer (buf, REGISTER_RAW_SIZE (PC_REGNUM), rpc);
1760       supply_register (PC_REGNUM, buf);
1761
1762       store_unsigned_integer (buf, REGISTER_RAW_SIZE (PC_REGNUM), rfp);
1763       supply_register (30, buf); /* This register they are avoiding and so it is unnamed */
1764
1765       store_unsigned_integer (buf, REGISTER_RAW_SIZE (SP_REGNUM), rsp);
1766       supply_register (SP_REGNUM, buf);
1767
1768       store_unsigned_integer (buf, REGISTER_RAW_SIZE (FP_REGNUM), 0);
1769       supply_register (FP_REGNUM, buf);
1770
1771       if (nfields == 9)
1772         {
1773           int i;
1774
1775           for (i = 0; i <= 2; i++)
1776             if (flags[i] == 'r' || flags[i] == 'w')
1777               hit_watchpoint = 1;
1778             else if (flags[i] == '\000')
1779               break;
1780         }
1781     }
1782
1783   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
1784      and so on, because the constants we want here are determined by the
1785      MIPS protocol and have nothing to do with what host we are running on.  */
1786   if ((rstatus & 0377) == 0)
1787     {
1788       status->kind = TARGET_WAITKIND_EXITED;
1789       status->value.integer = (((rstatus) >> 8) & 0377);
1790     }
1791   else if ((rstatus & 0377) == 0177)
1792     {
1793       status->kind = TARGET_WAITKIND_STOPPED;
1794       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0377);
1795     }
1796   else
1797     {
1798       status->kind = TARGET_WAITKIND_SIGNALLED;
1799       status->value.sig = mips_signal_from_protocol (rstatus & 0177);
1800     }
1801
1802   return 0;
1803 }
1804
1805 static int
1806 pmon_wait (pid, status)
1807      int pid;
1808      struct target_waitstatus *status;
1809 {
1810   int rstatus;
1811   int err;
1812   char buff[DATA_MAXLEN];
1813
1814   interrupt_count = 0;
1815   hit_watchpoint = 0;
1816
1817   /* If we have not sent a single step or continue command, then the
1818      board is waiting for us to do something.  Return a status
1819      indicating that it is stopped.  */
1820   if (! mips_need_reply)
1821     {
1822       status->kind = TARGET_WAITKIND_STOPPED;
1823       status->value.sig = TARGET_SIGNAL_TRAP;
1824       return 0;
1825     }
1826
1827   /* Sit, polling the serial until the target decides to talk to
1828      us. NOTE: the timeout value we use is used not just for the
1829      first character, but for all the characters. */
1830   mips_wait_flag = 1;
1831   rstatus = mips_request ('\000', (unsigned int) 0, (unsigned int) 0, &err, -1,
1832                           buff);
1833   mips_wait_flag = 0;
1834   if (err)
1835     mips_error ("Remote failure: %s", safe_strerror (errno));
1836
1837   /* NOTE: The following (sig) numbers are defined by PMON:
1838         SPP_SIGTRAP     5       breakpoint
1839         SPP_SIGINT      2
1840         SPP_SIGSEGV     11
1841         SPP_SIGBUS      10
1842         SPP_SIGILL      4
1843         SPP_SIGFPE      8
1844         SPP_SIGTERM     15 */
1845
1846   /* On returning from a continue, the PMON monitor seems to start
1847      echoing back the messages we send prior to sending back the
1848      ACK. The code can cope with this, but to try and avoid the
1849      unnecessary serial traffic, and "spurious" characters displayed
1850      to the user, we cheat and reset the debug protocol. The problems
1851      seems to be caused by a check on the number of arguments, and the
1852      command length, within the monitor causing it to echo the command
1853      as a bad packet. */
1854   if (mips_monitor != MON_DDB && mips_monitor != MON_LSI)
1855     {
1856       mips_exit_debug ();
1857       mips_enter_debug ();
1858     }
1859
1860   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
1861      and so on, because the constants we want here are determined by the
1862      MIPS protocol and have nothing to do with what host we are running on.  */
1863   if ((rstatus & 0377) == 0)
1864     {
1865       status->kind = TARGET_WAITKIND_EXITED;
1866       status->value.integer = (((rstatus) >> 8) & 0377);
1867     }
1868   else if ((rstatus & 0377) == 0177)
1869     {
1870       status->kind = TARGET_WAITKIND_STOPPED;
1871       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0377);
1872     }
1873   else
1874     {
1875       status->kind = TARGET_WAITKIND_SIGNALLED;
1876       status->value.sig = mips_signal_from_protocol (rstatus & 0177);
1877     }
1878
1879   return 0;
1880 }
1881
1882 /* We have to map between the register numbers used by gdb and the
1883    register numbers used by the debugging protocol.  This function
1884    assumes that we are using tm-mips.h.  */
1885
1886 #define REGNO_OFFSET 96
1887
1888 static int
1889 mips_map_regno (regno)
1890      int regno;
1891 {
1892   if (regno < 32)
1893     return regno;
1894   if (regno >= FP0_REGNUM && regno < FP0_REGNUM + 32)
1895     return regno - FP0_REGNUM + 32;
1896   switch (regno)
1897     {
1898     case PC_REGNUM:
1899       return REGNO_OFFSET + 0;
1900     case CAUSE_REGNUM:
1901       return REGNO_OFFSET + 1;
1902     case HI_REGNUM:
1903       return REGNO_OFFSET + 2;
1904     case LO_REGNUM:
1905       return REGNO_OFFSET + 3;
1906     case FCRCS_REGNUM:
1907       return REGNO_OFFSET + 4;
1908     case FCRIR_REGNUM:
1909       return REGNO_OFFSET + 5;
1910     default:
1911       /* FIXME: Is there a way to get the status register?  */
1912       return 0;
1913     }
1914 }
1915
1916 /* Fetch the remote registers.  */
1917
1918 static void
1919 mips_fetch_registers (regno)
1920      int regno;
1921 {
1922   unsigned LONGEST val;
1923   int err;
1924
1925   if (regno == -1)
1926     {
1927       for (regno = 0; regno < NUM_REGS; regno++)
1928         mips_fetch_registers (regno);
1929       return;
1930     }
1931
1932   if (regno == FP_REGNUM || regno == ZERO_REGNUM)
1933     /* FP_REGNUM on the mips is a hack which is just supposed to read
1934        zero (see also mips-nat.c).  */
1935     val = 0;
1936   else
1937     {
1938       /* If PMON doesn't support this register, don't waste serial
1939          bandwidth trying to read it.  */
1940       int pmon_reg = mips_map_regno (regno);
1941       if (regno != 0 && pmon_reg == 0)
1942         val = 0;
1943       else
1944         {
1945           /* Unfortunately the PMON version in the Vr4300 board has been
1946              compiled without the 64bit register access commands. This
1947              means we cannot get hold of the full register width. */
1948           if (mips_monitor == MON_DDB)
1949             val = (unsigned)mips_request ('t', (unsigned int) pmon_reg,
1950                                 (unsigned int) 0, &err, mips_receive_wait, NULL);
1951           else
1952             val = mips_request ('r', (unsigned int) pmon_reg,
1953                                 (unsigned int) 0, &err, mips_receive_wait, NULL);
1954           if (err)
1955             mips_error ("Can't read register %d: %s", regno,
1956                         safe_strerror (errno));
1957         }
1958     }
1959
1960   {
1961     char buf[MAX_REGISTER_RAW_SIZE];
1962
1963     /* We got the number the register holds, but gdb expects to see a
1964        value in the target byte ordering.  */
1965     store_unsigned_integer (buf, REGISTER_RAW_SIZE (regno), val);
1966     supply_register (regno, buf);
1967   }
1968 }
1969
1970 /* Prepare to store registers.  The MIPS protocol can store individual
1971    registers, so this function doesn't have to do anything.  */
1972
1973 static void
1974 mips_prepare_to_store ()
1975 {
1976 }
1977
1978 /* Store remote register(s).  */
1979
1980 static void
1981 mips_store_registers (regno)
1982      int regno;
1983 {
1984   int err;
1985
1986   if (regno == -1)
1987     {
1988       for (regno = 0; regno < NUM_REGS; regno++)
1989         mips_store_registers (regno);
1990       return;
1991     }
1992
1993   mips_request ('R', (unsigned int) mips_map_regno (regno),
1994                 read_register (regno),
1995                 &err, mips_receive_wait, NULL);
1996   if (err)
1997     mips_error ("Can't write register %d: %s", regno, safe_strerror (errno));
1998 }
1999
2000 /* Fetch a word from the target board.  */
2001
2002 static unsigned int 
2003 mips_fetch_word (addr)
2004      CORE_ADDR addr;
2005 {
2006   unsigned int val;
2007   int err;
2008
2009   /* FIXME! addr was cast to uint! */
2010   val = mips_request ('d', addr, (unsigned int) 0, &err,
2011                       mips_receive_wait, NULL);
2012   if (err)
2013     {
2014       /* Data space failed; try instruction space.  */
2015       /* FIXME! addr was cast to uint! */
2016       val = mips_request ('i', addr, (unsigned int) 0, &err,
2017                           mips_receive_wait, NULL);
2018       if (err)
2019         mips_error ("Can't read address 0x%s: %s",
2020               paddr_nz (addr), safe_strerror (errno));
2021     }
2022   return val;
2023 }
2024
2025 /* Store a word to the target board.  Returns errno code or zero for
2026    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
2027    memory location there.  */
2028
2029 /* FIXME! make sure only 32-bit quantities get stored! */
2030 static int
2031 mips_store_word (addr, val, old_contents)
2032      CORE_ADDR addr;
2033      unsigned int val;
2034      char *old_contents;
2035 {
2036   int err;
2037   unsigned int oldcontents;
2038
2039   oldcontents = mips_request ('D', addr, (unsigned int) val,
2040                               &err,
2041                               mips_receive_wait, NULL);
2042   if (err)
2043     {
2044       /* Data space failed; try instruction space.  */
2045       oldcontents = mips_request ('I', addr,
2046                                   (unsigned int) val, &err,
2047                                   mips_receive_wait, NULL);
2048       if (err)
2049         return errno;
2050     }
2051   if (old_contents != NULL)
2052     store_unsigned_integer (old_contents, 4, oldcontents);
2053   return 0;
2054 }
2055
2056 /* Read or write LEN bytes from inferior memory at MEMADDR,
2057    transferring to or from debugger address MYADDR.  Write to inferior
2058    if SHOULD_WRITE is nonzero.  Returns length of data written or
2059    read; 0 for error.  Note that protocol gives us the correct value
2060    for a longword, since it transfers values in ASCII.  We want the
2061    byte values, so we have to swap the longword values.  */
2062
2063 static int
2064 mips_xfer_memory (memaddr, myaddr, len, write, ignore)
2065      CORE_ADDR memaddr;
2066      char *myaddr;
2067      int len;
2068      int write;
2069      struct target_ops *ignore;
2070 {
2071   register int i;
2072   /* Round starting address down to longword boundary.  */
2073   register CORE_ADDR addr = memaddr &~ 3;
2074   /* Round ending address up; get number of longwords that makes.  */
2075   register int count = (((memaddr + len) - addr) + 3) / 4;
2076   /* Allocate buffer of that many longwords.  */
2077   register char *buffer = alloca (count * 4);
2078
2079   int status;
2080
2081   if (write)
2082     {
2083       /* Fill start and end extra bytes of buffer with existing data.  */
2084       if (addr != memaddr || len < 4)
2085         {
2086           /* Need part of initial word -- fetch it.  */
2087           store_unsigned_integer (&buffer[0], 4, mips_fetch_word (addr));
2088         }
2089
2090       if (count > 1)
2091         {
2092           /* Need part of last word -- fetch it.  FIXME: we do this even
2093              if we don't need it.  */
2094           store_unsigned_integer (&buffer[(count - 1) * 4], 4,
2095                                   mips_fetch_word (addr + (count - 1) * 4));
2096         }
2097
2098       /* Copy data to be written over corresponding part of buffer */
2099
2100       memcpy ((char *) buffer + (memaddr & 3), myaddr, len);
2101
2102       /* Write the entire buffer.  */
2103
2104       for (i = 0; i < count; i++, addr += 4)
2105         {
2106           status = mips_store_word (addr,
2107                                     extract_unsigned_integer (&buffer[i*4], 4),
2108                                     NULL);
2109           /* Report each kilobyte (we download 32-bit words at a time) */
2110           if (i % 256 == 255) 
2111             {
2112               printf_unfiltered ("*");
2113               fflush (stdout);
2114             }
2115           if (status)
2116             {
2117               errno = status;
2118               return 0;
2119             }
2120           /* FIXME: Do we want a QUIT here?  */
2121         }
2122       if (count >= 256)
2123         printf_unfiltered ("\n");
2124     }
2125   else
2126     {
2127       /* Read all the longwords */
2128       for (i = 0; i < count; i++, addr += 4)
2129         {
2130           store_unsigned_integer (&buffer[i*4], 4, mips_fetch_word (addr));
2131           QUIT;
2132         }
2133
2134       /* Copy appropriate bytes out of the buffer.  */
2135       memcpy (myaddr, buffer + (memaddr & 3), len);
2136     }
2137   return len;
2138 }
2139
2140 /* Print info on this target.  */
2141
2142 static void
2143 mips_files_info (ignore)
2144      struct target_ops *ignore;
2145 {
2146   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
2147 }
2148
2149 /* Kill the process running on the board.  This will actually only
2150    work if we are doing remote debugging over the console input.  I
2151    think that if IDT/sim had the remote debug interrupt enabled on the
2152    right port, we could interrupt the process with a break signal.  */
2153
2154 static void
2155 mips_kill ()
2156 {
2157   if (!mips_wait_flag)
2158     return;
2159
2160   interrupt_count++;
2161
2162   if (interrupt_count >= 2)
2163     {
2164       interrupt_count = 0;
2165
2166       target_terminal_ours ();
2167
2168       if (query ("Interrupted while waiting for the program.\n\
2169 Give up (and stop debugging it)? "))
2170         {
2171           /* Clean up in such a way that mips_close won't try to talk to the
2172              board (it almost surely won't work since we weren't able to talk to
2173              it).  */
2174           mips_wait_flag = 0;
2175           close_ports();
2176
2177           printf_unfiltered ("Ending remote MIPS debugging.\n");
2178           target_mourn_inferior ();
2179
2180           return_to_top_level (RETURN_QUIT);
2181         }
2182
2183       target_terminal_inferior ();
2184     }
2185
2186   if (remote_debug > 0)
2187     printf_unfiltered ("Sending break\n");
2188
2189   SERIAL_SEND_BREAK (mips_desc);
2190
2191 #if 0
2192   if (mips_is_open)
2193     {
2194       char cc;
2195
2196       /* Send a ^C.  */
2197       cc = '\003';
2198       SERIAL_WRITE (mips_desc, &cc, 1);
2199       sleep (1);
2200       target_mourn_inferior ();
2201     }
2202 #endif
2203 }
2204
2205 /* Start running on the target board.  */
2206
2207 static void
2208 mips_create_inferior (execfile, args, env)
2209      char *execfile;
2210      char *args;
2211      char **env;
2212 {
2213   CORE_ADDR entry_pt;
2214
2215   if (args && *args)
2216     {
2217       warning ("\
2218 Can't pass arguments to remote MIPS board; arguments ignored.");
2219       /* And don't try to use them on the next "run" command.  */
2220       execute_command ("set args", 0);
2221     }
2222
2223   if (execfile == 0 || exec_bfd == 0)
2224     error ("No executable file specified");
2225
2226   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
2227
2228   init_wait_for_inferior ();
2229
2230   /* FIXME: Should we set inferior_pid here?  */
2231
2232 /* start-sanitize-gm */
2233 #ifdef GENERAL_MAGIC
2234   magic_create_inferior_hook ();
2235   proceed (entry_pt, TARGET_SIGNAL_PWR, 0);
2236 #else
2237 /* end-sanitize-gm */
2238   proceed (entry_pt, TARGET_SIGNAL_DEFAULT, 0);
2239 /* start-sanitize-gm */
2240 #endif /* GENERAL_MAGIC */
2241 /* end-sanitize-gm */
2242 }
2243
2244 /* Clean up after a process.  Actually nothing to do.  */
2245
2246 static void
2247 mips_mourn_inferior ()
2248 {
2249   if (current_ops != NULL)
2250     unpush_target (current_ops);
2251   generic_mourn_inferior ();
2252 }
2253
2254
2255 /* We can write a breakpoint and read the shadow contents in one
2256    operation.  */
2257
2258 /* The IDT board uses an unusual breakpoint value, and sometimes gets
2259    confused when it sees the usual MIPS breakpoint instruction.  */
2260
2261 #define BREAK_INSN (0x00000a0d)
2262 #define BREAK_INSN_SIZE (4)
2263
2264 /* Insert a breakpoint on targets that don't have any better breakpoint
2265    support.  We read the contents of the target location and stash it,
2266    then overwrite it with a breakpoint instruction.  ADDR is the target
2267    location in the target machine.  CONTENTS_CACHE is a pointer to 
2268    memory allocated for saving the target contents.  It is guaranteed
2269    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
2270    is accomplished via BREAKPOINT_MAX).  */
2271
2272 static int
2273 mips_insert_breakpoint (addr, contents_cache)
2274      CORE_ADDR addr;
2275      char *contents_cache;
2276 {
2277   if (monitor_supports_breakpoints)
2278     return common_breakpoint ('B', addr, 0x3, "f");
2279
2280   return mips_store_word (addr, BREAK_INSN, contents_cache);
2281 }
2282
2283 static int
2284 mips_remove_breakpoint (addr, contents_cache)
2285      CORE_ADDR addr;
2286      char *contents_cache;
2287 {
2288   if (monitor_supports_breakpoints)
2289     return common_breakpoint ('b', addr, 0, NULL);
2290
2291   return target_write_memory (addr, contents_cache, BREAK_INSN_SIZE);
2292 }
2293
2294 #if 0 /* currently not used */
2295 /* PMON does not currently provide support for the debug mode 'b'
2296    commands to manipulate breakpoints. However, if we wanted to use
2297    the monitor breakpoints (rather than the GDB BREAK_INSN version)
2298    then this code performs the work needed to leave debug mode,
2299    set/clear the breakpoint, and then return to debug mode. */
2300
2301 #define PMON_MAX_BP (33) /* 32 SW, 1 HW */
2302 static CORE_ADDR mips_pmon_bp_info[PMON_MAX_BP];
2303 /* NOTE: The code relies on this vector being zero-initialised by the system */
2304
2305 static int
2306 pmon_insert_breakpoint (addr, contents_cache)
2307      CORE_ADDR addr;
2308      char *contents_cache;
2309 {
2310   int status;
2311
2312   if (monitor_supports_breakpoints)
2313     {
2314       char tbuff[12]; /* space for breakpoint command */
2315       int bpnum;
2316       CORE_ADDR bpaddr;
2317
2318       /* PMON does not support debug level breakpoint set/remove: */
2319       if (mips_exit_debug ())
2320         mips_error ("Failed to exit debug mode");
2321
2322       sprintf (tbuff, "b %08x\r", addr);
2323       mips_send_command (tbuff, 0);
2324
2325       mips_expect ("Bpt ");
2326
2327       if (!mips_getstring (tbuff, 2))
2328         return 1;
2329       tbuff[2] = '\0'; /* terminate the string */
2330       if (sscanf (tbuff, "%d", &bpnum) != 1)
2331         {
2332           fprintf_unfiltered (stderr, "Invalid decimal breakpoint number from target: %s\n", tbuff);
2333           return 1;
2334         }
2335
2336       mips_expect (" = ");
2337
2338       /* Lead in the hex number we are expecting: */
2339       tbuff[0] = '0';
2340       tbuff[1] = 'x';
2341
2342       /* FIXME!! only 8 bytes!  need to expand for Bfd64; 
2343          which targets return 64-bit addresses?  PMON returns only 32! */
2344       if (!mips_getstring (&tbuff[2], 8))
2345         return 1;
2346       tbuff[10] = '\0'; /* terminate the string */
2347
2348       if (sscanf (tbuff, "0x%08x", &bpaddr) != 1)
2349         {
2350           fprintf_unfiltered (stderr, "Invalid hex address from target: %s\n", tbuff);
2351           return 1;
2352         }
2353
2354       if (bpnum >= PMON_MAX_BP)
2355         {
2356           fprintf_unfiltered (stderr, "Error: Returned breakpoint number %d outside acceptable range (0..%d)\n",
2357                               bpnum, PMON_MAX_BP - 1);
2358           return 1;
2359         }
2360
2361       if (bpaddr != addr)
2362         fprintf_unfiltered (stderr, "Warning: Breakpoint addresses do not match: 0x%x != 0x%x\n", addr, bpaddr);
2363
2364       mips_pmon_bp_info[bpnum] = bpaddr;
2365
2366       mips_expect ("\r\n");
2367       mips_expect (mips_monitor_prompt);
2368
2369       mips_enter_debug ();
2370
2371       return 0;
2372     }
2373
2374   return mips_store_word (addr, BREAK_INSN, contents_cache);
2375 }
2376
2377 static int
2378 pmon_remove_breakpoint (addr, contents_cache)
2379      CORE_ADDR addr;
2380      char *contents_cache;
2381 {
2382   if (monitor_supports_breakpoints)
2383     {
2384       int bpnum;
2385       char tbuff[7]; /* enough for delete breakpoint command */
2386
2387       for (bpnum = 0; bpnum < PMON_MAX_BP; bpnum++)
2388         if (mips_pmon_bp_info[bpnum] == addr)
2389           break;
2390
2391       if (bpnum >= PMON_MAX_BP)
2392         {
2393           fprintf_unfiltered (stderr,
2394             "pmon_remove_breakpoint: Failed to find breakpoint at address 0x%s\n",
2395             paddr_nz (addr));
2396           return 1;
2397         }
2398
2399       if (mips_exit_debug ())
2400         mips_error ("Failed to exit debug mode");
2401
2402       sprintf (tbuff, "db %02d\r", bpnum);
2403
2404       mips_send_command (tbuff, -1);
2405       /* NOTE: If the breakpoint does not exist then a "Bpt <dd> not
2406          set" message will be returned. */
2407
2408       mips_enter_debug ();
2409
2410       return 0;
2411     }
2412
2413   return target_write_memory (addr, contents_cache, BREAK_INSN_SIZE);
2414 }
2415 #endif
2416
2417 /* Compute a don't care mask for the region bounding ADDR and ADDR + LEN - 1.
2418    This is used for memory ref breakpoints.  */
2419
2420 static unsigned long
2421 calculate_mask (addr, len)
2422      CORE_ADDR addr;
2423      int len;
2424 {
2425   unsigned long mask;
2426   int i;
2427
2428   mask = addr ^ (addr + len - 1);
2429
2430   for (i = 32; i >= 0; i--)
2431     if (mask == 0)
2432       break;
2433     else
2434       mask >>= 1;
2435
2436   mask = (unsigned long) 0xffffffff >> i;
2437
2438   return mask;
2439 }
2440
2441 /* Set a data watchpoint.  ADDR and LEN should be obvious.  TYPE is either 1
2442    for a read watchpoint, or 2 for a read/write watchpoint. */
2443
2444 int
2445 remote_mips_set_watchpoint (addr, len, type)
2446      CORE_ADDR addr;
2447      int len;
2448      int type;
2449 {
2450   CORE_ADDR first_addr;
2451   unsigned long mask;
2452   char *flags;
2453
2454   mask = calculate_mask (addr, len);
2455
2456   first_addr = addr & ~mask;
2457
2458   switch (type)
2459     {
2460     case 0:                     /* write */
2461       flags = "w";
2462       break;
2463     case 1:                     /* read */
2464       flags = "r";
2465       break;
2466     case 2:                     /* read/write */
2467       flags = "rw";
2468       break;
2469     default:
2470       abort ();
2471     }
2472
2473   if (common_breakpoint ('B', first_addr, mask, flags))
2474     return -1;
2475
2476   return 0;
2477 }
2478
2479 int
2480 remote_mips_remove_watchpoint (addr, len, type)
2481      CORE_ADDR addr;
2482      int len;
2483      int type;
2484 {
2485   CORE_ADDR first_addr;
2486   unsigned long mask;
2487
2488   mask = calculate_mask (addr, len);
2489
2490   first_addr = addr & ~mask;
2491
2492   if (common_breakpoint ('b', first_addr, 0, NULL))
2493     return -1;
2494
2495   return 0;
2496 }
2497
2498 int
2499 remote_mips_stopped_by_watchpoint ()
2500 {
2501   return hit_watchpoint;
2502 }
2503
2504 /* This routine generates the a breakpoint command of the form:
2505
2506    0x0 <CMD> <ADDR> <MASK> <FLAGS>
2507
2508    Where <CMD> is one of: `B' to set, or `b' to clear a breakpoint.  <ADDR> is
2509    the address of the breakpoint.  <MASK> is a don't care mask for addresses.
2510    <FLAGS> is any combination of `r', `w', or `f' for read/write/or fetch.
2511
2512    Return 0 if successful; otherwise 1.  */
2513
2514 static int
2515 common_breakpoint (cmd, addr, mask, flags)
2516      int cmd;
2517      CORE_ADDR addr;
2518      CORE_ADDR mask;
2519      char *flags;
2520 {
2521   int len;
2522   char buf[DATA_MAXLEN + 1];
2523   char rcmd;
2524   int rpid, rerrflg, rresponse;
2525   int nfields;
2526
2527   addr = ADDR_BITS_REMOVE (addr);
2528   if (flags)
2529     sprintf (buf, "0x0 %c 0x%s 0x%s %s", cmd, paddr_nz (addr), paddr_nz (mask),
2530              flags);
2531   else
2532     sprintf (buf, "0x0 %c 0x%s", cmd, paddr_nz (addr));
2533
2534   mips_send_packet (buf, 1);
2535
2536   len = mips_receive_packet (buf, 1, mips_receive_wait);
2537   buf[len] = '\0';
2538
2539   nfields = sscanf (buf, "0x%x %c 0x%x 0x%x", &rpid, &rcmd, &rerrflg, &rresponse);
2540
2541   if (nfields != 4
2542       || rcmd != cmd)
2543     mips_error ("common_breakpoint: Bad response from remote board: %s", buf);
2544
2545   if (rerrflg != 0)
2546     {
2547       /* Ddb returns "0x0 b 0x16 0x0\000", whereas
2548          Cogent returns "0x0 b 0xffffffff 0x16\000": */
2549       if (mips_monitor == MON_DDB)
2550         rresponse = rerrflg;
2551       if (rresponse != 22) /* invalid argument */
2552         fprintf_unfiltered (stderr, "common_breakpoint (0x%s):  Got error: 0x%x\n",
2553                             paddr_nz (addr), rresponse);
2554       return 1;
2555     }
2556
2557   return 0;
2558 }
2559
2560
2561 static void
2562 send_srec (srec, len, addr)
2563      char *srec;
2564      int len;
2565      CORE_ADDR addr;
2566 {
2567   while (1)
2568     {
2569       int ch;
2570
2571       SERIAL_WRITE (mips_desc, srec, len);
2572
2573       ch = mips_readchar (2);
2574
2575       switch (ch)
2576         {
2577         case SERIAL_TIMEOUT:
2578           error ("Timeout during download.");
2579           break;
2580         case 0x6:               /* ACK */
2581           return;
2582         case 0x15:              /* NACK */
2583           fprintf_unfiltered (gdb_stderr, "Download got a NACK at byte %d!  Retrying.\n", addr);
2584           continue;
2585         default:
2586           error ("Download got unexpected ack char: 0x%x, retrying.\n", ch);
2587         }
2588     }
2589 }
2590
2591 /*  Download a binary file by converting it to S records. */
2592
2593 static void
2594 mips_load_srec (args)
2595      char *args;
2596 {
2597   bfd *abfd;
2598   asection *s;
2599   char *buffer, srec[1024];
2600   unsigned int i;
2601   unsigned int srec_frame = 200;
2602   int reclen;
2603   static int hashmark = 1;
2604
2605   buffer = alloca (srec_frame * 2 + 256);
2606
2607   abfd = bfd_openr (args, 0);
2608   if (!abfd)
2609     {
2610       printf_filtered ("Unable to open file %s\n", args);
2611       return;
2612     }
2613
2614   if (bfd_check_format (abfd, bfd_object) == 0)
2615     {
2616       printf_filtered ("File is not an object file\n");
2617       return;
2618     }
2619
2620 /* This actually causes a download in the IDT binary format: */
2621   mips_send_command (LOAD_CMD, 0);
2622
2623   for (s = abfd->sections; s; s = s->next)
2624     {
2625       if (s->flags & SEC_LOAD)
2626         {
2627           unsigned int numbytes;
2628
2629           /* FIXME!  vma too small?? */
2630           printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, s->vma,
2631                            s->vma + s->_raw_size);
2632           gdb_flush (gdb_stdout);
2633
2634           for (i = 0; i < s->_raw_size; i += numbytes)
2635             {
2636               numbytes = min (srec_frame, s->_raw_size - i);
2637
2638               bfd_get_section_contents (abfd, s, buffer, i, numbytes);
2639
2640               reclen = mips_make_srec (srec, '3', s->vma + i, buffer, numbytes);
2641               send_srec (srec, reclen, s->vma + i);
2642
2643               if (hashmark)
2644                 {
2645                   putchar_unfiltered ('#');
2646                   gdb_flush (gdb_stdout);
2647                 }
2648
2649             } /* Per-packet (or S-record) loop */
2650           
2651           putchar_unfiltered ('\n');
2652         } /* Loadable sections */
2653     }
2654   if (hashmark) 
2655     putchar_unfiltered ('\n');
2656   
2657   /* Write a type 7 terminator record. no data for a type 7, and there
2658      is no data, so len is 0.  */
2659
2660   reclen = mips_make_srec (srec, '7', abfd->start_address, NULL, 0);
2661
2662   send_srec (srec, reclen, abfd->start_address);
2663
2664   SERIAL_FLUSH_INPUT (mips_desc);
2665 }
2666
2667 /*
2668  * mips_make_srec -- make an srecord. This writes each line, one at a
2669  *      time, each with it's own header and trailer line.
2670  *      An srecord looks like this:
2671  *
2672  * byte count-+     address
2673  * start ---+ |        |       data        +- checksum
2674  *          | |        |                   |
2675  *        S01000006F6B692D746573742E73726563E4
2676  *        S315000448600000000000000000FC00005900000000E9
2677  *        S31A0004000023C1400037DE00F023604000377B009020825000348D
2678  *        S30B0004485A0000000000004E
2679  *        S70500040000F6
2680  *
2681  *      S<type><length><address><data><checksum>
2682  *
2683  *      Where
2684  *      - length
2685  *        is the number of bytes following upto the checksum. Note that
2686  *        this is not the number of chars following, since it takes two
2687  *        chars to represent a byte.
2688  *      - type
2689  *        is one of:
2690  *        0) header record
2691  *        1) two byte address data record
2692  *        2) three byte address data record
2693  *        3) four byte address data record
2694  *        7) four byte address termination record
2695  *        8) three byte address termination record
2696  *        9) two byte address termination record
2697  *       
2698  *      - address
2699  *        is the start address of the data following, or in the case of
2700  *        a termination record, the start address of the image
2701  *      - data
2702  *        is the data.
2703  *      - checksum
2704  *        is the sum of all the raw byte data in the record, from the length
2705  *        upwards, modulo 256 and subtracted from 255.
2706  *
2707  * This routine returns the length of the S-record.
2708  *
2709  */
2710
2711 static int
2712 mips_make_srec (buf, type, memaddr, myaddr, len)
2713      char *buf;
2714      int type;
2715      CORE_ADDR memaddr;
2716      unsigned char *myaddr;
2717      int len;
2718 {
2719   unsigned char checksum;
2720   int i;
2721
2722   /* Create the header for the srec. addr_size is the number of bytes in the address,
2723      and 1 is the number of bytes in the count.  */
2724
2725   /* FIXME!! bigger buf required for 64-bit! */
2726   buf[0] = 'S';
2727   buf[1] = type;
2728   buf[2] = len + 4 + 1;         /* len + 4 byte address + 1 byte checksum */
2729   /* This assumes S3 style downloads (4byte addresses). There should
2730      probably be a check, or the code changed to make it more
2731      explicit. */
2732   buf[3] = memaddr >> 24;
2733   buf[4] = memaddr >> 16;
2734   buf[5] = memaddr >> 8;
2735   buf[6] = memaddr;
2736   memcpy (&buf[7], myaddr, len);
2737
2738   /* Note that the checksum is calculated on the raw data, not the
2739      hexified data.  It includes the length, address and the data
2740      portions of the packet.  */
2741   checksum = 0;
2742   buf += 2;                     /* Point at length byte */
2743   for (i = 0; i < len + 4 + 1; i++)
2744     checksum += *buf++;
2745
2746   *buf = ~checksum;
2747
2748   return len + 8;
2749 }
2750
2751 /* The following manifest controls whether we enable the simple flow
2752    control support provided by the monitor. If enabled the code will
2753    wait for an affirmative ACK between transmitting packets. */
2754 #define DOETXACK (1)
2755
2756 /* The PMON fast-download uses an encoded packet format constructed of
2757    3byte data packets (encoded as 4 printable ASCII characters), and
2758    escape sequences (preceded by a '/'):
2759
2760         'K'     clear checksum
2761         'C'     compare checksum (12bit value, not included in checksum calculation)
2762         'S'     define symbol name (for addr) terminated with "," and padded to 4char boundary
2763         'Z'     zero fill multiple of 3bytes
2764         'B'     byte (12bit encoded value, of 8bit data)
2765         'A'     address (36bit encoded value)
2766         'E'     define entry as original address, and exit load
2767
2768    The packets are processed in 4 character chunks, so the escape
2769    sequences that do not have any data (or variable length data)
2770    should be padded to a 4 character boundary.  The decoder will give
2771    an error if the complete message block size is not a multiple of
2772    4bytes (size of record).
2773
2774    The encoding of numbers is done in 6bit fields.  The 6bit value is
2775    used to index into this string to get the specific character
2776    encoding for the value: */
2777 static char encoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.";
2778
2779 /* Convert the number of bits required into an encoded number, 6bits
2780    at a time (range 0..63).  Keep a checksum if required (passed
2781    pointer non-NULL). The function returns the number of encoded
2782    characters written into the buffer. */
2783 static int
2784 pmon_makeb64 (v, p, n, chksum)
2785      unsigned long v;
2786      char *p;
2787      int n;
2788      int *chksum;
2789 {
2790   int count = (n / 6);
2791
2792   if ((n % 12) != 0) {
2793     fprintf_unfiltered(stderr,"Fast encoding bitcount must be a multiple of 12bits: %dbit%s\n",n,(n == 1)?"":"s");
2794     return(0);
2795   }
2796   if (n > 36) {
2797     fprintf_unfiltered(stderr,"Fast encoding cannot process more than 36bits at the moment: %dbits\n",n);
2798     return(0);
2799   }
2800
2801   /* Deal with the checksum: */
2802   if (chksum != NULL) {
2803     switch (n) {
2804      case 36: *chksum += ((v >> 24) & 0xFFF);
2805      case 24: *chksum += ((v >> 12) & 0xFFF);
2806      case 12: *chksum += ((v >>  0) & 0xFFF);
2807     }
2808   }
2809
2810   do {
2811     n -= 6;
2812     *p++ = encoding[(v >> n) & 0x3F];
2813   } while (n > 0);
2814
2815   return(count);
2816 }
2817
2818 /* Shorthand function (that could be in-lined) to output the zero-fill
2819    escape sequence into the data stream. */
2820 static int
2821 pmon_zeroset (recsize, buff, amount, chksum)
2822      int recsize;
2823      char **buff;
2824      int *amount;
2825      unsigned int *chksum;
2826 {
2827   int count;
2828
2829   sprintf(*buff,"/Z");
2830   count = pmon_makeb64 (*amount, (*buff + 2), 12, chksum);
2831   *buff += (count + 2);
2832   *amount = 0;
2833   return(recsize + count + 2);
2834 }
2835
2836 static int
2837 pmon_checkset (recsize, buff, value)
2838      int recsize;
2839      char **buff;
2840      int *value;
2841 {
2842   int count;
2843
2844   /* Add the checksum (without updating the value): */
2845   sprintf (*buff, "/C");
2846   count = pmon_makeb64 (*value, (*buff + 2), 12, NULL);
2847   *buff += (count + 2);
2848   sprintf (*buff, "\n");
2849   *buff += 2; /* include zero terminator */
2850   /* Forcing a checksum validation clears the sum: */
2851   *value = 0;
2852   return(recsize + count + 3);
2853 }
2854
2855 /* Amount of padding we leave after at the end of the output buffer,
2856    for the checksum and line termination characters: */
2857 #define CHECKSIZE (4 + 4 + 4 + 2)
2858 /* zero-fill, checksum, transfer end and line termination space. */
2859
2860 /* The amount of binary data loaded from the object file in a single
2861    operation: */
2862 #define BINCHUNK (1024)
2863
2864 /* Maximum line of data accepted by the monitor: */
2865 #define MAXRECSIZE (550)
2866 /* NOTE: This constant depends on the monitor being used. This value
2867    is for PMON 5.x on the Cogent Vr4300 board. */
2868
2869 static void
2870 pmon_make_fastrec (outbuf, inbuf, inptr, inamount, recsize, csum, zerofill)
2871      char **outbuf;
2872      unsigned char *inbuf;
2873      int *inptr;
2874      int inamount;
2875      int *recsize;
2876      unsigned int *csum;
2877      unsigned int *zerofill;
2878 {
2879   int count = 0;
2880   char *p = *outbuf;
2881
2882   /* This is a simple check to ensure that our data will fit within
2883      the maximum allowable record size. Each record output is 4bytes
2884      in length. We must allow space for a pending zero fill command,
2885      the record, and a checksum record. */
2886   while ((*recsize < (MAXRECSIZE - CHECKSIZE)) && ((inamount - *inptr) > 0)) {
2887     /* Process the binary data: */
2888     if ((inamount - *inptr) < 3) {
2889       if (*zerofill != 0)
2890        *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2891       sprintf (p, "/B");
2892       count = pmon_makeb64 (inbuf[*inptr], &p[2], 12, csum);
2893       p += (2 + count);
2894       *recsize += (2 + count);
2895       (*inptr)++;
2896     } else {
2897       unsigned int value = ((inbuf[*inptr + 0] << 16) | (inbuf[*inptr + 1] << 8) | inbuf[*inptr + 2]);
2898       /* Simple check for zero data. TODO: A better check would be
2899          to check the last, and then the middle byte for being zero
2900          (if the first byte is not). We could then check for
2901          following runs of zeros, and if above a certain size it is
2902          worth the 4 or 8 character hit of the byte insertions used
2903          to pad to the start of the zeroes. NOTE: This also depends
2904          on the alignment at the end of the zero run. */
2905       if (value == 0x00000000) {
2906         (*zerofill)++;
2907         if (*zerofill == 0xFFF) /* 12bit counter */
2908          *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2909       }else {
2910         if (*zerofill != 0)
2911          *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2912         count = pmon_makeb64 (value, p, 24, csum);
2913         p += count;
2914         *recsize += count;
2915       }
2916       *inptr += 3;
2917     }
2918   }
2919
2920   *outbuf = p;
2921   return;
2922 }
2923
2924 static int
2925 pmon_check_ack(mesg)
2926      char *mesg;
2927 {
2928 #if defined(DOETXACK)
2929   int c;
2930
2931   if (!tftp_in_use)
2932     {
2933       c = SERIAL_READCHAR (udp_in_use ? udp_desc : mips_desc, 2);
2934       if ((c == SERIAL_TIMEOUT) || (c != 0x06))
2935         {
2936           fprintf_unfiltered (gdb_stderr,
2937                               "Failed to receive valid ACK for %s\n", mesg);
2938           return(-1); /* terminate the download */
2939         }
2940     }
2941 #endif /* DOETXACK */
2942   return(0);
2943 }
2944
2945 /* pmon_download - Send a sequence of characters to the PMON download port,
2946    which is either a serial port or a UDP socket.  */
2947
2948 static void
2949 pmon_start_download ()
2950 {
2951   if (tftp_in_use)
2952     {
2953       /* Create the temporary download file.  */
2954       if ((tftp_file = fopen (tftp_localname, "w")) == NULL)
2955         perror_with_name (tftp_localname);
2956     }
2957   else
2958     {
2959       mips_send_command (udp_in_use ? LOAD_CMD_UDP : LOAD_CMD, 0);
2960       mips_expect ("Downloading from ");
2961       mips_expect (udp_in_use ? "udp" : "tty0");
2962       mips_expect (", ^C to abort\r\n");
2963     }
2964 }
2965
2966 static int
2967 mips_expect_download (char *string)
2968 {
2969   if (!mips_expect (string))
2970     {
2971       fprintf_unfiltered (gdb_stderr, "Load did not complete successfully.\n");
2972       if (tftp_in_use)
2973         remove (tftp_localname);        /* Remove temporary file */
2974       return 0;
2975     }
2976   else
2977     return 1;
2978 }
2979
2980 static void
2981 pmon_end_download (final, bintotal)
2982      int final;
2983      int bintotal;
2984 {
2985   char hexnumber[9]; /* includes '\0' space */
2986
2987   if (tftp_in_use)
2988     {
2989       static char *load_cmd_prefix = "load -b -s ";
2990       char *cmd;
2991       struct stat stbuf;
2992
2993       /* Close off the temporary file containing the load data.  */
2994       fclose (tftp_file);
2995       tftp_file = NULL;
2996
2997       /* Make the temporary file readable by the world.  */
2998       if (stat (tftp_localname, &stbuf) == 0)
2999         chmod (tftp_localname, stbuf.st_mode | S_IROTH);
3000
3001       /* Must reinitialize the board to prevent PMON from crashing.  */
3002       mips_send_command ("initEther\r", -1);
3003
3004       /* Send the load command.  */
3005       cmd = xmalloc (strlen (load_cmd_prefix) + strlen (tftp_name) + 2);
3006       strcpy (cmd, load_cmd_prefix);
3007       strcat (cmd, tftp_name);
3008       strcat (cmd, "\r");
3009       mips_send_command (cmd, 0);
3010       free (cmd);
3011       if (!mips_expect_download ("Downloading from "))
3012         return;
3013       if (!mips_expect_download (tftp_name))
3014         return;
3015       if (!mips_expect_download (", ^C to abort\r\n"))
3016         return;
3017     }
3018
3019   /* Wait for the stuff that PMON prints after the load has completed.
3020      The timeout value for use in the tftp case (15 seconds) was picked
3021      arbitrarily but might be too small for really large downloads. FIXME. */
3022   if (mips_monitor == MON_LSI)
3023     {
3024       pmon_check_ack ("termination");
3025       mips_expect_timeout ("Entry address is ", tftp_in_use ? 15 : 2);
3026     }
3027   else
3028     mips_expect_timeout ("Entry Address  = ", tftp_in_use ? 15 : 2);
3029
3030   sprintf (hexnumber,"%x",final);
3031   mips_expect (hexnumber);
3032   mips_expect ("\r\n");
3033   if (mips_monitor != MON_LSI)
3034     pmon_check_ack ("termination");
3035   mips_expect ("\r\ntotal = 0x");
3036   sprintf (hexnumber,"%x",bintotal);
3037   mips_expect (hexnumber);
3038   if (!mips_expect_download (" bytes\r\n"))
3039     return;
3040
3041   if (tftp_in_use)
3042     remove (tftp_localname);    /* Remove temporary file */
3043 }
3044
3045 static void
3046 pmon_download (buffer, length)
3047      char *buffer;
3048      int length;
3049 {
3050   if (tftp_in_use)
3051     fwrite (buffer, 1, length, tftp_file);
3052   else
3053     SERIAL_WRITE (udp_in_use ? udp_desc : mips_desc, buffer, length);
3054 }
3055
3056 static void
3057 pmon_load_fast (file)
3058      char *file;
3059 {
3060   bfd *abfd;
3061   asection *s;
3062   unsigned char *binbuf;
3063   char *buffer;
3064   int reclen;
3065   unsigned int csum = 0;
3066   int hashmark = !tftp_in_use;
3067   int bintotal = 0;
3068   int final = 0;
3069   int finished = 0;
3070
3071   buffer = (char *)xmalloc(MAXRECSIZE + 1);
3072   binbuf = (unsigned char *)xmalloc(BINCHUNK);
3073
3074   abfd = bfd_openr(file,0);
3075   if (!abfd)
3076    {
3077      printf_filtered ("Unable to open file %s\n",file);
3078      return;
3079    }
3080
3081   if (bfd_check_format(abfd,bfd_object) == 0)
3082    {
3083      printf_filtered("File is not an object file\n");
3084      return;
3085    }
3086
3087   /* Setup the required download state: */
3088   mips_send_command ("set dlproto etxack\r", -1);
3089   mips_send_command ("set dlecho off\r", -1);
3090   /* NOTE: We get a "cannot set variable" message if the variable is
3091      already defined to have the argument we give. The code doesn't
3092      care, since it just scans to the next prompt anyway. */
3093   /* Start the download: */
3094   pmon_start_download();
3095   
3096   /* Zero the checksum */
3097   sprintf(buffer,"/Kxx\n");
3098   reclen = strlen(buffer);
3099   pmon_download (buffer, reclen);
3100   finished = pmon_check_ack("/Kxx");
3101
3102   for (s = abfd->sections; s && !finished; s = s->next)
3103    if (s->flags & SEC_LOAD) /* only deal with loadable sections */
3104     {
3105       bintotal += s->_raw_size;
3106       final = (s->vma + s->_raw_size);
3107
3108       printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, (unsigned int)s->vma,
3109                        (unsigned int)(s->vma + s->_raw_size));
3110       gdb_flush (gdb_stdout);
3111
3112       /* Output the starting address */
3113       sprintf(buffer,"/A");
3114       reclen = pmon_makeb64(s->vma,&buffer[2],36,&csum);
3115       buffer[2 + reclen] = '\n';
3116       buffer[3 + reclen] = '\0';
3117       reclen += 3; /* for the initial escape code and carriage return */
3118       pmon_download (buffer, reclen);
3119       finished = pmon_check_ack("/A");
3120
3121       if (!finished)
3122        {
3123          unsigned int binamount;
3124          unsigned int zerofill = 0;
3125          char *bp = buffer;
3126          unsigned int i;
3127
3128          reclen = 0;
3129
3130          for (i = 0; ((i < s->_raw_size) && !finished); i += binamount) {
3131            int binptr = 0;
3132
3133            binamount = min (BINCHUNK, s->_raw_size - i);
3134
3135            bfd_get_section_contents (abfd, s, binbuf, i, binamount);
3136
3137            /* This keeps a rolling checksum, until we decide to output
3138               the line: */
3139            for (; ((binamount - binptr) > 0);) {
3140              pmon_make_fastrec (&bp, binbuf, &binptr, binamount, &reclen, &csum, &zerofill);
3141              if (reclen >= (MAXRECSIZE - CHECKSIZE)) {
3142                reclen = pmon_checkset (reclen, &bp, &csum);
3143                pmon_download (buffer, reclen);
3144                finished = pmon_check_ack("data record");
3145                if (finished) {
3146                  zerofill = 0; /* do not transmit pending zerofills */
3147                  break;
3148                }
3149
3150                if (hashmark) {
3151                  putchar_unfiltered ('#');
3152                  gdb_flush (gdb_stdout);
3153                }
3154
3155                bp = buffer;
3156                reclen = 0; /* buffer processed */
3157              }
3158            }
3159          }
3160
3161          /* Ensure no out-standing zerofill requests: */
3162          if (zerofill != 0)
3163           reclen = pmon_zeroset (reclen, &bp, &zerofill, &csum);
3164
3165          /* and then flush the line: */
3166          if (reclen > 0) {
3167            reclen = pmon_checkset (reclen, &bp, &csum);
3168            /* Currently pmon_checkset outputs the line terminator by
3169               default, so we write out the buffer so far: */
3170            pmon_download (buffer, reclen);
3171            finished = pmon_check_ack("record remnant");
3172          }
3173        }
3174
3175       putchar_unfiltered ('\n');
3176     }
3177
3178   /* Terminate the transfer. We know that we have an empty output
3179      buffer at this point. */
3180   sprintf (buffer, "/E/E\n"); /* include dummy padding characters */
3181   reclen = strlen (buffer);
3182   pmon_download (buffer, reclen);
3183
3184   if (finished) { /* Ignore the termination message: */
3185     SERIAL_FLUSH_INPUT (udp_in_use ? udp_desc : mips_desc);
3186   } else { /* Deal with termination message: */
3187     pmon_end_download (final, bintotal);
3188   }
3189
3190   return;
3191 }
3192
3193 /* mips_load -- download a file. */
3194
3195 static void
3196 mips_load (file, from_tty)
3197     char *file;
3198     int  from_tty;
3199 {
3200   /* Get the board out of remote debugging mode.  */
3201   if (mips_exit_debug ())
3202     error ("mips_load:  Couldn't get into monitor mode.");
3203
3204   if (mips_monitor != MON_IDT)
3205    pmon_load_fast (file);
3206   else
3207    mips_load_srec (file);
3208
3209   mips_initialize ();
3210
3211   /* Finally, make the PC point at the start address */
3212   if (mips_monitor == MON_DDB)
3213     {
3214       /* Work around problem where DDB monitor does not update the
3215          PC after a load. The following ensures that the write_pc()
3216          WILL update the PC value: */
3217       register_valid[PC_REGNUM] = 0;
3218     }
3219   if (exec_bfd)
3220     write_pc (bfd_get_start_address (exec_bfd));
3221
3222   inferior_pid = 0;             /* No process now */
3223
3224 /* This is necessary because many things were based on the PC at the time that
3225    we attached to the monitor, which is no longer valid now that we have loaded
3226    new code (and just changed the PC).  Another way to do this might be to call
3227    normal_stop, except that the stack may not be valid, and things would get
3228    horribly confused... */
3229
3230   clear_symtab_users ();
3231 }
3232
3233
3234 /* The target vector.  */
3235
3236 struct target_ops mips_ops =
3237 {
3238   "mips",                       /* to_shortname */
3239   "Remote MIPS debugging over serial line",     /* to_longname */
3240   "\
3241 Debug a board using the MIPS remote debugging protocol over a serial line.\n\
3242 The argument is the device it is connected to or, if it contains a colon,\n\
3243 HOST:PORT to access a board over a network",  /* to_doc */
3244   mips_open,                    /* to_open */
3245   mips_close,                   /* to_close */
3246   NULL,                         /* to_attach */
3247   mips_detach,                  /* to_detach */
3248   mips_resume,                  /* to_resume */
3249   mips_wait,                    /* to_wait */
3250   mips_fetch_registers,         /* to_fetch_registers */
3251   mips_store_registers,         /* to_store_registers */
3252   mips_prepare_to_store,        /* to_prepare_to_store */
3253   mips_xfer_memory,             /* to_xfer_memory */
3254   mips_files_info,              /* to_files_info */
3255   mips_insert_breakpoint,       /* to_insert_breakpoint */
3256   mips_remove_breakpoint,       /* to_remove_breakpoint */
3257   NULL,                         /* to_terminal_init */
3258   NULL,                         /* to_terminal_inferior */
3259   NULL,                         /* to_terminal_ours_for_output */
3260   NULL,                         /* to_terminal_ours */
3261   NULL,                         /* to_terminal_info */
3262   mips_kill,                    /* to_kill */
3263   mips_load,                    /* to_load */
3264   NULL,                         /* to_lookup_symbol */
3265   mips_create_inferior,         /* to_create_inferior */
3266   mips_mourn_inferior,          /* to_mourn_inferior */
3267   NULL,                         /* to_can_run */
3268   NULL,                         /* to_notice_signals */
3269   0,                            /* to_thread_alive */
3270   0,                            /* to_stop */
3271   process_stratum,              /* to_stratum */
3272   NULL,                         /* to_next */
3273   1,                            /* to_has_all_memory */
3274   1,                            /* to_has_memory */
3275   1,                            /* to_has_stack */
3276   1,                            /* to_has_registers */
3277   1,                            /* to_has_execution */
3278   NULL,                         /* sections */
3279   NULL,                         /* sections_end */
3280   OPS_MAGIC                     /* to_magic */
3281 };
3282
3283
3284 /* An alternative target vector: */
3285 struct target_ops pmon_ops =
3286 {
3287   "pmon",                       /* to_shortname */
3288   "Remote MIPS debugging over serial line",     /* to_longname */
3289   "\
3290 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3291 line. The argument is the device it is connected to or, if it contains a\n\
3292 colon, HOST:PORT to access a board over a network",  /* to_doc */
3293   pmon_open,                    /* to_open */
3294   mips_close,                   /* to_close */
3295   NULL,                         /* to_attach */
3296   mips_detach,                  /* to_detach */
3297   mips_resume,                  /* to_resume */
3298   pmon_wait,                    /* to_wait */
3299   mips_fetch_registers,         /* to_fetch_registers */
3300   mips_store_registers,         /* to_store_registers */
3301   mips_prepare_to_store,        /* to_prepare_to_store */
3302   mips_xfer_memory,             /* to_xfer_memory */
3303   mips_files_info,              /* to_files_info */
3304   mips_insert_breakpoint,       /* to_insert_breakpoint */
3305   mips_remove_breakpoint,       /* to_remove_breakpoint */
3306   NULL,                         /* to_terminal_init */
3307   NULL,                         /* to_terminal_inferior */
3308   NULL,                         /* to_terminal_ours_for_output */
3309   NULL,                         /* to_terminal_ours */
3310   NULL,                         /* to_terminal_info */
3311   mips_kill,                    /* to_kill */
3312   mips_load,                    /* to_load */
3313   NULL,                         /* to_lookup_symbol */
3314   mips_create_inferior,         /* to_create_inferior */
3315   mips_mourn_inferior,          /* to_mourn_inferior */
3316   NULL,                         /* to_can_run */
3317   NULL,                         /* to_notice_signals */
3318   0,                            /* to_thread_alive */
3319   0,                            /* to_stop */
3320   process_stratum,              /* to_stratum */
3321   NULL,                         /* to_next */
3322   1,                            /* to_has_all_memory */
3323   1,                            /* to_has_memory */
3324   1,                            /* to_has_stack */
3325   1,                            /* to_has_registers */
3326   1,                            /* to_has_execution */
3327   NULL,                         /* sections */
3328   NULL,                         /* sections_end */
3329   OPS_MAGIC                     /* to_magic */
3330 };
3331
3332
3333 /* Another alternative target vector. This is a PMON system, but with
3334    a different monitor prompt, aswell as some other operational
3335    differences: */
3336 struct target_ops ddb_ops =
3337 {
3338   "ddb",                        /* to_shortname */
3339   "Remote MIPS debugging over serial line",     /* to_longname */
3340   "\
3341 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3342 line. The first argument is the device it is connected to or, if it contains\n\
3343 a colon, HOST:PORT to access a board over a network.  The optional second\n\
3344 parameter is the temporary file in the form HOST:FILENAME to be used for\n\
3345 TFTP downloads to the board.  The optional third parameter is the local\n\
3346 of the TFTP temporary file, if it differs from the filename seen by the board",
3347                                 /* to_doc */
3348   ddb_open,                     /* to_open */
3349   mips_close,                   /* to_close */
3350   NULL,                         /* to_attach */
3351   mips_detach,                  /* to_detach */
3352   mips_resume,                  /* to_resume */
3353   pmon_wait,                    /* to_wait */
3354   mips_fetch_registers,         /* to_fetch_registers */
3355   mips_store_registers,         /* to_store_registers */
3356   mips_prepare_to_store,        /* to_prepare_to_store */
3357   mips_xfer_memory,             /* to_xfer_memory */
3358   mips_files_info,              /* to_files_info */
3359   mips_insert_breakpoint,       /* to_insert_breakpoint */
3360   mips_remove_breakpoint,       /* to_remove_breakpoint */
3361   NULL,                         /* to_terminal_init */
3362   NULL,                         /* to_terminal_inferior */
3363   NULL,                         /* to_terminal_ours_for_output */
3364   NULL,                         /* to_terminal_ours */
3365   NULL,                         /* to_terminal_info */
3366   mips_kill,                    /* to_kill */
3367   mips_load,                    /* to_load */
3368   NULL,                         /* to_lookup_symbol */
3369   mips_create_inferior,         /* to_create_inferior */
3370   mips_mourn_inferior,          /* to_mourn_inferior */
3371   NULL,                         /* to_can_run */
3372   NULL,                         /* to_notice_signals */
3373   0,                            /* to_thread_alive */
3374   0,                            /* to_stop */
3375   process_stratum,              /* to_stratum */
3376   NULL,                         /* to_next */
3377   1,                            /* to_has_all_memory */
3378   1,                            /* to_has_memory */
3379   1,                            /* to_has_stack */
3380   1,                            /* to_has_registers */
3381   1,                            /* to_has_execution */
3382   NULL,                         /* sections */
3383   NULL,                         /* sections_end */
3384   OPS_MAGIC                     /* to_magic */
3385 };
3386 /* Another alternative target vector for LSI Logic MiniRISC boards.
3387    This is a PMON system, but with some other operational differences.  */
3388 struct target_ops lsi_ops =
3389 {
3390   "lsi",                        /* to_shortname */
3391   "Remote MIPS debugging over serial line",     /* to_longname */
3392   "\
3393 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3394 line. The first argument is the device it is connected to or, if it contains\n\
3395 a colon, HOST:PORT to access a board over a network.  The optional second\n\
3396 parameter is the temporary file in the form HOST:FILENAME to be used for\n\
3397 TFTP downloads to the board.  The optional third parameter is the local\n\
3398 of the TFTP temporary file, if it differs from the filename seen by the board",
3399                                 /* to_doc */
3400   lsi_open,                     /* to_open */
3401   mips_close,                   /* to_close */
3402   NULL,                         /* to_attach */
3403   mips_detach,                  /* to_detach */
3404   mips_resume,                  /* to_resume */
3405   pmon_wait,                    /* to_wait */
3406   mips_fetch_registers,         /* to_fetch_registers */
3407   mips_store_registers,         /* to_store_registers */
3408   mips_prepare_to_store,        /* to_prepare_to_store */
3409   mips_xfer_memory,             /* to_xfer_memory */
3410   mips_files_info,              /* to_files_info */
3411   mips_insert_breakpoint,       /* to_insert_breakpoint */
3412   mips_remove_breakpoint,       /* to_remove_breakpoint */
3413   NULL,                         /* to_terminal_init */
3414   NULL,                         /* to_terminal_inferior */
3415   NULL,                         /* to_terminal_ours_for_output */
3416   NULL,                         /* to_terminal_ours */
3417   NULL,                         /* to_terminal_info */
3418   mips_kill,                    /* to_kill */
3419   mips_load,                    /* to_load */
3420   NULL,                         /* to_lookup_symbol */
3421   mips_create_inferior,         /* to_create_inferior */
3422   mips_mourn_inferior,          /* to_mourn_inferior */
3423   NULL,                         /* to_can_run */
3424   NULL,                         /* to_notice_signals */
3425   0,                            /* to_thread_alive */
3426   0,                            /* to_stop */
3427   process_stratum,              /* to_stratum */
3428   NULL,                         /* to_next */
3429   1,                            /* to_has_all_memory */
3430   1,                            /* to_has_memory */
3431   1,                            /* to_has_stack */
3432   1,                            /* to_has_registers */
3433   1,                            /* to_has_execution */
3434   NULL,                         /* sections */
3435   NULL,                         /* sections_end */
3436   OPS_MAGIC                     /* to_magic */
3437 };
3438
3439
3440 void
3441 _initialize_remote_mips ()
3442 {
3443   add_target (&mips_ops);
3444   add_target (&pmon_ops);
3445   add_target (&ddb_ops);
3446   add_target (&lsi_ops);
3447
3448   add_show_from_set (
3449     add_set_cmd ("timeout", no_class, var_zinteger,
3450                  (char *) &mips_receive_wait,
3451                  "Set timeout in seconds for remote MIPS serial I/O.",
3452                  &setlist),
3453         &showlist);
3454
3455   add_show_from_set (
3456     add_set_cmd ("retransmit-timeout", no_class, var_zinteger,
3457                  (char *) &mips_retransmit_wait,
3458          "Set retransmit timeout in seconds for remote MIPS serial I/O.\n\
3459 This is the number of seconds to wait for an acknowledgement to a packet\n\
3460 before resending the packet.", &setlist),
3461         &showlist);
3462
3463   add_show_from_set (
3464     add_set_cmd ("syn-garbage-limit", no_class, var_zinteger,
3465                  (char *) &mips_syn_garbage,
3466 "Set the maximum number of characters to ignore when scanning for a SYN.\n\
3467 This is the maximum number of characters GDB will ignore when trying to\n\
3468 synchronize with the remote system.  A value of -1 means that there is no limit\n\
3469 (Note that these characters are printed out even though they are ignored.)",
3470                  &setlist),
3471                      &showlist);
3472 }