PiDP-8/I Software

Check-in [0415aa0e8f]
Log In

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Merged v20161226 as the latest release
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | release | v20161226
Files: files | file ages | folders
SHA1: 0415aa0e8f082cb11241908b462c12c79097250c
User & Date: tangent 2016-12-26 22:04:45.624
Context
2017-01-06
00:15
Merged v20170105 changes into release branch check-in: 9cde1575d1 user: tangent tags: release, v20170105
2016-12-26
22:19
Merged release changes in check-in: 6e66483574 user: tangent tags: no-lamp-simulator
22:04
Merged v20161226 as the latest release check-in: 0415aa0e8f user: tangent tags: release, v20161226
22:04
Release v20161226 check-in: 242018031d user: tangent tags: trunk
2016-12-23
17:24
Moved the new "disable competing services" install step above the "enable pidp8i service" step, and using parallel methods to enable the latter as we do to disble the former. check-in: cbbee9c080 user: tangent tags: release
Changes
Unified Diff Ignore Whitespace Patch
Added .fossil-settings/crlf-glob.








>
>
>
>
1
2
3
4
src/sim_*.[ch]
src/sim_*.in
src/PDP8/pdp8_*.[ch]
src/PDP8/pdp8_*.in
Changes to ChangeLog.md.
1





















































2
3
4
5
6
7
8
# PiDP-8/I Changes






















































## Version 2016.12.18

*   The entire software stack now runs without explicit root privileges.
    It now runs under the user and group of the one who built the
    software.


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# PiDP-8/I Changes

## Version 2016.12.26 (The Boxing Day release)

*   Updated SIMH to the latest upstream version. This represents about
    15 months worth of work in the [upstream project][simh], so I will
    only summarize the improvements affecting the PDP-8 simulator here:

    *   Many improvements to the internal handling of timers.
    
        The most user-visible improvement is that you can now clock your
        emulated PDP-8 down to well below the performance of a real
        PDP-8 via `SET THROTTLE`, which can be useful for making
        blinkenlights demos run at human speeds without adding huge
        delay loops to the PDP-8 code implementing that demo.

    *   Increased the number of supported terminals from four to either
        twelve or sixteen, depending on how you look at it.  Eight of
        the additional supported terminal devices are conflict-free,
        while the final four variously conflict with one or more of the
        other features of the simulated PDP-8.  If you want to use all
        16, you will be unable to use the FPP, CT, MT and TSC features
        of the system.

        This limitation reflects the way the PDP-8 worked.  It is not an
        arbitrary limitation of SIMH.

    *   Added support for the LS8E printer interface option used by the
        WPS8 word processing system.

    *   The simulator's command console now shows the FPP register
        descriptions when using it as a PDP-8 debugger.

    *   Added the `SHOW TTIX/TTOX DEVNO` SIMH command to display the
        device numbers used for TTIX and TTOX.

    *   The `SHOW TTIX SUMMARY` SIMH command is now case-insensitive.

    *   Upstream improvements to host OS/compiler compatibility.  This
        increases the chances that this software will build out of the
        box on random non-Raspbian systems such as your development
        laptop running some uncommon operating system.

*   When you `make install`, we now disable Deeper Thought 2 and the
    legacy `pidp8` service if we find them, since they conflict with our
    `pidp8i` service.

*   Added the install user to the `gpio` group if you `make install` if
    that group is present at install time.  This is useful when building
    and installing the software on an existing Raspbian SD card while
    logged in as a user other than `pi` or `pidp8i`.

[simh]: https://github.com/simh/simh/


## Version 2016.12.18

*   The entire software stack now runs without explicit root privileges.
    It now runs under the user and group of the one who built the
    software.

Changes to README.md.
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

    else you can do with the simulator command language, or read the
    [SimH Users' Guide][sdoc].

5.  To shut the simulator down from the Raspbian command line:

        $ sudo systemctl stop pidp8i

The other major difference between the upstream distribution and this
one is that there is no separate install script. The `make install`
command you ran above did everything for you.



[smod]: http://obsolescence.wixsite.com/obsolescence/2016-pidp-8-building-instructions
[usd]:  http://obsolescence.wixsite.com/obsolescence/pidp-8-details
[dt2]:  https://github.com/VentureKing/Deeper-Thought-2
[sdoc]: http://simh.trailing-edge.com/pdf/simh_doc.pdf
[prj]:  http://obsolescence.wixsite.com/obsolescence/pidp-8
[rmt]:  /doc/trunk/README-test.md
[rmsc]: /doc/trunk/README-single-core.md








|
|
<








|
|
>
146
147
148
149
150
151
152
153
154

155
156
157
158
159
160
161
162
163
164
165
    else you can do with the simulator command language, or read the
    [SimH Users' Guide][sdoc].

5.  To shut the simulator down from the Raspbian command line:

        $ sudo systemctl stop pidp8i

There are [other major differences][mdif] between the upstream
distribution and this one. See that linked wiki article for details.




[smod]: http://obsolescence.wixsite.com/obsolescence/2016-pidp-8-building-instructions
[usd]:  http://obsolescence.wixsite.com/obsolescence/pidp-8-details
[dt2]:  https://github.com/VentureKing/Deeper-Thought-2
[sdoc]: http://simh.trailing-edge.com/pdf/simh_doc.pdf
[prj]:  http://obsolescence.wixsite.com/obsolescence/pidp-8
[rmt]:  https://tangentsoft.com/pidp8i/doc/trunk/README-test.md
[rmsc]: https://tangentsoft.com/pidp8i/doc/trunk/README-single-core.md
[mdif]: https://tangentsoft.com/pidp8i/wiki?name=Major+Differences
Changes to src/PDP8/pdp8_clk.c.
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

int32 clk_tps = 60;                                     /* ticks/second */
int32 tmxr_poll = 16000;                                /* term mux poll */

int32 clk (int32 IR, int32 AC);
t_stat clk_svc (UNIT *uptr);
t_stat clk_reset (DEVICE *dptr);
t_stat clk_set_freq (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat clk_show_freq (FILE *st, UNIT *uptr, int32 val, void *desc);

/* CLK data structures

   clk_dev      CLK device descriptor
   clk_unit     CLK unit descriptor
   clk_reg      CLK register list
*/

DIB clk_dib = { DEV_CLK, 1, { &clk } };

UNIT clk_unit = { UDATA (&clk_svc, UNIT_IDLE, 0), 16000 };

REG clk_reg[] = {
    { FLDATA (DONE, dev_done, INT_V_CLK) },
    { FLDATA (ENABLE, int_enable, INT_V_CLK) },
    { FLDATA (INT, int_req, INT_V_CLK) },
    { DRDATA (TIME, clk_unit.wait, 24), REG_NZ + PV_LEFT },
    { DRDATA (TPS, clk_tps, 8), PV_LEFT + REG_HRO },
    { NULL }
    };

MTAB clk_mod[] = {
    { MTAB_XTD|MTAB_VDV, 50, NULL, "50HZ",
      &clk_set_freq, NULL, NULL },







|
|













|
|
|
|







43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

int32 clk_tps = 60;                                     /* ticks/second */
int32 tmxr_poll = 16000;                                /* term mux poll */

int32 clk (int32 IR, int32 AC);
t_stat clk_svc (UNIT *uptr);
t_stat clk_reset (DEVICE *dptr);
t_stat clk_set_freq (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat clk_show_freq (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

/* CLK data structures

   clk_dev      CLK device descriptor
   clk_unit     CLK unit descriptor
   clk_reg      CLK register list
*/

DIB clk_dib = { DEV_CLK, 1, { &clk } };

UNIT clk_unit = { UDATA (&clk_svc, UNIT_IDLE, 0), 16000 };

REG clk_reg[] = {
    { FLDATAD (DONE, dev_done, INT_V_CLK, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_CLK, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_CLK, "interrupt pending flag") },
    { DRDATAD (TIME, clk_unit.wait, 24, "clock interval"), REG_NZ + PV_LEFT },
    { DRDATA (TPS, clk_tps, 8), PV_LEFT + REG_HRO },
    { NULL }
    };

MTAB clk_mod[] = {
    { MTAB_XTD|MTAB_VDV, 50, NULL, "50HZ",
      &clk_set_freq, NULL, NULL },
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        }                                               /* end switch */
}

/* Unit service */

t_stat clk_svc (UNIT *uptr)
{
int32 t;

dev_done = dev_done | INT_CLK;                          /* set done */
int_req = INT_UPDATE;                                   /* update interrupts */
t = sim_rtcn_calb (clk_tps, TMR_CLK);                   /* calibrate clock */
tmxr_poll = t;                                          /* set mux poll */
sim_activate_after (uptr, 1000000/clk_tps);             /* reactivate unit */
return SCPE_OK;
}

/* Reset routine */

t_stat clk_reset (DEVICE *dptr)
{
int32 t;

sim_register_clock_unit (&clk_unit);                    /* declare clock unit */
dev_done = dev_done & ~INT_CLK;                         /* clear done, int */
int_req = int_req & ~INT_CLK;
int_enable = int_enable & ~INT_CLK;                     /* clear enable */
if (!sim_is_running) {                                  /* RESET (not CAF)? */
    t = sim_rtcn_init (clk_unit.wait, TMR_CLK);
    sim_activate (&clk_unit, t);                        /* activate unit */
    tmxr_poll = t;
    }
return SCPE_OK;
}

/* Set frequency */

t_stat clk_set_freq (UNIT *uptr, int32 val, char *cptr, void *desc)
{
if (cptr)
    return SCPE_ARG;
if ((val != 50) && (val != 60))
    return SCPE_IERR;
clk_tps = val;
return SCPE_OK;
}

/* Show frequency */

t_stat clk_show_freq (FILE *st, UNIT *uptr, int32 val, void *desc)
{
fprintf (st, (clk_tps == 50)? "50Hz": "60Hz");
return SCPE_OK;
}







<
<


|
<








<
<
<




|
|
<






|











|




137
138
139
140
141
142
143


144
145
146

147
148
149
150
151
152
153
154



155
156
157
158
159
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        }                                               /* end switch */
}

/* Unit service */

t_stat clk_svc (UNIT *uptr)
{


dev_done = dev_done | INT_CLK;                          /* set done */
int_req = INT_UPDATE;                                   /* update interrupts */
tmxr_poll = sim_rtcn_calb (clk_tps, TMR_CLK);           /* calibrate clock */

sim_activate_after (uptr, 1000000/clk_tps);             /* reactivate unit */
return SCPE_OK;
}

/* Reset routine */

t_stat clk_reset (DEVICE *dptr)
{



dev_done = dev_done & ~INT_CLK;                         /* clear done, int */
int_req = int_req & ~INT_CLK;
int_enable = int_enable & ~INT_CLK;                     /* clear enable */
if (!sim_is_running) {                                  /* RESET (not CAF)? */
    tmxr_poll = sim_rtcn_init_unit (&clk_unit, clk_unit.wait, TMR_CLK);/* init 100Hz timer */
    sim_activate_after (&clk_unit, 1000000/clk_tps);        /* activate 100Hz unit */

    }
return SCPE_OK;
}

/* Set frequency */

t_stat clk_set_freq (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
if (cptr)
    return SCPE_ARG;
if ((val != 50) && (val != 60))
    return SCPE_IERR;
clk_tps = val;
return SCPE_OK;
}

/* Show frequency */

t_stat clk_show_freq (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
fprintf (st, (clk_tps == 50)? "50Hz": "60Hz");
return SCPE_OK;
}
Changes to src/PDP8/pdp8_cpu.c.in.
1
2
3
4
5
6
7
8
9
10
/* pdp8_cpu.c: PDP-8 CPU simulator

   Copyright (c) 1993-2011, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_cpu.c: PDP-8 CPU simulator

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
21
22
23
24
25
26
27


28
29
30
31
32
33
34

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   cpu          central processor



   28-Apr-07    RMS     Removed clock initialization
   30-Oct-06    RMS     Added idle and infinite loop detection
   30-Sep-06    RMS     Fixed SC value after DVI overflow (Don North)
   22-Sep-05    RMS     Fixed declarations (Sterling Garwood)
   16-Aug-05    RMS     Fixed C++ declaration and cast problems
   06-Nov-04    RMS     Added =n to SHOW HISTORY
   31-Dec-03    RMS     Fixed bug in set_cpu_hist







>
>







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   cpu          central processor

   18-Sep-16    RMS     Added alternate dispatch table for non-contiguous devices
   17-Sep-13    RMS     Fixed boot in wrong field problem (Dave Gesswein)
   28-Apr-07    RMS     Removed clock initialization
   30-Oct-06    RMS     Added idle and infinite loop detection
   30-Sep-06    RMS     Fixed SC value after DVI overflow (Don North)
   22-Sep-05    RMS     Fixed declarations (Sterling Garwood)
   16-Aug-05    RMS     Fixed C++ declaration and cast problems
   06-Nov-04    RMS     Added =n to SHOW HISTORY
   31-Dec-03    RMS     Fixed bug in set_cpu_hist
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#define UNIT_V_MSIZE    (UNIT_V_UF + 1)                 /* dummy mask */
#define UNIT_MSIZE      (1 << UNIT_V_MSIZE)
#define OP_KSF          06031                           /* for idle */

#define HIST_PC         0x40000000
#define HIST_MIN        64
#define HIST_MAX        65536
#define DECAY		0.01

typedef struct {
    int32               pc;
    int32               ea;
    int16               ir;
    int16               opnd;
    int16               lac;







|







200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#define UNIT_V_MSIZE    (UNIT_V_UF + 1)                 /* dummy mask */
#define UNIT_MSIZE      (1 << UNIT_V_MSIZE)
#define OP_KSF          06031                           /* for idle */

#define HIST_PC         0x40000000
#define HIST_MIN        64
#define HIST_MAX        65536
#define DECAY       0.01

typedef struct {
    int32               pc;
    int32               ea;
    int16               ir;
    int16               opnd;
    int16               lac;
226
227
228
229
230
231
232

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
int32 UB = 0;                                           /* User mode Buffer */
int32 UF = 0;                                           /* User mode Flag */
int32 OSR = 0;                                          /* Switch Register */
int32 tsc_ir = 0;                                       /* TSC8-75 IR */
int32 tsc_pc = 0;                                       /* TSC8-75 PC */
int32 tsc_cdf = 0;                                      /* TSC8-75 CDF flag */
int32 tsc_enb = 0;                                      /* TSC8-75 enabled */

int16 pcq[PCQ_SIZE] = { 0 };                            /* PC queue */
int32 pcq_p = 0;                                        /* PC queue ptr */
REG *pcq_r = NULL;                                      /* PC queue reg ptr */
int32 dev_done = 0;                                     /* dev done flags */
int32 int_enable = INT_INIT_ENABLE;                     /* intr enables */
int32 int_req = 0;                                      /* intr requests */
int32 stop_inst = 0;                                    /* trap on ill inst */
int32 (*dev_tab[DEV_MAX])(int32 IR, int32 dat);         /* device dispatch */
int32 hst_p = 0;                                        /* history pointer */
int32 hst_lnt = 0;                                      /* history length */
InstHistory *hst = NULL;                                /* instruction history */

extern int32 sim_interval;
extern int32 sim_int_char;
extern uint32 sim_brk_types, sim_brk_dflt, sim_brk_summ; /* breakpoint info */
extern DEVICE *sim_devices[];
extern FILE *sim_log;
extern t_bool sim_idle_enab;
extern float brtval[96];

/* ------------------------------------------------------------------------------------------------- */
void setleds(uint32 sPC, uint32 sMA, uint16 sMB, uint16 sIR, int32 sLAC, int32 sMQ, int32 sIF, int32 sDF, int32 sTT);
uint16 lctr=0;
/* ------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
int swStop = 0, swExam = 0, swDep = 0, swCont2 = 0, swStart = 0, swSingStep = 0, swAttach = 0;
char mountedFiles[8][CBUFSIZE];
char	swDevCode[4];
int	awfulHackFlag=0;	// truly terrible even for me - break out of sim and start new script in scp.c

/* --------------------------------------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
#include <dirent.h>	// for USB stick searching
int mountUSBStickFile(int devNo, char *devCode, char *sPath);
extern t_stat attach_cmd (int32 flag, char *cptr); // from scp
extern t_stat do_cmd (int32 flag, char *cptr); // from scp
extern t_stat spawn_cmd (int32 flag, char *cptr);
extern t_stat exit_cmd (int32 flag, char *cptr);
char xcbuf[CBUFSIZE], *xcptr;
/* --------------------------------------------------------------------------------------------------------- */



t_stat cpu_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw);
t_stat cpu_dep (t_value val, t_addr addr, UNIT *uptr, int32 sw);
t_stat cpu_reset (DEVICE *dptr);
t_stat cpu_set_size (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat cpu_set_hist (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat cpu_show_hist (FILE *st, UNIT *uptr, int32 val, void *desc);
t_bool build_dev_tab (void);

/* CPU data structures

   cpu_dev      CPU device descriptor
   cpu_unit     CPU unit descriptor
   cpu_reg      CPU register list
   cpu_mod      CPU modifier list
*/

UNIT cpu_unit = { UDATA (NULL, UNIT_FIX + UNIT_BINK, MAXMEMSIZE) };

REG cpu_reg[] = {
    { ORDATA (PC, saved_PC, 15) },
    { ORDATA (AC, saved_LAC, 12) },
    { FLDATA (L, saved_LAC, 12) },
    { ORDATA (MQ, saved_MQ, 12) },
    { ORDATA (SR, OSR, 12) },
    { GRDATA (IF, saved_PC, 8, 3, 12) },
    { GRDATA (DF, saved_DF, 8, 3, 12) },
    { GRDATA (IB, IB, 8, 3, 12) },
    { ORDATA (SF, SF, 7) },
    { FLDATA (UB, UB, 0) },
    { FLDATA (UF, UF, 0) },
    { ORDATA (SC, SC, 5) },
    { FLDATA (GTF, gtf, 0) },
    { FLDATA (EMODE, emode, 0) },
    { FLDATA (ION, int_req, INT_V_ION) },
    { FLDATA (ION_DELAY, int_req, INT_V_NO_ION_PENDING) },
    { FLDATA (CIF_DELAY, int_req, INT_V_NO_CIF_PENDING) },
    { FLDATA (PWR_INT, int_req, INT_V_PWR) },
    { FLDATA (UF_INT, int_req, INT_V_UF) },
    { ORDATA (INT, int_req, INT_V_ION+1), REG_RO },
    { ORDATA (DONE, dev_done, INT_V_DIRECT), REG_RO },
    { ORDATA (ENABLE, int_enable, INT_V_DIRECT), REG_RO },
    { BRDATA (PCQ, pcq, 8, 15, PCQ_SIZE), REG_RO+REG_CIRC },
    { ORDATA (PCQP, pcq_p, 6), REG_HRO },
    { FLDATA (STOP_INST, stop_inst, 0) },
    { ORDATA (WRU, sim_int_char, 8) },
    { NULL }
    };

MTAB cpu_mod[] = {
    { UNIT_NOEAE, UNIT_NOEAE, "no EAE", "NOEAE", NULL },
    { UNIT_NOEAE, 0, "EAE", "EAE", NULL },
    { MTAB_XTD|MTAB_VDV, 0, "IDLE", "IDLE", &sim_set_idle, &sim_show_idle },







>












|
<
<
<
<
<

<
<


<
<


|
|
<
<
<
|

<
<
<
<

<
|
<




|
|
|













|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|







228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248





249


250
251


252
253
254
255



256
257




258

259

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
int32 UB = 0;                                           /* User mode Buffer */
int32 UF = 0;                                           /* User mode Flag */
int32 OSR = 0;                                          /* Switch Register */
int32 tsc_ir = 0;                                       /* TSC8-75 IR */
int32 tsc_pc = 0;                                       /* TSC8-75 PC */
int32 tsc_cdf = 0;                                      /* TSC8-75 CDF flag */
int32 tsc_enb = 0;                                      /* TSC8-75 enabled */
int32 cpu_astop = 0;                                    /* address stop */
int16 pcq[PCQ_SIZE] = { 0 };                            /* PC queue */
int32 pcq_p = 0;                                        /* PC queue ptr */
REG *pcq_r = NULL;                                      /* PC queue reg ptr */
int32 dev_done = 0;                                     /* dev done flags */
int32 int_enable = INT_INIT_ENABLE;                     /* intr enables */
int32 int_req = 0;                                      /* intr requests */
int32 stop_inst = 0;                                    /* trap on ill inst */
int32 (*dev_tab[DEV_MAX])(int32 IR, int32 dat);         /* device dispatch */
int32 hst_p = 0;                                        /* history pointer */
int32 hst_lnt = 0;                                      /* history length */
InstHistory *hst = NULL;                                /* instruction history */

/* ---PiDP add--------------------------------------------------------------------------------------------- */





extern float brtval[96];


void setleds(uint32 sPC, uint32 sMA, uint16 sMB, uint16 sIR, int32 sLAC, int32 sMQ, int32 sIF, int32 sDF, int32 sTT);
uint16 lctr=0;


int swStop = 0, swExam = 0, swDep = 0, swCont2 = 0, swStart = 0, swSingStep = 0, swAttach = 0;
char mountedFiles[8][CBUFSIZE];
char    swDevCode[4];
int awfulHackFlag=0;    // truly terrible even for me - break out of sim and start new script in scp.c



#include <dirent.h> // for USB stick searching
int mountUSBStickFile(int devNo, char *devCode, char *sPath);




char xcbuf[CBUFSIZE], *xcptr;

/* ---PiDP end---------------------------------------------------------------------------------------------- */


t_stat cpu_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw);
t_stat cpu_dep (t_value val, t_addr addr, UNIT *uptr, int32 sw);
t_stat cpu_reset (DEVICE *dptr);
t_stat cpu_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat cpu_set_hist (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat cpu_show_hist (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_bool build_dev_tab (void);

/* CPU data structures

   cpu_dev      CPU device descriptor
   cpu_unit     CPU unit descriptor
   cpu_reg      CPU register list
   cpu_mod      CPU modifier list
*/

UNIT cpu_unit = { UDATA (NULL, UNIT_FIX + UNIT_BINK, MAXMEMSIZE) };

REG cpu_reg[] = {
    { ORDATAD (PC, saved_PC, 15, "program counter") },
    { ORDATAD (AC, saved_LAC, 12, "accumulator") },
    { FLDATAD (L, saved_LAC, 12, "link") },
    { ORDATAD (MQ, saved_MQ, 12, "multiplier-quotient") },
    { ORDATAD (SR, OSR, 12, "front panel switches") },
    { GRDATAD (IF, saved_PC, 8, 3, 12, "instruction field") },
    { GRDATAD (DF, saved_DF, 8, 3, 12, "data field") },
    { GRDATAD (IB, IB, 8, 3, 12, "instruction field buffter") },
    { ORDATAD (SF, SF, 7, "save field") },
    { FLDATAD (UB, UB, 0, "user mode buffer") },
    { FLDATAD (UF, UF, 0, "user mode flag") },
    { ORDATAD (SC, SC, 5, "EAE shift counter") },
    { FLDATAD (GTF, gtf, 0, "EAE greater than flag") },
    { FLDATAD (EMODE, emode, 0, "EAE mode (0 = A, 1 = B)") },
    { FLDATAD (ION, int_req, INT_V_ION, "interrupt enable") },
    { FLDATAD (ION_DELAY, int_req, INT_V_NO_ION_PENDING, "interrupt enable delay for ION") },
    { FLDATAD (CIF_DELAY, int_req, INT_V_NO_CIF_PENDING, "interrupt enable delay for CIF") },
    { FLDATAD (PWR_INT, int_req, INT_V_PWR, "power fail interrupt") },
    { FLDATAD (UF_INT, int_req, INT_V_UF, "user mode violation interrupt") },
    { ORDATAD (INT, int_req, INT_V_ION+1, "interrupt pending flags"), REG_RO },
    { ORDATAD (DONE, dev_done, INT_V_DIRECT, "device done flags"), REG_RO },
    { ORDATAD (ENABLE, int_enable, INT_V_DIRECT, "device interrupt enable flags"), REG_RO },
    { BRDATAD (PCQ, pcq, 8, 15, PCQ_SIZE, "PC prior to last JMP, JMS, or interrupt;                                        most recent PC change first"), REG_RO+REG_CIRC },
    { ORDATA (PCQP, pcq_p, 6), REG_HRO },
    { FLDATAD (STOP_INST, stop_inst, 0, "stop on undefined instruction") },
    { ORDATAD (WRU, sim_int_char, 8, "interrupt character") },
    { NULL }
    };

MTAB cpu_mod[] = {
    { UNIT_NOEAE, UNIT_NOEAE, "no EAE", "NOEAE", NULL },
    { UNIT_NOEAE, 0, "EAE", "EAE", NULL },
    { MTAB_XTD|MTAB_VDV, 0, "IDLE", "IDLE", &sim_set_idle, &sim_show_idle },
352
353
354
355
356
357
358

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
int32 IR, MB, IF, DF, LAC, MQ;
uint32 PC, MA;
int32 device, pulse, temp, iot_data;
t_stat reason;

/* Restore register state */


if (build_dev_tab ()) return SCPE_STOP;                 /* build dev_tab */
PC = saved_PC & 007777;                                 /* load local copies */
IF = saved_PC & 070000;
DF = saved_DF & 070000;
LAC = saved_LAC & 017777;
MQ = saved_MQ & 07777;
int_req = INT_UPDATE;
reason = 0;


/* ---PiDP add--------------------------------------------------------------------------------------------- */
int swDevice;
char sScript[256];
MA = MB = IR = 0;	// have to add this to avoid crash when stop switch is set at start - MA would be undefined in setleds
setleds(PC, MA, MB, MB, LAC, MQ, IF, DF, 0); // note MB used // light up leds for 1st time, only needed when stop switch set at start
/* ---PiDP end---------------------------------------------------------------------------------------------- */


/* Main instruction fetch/decode loop */

while (reason == 0) {                                   /* loop until halted */


/* ---PiDP add--------------------------------------------------------------------------------------------- */
awfulHackFlag = 0; // no do script pending. Did I mention awful?
/* ---PiDP end---------------------------------------------------------------------------------------------- */


    if (sim_interval <= 0) {                            /* check clock queue */
        if (reason = sim_process_event ())
            break;
        }

/* ---PiDP add--------------------------------------------------------------------------------------------- */

// this bit of code detects SING_INST as the special features switch.
// when DF switches are set, that raises a hacked-in-to-simh signal to ATTACH PTR <filename>
// when IF switches are set, that raises a hacked-in-to-simh signal to DO <filename> (boot script)

if (pidp8i_gpio_present && (switchstatus[2] & SS2_S_STEP)==0)
{
	if (swAttach==0)		// if this is the first time we detect it,
	{
		swAttach=1;		// make this a momentary switch in software

		// 1. Scan DF to see if any devices need to be mounted (DF=0 --> nothing to mount)

		swDevice = (((switchstatus[1] >> 11) & 1)==0?4:0)
			+(((switchstatus[1] >> 10) & 1)==0?2:0)
			+(((switchstatus[1] >> 9) & 1)==0?1:0);

		if (swDevice!=0)
		{
			switch(swDevice)
			{
				case 1:	strcpy(swDevCode,"ptr"); break;	// PTR paper tape reader
				case 2:	strcpy(swDevCode,"ptp"); break;	// High speed paper tape punch
				case 3:	strcpy(swDevCode,"dt0"); break;	// TC08 DECtape (#8 is first!)
				case 4:	strcpy(swDevCode,"dt1"); break;
				case 5:	strcpy(swDevCode,"rx0"); break;	// RX8E (8/e peripheral!)
				case 6:	strcpy(swDevCode,"rx1"); break;
				case 7:	strcpy(swDevCode,"rl0"); break;	// RL8A
			}
			xcptr=&xcbuf[0];				// set string pointer to start
			mountUSBStickFile(swDevice, swDevCode, xcptr);
		}

		// 2. Scan IF to see if we need to reboot with a new bootscript

		swDevice = (((switchstatus[1] >> 8) & 1)==0?4:0)
			+(((switchstatus[1] >> 7) & 1)==0?2:0)
			+(((switchstatus[1] >> 6) & 1)==0?1:0);

		if (swDevice!=0)
		{
			sprintf(sScript,"@BOOTDIR@/%d.script", swDevice);	// make filename
			printf("\r\n\nRebooting %s\r\n\n", sScript);
			reason = STOP_HALT;
			awfulHackFlag = swDevice;	// this triggers a do command after leaving the simulator run.
			PC = saved_PC = 0;                                 /* Clear all registers */
            IF = saved_PC = 0;
            DF = saved_DF = 0;
            LAC = saved_LAC = 0;
            MQ = saved_MQ = 0;
            int_req = 0;

		}
	}
}
if (swAttach==1)		// Sing_Step switch is back to off again
	if ((switchstatus[2] & SS2_S_STEP)!=0)		// switch deactivated
		swAttach=0;				// reset 'avoid repeat' indicator

// 3. Scan for host poweroff command (Sing_Step + Sing_Inst + Stop)

if (pidp8i_gpio_present &&
		((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_STOP))==0))
{
	printf("\r\nShutdown\r\n\r\n");
	reason = STOP_HALT;
	awfulHackFlag = 8;	// this triggers an exit command after leaving the simulator run.
	if(spawn_cmd (0, "sudo /bin/systemctl poweroff")!=SCPE_OK)
		printf("\r\n\r\npoweroff failed\r\n\r\n");
}

// 4. Scan for host reboot command (Sing_Step + Sing_Inst + Start)

if (pidp8i_gpio_present &&
		((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_START))==0))
{
	printf("\r\nReboot\r\n\r\n");
	reason = STOP_HALT;
	awfulHackFlag = 8;      // this triggers an exit command after leaving the simulator run.
	if(spawn_cmd (0, "sudo /bin/systemctl reboot")!=SCPE_OK)
		printf("\r\n\r\nreboot failed\r\n\r\n");
}

#if 0
// 5. Sing_Step + Sing_Inst + Load Add

if (pidp8i_gpio_present &&
		((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_L_ADD))==0))
{
}

// 6. Sing_Step + Sing_Inst + Deposit

if (pidp8i_gpio_present &&
		((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_DEP))==0))
{
}
#endif

/* ---PiDP end---------------------------------------------------------------------------------------------- */


/* ---PiDP add--------------------------------------------------------------------------------------------- */

if (pidp8i_gpio_present && (switchstatus[2] & SS2_START)==0)	// START switch activated
	if (swStart==0)
	{
	        int_req = int_req & ~INT_ION;		// disable ION. says so in handbook, true?
		LAC = 0;				// Clear LAC;
		// IR = 0 				// clear IR (handbook says so but would be weird)
		MB = 0;					// clear MB.
		MA = PC & 07777;			// transfer PC into MA  (not necessary because IR is redone in code below?
		swStop = 0;
		swStart = 1;				// single shot
	}
if (swStart==1)
	if ((switchstatus[2] & SS2_START)!=0)		// START switch deactivated
		swStart=0;				// reset 'avoid repeat' indicator


if (pidp8i_gpio_present && (switchstatus[2] & SS2_CONT)==0)			// CONT switch activated
	if (swCont2==0)
	{	swStop = 0;				// meaning resume execution
			// ? is this done: MB contains instruction to be executed after CONT is pressed
		swCont2 = 1;				// single shot
		goto contPoint;				// note: only for cont not for start
	}
if (swCont2==1)
	if ((switchstatus[2] & SS2_CONT)!=0)		// CONT switch deactivated
		swCont2=0;				// reset 'avoid repeat' indicator


if (pidp8i_gpio_present && (switchstatus[2] & SS2_L_ADD)==0)			// LOAD_ADD switch activated
{
	PC = switchstatus[0] ^ 07777;			// copy SR into PC
							// copy DF and IF too
	DF = (((switchstatus[1] >> 11) & 1)==0?4:0)
	+(((switchstatus[1] >> 10) & 1)==0?2:0)
	+(((switchstatus[1] >> 9) & 1)==0?1:0);
	DF = DF<<12;					// DF is saved in oct digit 5, so it's easy to add to PC

	IF = (((switchstatus[1] >> 8) & 1)==0?4:0)
	+(((switchstatus[1] >> 7) & 1)==0?2:0)
	+(((switchstatus[1] >> 6) & 1)==0?1:0);
	IF = IF<<12;					// DF is saved in oct digit 5, so it's easy to add to PC
}

if (pidp8i_gpio_present && (switchstatus[2] & SS2_DEP)==0)			// DEP switch activated
{	if (swDep==0)
	{	M[PC] = switchstatus[0] ^ 07777;
		/* ??? in 66 handbook: strictly speaking, SR goes into AC, then AC into MB. Does it clear AC afterwards? If not, needs fix */
		MB = M[PC];
		MA = PC & 07777;			// 20150315: MA trails PC on FP
		PC = (PC + 1) & 07777;			// increment PC
		swDep=1;				// avoid repeat
	}
}
if (swDep==1)
	if ((switchstatus[2] & SS2_DEP)!=0)		// DEP switch deactivated
		swDep=0;				// reset 'avoid repeat' indicator

if (pidp8i_gpio_present && (switchstatus[2] & SS2_EXAM)==0)			// EXAM switch activated
{	if (swExam==0)
	{	MB = M[PC];
		MA = PC & 07777;			// 20150315: MA trails PC on FP
		PC = (PC + 1) & 07777;			// increment PC
		swExam=1;				// avoid repeat
	}
}
if (swExam==1)
	if ((switchstatus[2] & SS2_EXAM)!=0)		// EXAM switch deactivated
		swExam=0;				// reset 'avoid repeat' indicator


// do what needs to be done in STOP mode:
if (swStop==1)
{
	setleds(PC, MA, M[MA] , IR, LAC, MQ, IF, DF, 0); 		// note M[MA] used in this call, not MB
	sim_interval = sim_interval - 1;		                // otherwise, CTRL-E will never be acted upon in stop mode
                                                            // WARNING: THIS MAY LEAD TO TROUBLE. MAYBE?
	goto skip;					// a goto is period correct methinks
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */


    if (int_req > INT_PENDING) {                        /* interrupt? */
        int_req = int_req & ~INT_ION;                   /* interrupts off */
        SF = (UF << 6) | (IF >> 9) | (DF >> 12);        /* form save field */
        IF = IB = DF = UF = UB = 0;                     /* clear mem ext */
        PCQ_ENTRY;                                      /* save old PC */
        M[0] = PC;                                      /* save PC in 0 */
        PC = 1;                                         /* fetch next from 1 */
        }

    MA = IF | PC;                                       /* form PC */
    if (sim_brk_summ && sim_brk_test (MA, SWMASK ('E'))) { /* breakpoint? */

        reason = STOP_IBKPT;                            /* stop simulation */
        break;
	}

    IR = M[MA];                                         /* fetch instruction */

//PC increment was moved down before, bad idea? now is where it originally was.
    setleds(PC, MA, M[MA], IR, LAC, MQ, IF, DF, 0);	// State=0:Fetch

    int_req = int_req | INT_NO_ION_PENDING;             /* clear ION delay */
    sim_interval = sim_interval - 1;


/* ---PiDP add--------------------------------------------------------------------------------------------- */

if  (pidp8i_gpio_present && (switchstatus[2] & SS2_STOP)==0)  		// STOP switch activated
{	swStop = 1;
	goto skip;
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */

//--------------- moved to here:
//no longer    PC = (PC + 1) & 07777;                              /* increment PC */
//---------------


/* ---PiDP add--------------------------------------------------------------------------------------------- */
contPoint:	;	// goto here if CONT has been pressed to finish current instruction

// SING_STEP: swStop=0 if we're here. If SingStep then this time, let it go but trigger a stop on the next pass

if (pidp8i_gpio_present && (switchstatus[2] & SS2_S_INST)==0)		// SING_INST switch activated
{	if (swSingStep==0)		// allow it this time,
		swSingStep=1;		// but note to block it next time!
	else				// else: this is the next time...
	{	swSingStep=0;		// reset flipflop
		swStop=1;		// and do what you do when STOP is pressed.
		goto skip;
	}
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */

    PC = (PC + 1) & 07777;                              /* increment PC */

/* Instruction decoding.







>
|












|















|











|
|
|

|

|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|

|
|
|

|
|
|
|
|
|
|






|
|

|
|
|




|

|
|
|
|
|





|

|
|
|
|
|






|






|









|
|
|
|
|
|
|
|
|
|
|

|
|


|
|
|
|
|
|
|

|
|


|

|
|
|
|
|
|

|
|
|
|


|
|
|
|
|
|
|
|
|


|
|

|
|
|
|
|
|
|


|
|





|
|

|















|
>


|




|







|
|
|










|



|
|
|
|
|
|
|
|







337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
int32 IR, MB, IF, DF, LAC, MQ;
uint32 PC, MA;
int32 device, pulse, temp, iot_data;
t_stat reason;

/* Restore register state */

if (build_dev_tab ())                                   /* build dev_tab */
    return SCPE_STOP;
PC = saved_PC & 007777;                                 /* load local copies */
IF = saved_PC & 070000;
DF = saved_DF & 070000;
LAC = saved_LAC & 017777;
MQ = saved_MQ & 07777;
int_req = INT_UPDATE;
reason = 0;


/* ---PiDP add--------------------------------------------------------------------------------------------- */
int swDevice;
char sScript[256];
MA = MB = IR = 0;   // have to add this to avoid crash when stop switch is set at start - MA would be undefined in setleds
setleds(PC, MA, MB, MB, LAC, MQ, IF, DF, 0); // note MB used // light up leds for 1st time, only needed when stop switch set at start
/* ---PiDP end---------------------------------------------------------------------------------------------- */


/* Main instruction fetch/decode loop */

while (reason == 0) {                                   /* loop until halted */


/* ---PiDP add--------------------------------------------------------------------------------------------- */
awfulHackFlag = 0; // no do script pending. Did I mention awful?
/* ---PiDP end---------------------------------------------------------------------------------------------- */


    if (sim_interval <= 0) {                            /* check clock queue */
        if ((reason = sim_process_event ()))
            break;
        }

/* ---PiDP add--------------------------------------------------------------------------------------------- */

// this bit of code detects SING_INST as the special features switch.
// when DF switches are set, that raises a hacked-in-to-simh signal to ATTACH PTR <filename>
// when IF switches are set, that raises a hacked-in-to-simh signal to DO <filename> (boot script)

if (pidp8i_gpio_present && (switchstatus[2] & SS2_S_STEP)==0)
{
    if (swAttach==0)        // if this is the first time we detect it,
    {
        swAttach=1;     // make this a momentary switch in software

        // 1. Scan DF to see if any devices need to be mounted (DF=0 --> nothing to mount)

        swDevice = (((switchstatus[1] >> 11) & 1)==0?4:0)
            +(((switchstatus[1] >> 10) & 1)==0?2:0)
            +(((switchstatus[1] >> 9) & 1)==0?1:0);

        if (swDevice!=0)
        {
            switch(swDevice)
            {
                case 1: strcpy(swDevCode,"ptr"); break; // PTR paper tape reader
                case 2: strcpy(swDevCode,"ptp"); break; // High speed paper tape punch
                case 3: strcpy(swDevCode,"dt0"); break; // TC08 DECtape (#8 is first!)
                case 4: strcpy(swDevCode,"dt1"); break;
                case 5: strcpy(swDevCode,"rx0"); break; // RX8E (8/e peripheral!)
                case 6: strcpy(swDevCode,"rx1"); break;
                case 7: strcpy(swDevCode,"rl0"); break; // RL8A
            }
            xcptr=&xcbuf[0];                // set string pointer to start
            mountUSBStickFile(swDevice, swDevCode, xcptr);
        }

        // 2. Scan IF to see if we need to reboot with a new bootscript

        swDevice = (((switchstatus[1] >> 8) & 1)==0?4:0)
            +(((switchstatus[1] >> 7) & 1)==0?2:0)
            +(((switchstatus[1] >> 6) & 1)==0?1:0);

        if (swDevice!=0)
        {
            sprintf(sScript,"@BOOTDIR@/%d.script", swDevice);   // make filename
            printf("\r\n\nRebooting %s\r\n\n", sScript);
            reason = STOP_HALT;
            awfulHackFlag = swDevice;   // this triggers a do command after leaving the simulator run.
            PC = saved_PC = 0;                                 /* Clear all registers */
            IF = saved_PC = 0;
            DF = saved_DF = 0;
            LAC = saved_LAC = 0;
            MQ = saved_MQ = 0;
            int_req = 0;

        }
    }
}
if (swAttach==1)        // Sing_Step switch is back to off again
    if ((switchstatus[2] & SS2_S_STEP)!=0)      // switch deactivated
        swAttach=0;             // reset 'avoid repeat' indicator

// 3. Scan for host poweroff command (Sing_Step + Sing_Inst + Stop)

if (pidp8i_gpio_present &&
        ((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_STOP))==0))
{
    printf("\r\nShutdown\r\n\r\n");
    reason = STOP_HALT;
    awfulHackFlag = 8;  // this triggers an exit command after leaving the simulator run.
    if(spawn_cmd (0, "sudo /bin/systemctl poweroff")!=SCPE_OK)
        printf("\r\n\r\npoweroff failed\r\n\r\n");
}

// 4. Scan for host reboot command (Sing_Step + Sing_Inst + Start)

if (pidp8i_gpio_present &&
        ((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_START))==0))
{
    printf("\r\nReboot\r\n\r\n");
    reason = STOP_HALT;
    awfulHackFlag = 8;      // this triggers an exit command after leaving the simulator run.
    if(spawn_cmd (0, "sudo /bin/systemctl reboot")!=SCPE_OK)
        printf("\r\n\r\nreboot failed\r\n\r\n");
}

#if 0
// 5. Sing_Step + Sing_Inst + Load Add

if (pidp8i_gpio_present &&
        ((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_L_ADD))==0))
{
}

// 6. Sing_Step + Sing_Inst + Deposit

if (pidp8i_gpio_present &&
        ((switchstatus[2] & (SS2_S_STEP | SS2_S_INST | SS2_DEP))==0))
{
}
#endif

/* ---PiDP end---------------------------------------------------------------------------------------------- */


/* ---PiDP add--------------------------------------------------------------------------------------------- */

if (pidp8i_gpio_present && (switchstatus[2] & SS2_START)==0)    // START switch activated
    if (swStart==0)
    {
            int_req = int_req & ~INT_ION;       // disable ION. says so in handbook, true?
        LAC = 0;                // Clear LAC;
        // IR = 0               // clear IR (handbook says so but would be weird)
        MB = 0;                 // clear MB.
        MA = PC & 07777;            // transfer PC into MA  (not necessary because IR is redone in code below?
        swStop = 0;
        swStart = 1;                // single shot
    }
if (swStart==1)
    if ((switchstatus[2] & SS2_START)!=0)       // START switch deactivated
        swStart=0;              // reset 'avoid repeat' indicator


if (pidp8i_gpio_present && (switchstatus[2] & SS2_CONT)==0)         // CONT switch activated
    if (swCont2==0)
    {   swStop = 0;             // meaning resume execution
            // ? is this done: MB contains instruction to be executed after CONT is pressed
        swCont2 = 1;                // single shot
        goto contPoint;             // note: only for cont not for start
    }
if (swCont2==1)
    if ((switchstatus[2] & SS2_CONT)!=0)        // CONT switch deactivated
        swCont2=0;              // reset 'avoid repeat' indicator


if (pidp8i_gpio_present && (switchstatus[2] & SS2_L_ADD)==0)            // LOAD_ADD switch activated
{
    PC = switchstatus[0] ^ 07777;           // copy SR into PC
                            // copy DF and IF too
    DF = (((switchstatus[1] >> 11) & 1)==0?4:0)
    +(((switchstatus[1] >> 10) & 1)==0?2:0)
    +(((switchstatus[1] >> 9) & 1)==0?1:0);
    DF = DF<<12;                    // DF is saved in oct digit 5, so it's easy to add to PC

    IF = (((switchstatus[1] >> 8) & 1)==0?4:0)
    +(((switchstatus[1] >> 7) & 1)==0?2:0)
    +(((switchstatus[1] >> 6) & 1)==0?1:0);
    IF = IF<<12;                    // DF is saved in oct digit 5, so it's easy to add to PC
}

if (pidp8i_gpio_present && (switchstatus[2] & SS2_DEP)==0)          // DEP switch activated
{   if (swDep==0)
    {   M[PC] = switchstatus[0] ^ 07777;
        /* ??? in 66 handbook: strictly speaking, SR goes into AC, then AC into MB. Does it clear AC afterwards? If not, needs fix */
        MB = M[PC];
        MA = PC & 07777;            // 20150315: MA trails PC on FP
        PC = (PC + 1) & 07777;          // increment PC
        swDep=1;                // avoid repeat
    }
}
if (swDep==1)
    if ((switchstatus[2] & SS2_DEP)!=0)     // DEP switch deactivated
        swDep=0;                // reset 'avoid repeat' indicator

if (pidp8i_gpio_present && (switchstatus[2] & SS2_EXAM)==0)         // EXAM switch activated
{   if (swExam==0)
    {   MB = M[PC];
        MA = PC & 07777;            // 20150315: MA trails PC on FP
        PC = (PC + 1) & 07777;          // increment PC
        swExam=1;               // avoid repeat
    }
}
if (swExam==1)
    if ((switchstatus[2] & SS2_EXAM)!=0)        // EXAM switch deactivated
        swExam=0;               // reset 'avoid repeat' indicator


// do what needs to be done in STOP mode:
if (swStop==1)
{
    setleds(PC, MA, M[MA] , IR, LAC, MQ, IF, DF, 0);        // note M[MA] used in this call, not MB
    sim_interval = sim_interval - 1;                        // otherwise, CTRL-E will never be acted upon in stop mode
                                                            // WARNING: THIS MAY LEAD TO TROUBLE. MAYBE?
    goto skip;                  // a goto is period correct methinks
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */


    if (int_req > INT_PENDING) {                        /* interrupt? */
        int_req = int_req & ~INT_ION;                   /* interrupts off */
        SF = (UF << 6) | (IF >> 9) | (DF >> 12);        /* form save field */
        IF = IB = DF = UF = UB = 0;                     /* clear mem ext */
        PCQ_ENTRY;                                      /* save old PC */
        M[0] = PC;                                      /* save PC in 0 */
        PC = 1;                                         /* fetch next from 1 */
        }

    MA = IF | PC;                                       /* form PC */
    if (sim_brk_summ &&
        sim_brk_test (MA, (1u << SIM_BKPT_V_SPC) | SWMASK ('E'))) { /* breakpoint? */
        reason = STOP_IBKPT;                            /* stop simulation */
        break;
        }

    IR = M[MA];                                         /* fetch instruction */

//PC increment was moved down before, bad idea? now is where it originally was.
    setleds(PC, MA, M[MA], IR, LAC, MQ, IF, DF, 0); // State=0:Fetch

    int_req = int_req | INT_NO_ION_PENDING;             /* clear ION delay */
    sim_interval = sim_interval - 1;


/* ---PiDP add--------------------------------------------------------------------------------------------- */

if  (pidp8i_gpio_present && (switchstatus[2] & SS2_STOP)==0)        // STOP switch activated
{   swStop = 1;
    goto skip;
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */

//--------------- moved to here:
//no longer    PC = (PC + 1) & 07777;                              /* increment PC */
//---------------


/* ---PiDP add--------------------------------------------------------------------------------------------- */
contPoint:  ;   // goto here if CONT has been pressed to finish current instruction

// SING_STEP: swStop=0 if we're here. If SingStep then this time, let it go but trigger a stop on the next pass

if (pidp8i_gpio_present && (switchstatus[2] & SS2_S_INST)==0)       // SING_INST switch activated
{   if (swSingStep==0)      // allow it this time,
        swSingStep=1;       // but note to block it next time!
    else                // else: this is the next time...
    {   swSingStep=0;       // reset flipflop
        swStop=1;       // and do what you do when STOP is pressed.
        goto skip;
    }
}

/* ---PiDP end---------------------------------------------------------------------------------------------- */

    PC = (PC + 1) & 07777;                              /* increment PC */

/* Instruction decoding.
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663

   Autoindex calculations always occur within the same field as the
   instruction fetch.  The field must exist; otherwise, the instruction
   fetched would be 0000, and indirect addressing could not occur.

   Note that MA contains IF'PC.
*/

/* --------------------------------------------------------------------------------------------------------- */

/* --------------------------------------------------------------------------------------------------------- */


    if (hst_lnt) {                                      /* history enabled? */
        int32 ea;

        hst_p = (hst_p + 1);                            /* next entry */
        if (hst_p >= hst_lnt)
            hst_p = 0;







<
<
<
<
<







632
633
634
635
636
637
638





639
640
641
642
643
644
645

   Autoindex calculations always occur within the same field as the
   instruction fetch.  The field must exist; otherwise, the instruction
   fetched would be 0000, and indirect addressing could not occur.

   Note that MA contains IF'PC.
*/






    if (hst_lnt) {                                      /* history enabled? */
        int32 ea;

        hst_p = (hst_p + 1);                            /* next entry */
        if (hst_p >= hst_lnt)
            hst_p = 0;
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
            else {
                if (IR & 04){                           /* OSR */
//--- PiDP bug fix 20150822----------------------------------------------------------------
//OSR never got updated when PDP-8 is running
//separate bug, not fixed yet: OSR should be updated by DEP and LOAD_ADD switch handlers I think
// OSR should probably be loaded with switchstatus[0] in every cycle. Doing it here is just a temp fix.
//-----------------------------------------------------------------------------------------

 		    OSR = switchstatus[0] ^ 07777;
                    LAC = LAC | OSR;
		}
                if (IR & 02)                            /* HLT */
//--- PiDP change--------------------------------------------------------------------------
//                    reason = STOP_HALT;
//-----------------------------------------------------------------------------------------
			swStop=1;	// don't step out of simulation, just do STOP
//--- end of PiDP change--------------------------------------------------------------------------

                }
            break;
            }                                           /* end if group 2 */

/* OPR group 3 standard

   MQA!MQL exchanges AC and MQ, as follows:







<
|

|


|

|

<







1165
1166
1167
1168
1169
1170
1171

1172
1173
1174
1175
1176
1177
1178
1179
1180

1181
1182
1183
1184
1185
1186
1187
            else {
                if (IR & 04){                           /* OSR */
//--- PiDP bug fix 20150822----------------------------------------------------------------
//OSR never got updated when PDP-8 is running
//separate bug, not fixed yet: OSR should be updated by DEP and LOAD_ADD switch handlers I think
// OSR should probably be loaded with switchstatus[0] in every cycle. Doing it here is just a temp fix.
//-----------------------------------------------------------------------------------------

                    OSR = switchstatus[0] ^ 07777;
                    LAC = LAC | OSR;
                    }
                if (IR & 02)                            /* HLT */
//--- PiDP change--------------------------------------------------------------------------
//                  reason = STOP_HALT;
//-----------------------------------------------------------------------------------------
                    swStop=1;   // don't step out of simulation, just do STOP
//--- end of PiDP change--------------------------------------------------------------------------

                }
            break;
            }                                           /* end if group 2 */

/* OPR group 3 standard

   MQA!MQL exchanges AC and MQ, as follows:
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681

        default:                                        /* I/O device */
            if (dev_tab[device]) {                      /* dev present? */

/* --------------------------------------------------------------------------------------------------------- */
// Any other device will trigger IOP --> light pause:
/* --------------------------------------------------------------------------------------------------------- */
		setleds(PC, MA, MB, IR, LAC, MQ, IF, DF, 2); // State 2:Pause
                iot_data = dev_tab[device] (IR, iot_data);
                LAC = (LAC & 010000) | (iot_data & 07777);
                if (iot_data & IOT_SKP)
                    PC = (PC + 1) & 07777;
/* --------------------------------------------------------------------------------------------------------- */
		else
		{
// simh does not distinguish between the various Data Break types.
// WC, CA and Break are lit up jointly on the PiDP. Although this can be improved upon.

//ledstatus[5] |= 1<<0; // set WC led
//ledstatus[6] |= 1<<11; // set CA led
//ledstatus[6] |= 1<<10; // set Break led
		}
/* --------------------------------------------------------------------------------------------------------- */

                if (iot_data >= IOT_REASON)
                    reason = iot_data >> IOT_V_REASON;
                }
            else reason = stop_inst;                    /* stop on flag */
            break;
            }                                           /* end switch device */
/* --------------------------------------------------------------------------------------------------------- */
//ledstatus[5] &= ~(1<<0); // clear WC led
//ledstatus[6] &= ~(1<<11); // clear CA led
//ledstatus[6] &= ~(1<<10); // clear Break led
/* --------------------------------------------------------------------------------------------------------- */
        break;                                          /* end case IOT */
        }                                               /* end switch opcode */

/* ------------------------------------------------------------------------- */

	if (IR<05000)
		setleds(PC, MA, MB, IR, LAC, MQ, IF, DF, 1); // State 1:Execute

/* ------------------------------------------------------------------------- */


/* ------------------------------------------------------------------------- */
skip:	;	// goto label
/* ------------------------------------------------------------------------- */

    }                                                   /* end while */

/* Simulation halted */

saved_PC = IF | (PC & 07777);                           /* save copies */







|





|
|






|


















|
|





|







1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661

        default:                                        /* I/O device */
            if (dev_tab[device]) {                      /* dev present? */

/* --------------------------------------------------------------------------------------------------------- */
// Any other device will trigger IOP --> light pause:
/* --------------------------------------------------------------------------------------------------------- */
        setleds(PC, MA, MB, IR, LAC, MQ, IF, DF, 2); // State 2:Pause
                iot_data = dev_tab[device] (IR, iot_data);
                LAC = (LAC & 010000) | (iot_data & 07777);
                if (iot_data & IOT_SKP)
                    PC = (PC + 1) & 07777;
/* --------------------------------------------------------------------------------------------------------- */
        else
        {
// simh does not distinguish between the various Data Break types.
// WC, CA and Break are lit up jointly on the PiDP. Although this can be improved upon.

//ledstatus[5] |= 1<<0; // set WC led
//ledstatus[6] |= 1<<11; // set CA led
//ledstatus[6] |= 1<<10; // set Break led
        }
/* --------------------------------------------------------------------------------------------------------- */

                if (iot_data >= IOT_REASON)
                    reason = iot_data >> IOT_V_REASON;
                }
            else reason = stop_inst;                    /* stop on flag */
            break;
            }                                           /* end switch device */
/* --------------------------------------------------------------------------------------------------------- */
//ledstatus[5] &= ~(1<<0); // clear WC led
//ledstatus[6] &= ~(1<<11); // clear CA led
//ledstatus[6] &= ~(1<<10); // clear Break led
/* --------------------------------------------------------------------------------------------------------- */
        break;                                          /* end case IOT */
        }                                               /* end switch opcode */

/* ------------------------------------------------------------------------- */

    if (IR<05000)
        setleds(PC, MA, MB, IR, LAC, MQ, IF, DF, 1); // State 1:Execute

/* ------------------------------------------------------------------------- */


/* ------------------------------------------------------------------------- */
skip:   ;   // goto label
/* ------------------------------------------------------------------------- */

    }                                                   /* end while */

/* Simulation halted */

saved_PC = IF | (PC & 07777);                           /* save copies */
1693
1694
1695
1696
1697
1698
1699

1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711

1712
1713
1714
1715
1716
1717
1718
int_req = (int_req & ~INT_ION) | INT_NO_CIF_PENDING;
saved_DF = IB = saved_PC & 070000;
UF = UB = gtf = emode = 0;
pcq_r = find_reg ("PCQ", NULL, dptr);
if (pcq_r)
    pcq_r->qptr = 0;
else return SCPE_IERR;

sim_brk_types = sim_brk_dflt = SWMASK ('E');
return SCPE_OK;
}

/* Set PC for boot (PC<14:12> will typically be 0) */

void cpu_set_bootpc (int32 pc)
{
saved_PC = pc;                                          /* set PC, IF */
saved_DF = IB = pc & 070000;                            /* set IB, DF */
return;
}

/* Memory examine */

t_stat cpu_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw)
{
if (addr >= MEMSIZE)
    return SCPE_NXM;
if (vptr != NULL)







>
|











>







1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
int_req = (int_req & ~INT_ION) | INT_NO_CIF_PENDING;
saved_DF = IB = saved_PC & 070000;
UF = UB = gtf = emode = 0;
pcq_r = find_reg ("PCQ", NULL, dptr);
if (pcq_r)
    pcq_r->qptr = 0;
else return SCPE_IERR;
sim_brk_types = SWMASK ('E') | SWMASK('I');
sim_brk_dflt = SWMASK ('E');
return SCPE_OK;
}

/* Set PC for boot (PC<14:12> will typically be 0) */

void cpu_set_bootpc (int32 pc)
{
saved_PC = pc;                                          /* set PC, IF */
saved_DF = IB = pc & 070000;                            /* set IB, DF */
return;
}

/* Memory examine */

t_stat cpu_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw)
{
if (addr >= MEMSIZE)
    return SCPE_NXM;
if (vptr != NULL)
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
    return SCPE_NXM;
M[addr] = val & 07777;
return SCPE_OK;
}

/* Memory size change */

t_stat cpu_set_size (UNIT *uptr, int32 val, char *cptr, void *desc)
{
int32 mc = 0;
uint32 i;

if ((val <= 0) || (val > MAXMEMSIZE) || ((val & 07777) != 0))
    return SCPE_ARG;
for (i = val; i < MEMSIZE; i++)
    mc = mc | M[i];
if ((mc != 0) && (!get_yn ("Really truncate memory [N]?", FALSE)))
    return SCPE_OK;
MEMSIZE = val;
for (i = MEMSIZE; i < MAXMEMSIZE; i++)
    M[i] = 0;
return SCPE_OK;
}

/* Change device number for a device */

t_stat set_dev (UNIT *uptr, int32 val, char *cptr, void *desc)
{
DEVICE *dptr;
DIB *dibp;
uint32 newdev;
t_stat r;

if (cptr == NULL)







|


















|







1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
    return SCPE_NXM;
M[addr] = val & 07777;
return SCPE_OK;
}

/* Memory size change */

t_stat cpu_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 mc = 0;
uint32 i;

if ((val <= 0) || (val > MAXMEMSIZE) || ((val & 07777) != 0))
    return SCPE_ARG;
for (i = val; i < MEMSIZE; i++)
    mc = mc | M[i];
if ((mc != 0) && (!get_yn ("Really truncate memory [N]?", FALSE)))
    return SCPE_OK;
MEMSIZE = val;
for (i = MEMSIZE; i < MAXMEMSIZE; i++)
    M[i] = 0;
return SCPE_OK;
}

/* Change device number for a device */

t_stat set_dev (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
DEVICE *dptr;
DIB *dibp;
uint32 newdev;
t_stat r;

if (cptr == NULL)
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
    return r;
dibp->dev = newdev;                                     /* store */
return SCPE_OK;
}

/* Show device number for a device */

t_stat show_dev (FILE *st, UNIT *uptr, int32 val, void *desc)
{
DEVICE *dptr;
DIB *dibp;

if (uptr == NULL)
    return SCPE_IERR;
dptr = find_dev_from_unit (uptr);







|







1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
    return r;
dibp->dev = newdev;                                     /* store */
return SCPE_OK;
}

/* Show device number for a device */

t_stat show_dev (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
DEVICE *dptr;
DIB *dibp;

if (uptr == NULL)
    return SCPE_IERR;
dptr = find_dev_from_unit (uptr);
1817
1818
1819
1820
1821
1822
1823


1824
1825
1826
1827
1828









1829
1830
1831
1832
1833
1834
1835
1836

1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
for (i = 0; i < DEV_MAX; i++)                           /* clr table */
    dev_tab[i] = NULL;
for (i = 0; i < ((uint32) sizeof (std_dev)); i++)       /* std entries */
    dev_tab[std_dev[i]] = &bad_dev;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {     /* add devices */
    dibp = (DIB *) dptr->ctxt;                          /* get DIB */
    if (dibp && !(dptr->flags & DEV_DIS)) {             /* enabled? */


        for (j = 0; j < dibp->num; j++) {               /* loop thru disp */
            if (dibp->dsp[j]) {                         /* any dispatch? */
                if (dev_tab[dibp->dev + j]) {           /* already filled? */
                    printf ("%s device number conflict at %02o\n",
                            sim_dname (dptr), dibp->dev + j);









                    if (sim_log)
                        fprintf (sim_log, "%s device number conflict at %02o\n",
                                 sim_dname (dptr), dibp->dev + j);
                     return TRUE;
                    }
                dev_tab[dibp->dev + j] = dibp->dsp[j];  /* fill */
                }                                       /* end if dsp */
            }                                           /* end for j */

        }                                               /* end if enb */
    }                                                   /* end for i */
return FALSE;
}

/* Set history */

t_stat cpu_set_hist (UNIT *uptr, int32 val, char *cptr, void *desc)
{
int32 i, lnt;
t_stat r;

if (cptr == NULL) {
    for (i = 0; i < hst_lnt; i++)
        hst[i].pc = 0;







>
>
|
|
|
|

>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
>







|







1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
for (i = 0; i < DEV_MAX; i++)                           /* clr table */
    dev_tab[i] = NULL;
for (i = 0; i < ((uint32) sizeof (std_dev)); i++)       /* std entries */
    dev_tab[std_dev[i]] = &bad_dev;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {     /* add devices */
    dibp = (DIB *) dptr->ctxt;                          /* get DIB */
    if (dibp && !(dptr->flags & DEV_DIS)) {             /* enabled? */
        if (dibp->dsp_tbl) {                            /* dispatch table? */
            DIB_DSP *dspp = dibp->dsp_tbl;              /* set ptr */
            for (j = 0; j < dibp->num; j++, dspp++) {   /* loop thru tbl */
                if (dspp->dsp) {                        /* any dispatch? */
                    if (dev_tab[dspp->dev]) {           /* already filled? */
                        sim_printf ("%s device number conflict at %02o\n",
                            sim_dname (dptr), dibp->dev + j);
                        return TRUE;
                        }
                    dev_tab[dspp->dev] = dspp->dsp;     /* fill */
                    }                                   /* end if dsp */
                }                                       /* end for j */
            }                                           /* end if dsp_tbl */
        else {                                          /* inline dispatches */
            for (j = 0; j < dibp->num; j++) {           /* loop thru disp */
                if (dibp->dsp[j]) {                     /* any dispatch? */
                    if (dev_tab[dibp->dev + j]) {       /* already filled? */
                        sim_printf ("%s device number conflict at %02o\n",
                            sim_dname (dptr), dibp->dev + j);
                        return TRUE;
                        }
                    dev_tab[dibp->dev + j] = dibp->dsp[j]; /* fill */
                    }                                   /* end if dsp */
                }                                       /* end for j */
            }                                           /* end else */
        }                                               /* end if enb */
    }                                                   /* end for i */
return FALSE;
}

/* Set history */

t_stat cpu_set_hist (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 i, lnt;
t_stat r;

if (cptr == NULL) {
    for (i = 0; i < hst_lnt; i++)
        hst[i].pc = 0;
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
    hst_lnt = lnt;
    }
return SCPE_OK;
}

/* Show history */

t_stat cpu_show_hist (FILE *st, UNIT *uptr, int32 val, void *desc)
{
int32 l, k, di, lnt;
char *cptr = (char *) desc;
t_stat r;
t_value sim_eval;
InstHistory *h;
extern t_stat fprint_sym (FILE *ofile, t_addr addr, t_value *val,
    UNIT *uptr, int32 sw);

if (hst_lnt == 0)                                       /* enabled? */
    return SCPE_NOFNC;
if (cptr) {
    lnt = (int32) get_uint (cptr, 10, hst_lnt, &r);
    if ((r != SCPE_OK) || (lnt == 0))
        return SCPE_ARG;







|


|



<
<







1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875


1876
1877
1878
1879
1880
1881
1882
    hst_lnt = lnt;
    }
return SCPE_OK;
}

/* Show history */

t_stat cpu_show_hist (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
int32 l, k, di, lnt;
const char *cptr = (const char *) desc;
t_stat r;
t_value sim_eval;
InstHistory *h;



if (hst_lnt == 0)                                       /* enabled? */
    return SCPE_NOFNC;
if (cptr) {
    lnt = (int32) get_uint (cptr, 10, hst_lnt, &r);
    if ((r != SCPE_OK) || (lnt == 0))
        return SCPE_ARG;
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
/* ------------------------------------------------------------------------------------ */
uint32 tempLeds=0;
void setleds(uint32 sPC, uint32 sMA, uint16 sMB, uint16 sIR, int32 sLAC, int32 sMQ, int32 sIF, int32 sDF, int32 sTT)
{
int row,col,msk,m;
float *p;

	if (++lctr<1049)
	 return;
	lctr=0;
	//printf("%o,%d\r\n",sPC,sTT);

	ledstatus[0] = (uint32) sPC;
	ledstatus[1] = (uint32) sMA;
	ledstatus[2] = (uint32) sMB;
	ledstatus[3] = (uint32) sLAC;
	ledstatus[4] = (uint32) sMQ;

	// instruction leds: decode instruction in memory (could also be found in IR)
	//this *should* be found in IR, methinks. Just from memory is possibly problematic

//	tempLeds = ledstatus[5] & 12; // preserve value of fetch/execute handled in main loop
//	tempLeds = ledstatus[5] & 13; // preserve value of fetch/execute/WC handled in main loop
	tempLeds = 0;		      // Clear all lights
	if (sTT==0) tempLeds |= 1<<3; // set fetch
	if (sTT==1) tempLeds |= 1<<2; // set execute

	switch((sIR & 0xE00) >> 9)
	{
		case 0:	tempLeds+=(1<<11); break;		// 000 AND
		case 1:	tempLeds+=(1<<10); break;		// 001 TAD
		case 2:	tempLeds+=(1<<9); break;		// 010 DCA
		case 3:	tempLeds+=(1<<8); break;		// 011 ISZ
		case 4:	tempLeds+=(1<<7); break;		// 100 JMS
		case 5:	tempLeds+=(1<<6); break;		// 101 JMP
		case 6:	tempLeds+=(1<<5); break;		// 110 IOT
		case 7: tempLeds+=(1<<4); break;		// 111-0 and 111-1 OPR group 1 & 2
		default: printf("instruction error in multiplexer");	// debug only, remove
	}

	if ( ((sIR & 0xE00) >> 9) <= 5)	// <=5: all memory reference instructions
		if ((sIR & 0x100) != 0)	// if fourth bit is set, this is indirect addressing, so...
		tempLeds += (1<<1);		// ...light defer

	ledstatus[5]=tempLeds;

	tempLeds = 0; //ledstatus[6]; // want to preserve value of some leds set in main loop
//	tempLeds = ledstatus[6] & 0xd00; // want to preserve value of CA/break/pause set in main loop
	if (sTT==2) tempLeds |= 1<<8; // set pause led

							// CAddr led - handled in main loop
							// Break led - handled in main loop
	tempLeds |= ((int_req & INT_ION)==0?0:1)<<9;	// ION led
							// Pause led - handled in main loop
	if (swStop==0)	tempLeds |= (1<<7);		// RUN led
	ledstatus[6]=tempLeds;

	// DF & IF in simh live in the 3 bits of octal digit #5...
	tempLeds = (uint32) (sDF>>3); // shift down from oct digit 5 to HW cols 1-3 (SW col[3-5])
	tempLeds += (uint32) (sIF>>6); // shift down from oct digit 5 to HW cols 4-6 (SW col[9-11]
	// Link
	tempLeds += (uint32) ((sLAC & 010000)>>7); // shift down from bit 12 to bit 8

	ledstatus[7]=tempLeds;

	for (row=m=0,p=brtval;row<8;row++)
		for (col=0,msk=1;col<12;col++,p++,m++,msk=msk<<1) {
			if (ledstatus[row]&msk) (*p)+=(32.0-*p)*DECAY;
				else (*p)-=*p*DECAY;
		}

}
/* ------------------------------------------------------------------------------------ */

//--- PiDP add -------------------------------------------------------------

int mountUSBStickFile(int devNo, char *devCode, char *sPath)
{
	char	sUSBPath[CBUFSIZE];		// will be "/media/usb0" etc
	char	sFoundFile[CBUFSIZE];		// path & name of file that is found
	char	fileExtension[4];		// will be ".RX" etc
	FILE 	*fp;
	DIR 	*pDir;
	struct 	dirent *pDirent;
	int 	i,j, alreadyMounted;

	fileExtension[0]='.';			// extension starts with a .
	strncpy(&fileExtension[1], devCode, 2);	// extension is PT, RX, RL etc
	fileExtension[2]=0;			// don't want device number
	sFoundFile[0]=0;			// empty string, no file found yet

	// if mounting another image to a device, clear the current file from the mountlist:
	mountedFiles[devNo][0]=0x00;

	for (i=0;i<8;i++)				// search all 8 USB mount points
	{
		sprintf(sUSBPath,"/media/usb%d",i);	// usb sticks are numbered 0..7
//printf("1- %s\r\n", sUSBPath);
		pDir = opendir(sUSBPath);
		if (pDir==NULL) 			// that means usbmount not installed?
		{	printf("\r\nCannot open usb%d directory\r\n", i); return 1;	}

		while ((pDirent = readdir(pDir)) != NULL) // search all files in directory
		{
			if (strstr(pDirent->d_name,fileExtension))
			{
				sprintf(sPath, "%s/%s", sUSBPath, pDirent->d_name);
				alreadyMounted=0;
				for (j=0;j<7;j++)
				{
					if (strncmp(mountedFiles[j],sPath, CBUFSIZE)==0)
						alreadyMounted=1;
//printf("   >%s %d\r\n", mountedFiles[j], strncmp(mountedFiles[j],sPath, CBUFSIZE));

				}
				if (alreadyMounted==0)
				{
					strcpy(sFoundFile, sPath);
//printf("2-%s\r\n", sFoundFile);
					break;		// break out of while loop
				}
			}
		}
		closedir (pDir);

		if (sFoundFile[0]!=0)
			break;
	}

//printf("3-%s\r\n", sFoundFile);

	if (sFoundFile[0]==0x00)			// no file found, exit
	{	printf("\r\nNo unmounted %s file found\r\n", devCode);	return 1;	}

	fp = fopen(sFoundFile, "r");			// check file is OK
	if (fp==NULL)
	{	printf("\r\nError opening file %s\r\n", sFoundFile);	return 1;	}
	fclose (fp);


	sprintf(sPath,"%s %s", devCode, sFoundFile);	// print cmd string
//	printf("\r\nMounting %s\r\n", sPath);

	if(attach_cmd ((int32) 0, xcptr)==SCPE_OK)		// issue simh attach command
	{	strcpy(mountedFiles[devNo], sFoundFile);		// add file to mount list
printf("\r\nMounted %s %s\r\n", devCode, mountedFiles[devNo]);
	}
	else
	{	printf("\r\nSimH error mounting %s\r\n", devCode);	return 1;	}

	return 0;
}








|
|
|
|

|
|
|
|
|

|
|

|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|

|
|
|

|

|
|
|

|
|
|
|
|
|

|
|
|
|
|

|

|
|
|
|
|








|
|
|
|
|
|
|

|
|
|
|

|
|

|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|

|
|
|

|

|
|

|
|
|
|


|
|

|
|
|
|
|
|

|


1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
/* ------------------------------------------------------------------------------------ */
uint32 tempLeds=0;
void setleds(uint32 sPC, uint32 sMA, uint16 sMB, uint16 sIR, int32 sLAC, int32 sMQ, int32 sIF, int32 sDF, int32 sTT)
{
int row,col,msk,m;
float *p;

    if (++lctr<1049)
     return;
    lctr=0;
    //printf("%o,%d\r\n",sPC,sTT);

    ledstatus[0] = (uint32) sPC;
    ledstatus[1] = (uint32) sMA;
    ledstatus[2] = (uint32) sMB;
    ledstatus[3] = (uint32) sLAC;
    ledstatus[4] = (uint32) sMQ;

    // instruction leds: decode instruction in memory (could also be found in IR)
    //this *should* be found in IR, methinks. Just from memory is possibly problematic

//  tempLeds = ledstatus[5] & 12; // preserve value of fetch/execute handled in main loop
//  tempLeds = ledstatus[5] & 13; // preserve value of fetch/execute/WC handled in main loop
    tempLeds = 0;             // Clear all lights
    if (sTT==0) tempLeds |= 1<<3; // set fetch
    if (sTT==1) tempLeds |= 1<<2; // set execute

    switch((sIR & 0xE00) >> 9)
    {
        case 0: tempLeds+=(1<<11); break;       // 000 AND
        case 1: tempLeds+=(1<<10); break;       // 001 TAD
        case 2: tempLeds+=(1<<9); break;        // 010 DCA
        case 3: tempLeds+=(1<<8); break;        // 011 ISZ
        case 4: tempLeds+=(1<<7); break;        // 100 JMS
        case 5: tempLeds+=(1<<6); break;        // 101 JMP
        case 6: tempLeds+=(1<<5); break;        // 110 IOT
        case 7: tempLeds+=(1<<4); break;        // 111-0 and 111-1 OPR group 1 & 2
        default: printf("instruction error in multiplexer");    // debug only, remove
    }

    if ( ((sIR & 0xE00) >> 9) <= 5) // <=5: all memory reference instructions
        if ((sIR & 0x100) != 0) // if fourth bit is set, this is indirect addressing, so...
        tempLeds += (1<<1);     // ...light defer

    ledstatus[5]=tempLeds;

    tempLeds = 0; //ledstatus[6]; // want to preserve value of some leds set in main loop
//  tempLeds = ledstatus[6] & 0xd00; // want to preserve value of CA/break/pause set in main loop
    if (sTT==2) tempLeds |= 1<<8; // set pause led

                            // CAddr led - handled in main loop
                            // Break led - handled in main loop
    tempLeds |= ((int_req & INT_ION)==0?0:1)<<9;    // ION led
                            // Pause led - handled in main loop
    if (swStop==0)  tempLeds |= (1<<7);     // RUN led
    ledstatus[6]=tempLeds;

    // DF & IF in simh live in the 3 bits of octal digit #5...
    tempLeds = (uint32) (sDF>>3); // shift down from oct digit 5 to HW cols 1-3 (SW col[3-5])
    tempLeds += (uint32) (sIF>>6); // shift down from oct digit 5 to HW cols 4-6 (SW col[9-11]
    // Link
    tempLeds += (uint32) ((sLAC & 010000)>>7); // shift down from bit 12 to bit 8

    ledstatus[7]=tempLeds;

    for (row=m=0,p=brtval;row<8;row++)
        for (col=0,msk=1;col<12;col++,p++,m++,msk=msk<<1) {
            if (ledstatus[row]&msk) (*p)+=(32.0-*p)*DECAY;
                else (*p)-=*p*DECAY;
        }

}
/* ------------------------------------------------------------------------------------ */

//--- PiDP add -------------------------------------------------------------

int mountUSBStickFile(int devNo, char *devCode, char *sPath)
{
    char    sUSBPath[CBUFSIZE];     // will be "/media/usb0" etc
    char    sFoundFile[CBUFSIZE];       // path & name of file that is found
    char    fileExtension[4];       // will be ".RX" etc
    FILE    *fp;
    DIR     *pDir;
    struct  dirent *pDirent;
    int     i,j, alreadyMounted;

    fileExtension[0]='.';           // extension starts with a .
    strncpy(&fileExtension[1], devCode, 2); // extension is PT, RX, RL etc
    fileExtension[2]=0;         // don't want device number
    sFoundFile[0]=0;            // empty string, no file found yet

    // if mounting another image to a device, clear the current file from the mountlist:
    mountedFiles[devNo][0]=0x00;

    for (i=0;i<8;i++)               // search all 8 USB mount points
    {
        sprintf(sUSBPath,"/media/usb%d",i); // usb sticks are numbered 0..7
        //printf("1- %s\r\n", sUSBPath);
        pDir = opendir(sUSBPath);
        if (pDir==NULL)             // that means usbmount not installed?
        {   printf("\r\nCannot open usb%d directory\r\n", i); return 1; }

        while ((pDirent = readdir(pDir)) != NULL) // search all files in directory
        {
            if (strstr(pDirent->d_name,fileExtension))
            {
                sprintf(sPath, "%s/%s", sUSBPath, pDirent->d_name);
                alreadyMounted=0;
                for (j=0;j<7;j++)
                {
                    if (strncmp(mountedFiles[j],sPath, CBUFSIZE)==0)
                        alreadyMounted=1;
        //printf("   >%s %d\r\n", mountedFiles[j], strncmp(mountedFiles[j],sPath, CBUFSIZE));

                }
                if (alreadyMounted==0)
                {
                    strcpy(sFoundFile, sPath);
        //printf("2-%s\r\n", sFoundFile);
                    break;      // break out of while loop
                }
            }
        }
        closedir (pDir);

        if (sFoundFile[0]!=0)
            break;
    }

    //printf("3-%s\r\n", sFoundFile);

    if (sFoundFile[0]==0x00)            // no file found, exit
    {   printf("\r\nNo unmounted %s file found\r\n", devCode);  return 1;   }

    fp = fopen(sFoundFile, "r");            // check file is OK
    if (fp==NULL)
    {   printf("\r\nError opening file %s\r\n", sFoundFile);    return 1;   }
    fclose (fp);


    sprintf(sPath,"%s %s", devCode, sFoundFile);    // print cmd string
//  printf("\r\nMounting %s\r\n", sPath);

    if(attach_cmd ((int32) 0, xcptr)==SCPE_OK)      // issue simh attach command
    {   strcpy(mountedFiles[devNo], sFoundFile);        // add file to mount list
        printf("\r\nMounted %s %s\r\n", devCode, mountedFiles[devNo]);
    }
    else
    {   printf("\r\nSimH error mounting %s\r\n", devCode);  return 1;   }

    return 0;
}

Changes to src/PDP8/pdp8_ct.c.
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
uint32 ct_stopioe = 1;                                  /* stop on error */
uint8 *ct_xb = NULL;                                    /* transfer buffer */
static uint8 ct_fnc_tab[SRA_M_FNC + 1] = {
    OP_FWD,        0     , OP_WRI|OP_FWD, OP_REV,
    OP_WRI|OP_FWD, OP_REV, 0,             OP_FWD
    };

DEVICE ct_dev;
int32 ct70 (int32 IR, int32 AC);
t_stat ct_svc (UNIT *uptr);
t_stat ct_reset (DEVICE *dptr);
t_stat ct_attach (UNIT *uptr, char *cptr);
t_stat ct_detach (UNIT *uptr);
t_stat ct_boot (int32 unitno, DEVICE *dptr);
uint32 ct_updsta (UNIT *uptr);
int32 ct_go_start (int32 AC);
int32 ct_go_cont (UNIT *uptr, int32 AC);
t_stat ct_map_err (UNIT *uptr, t_stat st);
UNIT *ct_busy (void);







<



|







152
153
154
155
156
157
158

159
160
161
162
163
164
165
166
167
168
169
uint32 ct_stopioe = 1;                                  /* stop on error */
uint8 *ct_xb = NULL;                                    /* transfer buffer */
static uint8 ct_fnc_tab[SRA_M_FNC + 1] = {
    OP_FWD,        0     , OP_WRI|OP_FWD, OP_REV,
    OP_WRI|OP_FWD, OP_REV, 0,             OP_FWD
    };


int32 ct70 (int32 IR, int32 AC);
t_stat ct_svc (UNIT *uptr);
t_stat ct_reset (DEVICE *dptr);
t_stat ct_attach (UNIT *uptr, CONST char *cptr);
t_stat ct_detach (UNIT *uptr);
t_stat ct_boot (int32 unitno, DEVICE *dptr);
uint32 ct_updsta (UNIT *uptr);
int32 ct_go_start (int32 AC);
int32 ct_go_cont (UNIT *uptr, int32 AC);
t_stat ct_map_err (UNIT *uptr, t_stat st);
UNIT *ct_busy (void);
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

UNIT ct_unit[] = {
    { UDATA (&ct_svc, UNIT_ATTABLE+UNIT_ROABLE, CT_SIZE) },
    { UDATA (&ct_svc, UNIT_ATTABLE+UNIT_ROABLE, CT_SIZE) },
    };

REG ct_reg[] = {
    { ORDATA (CTSRA, ct_sra, 8) },
    { ORDATA (CTSRB, ct_srb, 8) },
    { ORDATA (CTDB, ct_db, 8) },
    { FLDATA (CTDF, ct_df, 0) },
    { FLDATA (RDY, ct_srb, 0) },
    { FLDATA (WLE, ct_srb, 8) },
    { FLDATA (WRITE, ct_write, 0) },
    { FLDATA (INT, int_req, INT_V_CT) },
    { DRDATA (BPTR, ct_bptr, 17) },
    { DRDATA (BLNT, ct_blnt, 17) },
    { DRDATA (STIME, ct_stime, 24), PV_LEFT + REG_NZ },
    { DRDATA (CTIME, ct_ctime, 24), PV_LEFT + REG_NZ },
    { FLDATA (STOP_IOE, ct_stopioe, 0) },
    { URDATA (UFNC, ct_unit[0].FNC, 8, 4, 0, CT_NUMDR, 0), REG_HRO },
    { URDATA (UST, ct_unit[0].UST, 8, 2, 0, CT_NUMDR, 0), REG_HRO },
    { URDATA (POS, ct_unit[0].pos, 10, T_ADDR_W, 0,
              CT_NUMDR, PV_LEFT | REG_RO) },
    { FLDATA (DEVNUM, ct_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB ct_mod[] = {
    { MTUF_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { MTUF_WLK, MTUF_WLK, "write locked", "LOCKED", NULL }, 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

UNIT ct_unit[] = {
    { UDATA (&ct_svc, UNIT_ATTABLE+UNIT_ROABLE, CT_SIZE) },
    { UDATA (&ct_svc, UNIT_ATTABLE+UNIT_ROABLE, CT_SIZE) },
    };

REG ct_reg[] = {
    { ORDATAD (CTSRA, ct_sra, 8, "status register A") },
    { ORDATAD (CTSRB, ct_srb, 8, "status register B") },
    { ORDATAD (CTDB, ct_db, 8, "data buffer") },
    { FLDATAD (CTDF, ct_df, 0, "data flag") },
    { FLDATAD (RDY, ct_srb, 0, "ready flag") },
    { FLDATAD (WLE, ct_srb, 8, "write lock error") },
    { FLDATAD (WRITE, ct_write, 0, "TA60 write operation flag") },
    { FLDATAD (INT, int_req, INT_V_CT, "interrupt request") },
    { DRDATAD (BPTR, ct_bptr, 17, "buffer pointer") },
    { DRDATAD (BLNT, ct_blnt, 17, "buffer length") },
    { DRDATAD (STIME, ct_stime, 24, "operation start time"), PV_LEFT + REG_NZ },
    { DRDATAD (CTIME, ct_ctime, 24, "character latency"), PV_LEFT + REG_NZ },
    { FLDATAD (STOP_IOE, ct_stopioe, 0, "stop on I/O errors flag") },
    { URDATA (UFNC, ct_unit[0].FNC, 8, 4, 0, CT_NUMDR, REG_HRO) },
    { URDATA (UST, ct_unit[0].UST, 8, 2, 0, CT_NUMDR, REG_HRO) },
    { URDATAD (POS, ct_unit[0].pos, 10, T_ADDR_W, 0,
              CT_NUMDR, PV_LEFT | REG_RO, "position, units 0-1") },
    { FLDATA (DEVNUM, ct_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB ct_mod[] = {
    { MTUF_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { MTUF_WLK, MTUF_WLK, "write locked", "LOCKED", NULL }, 
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
if (ct_xb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat ct_attach (UNIT *uptr, char *cptr)
{
t_stat r;

r = sim_tape_attach (uptr, cptr);
if (r != SCPE_OK)
    return r;
ct_updsta (NULL);







|







645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
if (ct_xb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat ct_attach (UNIT *uptr, CONST char *cptr)
{
t_stat r;

r = sim_tape_attach (uptr, cptr);
if (r != SCPE_OK)
    return r;
ct_updsta (NULL);
Changes to src/PDP8/pdp8_defs.h.
1
2
3
4
5
6
7
8
9
10
/* pdp8_defs.h: PDP-8 simulator definitions

   Copyright (c) 1993-2013, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_defs.h: PDP-8 simulator definitions

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
19
20
21
22
23
24
25

26
27
28
29
30
31
32
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.


   18-Sep-13    RMS     Added set_bootpc prototype
   18-Apr-12    RMS     Removed separate timer for additional terminals;
                        Added clock_cosched prototype
   22-May-10    RMS     Added check for 64b definitions
   21-Aug-07    RMS     Added FPP8 support
   13-Dec-06    RMS     Added TA8E support
   30-Oct-06    RMS     Added infinite loop stop







>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   18-Sep-16    RMS     Added support for 16 additional terminals
   18-Sep-13    RMS     Added set_bootpc prototype
   18-Apr-12    RMS     Removed separate timer for additional terminals;
                        Added clock_cosched prototype
   22-May-10    RMS     Added check for 64b definitions
   21-Aug-07    RMS     Added FPP8 support
   13-Dec-06    RMS     Added TA8E support
   30-Oct-06    RMS     Added infinite loop stop
83
84
85
86
87
88
89





90
91
92
93
94

95
96
97
98
99
100
101

#define TMR_CLK         0                               /* timer 0 = clock */

/* Device information block */

#define DEV_MAXBLK      8                               /* max dev block */
#define DEV_MAX         64                              /* total devices */






typedef struct {
    uint32              dev;                            /* base dev number */
    uint32              num;                            /* number of slots */
    int32               (*dsp[DEV_MAXBLK])(int32 IR, int32 dat);

    } DIB;

/* Standard device numbers */

#define DEV_PTR         001                             /* paper tape reader */
#define DEV_PTP         002                             /* paper tape punch */
#define DEV_TTI         003                             /* console input */







>
>
>
>
>





>







84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

#define TMR_CLK         0                               /* timer 0 = clock */

/* Device information block */

#define DEV_MAXBLK      8                               /* max dev block */
#define DEV_MAX         64                              /* total devices */

typedef struct {
    uint32              dev;                            /* device number */
    int32               (*dsp)(int32 IR, int32 dat);    /* dispatch */
    } DIB_DSP;

typedef struct {
    uint32              dev;                            /* base dev number */
    uint32              num;                            /* number of slots */
    int32               (*dsp[DEV_MAXBLK])(int32 IR, int32 dat);
    DIB_DSP             *dsp_tbl;                       /* optional table */
    } DIB;

/* Standard device numbers */

#define DEV_PTR         001                             /* paper tape reader */
#define DEV_PTP         002                             /* paper tape punch */
#define DEV_TTI         003                             /* console input */
110
111
112
113
114
115
116



































117
118
119
120
121
122
123
#define DEV_LPT         066                             /* line printer */
#define DEV_MT          070                             /* TM8E */
#define DEV_CT          070                             /* TA8E */
#define DEV_RK          074                             /* RK8E */
#define DEV_RX          075                             /* RX8E/RX28 */
#define DEV_DTA         076                             /* TC08 */
#define DEV_TD8E        077                             /* TD8E */




































/* Interrupt flags

   The interrupt flags consist of three groups:

   1.   Devices with individual interrupt enables.  These record
        their interrupt requests in device_done and their enables







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#define DEV_LPT         066                             /* line printer */
#define DEV_MT          070                             /* TM8E */
#define DEV_CT          070                             /* TA8E */
#define DEV_RK          074                             /* RK8E */
#define DEV_RX          075                             /* RX8E/RX28 */
#define DEV_DTA         076                             /* TC08 */
#define DEV_TD8E        077                             /* TD8E */

/* Extra PTO8/KL8JA devices */

#define DEV_TTI1        040
#define DEV_TTO1        041
#define DEV_TTI2        042
#define DEV_TTO2        043
#define DEV_TTI3        044
#define DEV_TTO3        045
#define DEV_TTI4        046
#define DEV_TTO4        047
#define DEV_TTI5        034
#define DEV_TTO5        035
#define DEV_TTI6        011
#define DEV_TTO6        012
#define DEV_TTI7        030
#define DEV_TTO7        031
#define DEV_TTI8        032
#define DEV_TTO8        033
#define DEV_TTI9        050
#define DEV_TTO9        051
#define DEV_TTI10       052
#define DEV_TTO10       053
#define DEV_TTI11       054
#define DEV_TTO11       055                             /* conflict: FPP */
#define DEV_TTI12       056                             /* conflict: FPP */
#define DEV_TTO12       057
#define DEV_TTI13       070                             /* conflict: CT, MT */
#define DEV_TTO13       071
#define DEV_TTI14       036                             /* conflict: TSC */
#define DEV_TTO14       037
#define DEV_TTI15       072
#define DEV_TTO15       073
#define DEV_TTI16       006
#define DEV_TTO16       007

/* Interrupt flags

   The interrupt flags consist of three groups:

   1.   Devices with individual interrupt enables.  These record
        their interrupt requests in device_done and their enables
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#define INT_V_LPT       (INT_V_START+0)                 /* line printer */
#define INT_V_PTP       (INT_V_START+1)                 /* tape punch */
#define INT_V_PTR       (INT_V_START+2)                 /* tape reader */
#define INT_V_TTO       (INT_V_START+3)                 /* terminal */
#define INT_V_TTI       (INT_V_START+4)                 /* keyboard */
#define INT_V_CLK       (INT_V_START+5)                 /* clock */
#define INT_V_TTO1      (INT_V_START+6)                 /* tto1 */
#define INT_V_TTO2      (INT_V_START+7)                 /* tto2 */
#define INT_V_TTO3      (INT_V_START+8)                 /* tto3 */
#define INT_V_TTO4      (INT_V_START+9)                 /* tto4 */
#define INT_V_TTI1      (INT_V_START+10)                /* tti1 */
#define INT_V_TTI2      (INT_V_START+11)                /* tti2 */
#define INT_V_TTI3      (INT_V_START+12)                /* tti3 */
#define INT_V_TTI4      (INT_V_START+13)                /* tti4 */
#define INT_V_DIRECT    (INT_V_START+14)                /* direct start */
#define INT_V_RX        (INT_V_DIRECT+0)                /* RX8E */
#define INT_V_RK        (INT_V_DIRECT+1)                /* RK8E */
#define INT_V_RF        (INT_V_DIRECT+2)                /* RF08 */
#define INT_V_DF        (INT_V_DIRECT+3)                /* DF32 */
#define INT_V_MT        (INT_V_DIRECT+4)                /* TM8E */
#define INT_V_DTA       (INT_V_DIRECT+5)                /* TC08 */







|
|
|

|
|
|







183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#define INT_V_LPT       (INT_V_START+0)                 /* line printer */
#define INT_V_PTP       (INT_V_START+1)                 /* tape punch */
#define INT_V_PTR       (INT_V_START+2)                 /* tape reader */
#define INT_V_TTO       (INT_V_START+3)                 /* terminal */
#define INT_V_TTI       (INT_V_START+4)                 /* keyboard */
#define INT_V_CLK       (INT_V_START+5)                 /* clock */
#define INT_V_TTO1      (INT_V_START+6)                 /* tto1 */
//#define INT_V_TTO2      (INT_V_START+7)                 /* tto2 */
//#define INT_V_TTO3      (INT_V_START+8)                 /* tto3 */
//#define INT_V_TTO4      (INT_V_START+9)                 /* tto4 */
#define INT_V_TTI1      (INT_V_START+10)                /* tti1 */
//#define INT_V_TTI2      (INT_V_START+11)                /* tti2 */
//#define INT_V_TTI3      (INT_V_START+12)                /* tti3 */
//#define INT_V_TTI4      (INT_V_START+13)                /* tti4 */
#define INT_V_DIRECT    (INT_V_START+14)                /* direct start */
#define INT_V_RX        (INT_V_DIRECT+0)                /* RX8E */
#define INT_V_RK        (INT_V_DIRECT+1)                /* RK8E */
#define INT_V_RF        (INT_V_DIRECT+2)                /* RF08 */
#define INT_V_DF        (INT_V_DIRECT+3)                /* DF32 */
#define INT_V_MT        (INT_V_DIRECT+4)                /* TM8E */
#define INT_V_DTA       (INT_V_DIRECT+5)                /* TC08 */
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#define INT_LPT         (1 << INT_V_LPT)
#define INT_PTP         (1 << INT_V_PTP)
#define INT_PTR         (1 << INT_V_PTR)
#define INT_TTO         (1 << INT_V_TTO)
#define INT_TTI         (1 << INT_V_TTI)
#define INT_CLK         (1 << INT_V_CLK)
#define INT_TTO1        (1 << INT_V_TTO1)
#define INT_TTO2        (1 << INT_V_TTO2)
#define INT_TTO3        (1 << INT_V_TTO3)
#define INT_TTO4        (1 << INT_V_TTO4)
#define INT_TTI1        (1 << INT_V_TTI1)
#define INT_TTI2        (1 << INT_V_TTI2)
#define INT_TTI3        (1 << INT_V_TTI3)
#define INT_TTI4        (1 << INT_V_TTI4)
#define INT_RX          (1 << INT_V_RX)
#define INT_RK          (1 << INT_V_RK)
#define INT_RF          (1 << INT_V_RF)
#define INT_DF          (1 << INT_V_DF)
#define INT_MT          (1 << INT_V_MT)
#define INT_DTA         (1 << INT_V_DTA)
#define INT_RL          (1 << INT_V_RL)
#define INT_CT          (1 << INT_V_CT)
#define INT_PWR         (1 << INT_V_PWR)
#define INT_UF          (1 << INT_V_UF)
#define INT_TSC         (1 << INT_V_TSC)
#define INT_FPP         (1 << INT_V_FPP)
#define INT_NO_ION_PENDING (1 << INT_V_NO_ION_PENDING)
#define INT_NO_CIF_PENDING (1 << INT_V_NO_CIF_PENDING)
#define INT_ION         (1 << INT_V_ION)
#define INT_DEV_ENABLE  ((1 << INT_V_DIRECT) - 1)       /* devices w/enables */
#define INT_ALL         ((1 << INT_V_OVHD) - 1)         /* all interrupts */
#define INT_INIT_ENABLE (INT_TTI+INT_TTO+INT_PTR+INT_PTP+INT_LPT) | \
                        (INT_TTI1+INT_TTI2+INT_TTI3+INT_TTI4) | \
                        (INT_TTO1+INT_TTO2+INT_TTO3+INT_TTO4)
#define INT_PENDING     (INT_ION+INT_NO_CIF_PENDING+INT_NO_ION_PENDING)
#define INT_UPDATE      ((int_req & ~INT_DEV_ENABLE) | (dev_done & int_enable))

/* Function prototypes */

t_stat set_dev (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat show_dev (FILE *st, UNIT *uptr, int32 val, void *desc);

void cpu_set_bootpc (int32 pc);

#endif







|
|
|

|
|
|


















|
<





|
|




215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

248
249
250
251
252
253
254
255
256
257
258
#define INT_LPT         (1 << INT_V_LPT)
#define INT_PTP         (1 << INT_V_PTP)
#define INT_PTR         (1 << INT_V_PTR)
#define INT_TTO         (1 << INT_V_TTO)
#define INT_TTI         (1 << INT_V_TTI)
#define INT_CLK         (1 << INT_V_CLK)
#define INT_TTO1        (1 << INT_V_TTO1)
//#define INT_TTO2        (1 << INT_V_TTO2)
//#define INT_TTO3        (1 << INT_V_TTO3)
//#define INT_TTO4        (1 << INT_V_TTO4)
#define INT_TTI1        (1 << INT_V_TTI1)
//#define INT_TTI2        (1 << INT_V_TTI2)
//#define INT_TTI3        (1 << INT_V_TTI3)
//#define INT_TTI4        (1 << INT_V_TTI4)
#define INT_RX          (1 << INT_V_RX)
#define INT_RK          (1 << INT_V_RK)
#define INT_RF          (1 << INT_V_RF)
#define INT_DF          (1 << INT_V_DF)
#define INT_MT          (1 << INT_V_MT)
#define INT_DTA         (1 << INT_V_DTA)
#define INT_RL          (1 << INT_V_RL)
#define INT_CT          (1 << INT_V_CT)
#define INT_PWR         (1 << INT_V_PWR)
#define INT_UF          (1 << INT_V_UF)
#define INT_TSC         (1 << INT_V_TSC)
#define INT_FPP         (1 << INT_V_FPP)
#define INT_NO_ION_PENDING (1 << INT_V_NO_ION_PENDING)
#define INT_NO_CIF_PENDING (1 << INT_V_NO_CIF_PENDING)
#define INT_ION         (1 << INT_V_ION)
#define INT_DEV_ENABLE  ((1 << INT_V_DIRECT) - 1)       /* devices w/enables */
#define INT_ALL         ((1 << INT_V_OVHD) - 1)         /* all interrupts */
#define INT_INIT_ENABLE (INT_TTI+INT_TTO+INT_PTR+INT_PTP+INT_LPT) | \
                        (INT_TTI1+INT_TTO1)

#define INT_PENDING     (INT_ION+INT_NO_CIF_PENDING+INT_NO_ION_PENDING)
#define INT_UPDATE      ((int_req & ~INT_DEV_ENABLE) | (dev_done & int_enable))

/* Function prototypes */

t_stat set_dev (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat show_dev (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

void cpu_set_bootpc (int32 pc);

#endif
Changes to src/PDP8/pdp8_df.c.
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
int32 df_da = 0;                                        /* disk address */
int32 df_done = 0;                                      /* done flag */
int32 df_wlk = 0;                                       /* write lock */
int32 df_time = 10;                                     /* inter-word time */
int32 df_burst = 1;                                     /* burst mode flag */
int32 df_stopioe = 1;                                   /* stop on error */

DEVICE df_dev;
int32 df60 (int32 IR, int32 AC);
int32 df61 (int32 IR, int32 AC);
int32 df62 (int32 IR, int32 AC);
t_stat df_svc (UNIT *uptr);
t_stat pcell_svc (UNIT *uptr);
t_stat df_reset (DEVICE *dptr);
t_stat df_boot (int32 unitno, DEVICE *dptr);
t_stat df_attach (UNIT *uptr, char *cptr);
t_stat df_set_size (UNIT *uptr, int32 val, char *cptr, void *desc);

/* DF32 data structures

   df_dev       RF device descriptor
   df_unit      RF unit descriptor
   pcell_unit   photocell timing unit (orphan)
   df_reg       RF register list
*/

DIB df_dib = { DEV_DF, 3, { &df60, &df61, &df62 } };

UNIT df_unit = {
    UDATA (&df_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF,
           DF_DKSIZE)
    };

REG df_reg[] = {
    { ORDATA (STA, df_sta, 12) },
    { ORDATA (DA, df_da, 12) },
    { ORDATA (WC, M[DF_WC], 12), REG_FIT },
    { ORDATA (MA, M[DF_MA], 12), REG_FIT },
    { FLDATA (DONE, df_done, 0) },
    { FLDATA (INT, int_req, INT_V_DF) },
    { ORDATA (WLS, df_wlk, 8) },
    { DRDATA (TIME, df_time, 24), REG_NZ + PV_LEFT },
    { FLDATA (BURST, df_burst, 0) },
    { FLDATA (STOP_IOE, df_stopioe, 0) },
    { DRDATA (CAPAC, df_unit.capac, 18), REG_HRO },
    { ORDATA (DEVNUM, df_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB df_mod[] = {
    { UNIT_PLAT, (0 << UNIT_V_PLAT), NULL, "1P", &df_set_size },







<







|
|

















|
|
|
|
|
|
|
|
|
|







104
105
106
107
108
109
110

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
int32 df_da = 0;                                        /* disk address */
int32 df_done = 0;                                      /* done flag */
int32 df_wlk = 0;                                       /* write lock */
int32 df_time = 10;                                     /* inter-word time */
int32 df_burst = 1;                                     /* burst mode flag */
int32 df_stopioe = 1;                                   /* stop on error */


int32 df60 (int32 IR, int32 AC);
int32 df61 (int32 IR, int32 AC);
int32 df62 (int32 IR, int32 AC);
t_stat df_svc (UNIT *uptr);
t_stat pcell_svc (UNIT *uptr);
t_stat df_reset (DEVICE *dptr);
t_stat df_boot (int32 unitno, DEVICE *dptr);
t_stat df_attach (UNIT *uptr, CONST char *cptr);
t_stat df_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc);

/* DF32 data structures

   df_dev       RF device descriptor
   df_unit      RF unit descriptor
   pcell_unit   photocell timing unit (orphan)
   df_reg       RF register list
*/

DIB df_dib = { DEV_DF, 3, { &df60, &df61, &df62 } };

UNIT df_unit = {
    UDATA (&df_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF,
           DF_DKSIZE)
    };

REG df_reg[] = {
    { ORDATAD (STA, df_sta, 12, "status, disk and memory address extension") },
    { ORDATAD (DA, df_da, 12, "low order disk address") },
    { ORDATAD (WC, M[DF_WC], 12, "word count (in memory)"), REG_FIT },
    { ORDATAD (MA, M[DF_MA], 12, "memory address (in memory)"), REG_FIT },
    { FLDATAD (DONE, df_done, 0, "device done flag") },
    { FLDATAD (INT, int_req, INT_V_DF, "interrupt pending flag") },
    { ORDATAD (WLS, df_wlk, 8, "write lock switches") },
    { DRDATAD (TIME, df_time, 24, "rotational delay, per word"), REG_NZ + PV_LEFT },
    { FLDATAD (BURST, df_burst, 0, "burst flag") },
    { FLDATAD (STOP_IOE, df_stopioe, 0, "stop on I/O error") },
    { DRDATA (CAPAC, df_unit.capac, 18), REG_HRO },
    { ORDATA (DEVNUM, df_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB df_mod[] = {
    { UNIT_PLAT, (0 << UNIT_V_PLAT), NULL, "1P", &df_set_size },
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    cpu_set_bootpc (OS8_START);
    }
return SCPE_OK;
}

/* Attach routine */

t_stat df_attach (UNIT *uptr, char *cptr)
{
uint32 p, sz;
uint32 ds_bytes = DF_DKSIZE * sizeof (int16);

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    p = (sz + ds_bytes - 1) / ds_bytes;
    if (p >= DF_NUMDK)
        p = DF_NUMDK - 1;
    uptr->flags = (uptr->flags & ~UNIT_PLAT) |
         (p << UNIT_V_PLAT);
    }
uptr->capac = UNIT_GETP (uptr->flags) * DF_DKSIZE;
return attach_unit (uptr, cptr);
}

/* Change disk size */

t_stat df_set_size (UNIT *uptr, int32 val, char *cptr, void *desc)
{
if (val < 0)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = UNIT_GETP (val) * DF_DKSIZE;
uptr->flags = uptr->flags & ~UNIT_AUTO;
return SCPE_OK;
}







|

















|









348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    cpu_set_bootpc (OS8_START);
    }
return SCPE_OK;
}

/* Attach routine */

t_stat df_attach (UNIT *uptr, CONST char *cptr)
{
uint32 p, sz;
uint32 ds_bytes = DF_DKSIZE * sizeof (int16);

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    p = (sz + ds_bytes - 1) / ds_bytes;
    if (p >= DF_NUMDK)
        p = DF_NUMDK - 1;
    uptr->flags = (uptr->flags & ~UNIT_PLAT) |
         (p << UNIT_V_PLAT);
    }
uptr->capac = UNIT_GETP (uptr->flags) * DF_DKSIZE;
return attach_unit (uptr, cptr);
}

/* Change disk size */

t_stat df_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
if (val < 0)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = UNIT_GETP (val) * DF_DKSIZE;
uptr->flags = uptr->flags & ~UNIT_AUTO;
return SCPE_OK;
}
Changes to src/PDP8/pdp8_dt.c.
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
int32 dtsb = 0;                                         /* status B */
int32 dt_ltime = 12;                                    /* interline time */
int32 dt_dctime = 40000;                                /* decel time */
int32 dt_substate = 0;
int32 dt_logblk = 0;
int32 dt_stopoffr = 0;

DEVICE dt_dev;
int32 dt76 (int32 IR, int32 AC);
int32 dt77 (int32 IR, int32 AC);
t_stat dt_svc (UNIT *uptr);
t_stat dt_reset (DEVICE *dptr);
t_stat dt_attach (UNIT *uptr, char *cptr);
void dt_flush (UNIT *uptr);
t_stat dt_detach (UNIT *uptr);
t_stat dt_boot (int32 unitno, DEVICE *dptr);
void dt_deselect (int32 oldf);
void dt_newsa (int32 newf);
void dt_newfnc (UNIT *uptr, int32 newsta);
t_bool dt_setpos (UNIT *uptr);







<




|







272
273
274
275
276
277
278

279
280
281
282
283
284
285
286
287
288
289
290
int32 dtsb = 0;                                         /* status B */
int32 dt_ltime = 12;                                    /* interline time */
int32 dt_dctime = 40000;                                /* decel time */
int32 dt_substate = 0;
int32 dt_logblk = 0;
int32 dt_stopoffr = 0;


int32 dt76 (int32 IR, int32 AC);
int32 dt77 (int32 IR, int32 AC);
t_stat dt_svc (UNIT *uptr);
t_stat dt_reset (DEVICE *dptr);
t_stat dt_attach (UNIT *uptr, CONST char *cptr);
void dt_flush (UNIT *uptr);
t_stat dt_detach (UNIT *uptr);
t_stat dt_boot (int32 unitno, DEVICE *dptr);
void dt_deselect (int32 oldf);
void dt_newsa (int32 newf);
void dt_newfnc (UNIT *uptr, int32 newsta);
t_bool dt_setpos (UNIT *uptr);
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    { UDATA (&dt_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) },
    { UDATA (&dt_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) }
    };

REG dt_reg[] = {
    { ORDATA (DTSA, dtsa, 12) },
    { ORDATA (DTSB, dtsb, 12) },
    { FLDATA (INT, int_req, INT_V_DTA) },
    { FLDATA (ENB, dtsa, DTA_V_ENB) },
    { FLDATA (DTF, dtsb, DTB_V_DTF) },
    { FLDATA (ERF, dtsb, DTB_V_ERF) },
    { ORDATA (WC, M[DT_WC], 12), REG_FIT },
    { ORDATA (CA, M[DT_CA], 12), REG_FIT },
    { DRDATA (LTIME, dt_ltime, 24), REG_NZ | PV_LEFT },
    { DRDATA (DCTIME, dt_dctime, 24), REG_NZ | PV_LEFT },
    { ORDATA (SUBSTATE, dt_substate, 2) },
    { DRDATA (LBLK, dt_logblk, 12), REG_HIDDEN },
    { URDATA (POS, dt_unit[0].pos, 10, T_ADDR_W, 0,
              DT_NUMDR, PV_LEFT | REG_RO) },
    { URDATA (STATT, dt_unit[0].STATE, 8, 18, 0,
              DT_NUMDR, REG_RO) },
    { URDATA (LASTT, dt_unit[0].LASTT, 10, 32, 0,
              DT_NUMDR, REG_HRO) },
    { FLDATA (STOP_OFFR, dt_stopoffr, 0) },
    { ORDATA (DEVNUM, dt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB dt_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL }, 







|
|
|
|
|
|
|
|
|
|
|

|
|
|
|


|







320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    { UDATA (&dt_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) },
    { UDATA (&dt_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) }
    };

REG dt_reg[] = {
    { ORDATAD (DTSA, dtsa, 12, "status register A") },
    { ORDATAD (DTSB, dtsb, 12, "status register B") },
    { FLDATAD (INT, int_req, INT_V_DTA, "interrupt pending flag") },
    { FLDATAD (ENB, dtsa, DTA_V_ENB, "interrupt enable flag") },
    { FLDATAD (DTF, dtsb, DTB_V_DTF, "DECtape flag") },
    { FLDATAD (ERF, dtsb, DTB_V_ERF, "error flag") },
    { ORDATAD (WC, M[DT_WC], 12, "word count (memory location 7755)"), REG_FIT },
    { ORDATAD (CA, M[DT_CA], 12, "current address (memory location 7754)"), REG_FIT },
    { DRDATAD (LTIME, dt_ltime, 24, "time between lines"), REG_NZ | PV_LEFT },
    { DRDATAD (DCTIME, dt_dctime, 24, "time to decelerate to a full stop"), REG_NZ | PV_LEFT },
    { ORDATAD (SUBSTATE, dt_substate, 2, "read/write command substate") },
    { DRDATA (LBLK, dt_logblk, 12), REG_HIDDEN },
    { URDATAD (POS, dt_unit[0].pos, 10, T_ADDR_W, 0,
              DT_NUMDR, PV_LEFT | REG_RO, "position, in lines, units 0 to 7") },
    { URDATAD (STATT, dt_unit[0].STATE, 8, 18, 0,
              DT_NUMDR, REG_RO, "unit state, units 0 to 7") },
    { URDATA (LASTT, dt_unit[0].LASTT, 10, 32, 0,
              DT_NUMDR, REG_HRO) },
    { FLDATAD (STOP_OFFR, dt_stopoffr, 0, "stop on off-reel error") },
    { ORDATA (DEVNUM, dt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB dt_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL }, 
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212

   Determine 12b, 16b, or 18b/36b format
   Allocate buffer
   If 16b or 18b, read 16b or 18b format and convert to 12b in buffer
   If 12b, read data into buffer
*/

t_stat dt_attach (UNIT *uptr, char *cptr)
{
uint32 pdp18b[D18_NBSIZE];
uint16 pdp11b[D18_NBSIZE], *fbuf;
int32 i, k;
int32 u = uptr - dt_dev.units;
t_stat r;
uint32 ba, sz;







|







1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211

   Determine 12b, 16b, or 18b/36b format
   Allocate buffer
   If 16b or 18b, read 16b or 18b format and convert to 12b in buffer
   If 12b, read data into buffer
*/

t_stat dt_attach (UNIT *uptr, CONST char *cptr)
{
uint32 pdp18b[D18_NBSIZE];
uint16 pdp11b[D18_NBSIZE], *fbuf;
int32 i, k;
int32 u = uptr - dt_dev.units;
t_stat r;
uint32 ba, sz;
Changes to src/PDP8/pdp8_fpp.c.
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
FPN fpp_ac;                                             /* FAC */
uint32 fpp_ssf = 0;                                     /* single-step flag */
uint32 fpp_last_lockbit = 0;                            /* last lockbit */

static FPN fpp_zero = { 0, { 0, 0, 0, 0, 0 } };
static FPN fpp_one = { 1, { 02000, 0, 0, 0, 0 } };

DEVICE fpp_dev;
int32 fpp55 (int32 IR, int32 AC);
int32 fpp56 (int32 IR, int32 AC);
void fpp_load_apt (uint32 apta);
void fpp_dump_apt (uint32 apta, uint32 sta);
uint32 fpp_1wd_dir (uint32 ir);
uint32 fpp_2wd_dir (uint32 ir);
uint32 fpp_indir (uint32 ir);







<







163
164
165
166
167
168
169

170
171
172
173
174
175
176
FPN fpp_ac;                                             /* FAC */
uint32 fpp_ssf = 0;                                     /* single-step flag */
uint32 fpp_last_lockbit = 0;                            /* last lockbit */

static FPN fpp_zero = { 0, { 0, 0, 0, 0, 0 } };
static FPN fpp_one = { 1, { 02000, 0, 0, 0, 0 } };


int32 fpp55 (int32 IR, int32 AC);
int32 fpp56 (int32 IR, int32 AC);
void fpp_load_apt (uint32 apta);
void fpp_dump_apt (uint32 apta, uint32 sta);
uint32 fpp_1wd_dir (uint32 ir);
uint32 fpp_2wd_dir (uint32 ir);
uint32 fpp_indir (uint32 ir);
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
*/

DIB fpp_dib = { DEV_FPP, 2, { &fpp55, &fpp56 } };

UNIT fpp_unit = { UDATA (&fpp_svc, 0, 0) };

REG fpp_reg[] = {
    { ORDATA (FPACE, fpp_ac.exp, 12) },
    { ORDATA (FPAC0, fpp_ac.fr[0], 12) },
    { ORDATA (FPAC1, fpp_ac.fr[1], 12) },
    { ORDATA (FPAC2, fpp_ac.fr[2], 12) },
    { ORDATA (FPAC3, fpp_ac.fr[3], 12) },
    { ORDATA (FPAC4, fpp_ac.fr[4], 12) },
    { ORDATA (CMD, fpp_cmd, 12) },
    { ORDATA (STA, fpp_sta, 12) },
    { ORDATA (APTA, fpp_apta, 15) },
    { GRDATA (APTSVF, fpp_aptsvf, 8, 3, 12) },
    { ORDATA (FPC, fpp_fpc, 15) },
    { ORDATA (BRA, fpp_bra, 15) },
    { ORDATA (XRA, fpp_xra, 15) },
    { ORDATA (OPA, fpp_opa, 15) },
    { ORDATA (SSF, fpp_ssf, 12) },
    { ORDATA (LASTLOCK, fpp_last_lockbit, 12) },
    { FLDATA (FLAG, fpp_flag, 0) },
    { NULL }
    };

DEVICE fpp_dev = {
    "FPP", &fpp_unit, fpp_reg, NULL,
    1, 10, 31, 1, 8, 8,
    NULL, NULL, &fpp_reset,







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
*/

DIB fpp_dib = { DEV_FPP, 2, { &fpp55, &fpp56 } };

UNIT fpp_unit = { UDATA (&fpp_svc, 0, 0) };

REG fpp_reg[] = {
    { ORDATAD (FPACE, fpp_ac.exp, 12, "floating accumulator") },
    { ORDATAD (FPAC0, fpp_ac.fr[0], 12, "first mantissa") },
    { ORDATAD (FPAC1, fpp_ac.fr[1], 12, "second mantissa") },
    { ORDATAD (FPAC2, fpp_ac.fr[2], 12, "third mantissa") },
    { ORDATAD (FPAC3, fpp_ac.fr[3], 12, "fourth mantissa") },
    { ORDATAD (FPAC4, fpp_ac.fr[4], 12, "fifth mantissa") },
    { ORDATAD (CMD, fpp_cmd, 12, "FPP command register") },
    { ORDATAD (STA, fpp_sta, 12, "status register") },
    { ORDATAD (APTA, fpp_apta, 15, "active parameter table (APT) pointer") },
    { GRDATAD (APTSVF, fpp_aptsvf, 8, 3, 12, "APT field") },
    { ORDATAD (FPC, fpp_fpc, 15, "floating program counter") },
    { ORDATAD (BRA, fpp_bra, 15, "base register") },
    { ORDATAD (XRA, fpp_xra, 15, "pointer to index register 0") },
    { ORDATAD (OPA, fpp_opa, 15, "operand address register") },
    { ORDATAD (SSF, fpp_ssf, 12, "single step flag") },
    { ORDATAD (LASTLOCK, fpp_last_lockbit, 12, "lockout from FPCOM") },
    { FLDATAD (FLAG, fpp_flag, 0, "done flag") },
    { NULL }
    };

DEVICE fpp_dev = {
    "FPP", &fpp_unit, fpp_reg, NULL,
    1, 10, 31, 1, 8, 8,
    NULL, NULL, &fpp_reset,
Changes to src/PDP8/pdp8_lp.c.
1
2
3
4
5
6
7
8
9
10
/* pdp8_lp.c: PDP-8 line printer simulator

   Copyright (c) 1993-2011, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_lp.c: PDP-8 line printer simulator

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   lpt          LP8E line printer


   19-Jan-07    RMS     Added UNIT_TEXT
   25-Apr-03    RMS     Revised for extended file support
   04-Oct-02    RMS     Added DIB, enable/disable, device number support
   30-May-02    RMS     Widened POS to 32b
*/

#include "pdp8_defs.h"

extern int32 int_req, int_enable, dev_done, stop_inst;

int32 lpt_err = 0;                                      /* error flag */
int32 lpt_stopioe = 0;                                  /* stop on error */

DEVICE lpt_dev;
int32 lpt (int32 IR, int32 AC);
t_stat lpt_svc (UNIT *uptr);
t_stat lpt_reset (DEVICE *dptr);
t_stat lpt_attach (UNIT *uptr, char *cptr);
t_stat lpt_detach (UNIT *uptr);

/* LPT data structures

   lpt_dev      LPT device descriptor
   lpt_unit     LPT unit descriptor
   lpt_reg      LPT register list
*/

DIB lpt_dib = { DEV_LPT, 1, { &lpt } };

UNIT lpt_unit = {
    UDATA (&lpt_svc, UNIT_SEQ+UNIT_ATTABLE+UNIT_TEXT, 0), SERIAL_OUT_WAIT
    };

REG lpt_reg[] = {
    { ORDATA (BUF, lpt_unit.buf, 8) },
    { FLDATA (ERR, lpt_err, 0) },
    { FLDATA (DONE, dev_done, INT_V_LPT) },
    { FLDATA (ENABLE, int_enable, INT_V_LPT) },
    { FLDATA (INT, int_req, INT_V_LPT) },
    { DRDATA (POS, lpt_unit.pos, T_ADDR_W), PV_LEFT },
    { DRDATA (TIME, lpt_unit.wait, 24), PV_LEFT },
    { FLDATA (STOP_IOE, lpt_stopioe, 0) },
    { ORDATA (DEVNUM, lpt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB lpt_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", "DEVNO",
      &set_dev, &show_dev, NULL },







>













<



|
















|
|
|
|
|
|
|
|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   lpt          LP8E line printer

   16-Dec-16    DJG     Added IOT 6660 to allow WPS WS78 3.4 to print
   19-Jan-07    RMS     Added UNIT_TEXT
   25-Apr-03    RMS     Revised for extended file support
   04-Oct-02    RMS     Added DIB, enable/disable, device number support
   30-May-02    RMS     Widened POS to 32b
*/

#include "pdp8_defs.h"

extern int32 int_req, int_enable, dev_done, stop_inst;

int32 lpt_err = 0;                                      /* error flag */
int32 lpt_stopioe = 0;                                  /* stop on error */


int32 lpt (int32 IR, int32 AC);
t_stat lpt_svc (UNIT *uptr);
t_stat lpt_reset (DEVICE *dptr);
t_stat lpt_attach (UNIT *uptr, CONST char *cptr);
t_stat lpt_detach (UNIT *uptr);

/* LPT data structures

   lpt_dev      LPT device descriptor
   lpt_unit     LPT unit descriptor
   lpt_reg      LPT register list
*/

DIB lpt_dib = { DEV_LPT, 1, { &lpt } };

UNIT lpt_unit = {
    UDATA (&lpt_svc, UNIT_SEQ+UNIT_ATTABLE+UNIT_TEXT, 0), SERIAL_OUT_WAIT
    };

REG lpt_reg[] = {
    { ORDATAD (BUF, lpt_unit.buf, 8,"last data item processed") },
    { FLDATAD (ERR, lpt_err, 0, "error status flag") },
    { FLDATAD (DONE, dev_done, INT_V_LPT, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_LPT, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_LPT, "interrupt pending flag") },
    { DRDATAD (POS, lpt_unit.pos, T_ADDR_W, "position in the output file"), PV_LEFT },
    { DRDATAD (TIME, lpt_unit.wait, 24, "time from I/O initiation to interrupt"), PV_LEFT },
    { FLDATAD (STOP_IOE, lpt_stopioe, 0, "stop on I/O error") },
    { ORDATA (DEVNUM, lpt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB lpt_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", "DEVNO",
      &set_dev, &show_dev, NULL },
86
87
88
89
90
91
92





93
94
95
96
97
98
99
    };

/* IOT routine */

int32 lpt (int32 IR, int32 AC)
{
switch (IR & 07) {                                      /* decode IR<9:11> */






    case 1:                                             /* PSKF */
        return (dev_done & INT_LPT)? IOT_SKP + AC: AC;

    case 2:                                             /* PCLF */
        dev_done = dev_done & ~INT_LPT;                 /* clear flag */
        int_req = int_req & ~INT_LPT;                   /* clear int req */







>
>
>
>
>







86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    };

/* IOT routine */

int32 lpt (int32 IR, int32 AC)
{
switch (IR & 07) {                                      /* decode IR<9:11> */

    case 0:                                             /* PKSTF */
        dev_done = dev_done | INT_LPT;                  /* set flag */
        int_req = INT_UPDATE;                           /* update interrupts */
        return AC;

    case 1:                                             /* PSKF */
        return (dev_done & INT_LPT)? IOT_SKP + AC: AC;

    case 2:                                             /* PCLF */
        dev_done = dev_done & ~INT_LPT;                 /* clear flag */
        int_req = int_req & ~INT_LPT;                   /* clear int req */
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
lpt_err = (lpt_unit.flags & UNIT_ATT) == 0;
sim_cancel (&lpt_unit);                                 /* deactivate unit */
return SCPE_OK;
}

/* Attach routine */

t_stat lpt_attach (UNIT *uptr, char *cptr)
{
t_stat reason;

reason = attach_unit (uptr, cptr);
lpt_err = (lpt_unit.flags & UNIT_ATT) == 0;
return reason;
}







|







166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
lpt_err = (lpt_unit.flags & UNIT_ATT) == 0;
sim_cancel (&lpt_unit);                                 /* deactivate unit */
return SCPE_OK;
}

/* Attach routine */

t_stat lpt_attach (UNIT *uptr, CONST char *cptr)
{
t_stat reason;

reason = attach_unit (uptr, cptr);
lpt_err = (lpt_unit.flags & UNIT_ATT) == 0;
return reason;
}
Changes to src/PDP8/pdp8_mt.c.
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
int32 mt_sta = 0;                                       /* status register */
int32 mt_db = 0;                                        /* data buffer */
int32 mt_done = 0;                                      /* mag tape flag */
int32 mt_time = 10;                                     /* record latency */
int32 mt_stopioe = 1;                                   /* stop on error */
uint8 *mtxb = NULL;                                     /* transfer buffer */

DEVICE mt_dev;
int32 mt70 (int32 IR, int32 AC);
int32 mt71 (int32 IR, int32 AC);
int32 mt72 (int32 IR, int32 AC);
t_stat mt_svc (UNIT *uptr);
t_stat mt_reset (DEVICE *dptr);
t_stat mt_attach (UNIT *uptr, char *cptr);
t_stat mt_detach (UNIT *uptr);
int32 mt_updcsta (UNIT *uptr);
int32 mt_ixma (int32 xma);
t_stat mt_map_err (UNIT *uptr, t_stat st);
t_stat mt_vlock (UNIT *uptr, int32 val, char *cptr, void *desc);
UNIT *mt_busy (void);
void mt_set_done (void);

/* MT data structures

   mt_dev       MT device descriptor
   mt_unit      MT unit list







<





|




|







141
142
143
144
145
146
147

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
int32 mt_sta = 0;                                       /* status register */
int32 mt_db = 0;                                        /* data buffer */
int32 mt_done = 0;                                      /* mag tape flag */
int32 mt_time = 10;                                     /* record latency */
int32 mt_stopioe = 1;                                   /* stop on error */
uint8 *mtxb = NULL;                                     /* transfer buffer */


int32 mt70 (int32 IR, int32 AC);
int32 mt71 (int32 IR, int32 AC);
int32 mt72 (int32 IR, int32 AC);
t_stat mt_svc (UNIT *uptr);
t_stat mt_reset (DEVICE *dptr);
t_stat mt_attach (UNIT *uptr, CONST char *cptr);
t_stat mt_detach (UNIT *uptr);
int32 mt_updcsta (UNIT *uptr);
int32 mt_ixma (int32 xma);
t_stat mt_map_err (UNIT *uptr, t_stat st);
t_stat mt_vlock (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
UNIT *mt_busy (void);
void mt_set_done (void);

/* MT data structures

   mt_dev       MT device descriptor
   mt_unit      MT unit list
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) }
    };

REG mt_reg[] = {
    { ORDATA (CMD, mt_cu, 12) },
    { ORDATA (FNC, mt_fn, 12) },
    { ORDATA (CA, mt_ca, 12) },
    { ORDATA (WC, mt_wc, 12) },
    { ORDATA (DB, mt_db, 12) },
    { GRDATA (STA, mt_sta, 8, 12, 12) },
    { ORDATA (STA2, mt_sta, 6) },
    { FLDATA (DONE, mt_done, 0) },
    { FLDATA (INT, int_req, INT_V_MT) },
    { FLDATA (STOP_IOE, mt_stopioe, 0) },
    { DRDATA (TIME, mt_time, 24), PV_LEFT },
    { URDATA (UST, mt_unit[0].USTAT, 8, 16, 0, MT_NUMDR, 0) },
    { URDATA (POS, mt_unit[0].pos, 10, T_ADDR_W, 0,
              MT_NUMDR, PV_LEFT | REG_RO) },
    { FLDATA (DEVNUM, mt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB mt_mod[] = {
    { MTUF_WLK, 0, "write enabled", "WRITEENABLED", &mt_vlock },
    { MTUF_WLK, MTUF_WLK, "write locked", "LOCKED", &mt_vlock }, 







|
|
|
|
|
|
|
|
|
|
|
|
|
|







177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) },
    { UDATA (&mt_svc, UNIT_ATTABLE+UNIT_DISABLE+UNIT_ROABLE, 0) }
    };

REG mt_reg[] = {
    { ORDATAD (CMD, mt_cu, 12, "command") },
    { ORDATAD (FNC, mt_fn, 12, "function") },
    { ORDATAD (CA, mt_ca, 12, "memory address") },
    { ORDATAD (WC, mt_wc, 12, "word count") },
    { ORDATAD (DB, mt_db, 12, "data buffer") },
    { GRDATAD (STA, mt_sta, 8, 12, 12, "status buffer") },
    { ORDATAD (STA2, mt_sta, 6, "secondary status") },
    { FLDATAD (DONE, mt_done, 0, "device done flag") },
    { FLDATAD (INT, int_req, INT_V_MT, "interrupt pending flag") },
    { FLDATAD (STOP_IOE, mt_stopioe, 0, "stop on I/O error") },
    { DRDATAD (TIME, mt_time, 24, "record delay"), PV_LEFT },
    { URDATAD (UST, mt_unit[0].USTAT, 8, 16, 0, MT_NUMDR, 0, "unit status, units 0 to 7") },
    { URDATAD (POS, mt_unit[0].pos, 10, T_ADDR_W, 0,
              MT_NUMDR, PV_LEFT | REG_RO, "position, units 0 to 7") },
    { FLDATA (DEVNUM, mt_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB mt_mod[] = {
    { MTUF_WLK, 0, "write enabled", "WRITEENABLED", &mt_vlock },
    { MTUF_WLK, MTUF_WLK, "write locked", "LOCKED", &mt_vlock }, 
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
if (mtxb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat mt_attach (UNIT *uptr, char *cptr)
{
t_stat r;
int32 u = uptr - mt_dev.units;                          /* get unit number */

r = sim_tape_attach (uptr, cptr);
if (r != SCPE_OK)
    return r;







|







613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
if (mtxb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat mt_attach (UNIT *uptr, CONST char *cptr)
{
t_stat r;
int32 u = uptr - mt_dev.units;                          /* get unit number */

r = sim_tape_attach (uptr, cptr);
if (r != SCPE_OK)
    return r;
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
if (u == GET_UNIT (mt_cu))
    mt_updcsta (uptr);
return sim_tape_detach (uptr);
}

/* Write lock/enable routine */

t_stat mt_vlock (UNIT *uptr, int32 val, char *cptr, void *desc)
{
int32 u = uptr - mt_dev.units;                          /* get unit number */

if ((uptr->flags & UNIT_ATT) && (val || sim_tape_wrp (uptr)))
    uptr->USTAT = uptr->USTAT | STA_WLK;
else uptr->USTAT = uptr->USTAT & ~STA_WLK;
if (u == GET_UNIT (mt_cu))
    mt_updcsta (uptr);
return SCPE_OK;
}







|










644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
if (u == GET_UNIT (mt_cu))
    mt_updcsta (uptr);
return sim_tape_detach (uptr);
}

/* Write lock/enable routine */

t_stat mt_vlock (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 u = uptr - mt_dev.units;                          /* get unit number */

if ((uptr->flags & UNIT_ATT) && (val || sim_tape_wrp (uptr)))
    uptr->USTAT = uptr->USTAT | STA_WLK;
else uptr->USTAT = uptr->USTAT & ~STA_WLK;
if (u == GET_UNIT (mt_cu))
    mt_updcsta (uptr);
return SCPE_OK;
}
Changes to src/PDP8/pdp8_pt.c.
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

UNIT ptr_unit = {
    UDATA (&ptr_svc, UNIT_SEQ+UNIT_ATTABLE+UNIT_ROABLE, 0),
           SERIAL_IN_WAIT
    };

REG ptr_reg[] = {
    { ORDATA (BUF, ptr_unit.buf, 8) },
    { FLDATA (DONE, dev_done, INT_V_PTR) },
    { FLDATA (ENABLE, int_enable, INT_V_PTR) },
    { FLDATA (INT, int_req, INT_V_PTR) },
    { DRDATA (POS, ptr_unit.pos, T_ADDR_W), PV_LEFT },
    { DRDATA (TIME, ptr_unit.wait, 24), PV_LEFT },
    { FLDATA (STOP_IOE, ptr_stopioe, 0) },
    { NULL }
    };

MTAB ptr_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev },
    { 0 }
    };







|
|
|
|
|
|
|







58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

UNIT ptr_unit = {
    UDATA (&ptr_svc, UNIT_SEQ+UNIT_ATTABLE+UNIT_ROABLE, 0),
           SERIAL_IN_WAIT
    };

REG ptr_reg[] = {
    { ORDATAD (BUF, ptr_unit.buf, 8, "last data item processed") },
    { FLDATAD (DONE, dev_done, INT_V_PTR, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_PTR, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_PTR, "interrupt pending flag") },
    { DRDATAD (POS, ptr_unit.pos, T_ADDR_W, "position in the input file"), PV_LEFT },
    { DRDATAD (TIME, ptr_unit.wait, 24, "time from I/O initiation to interrupt"), PV_LEFT },
    { FLDATAD (STOP_IOE, ptr_stopioe, 0, "stop on I/O error") },
    { NULL }
    };

MTAB ptr_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev },
    { 0 }
    };
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
DIB ptp_dib = { DEV_PTP, 1, { &ptp } };

UNIT ptp_unit = {
    UDATA (&ptp_svc, UNIT_SEQ+UNIT_ATTABLE, 0), SERIAL_OUT_WAIT
    };

REG ptp_reg[] = {
    { ORDATA (BUF, ptp_unit.buf, 8) },
    { FLDATA (DONE, dev_done, INT_V_PTP) },
    { FLDATA (ENABLE, int_enable, INT_V_PTP) },
    { FLDATA (INT, int_req, INT_V_PTP) },
    { DRDATA (POS, ptp_unit.pos, T_ADDR_W), PV_LEFT },
    { DRDATA (TIME, ptp_unit.wait, 24), PV_LEFT },
    { FLDATA (STOP_IOE, ptp_stopioe, 0) },
    { NULL }
    };

MTAB ptp_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev },
    { 0 }
    };







|
|
|
|
|
|
|







94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
DIB ptp_dib = { DEV_PTP, 1, { &ptp } };

UNIT ptp_unit = {
    UDATA (&ptp_svc, UNIT_SEQ+UNIT_ATTABLE, 0), SERIAL_OUT_WAIT
    };

REG ptp_reg[] = {
    { ORDATAD (BUF, ptp_unit.buf, 8, "last data item processed") },
    { FLDATAD (DONE, dev_done, INT_V_PTP, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_PTP, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_PTP, "interrupt pending flag") },
    { DRDATAD (POS, ptp_unit.pos, T_ADDR_W, "position in the output file"), PV_LEFT },
    { DRDATAD (TIME, ptp_unit.wait, 24, "time from I/O initiation to interrupt"), PV_LEFT },
    { FLDATAD (STOP_IOE, ptp_stopioe, 0, "stop on I/O error") },
    { NULL }
    };

MTAB ptp_mod[] = {
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev },
    { 0 }
    };
Changes to src/PDP8/pdp8_rf.c.
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
int32 rf_da = 0;                                        /* disk address */
int32 rf_done = 0;                                      /* done flag */
int32 rf_wlk = 0;                                       /* write lock */
int32 rf_time = 10;                                     /* inter-word time */
int32 rf_burst = 1;                                     /* burst mode flag */
int32 rf_stopioe = 1;                                   /* stop on error */

DEVICE rf_dev;
int32 rf60 (int32 IR, int32 AC);
int32 rf61 (int32 IR, int32 AC);
int32 rf62 (int32 IR, int32 AC);
int32 rf64 (int32 IR, int32 AC);
t_stat rf_svc (UNIT *uptr);
t_stat pcell_svc (UNIT *uptr);
t_stat rf_reset (DEVICE *dptr);
t_stat rf_boot (int32 unitno, DEVICE *dptr);
t_stat rf_attach (UNIT *uptr, char *cptr);
t_stat rf_set_size (UNIT *uptr, int32 val, char *cptr, void *desc);

/* RF08 data structures

   rf_dev       RF device descriptor
   rf_unit      RF unit descriptor
   pcell_unit   photocell timing unit (orphan)
   rf_reg       RF register list
*/

DIB rf_dib = { DEV_RF, 5, { &rf60, &rf61, &rf62, NULL, &rf64 } };

UNIT rf_unit = {
    UDATA (&rf_svc, UNIT_FIX+UNIT_ATTABLE+
           UNIT_BUFABLE+UNIT_MUSTBUF, RF_DKSIZE)
    };

UNIT pcell_unit = { UDATA (&pcell_svc, 0, 0) };

REG rf_reg[] = {
    { ORDATA (STA, rf_sta, 12) },
    { ORDATA (DA, rf_da, 20) },
    { ORDATA (WC, M[RF_WC], 12), REG_FIT },
    { ORDATA (MA, M[RF_MA], 12), REG_FIT },
    { FLDATA (DONE, rf_done, 0) },
    { FLDATA (INT, int_req, INT_V_RF) },
    { ORDATA (WLK, rf_wlk, 32) },
    { DRDATA (TIME, rf_time, 24), REG_NZ + PV_LEFT },
    { FLDATA (BURST, rf_burst, 0) },
    { FLDATA (STOP_IOE, rf_stopioe, 0) },
    { DRDATA (CAPAC, rf_unit.capac, 21), REG_HRO },
    { ORDATA (DEVNUM, rf_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rf_mod[] = {
    { UNIT_PLAT, (0 << UNIT_V_PLAT), NULL, "1P", &rf_set_size },







<








|
|



















|
|
|
|
|
|
|
|
|
|







113
114
115
116
117
118
119

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
int32 rf_da = 0;                                        /* disk address */
int32 rf_done = 0;                                      /* done flag */
int32 rf_wlk = 0;                                       /* write lock */
int32 rf_time = 10;                                     /* inter-word time */
int32 rf_burst = 1;                                     /* burst mode flag */
int32 rf_stopioe = 1;                                   /* stop on error */


int32 rf60 (int32 IR, int32 AC);
int32 rf61 (int32 IR, int32 AC);
int32 rf62 (int32 IR, int32 AC);
int32 rf64 (int32 IR, int32 AC);
t_stat rf_svc (UNIT *uptr);
t_stat pcell_svc (UNIT *uptr);
t_stat rf_reset (DEVICE *dptr);
t_stat rf_boot (int32 unitno, DEVICE *dptr);
t_stat rf_attach (UNIT *uptr, CONST char *cptr);
t_stat rf_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc);

/* RF08 data structures

   rf_dev       RF device descriptor
   rf_unit      RF unit descriptor
   pcell_unit   photocell timing unit (orphan)
   rf_reg       RF register list
*/

DIB rf_dib = { DEV_RF, 5, { &rf60, &rf61, &rf62, NULL, &rf64 } };

UNIT rf_unit = {
    UDATA (&rf_svc, UNIT_FIX+UNIT_ATTABLE+
           UNIT_BUFABLE+UNIT_MUSTBUF, RF_DKSIZE)
    };

UNIT pcell_unit = { UDATA (&pcell_svc, 0, 0) };

REG rf_reg[] = {
    { ORDATAD (STA, rf_sta, 12, "status") },
    { ORDATAD (DA, rf_da, 20, "low order disk address") },
    { ORDATAD (WC, M[RF_WC], 12, "word count (in memory)"), REG_FIT },
    { ORDATAD (MA, M[RF_MA], 12, "memory address (in memory)"), REG_FIT },
    { FLDATAD (DONE, rf_done, 0, "device done flag") },
    { FLDATAD (INT, int_req, INT_V_RF, "interrupt pending flag") },
    { ORDATAD (WLK, rf_wlk, 32, "write lock switches") },
    { DRDATAD (TIME, rf_time, 24, "rotational delay, per word"), REG_NZ + PV_LEFT },
    { FLDATAD (BURST, rf_burst, 0, "burst flag") },
    { FLDATAD (STOP_IOE, rf_stopioe, 0, "stop on I/O error") },
    { DRDATA (CAPAC, rf_unit.capac, 21), REG_HRO },
    { ORDATA (DEVNUM, rf_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rf_mod[] = {
    { UNIT_PLAT, (0 << UNIT_V_PLAT), NULL, "1P", &rf_set_size },
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    cpu_set_bootpc (OS8_START);
    }
return SCPE_OK;
}

/* Attach routine */

t_stat rf_attach (UNIT *uptr, char *cptr)
{
uint32 sz, p;
uint32 ds_bytes = RF_DKSIZE * sizeof (int16);

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    p = (sz + ds_bytes - 1) / ds_bytes;
    if (p >= RF_NUMDK)
        p = RF_NUMDK - 1;
    uptr->flags = (uptr->flags & ~UNIT_PLAT) |
        (p << UNIT_V_PLAT);
    }
uptr->capac = UNIT_GETP (uptr->flags) * RF_DKSIZE;
return attach_unit (uptr, cptr);
}

/* Change disk size */

t_stat rf_set_size (UNIT *uptr, int32 val, char *cptr, void *desc)
{
if (val < 0)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = UNIT_GETP (val) * RF_DKSIZE;
uptr->flags = uptr->flags & ~UNIT_AUTO;
return SCPE_OK;
}







|

















|









414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    cpu_set_bootpc (OS8_START);
    }
return SCPE_OK;
}

/* Attach routine */

t_stat rf_attach (UNIT *uptr, CONST char *cptr)
{
uint32 sz, p;
uint32 ds_bytes = RF_DKSIZE * sizeof (int16);

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    p = (sz + ds_bytes - 1) / ds_bytes;
    if (p >= RF_NUMDK)
        p = RF_NUMDK - 1;
    uptr->flags = (uptr->flags & ~UNIT_PLAT) |
        (p << UNIT_V_PLAT);
    }
uptr->capac = UNIT_GETP (uptr->flags) * RF_DKSIZE;
return attach_unit (uptr, cptr);
}

/* Change disk size */

t_stat rf_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
if (val < 0)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = UNIT_GETP (val) * RF_DKSIZE;
uptr->flags = uptr->flags & ~UNIT_AUTO;
return SCPE_OK;
}
Changes to src/PDP8/pdp8_rk.c.
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
int32 rk_sta = 0;                                       /* status register */
int32 rk_cmd = 0;                                       /* command register */
int32 rk_da = 0;                                        /* disk address */
int32 rk_ma = 0;                                        /* memory address */
int32 rk_swait = 10, rk_rwait = 10;                     /* seek, rotate wait */
int32 rk_stopioe = 1;                                   /* stop on error */

DEVICE rk_dev;
int32 rk (int32 IR, int32 AC);
t_stat rk_svc (UNIT *uptr);
t_stat rk_reset (DEVICE *dptr);
t_stat rk_boot (int32 unitno, DEVICE *dptr);
void rk_go (int32 function, int32 cylinder);

/* RK-8E data structures







<







134
135
136
137
138
139
140

141
142
143
144
145
146
147
int32 rk_sta = 0;                                       /* status register */
int32 rk_cmd = 0;                                       /* command register */
int32 rk_da = 0;                                        /* disk address */
int32 rk_ma = 0;                                        /* memory address */
int32 rk_swait = 10, rk_rwait = 10;                     /* seek, rotate wait */
int32 rk_stopioe = 1;                                   /* stop on error */


int32 rk (int32 IR, int32 AC);
t_stat rk_svc (UNIT *uptr);
t_stat rk_reset (DEVICE *dptr);
t_stat rk_boot (int32 unitno, DEVICE *dptr);
void rk_go (int32 function, int32 cylinder);

/* RK-8E data structures
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    { UDATA (&rk_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+
             UNIT_ROABLE, RK_SIZE) },
    { UDATA (&rk_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+
             UNIT_ROABLE, RK_SIZE) }
    };

REG rk_reg[] = {
    { ORDATA (RKSTA, rk_sta, 12) },
    { ORDATA (RKCMD, rk_cmd, 12) },
    { ORDATA (RKDA, rk_da, 12) },
    { ORDATA (RKMA, rk_ma, 12) },
    { FLDATA (BUSY, rk_busy, 0) },
    { FLDATA (INT, int_req, INT_V_RK) },
    { DRDATA (STIME, rk_swait, 24), PV_LEFT },
    { DRDATA (RTIME, rk_rwait, 24), PV_LEFT },
    { FLDATA (STOP_IOE, rk_stopioe, 0) },
    { ORDATA (DEVNUM, rk_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rk_mod[] = {
    { UNIT_HWLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_HWLK, UNIT_HWLK, "write locked", "LOCKED", NULL },







|
|
|
|
|
|
|
|
|







162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    { UDATA (&rk_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+
             UNIT_ROABLE, RK_SIZE) },
    { UDATA (&rk_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+
             UNIT_ROABLE, RK_SIZE) }
    };

REG rk_reg[] = {
    { ORDATAD (RKSTA, rk_sta, 12, "status") },
    { ORDATAD (RKCMD, rk_cmd, 12, "disk command") },
    { ORDATAD (RKDA, rk_da, 12, "disk address") },
    { ORDATAD (RKMA, rk_ma, 12, "current memory address") },
    { FLDATAD (BUSY, rk_busy, 0, "control busy flag") },
    { FLDATAD (INT, int_req, INT_V_RK, "interrupt pending flag") },
    { DRDATAD (STIME, rk_swait, 24, "seek time, per cylinder"), PV_LEFT },
    { DRDATAD (RTIME, rk_rwait, 24, "rotational delay"), PV_LEFT },
    { FLDATAD (STOP_IOE, rk_stopioe, 0, "stop on I/O error") },
    { ORDATA (DEVNUM, rk_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rk_mod[] = {
    { UNIT_HWLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_HWLK, UNIT_HWLK, "write locked", "LOCKED", NULL },
Changes to src/PDP8/pdp8_rl.c.
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
int32 rl_lft = 0;                                       /* silo left/right */
int32 rl_done = 0;                                      /* done flag */
int32 rl_erf = 0;                                       /* error flag */
int32 rl_swait = 10;                                    /* seek wait */
int32 rl_rwait = 10;                                    /* rotate wait */
int32 rl_stopioe = 1;                                   /* stop on error */

DEVICE rl_dev;
int32 rl60 (int32 IR, int32 AC);
int32 rl61 (int32 IR, int32 AC);
t_stat rl_svc (UNIT *uptr);
t_stat rl_reset (DEVICE *dptr);
void rl_set_done (int32 error);
t_stat rl_boot (int32 unitno, DEVICE *dptr);
t_stat rl_attach (UNIT *uptr, char *cptr);
t_stat rl_set_size (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat rl_set_bad (UNIT *uptr, int32 val, char *cptr, void *desc);

/* RL8A data structures

   rl_dev       RL device descriptor
   rl_unit      RL unit list
   rl_reg       RL register list
   rl_mod       RL modifier list







<






|
|
|







170
171
172
173
174
175
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
int32 rl_lft = 0;                                       /* silo left/right */
int32 rl_done = 0;                                      /* done flag */
int32 rl_erf = 0;                                       /* error flag */
int32 rl_swait = 10;                                    /* seek wait */
int32 rl_rwait = 10;                                    /* rotate wait */
int32 rl_stopioe = 1;                                   /* stop on error */


int32 rl60 (int32 IR, int32 AC);
int32 rl61 (int32 IR, int32 AC);
t_stat rl_svc (UNIT *uptr);
t_stat rl_reset (DEVICE *dptr);
void rl_set_done (int32 error);
t_stat rl_boot (int32 unitno, DEVICE *dptr);
t_stat rl_attach (UNIT *uptr, CONST char *cptr);
t_stat rl_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat rl_set_bad (UNIT *uptr, int32 val, CONST char *cptr, void *desc);

/* RL8A data structures

   rl_dev       RL device descriptor
   rl_unit      RL unit list
   rl_reg       RL register list
   rl_mod       RL modifier list
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    { UDATA (&rl_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+UNIT_AUTO+
             UNIT_ROABLE, RL01_SIZE) },
    { UDATA (&rl_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+UNIT_AUTO+
             UNIT_ROABLE, RL01_SIZE) }
    };

REG rl_reg[] = {
    { ORDATA (RLCSA, rlcsa, 12) },
    { ORDATA (RLCSB, rlcsb, 12) },
    { ORDATA (RLMA, rlma, 12) },
    { ORDATA (RLWC, rlwc, 12) },
    { ORDATA (RLSA, rlsa, 6) },
    { ORDATA (RLER, rler, 12) },
    { ORDATA (RLSI, rlsi, 16) },
    { ORDATA (RLSI1, rlsi1, 16) },
    { ORDATA (RLSI2, rlsi2, 16) },
    { FLDATA (RLSIL, rl_lft, 0) },
    { FLDATA (INT, int_req, INT_V_RL) },
    { FLDATA (DONE, rl_done, INT_V_RL) },
    { FLDATA (IE, rlcsb, RLCSB_V_IE) },
    { FLDATA (ERR, rl_erf, 0) },
    { DRDATA (STIME, rl_swait, 24), PV_LEFT },
    { DRDATA (RTIME, rl_rwait, 24), PV_LEFT },
    { URDATA (CAPAC, rl_unit[0].capac, 10, T_ADDR_W, 0,
              RL_NUMDR, PV_LEFT + REG_HRO) },
    { FLDATA (STOP_IOE, rl_stopioe, 0) },
    { ORDATA (DEVNUM, rl_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rl_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL },







|
|
|
|
|
|
|
|
|
|
|
|

|
|
|


|







202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    { UDATA (&rl_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+UNIT_AUTO+
             UNIT_ROABLE, RL01_SIZE) },
    { UDATA (&rl_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_DISABLE+UNIT_AUTO+
             UNIT_ROABLE, RL01_SIZE) }
    };

REG rl_reg[] = {
    { ORDATAD (RLCSA, rlcsa, 12, "control/status A") },
    { ORDATAD (RLCSB, rlcsb, 12, "control/status B") },
    { ORDATAD (RLMA, rlma, 12, "memory address") },
    { ORDATAD (RLWC, rlwc, 12, "word count") },
    { ORDATAD (RLSA, rlsa, 6, "sector address") },
    { ORDATAD (RLER, rler, 12, "error flags") },
    { ORDATAD (RLSI, rlsi, 16, "silo top word") },
    { ORDATAD (RLSI1, rlsi1, 16, "silo second word") },
    { ORDATAD (RLSI2, rlsi2, 16, "silo third word") },
    { FLDATAD (RLSIL, rl_lft, 0, "silo read left/right flag") },
    { FLDATAD (INT, int_req, INT_V_RL, "interrupt request") },
    { FLDATAD (DONE, rl_done, INT_V_RL, "done flag") },
    { FLDATA (IE, rlcsb, RLCSB_V_IE) },
    { FLDATAD (ERR, rl_erf, 0, "composite error flag") },
    { DRDATAD (STIME, rl_swait, 24, "seek time, per cylinder"), PV_LEFT },
    { DRDATAD (RTIME, rl_rwait, 24, "rotational delay"), PV_LEFT },
    { URDATA (CAPAC, rl_unit[0].capac, 10, T_ADDR_W, 0,
              RL_NUMDR, PV_LEFT + REG_HRO) },
    { FLDATAD (STOP_IOE, rl_stopioe, 0, "stop on I/O error") },
    { ORDATA (DEVNUM, rl_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB rl_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL },
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
if (rlxb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat rl_attach (UNIT *uptr, char *cptr)
{
uint32 p;
t_stat r;

uptr->capac = (uptr->flags & UNIT_RL02)? RL02_SIZE: RL01_SIZE;
r = attach_unit (uptr, cptr);                           /* attach unit */
if (r != SCPE_OK)                                       /* error? */







|







568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
if (rlxb == NULL)
    return SCPE_MEM;
return SCPE_OK;
}

/* Attach routine */

t_stat rl_attach (UNIT *uptr, CONST char *cptr)
{
uint32 p;
t_stat r;

uptr->capac = (uptr->flags & UNIT_RL02)? RL02_SIZE: RL01_SIZE;
r = attach_unit (uptr, cptr);                           /* attach unit */
if (r != SCPE_OK)                                       /* error? */
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    uptr->capac = RL01_SIZE;
    }
return SCPE_OK;
}

/* Set size routine */

t_stat rl_set_size (UNIT *uptr, int32 val, char *cptr, void *desc)
{
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = (val & UNIT_RL02)? RL02_SIZE: RL01_SIZE;
return SCPE_OK;
}








|







599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    uptr->capac = RL01_SIZE;
    }
return SCPE_OK;
}

/* Set size routine */

t_stat rl_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
uptr->capac = (val & UNIT_RL02)? RL02_SIZE: RL01_SIZE;
return SCPE_OK;
}

624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
   Inputs:
        uptr    =       pointer to unit
        val     =       ignored
   Outputs:
        sta     =       status code
*/

t_stat rl_set_bad (UNIT *uptr, int32 val, char *cptr, void *desc)
{
int32 i, da = RL_BBMAP * RL_NUMBY;

if ((uptr->flags & UNIT_ATT) == 0)
    return SCPE_UNATT;
if (uptr->flags & UNIT_RO)
    return SCPE_RO;







|







623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
   Inputs:
        uptr    =       pointer to unit
        val     =       ignored
   Outputs:
        sta     =       status code
*/

t_stat rl_set_bad (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 i, da = RL_BBMAP * RL_NUMBY;

if ((uptr->flags & UNIT_ATT) == 0)
    return SCPE_UNATT;
if (uptr->flags & UNIT_RO)
    return SCPE_RO;
Changes to src/PDP8/pdp8_rx.c.
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
int32 rx_cwait = 100;                                   /* command time */
int32 rx_swait = 10;                                    /* seek, per track */
int32 rx_xwait = 1;                                     /* tr set time */
int32 rx_stopioe = 0;                                   /* stop on error */
uint8 rx_buf[RX2_NUMBY] = { 0 };                        /* sector buffer */
int32 rx_bptr = 0;                                      /* buffer pointer */

DEVICE rx_dev;
int32 rx (int32 IR, int32 AC);
t_stat rx_svc (UNIT *uptr);
t_stat rx_reset (DEVICE *dptr);
t_stat rx_boot (int32 unitno, DEVICE *dptr);
t_stat rx_set_size (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat rx_attach (UNIT *uptr, char *cptr);
void rx_cmd (void);
void rx_done (int32 esr_flags, int32 new_ecode);
t_stat rx_settype (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat rx_showtype (FILE *st, UNIT *uptr, int32 val, void *desc);

/* RX8E data structures

   rx_dev       RX device descriptor
   rx_unit      RX unit list
   rx_reg       RX register list
   rx_mod       RX modifier list
*/

DIB rx_dib = { DEV_RX, 1, { &rx } };

UNIT rx_unit[] = {
    { UDATA (&rx_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF+
             UNIT_ROABLE, RX_SIZE) },
    { UDATA (&rx_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF+
             UNIT_ROABLE, RX_SIZE) }
    };

REG rx_reg[] = {
    { ORDATA (RXCS, rx_csr, 12) },
    { ORDATA (RXDB, rx_dbr, 12) },
    { ORDATA (RXES, rx_esr, 12) },
    { ORDATA (RXERR, rx_ecode, 8) },
    { ORDATA (RXTA, rx_track, 8) },
    { ORDATA (RXSA, rx_sector, 8) },
    { DRDATA (STAPTR, rx_state, 4), REG_RO },
    { DRDATA (BUFPTR, rx_bptr, 8)  },
    { FLDATA (TR, rx_tr, 0) },
    { FLDATA (ERR, rx_err, 0) },
    { FLDATA (DONE, dev_done, INT_V_RX) },
    { FLDATA (ENABLE, int_enable, INT_V_RX) },
    { FLDATA (INT, int_req, INT_V_RX) },
    { DRDATA (CTIME, rx_cwait, 24), PV_LEFT },
    { DRDATA (STIME, rx_swait, 24), PV_LEFT },
    { DRDATA (XTIME, rx_xwait, 24), PV_LEFT },
    { FLDATA (STOP_IOE, rx_stopioe, 0) },
    { BRDATA (SBUF, rx_buf, 8, 8, RX2_NUMBY) },
    { FLDATA (RX28, rx_28, 0), REG_HRO },
    { URDATA (CAPAC, rx_unit[0].capac, 10, T_ADDR_W, 0,
              RX_NUMDR, REG_HRO | PV_LEFT) },
    { ORDATA (DEVNUM, rx_dib.dev, 6), REG_HRO },
    { NULL }
    };








<




|
|


|
|



















|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|







133
134
135
136
137
138
139

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
int32 rx_cwait = 100;                                   /* command time */
int32 rx_swait = 10;                                    /* seek, per track */
int32 rx_xwait = 1;                                     /* tr set time */
int32 rx_stopioe = 0;                                   /* stop on error */
uint8 rx_buf[RX2_NUMBY] = { 0 };                        /* sector buffer */
int32 rx_bptr = 0;                                      /* buffer pointer */


int32 rx (int32 IR, int32 AC);
t_stat rx_svc (UNIT *uptr);
t_stat rx_reset (DEVICE *dptr);
t_stat rx_boot (int32 unitno, DEVICE *dptr);
t_stat rx_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat rx_attach (UNIT *uptr, CONST char *cptr);
void rx_cmd (void);
void rx_done (int32 esr_flags, int32 new_ecode);
t_stat rx_settype (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat rx_showtype (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

/* RX8E data structures

   rx_dev       RX device descriptor
   rx_unit      RX unit list
   rx_reg       RX register list
   rx_mod       RX modifier list
*/

DIB rx_dib = { DEV_RX, 1, { &rx } };

UNIT rx_unit[] = {
    { UDATA (&rx_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF+
             UNIT_ROABLE, RX_SIZE) },
    { UDATA (&rx_svc, UNIT_FIX+UNIT_ATTABLE+UNIT_BUFABLE+UNIT_MUSTBUF+
             UNIT_ROABLE, RX_SIZE) }
    };

REG rx_reg[] = {
    { ORDATAD (RXCS, rx_csr, 12, "status") },
    { ORDATAD (RXDB, rx_dbr, 12, "data buffer") },
    { ORDATAD (RXES, rx_esr, 12, "error status") },
    { ORDATA (RXERR, rx_ecode, 8) },
    { ORDATAD (RXTA, rx_track, 8, "current track") },
    { ORDATAD (RXSA, rx_sector, 8, "current sector") },
    { DRDATAD (STAPTR, rx_state, 4, "controller state"), REG_RO },
    { DRDATAD (BUFPTR, rx_bptr, 8, "buffer pointer")  },
    { FLDATAD (TR, rx_tr, 0, "transfer ready flag") },
    { FLDATAD (ERR, rx_err, 0, "error flag") },
    { FLDATAD (DONE, dev_done, INT_V_RX, "done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_RX, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_RX, "interrupt pending flag") },
    { DRDATAD (CTIME, rx_cwait, 24, "command completion time"), PV_LEFT },
    { DRDATAD (STIME, rx_swait, 24, "seek time per track"), PV_LEFT },
    { DRDATAD (XTIME, rx_xwait, 24, "transfer ready delay"), PV_LEFT },
    { FLDATAD (STOP_IOE, rx_stopioe, 0, "stop on I/O error") },
    { BRDATAD (SBUF, rx_buf, 8, 8, RX2_NUMBY, "sector buffer array") },
    { FLDATA (RX28, rx_28, 0), REG_HRO },
    { URDATA (CAPAC, rx_unit[0].capac, 10, T_ADDR_W, 0,
              RX_NUMDR, REG_HRO | PV_LEFT) },
    { ORDATA (DEVNUM, rx_dib.dev, 6), REG_HRO },
    { NULL }
    };

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    }
else rx_done (rx_esr | RXES_ID, 0010);                  /* no, error */
return SCPE_OK;
}

/* Attach routine */

t_stat rx_attach (UNIT *uptr, char *cptr)
{
uint32 sz;

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    if (sz > RX_SIZE)
        uptr->flags = uptr->flags | UNIT_DEN;
    else uptr->flags = uptr->flags & ~UNIT_DEN;
    }
uptr->capac = (uptr->flags & UNIT_DEN)? RX2_SIZE: RX_SIZE;
return attach_unit (uptr, cptr);
}

/* Set size routine */

t_stat rx_set_size (UNIT *uptr, int32 val, char *cptr, void *desc)
{
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if ((rx_28 == 0) && val)                                /* not on RX8E */
    return SCPE_NOFNC;
uptr->capac = val? RX2_SIZE: RX_SIZE;
return SCPE_OK;
}

/* Set controller type */

t_stat rx_settype (UNIT *uptr, int32 val, char *cptr, void *desc)
{
int32 i;

if ((val < 0) || (val > 1) || (cptr != NULL))
    return SCPE_ARG;
if (val == rx_28)
    return SCPE_OK;







|














|











|







588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    }
else rx_done (rx_esr | RXES_ID, 0010);                  /* no, error */
return SCPE_OK;
}

/* Attach routine */

t_stat rx_attach (UNIT *uptr, CONST char *cptr)
{
uint32 sz;

if ((uptr->flags & UNIT_AUTO) && (sz = sim_fsize_name (cptr))) {
    if (sz > RX_SIZE)
        uptr->flags = uptr->flags | UNIT_DEN;
    else uptr->flags = uptr->flags & ~UNIT_DEN;
    }
uptr->capac = (uptr->flags & UNIT_DEN)? RX2_SIZE: RX_SIZE;
return attach_unit (uptr, cptr);
}

/* Set size routine */

t_stat rx_set_size (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if ((rx_28 == 0) && val)                                /* not on RX8E */
    return SCPE_NOFNC;
uptr->capac = val? RX2_SIZE: RX_SIZE;
return SCPE_OK;
}

/* Set controller type */

t_stat rx_settype (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 i;

if ((val < 0) || (val > 1) || (cptr != NULL))
    return SCPE_ARG;
if (val == rx_28)
    return SCPE_OK;
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    }
rx_28 = val;
return SCPE_OK;
}

/* Show controller type */

t_stat rx_showtype (FILE *st, UNIT *uptr, int32 val, void *desc)
{
if (rx_28) fprintf (st, "RX28");
else fprintf (st, "RX8E");
return SCPE_OK;
}

/* Bootstrap routine */







|







639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    }
rx_28 = val;
return SCPE_OK;
}

/* Show controller type */

t_stat rx_showtype (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
if (rx_28) fprintf (st, "RX28");
else fprintf (st, "RX8E");
return SCPE_OK;
}

/* Bootstrap routine */
Changes to src/PDP8/pdp8_sys.c.
1
2
3
4
5
6
7
8
9
10
/* pdp8_sys.c: PDP-8 simulator interface

   Copyright (c) 1993-2013, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_sys.c: PDP-8 simulator interface

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
19
20
21
22
23
24
25

26
27
28
29
30
31
32
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.


   17-Sep-13    RMS     Fixed recognition of initial field change (Dave Gesswein)
   24-Mar-09    RMS     Added link to FPP
   24-Jun-08    RMS     Fixed bug in new rim loader (Don North)
   24-May-08    RMS     Fixed signed/unsigned declaration inconsistency
   03-Sep-07    RMS     Added FPP8 support
                        Rewrote rim and binary loaders
   15-Dec-06    RMS     Added TA8E support, IOT disambiguation







>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   15-Dec-16    RMS     Added PKSTF (Dave Gesswein)
   17-Sep-13    RMS     Fixed recognition of initial field change (Dave Gesswein)
   24-Mar-09    RMS     Added link to FPP
   24-Jun-08    RMS     Fixed bug in new rim loader (Don North)
   24-May-08    RMS     Fixed signed/unsigned declaration inconsistency
   03-Sep-07    RMS     Added FPP8 support
                        Rewrote rim and binary loaders
   15-Dec-06    RMS     Added TA8E support, IOT disambiguation
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
extern DEVICE dt_dev, td_dev;
extern DEVICE mt_dev, ct_dev;
extern DEVICE ttix_dev, ttox_dev;
extern REG cpu_reg[];
extern uint16 M[];

t_stat fprint_sym_fpp (FILE *of, t_value *val);
t_stat parse_sym_fpp (char *cptr, t_value *val);
char *parse_field (char *cptr, uint32 max, uint32 *val, uint32 c);
char *parse_fpp_xr (char *cptr, uint32 *xr, t_bool inc);
int32 test_fpp_addr (uint32 ad, uint32 max);

/* SCP data structures and interface routines

   sim_name             simulator name string
   sim_PC               pointer to saved PC register descriptor
   sim_emax             maximum number of words for examine/deposit







|
|
|







65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
extern DEVICE dt_dev, td_dev;
extern DEVICE mt_dev, ct_dev;
extern DEVICE ttix_dev, ttox_dev;
extern REG cpu_reg[];
extern uint16 M[];

t_stat fprint_sym_fpp (FILE *of, t_value *val);
t_stat parse_sym_fpp (CONST char *cptr, t_value *val);
CONST char *parse_field (CONST char *cptr, uint32 max, uint32 *val, uint32 c);
CONST char *parse_fpp_xr (CONST char *cptr, uint32 *xr, t_bool inc);
int32 test_fpp_addr (uint32 ad, uint32 max);

/* SCP data structures and interface routines

   sim_name             simulator name string
   sim_PC               pointer to saved PC register descriptor
   sim_emax             maximum number of words for examine/deposit
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
    }
return SCPE_IERR;
}

/* Binary loader
   Two loader formats are supported: RIM loader (-r) and BIN (-b) loader. */

t_stat sim_load (FILE *fileref, char *cptr, char *fnam, int flag)
{
if ((*cptr != 0) || (flag != 0))
    return SCPE_ARG;
if ((sim_switches & SWMASK ('R')) ||                    /* RIM format? */
    (match_ext (fnam, "RIM") && !(sim_switches & SWMASK ('B'))))
    return sim_load_rim (fileref);
else return sim_load_bin (fileref);                     /* no, BIN */







|







238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    }
return SCPE_IERR;
}

/* Binary loader
   Two loader formats are supported: RIM loader (-r) and BIN (-b) loader. */

t_stat sim_load (FILE *fileref, CONST char *cptr, CONST char *fnam, int flag)
{
if ((*cptr != 0) || (flag != 0))
    return SCPE_ARG;
if ((sim_switches & SWMASK ('R')) ||                    /* RIM format? */
    (match_ext (fnam, "RIM") && !(sim_switches & SWMASK ('B'))))
    return sim_load_rim (fileref);
else return sim_load_bin (fileref);                     /* no, BIN */
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
 "ADCL", "ADLM", "ADST", "ADRB",                        /* A/D */
 "ADSK", "ADSE", "ADLE", "ADRS",
 "DCMA", "DMAR", "DMAW",                                /* DF/RF */
 "DCIM", "DSAC", "DIML", "DIMA",
 "DCEA",         "DEAL", "DEAC",
 "DFSE", "DFSC", "DISK", "DMAC",
 "DCXA", "DXAL", "DXAC",
 "PSKF", "PCLF", "PSKE",                                /* LPT */
 "PSTB", "PSIE", "PCLF PSTB", "PCIE",
 "LWCR", "CWCR", "LCAR",                                /* MT */
 "CCAR", "LCMR", "LFGR", "LDBR",
 "RWCR", "CLT", "RCAR",
 "RMSR", "RCMR", "RFSR", "RDBR",
 "SKEF", "SKCB", "SKJD", "SKTR", "CLF",
 "DSKP", "DCLR", "DLAG",                                /* RK */







|







302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
 "ADCL", "ADLM", "ADST", "ADRB",                        /* A/D */
 "ADSK", "ADSE", "ADLE", "ADRS",
 "DCMA", "DMAR", "DMAW",                                /* DF/RF */
 "DCIM", "DSAC", "DIML", "DIMA",
 "DCEA",         "DEAL", "DEAC",
 "DFSE", "DFSC", "DISK", "DMAC",
 "DCXA", "DXAL", "DXAC",
 "PKSTF", "PSKF", "PCLF", "PSKE",                                /* LPT */
 "PSTB", "PSIE", "PCLF PSTB", "PCIE",
 "LWCR", "CWCR", "LCAR",                                /* MT */
 "CCAR", "LCMR", "LFGR", "LDBR",
 "RWCR", "CLT", "RCAR",
 "RMSR", "RCMR", "RFSR", "RDBR",
 "SKEF", "SKCB", "SKJD", "SKTR", "CLF",
 "DSKP", "DCLR", "DLAG",                                /* RK */
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
 06614+I_IOA+AMB_RL, 06615+I_IOA+AMB_RL, 06617+I_IOA+AMB_RL,
 06700+I_IOA+AMB_CT, 06701+I_IOA+AMB_CT, 06702+I_IOA+AMB_CT, 06703+I_IOA+AMB_CT,
 06704+I_IOA+AMB_CT, 06705+I_IOA+AMB_CT, 06706+I_IOA+AMB_CT, 06707+I_IOA+AMB_CT,
 06771+I_IOA+AMB_TD, 06772+I_IOA+AMB_TD, 06773+I_IOA+AMB_TD,
 06774+I_IOA+AMB_TD, 06775+I_IOA+AMB_TD, 06776+I_IOA+AMB_TD, 06777+I_IOA+AMB_TD,
 06530+I_NPN, 06531+I_NPN, 06532+I_NPN, 06533+I_NPN,    /* AD */
 06534+I_NPN, 06535+I_NPN, 06536+I_NPN, 06537+I_NPN,
 06601+I_NPN, 06603+I_NPN, 06605+I_NPN,                 /* DF/RF */
 06611+I_NPN, 06612+I_NPN, 06615+I_NPN, 06616+I_NPN,
 06611+I_NPN,              06615+I_NPN, 06616+I_NPN,
 06621+I_NPN, 06622+I_NPN, 06623+I_NPN, 06626+I_NPN,
 06641+I_NPN, 06643+I_NPN, 06645+I_NPN,
 06661+I_NPN, 06662+I_NPN, 06663+I_NPN,                 /* LPT */
 06664+I_NPN, 06665+I_NPN, 06666+I_NPN, 06667+I_NPN,
 06701+I_NPN, 06702+I_NPN, 06703+I_NPN,                 /* MT */







|







365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
 06614+I_IOA+AMB_RL, 06615+I_IOA+AMB_RL, 06617+I_IOA+AMB_RL,
 06700+I_IOA+AMB_CT, 06701+I_IOA+AMB_CT, 06702+I_IOA+AMB_CT, 06703+I_IOA+AMB_CT,
 06704+I_IOA+AMB_CT, 06705+I_IOA+AMB_CT, 06706+I_IOA+AMB_CT, 06707+I_IOA+AMB_CT,
 06771+I_IOA+AMB_TD, 06772+I_IOA+AMB_TD, 06773+I_IOA+AMB_TD,
 06774+I_IOA+AMB_TD, 06775+I_IOA+AMB_TD, 06776+I_IOA+AMB_TD, 06777+I_IOA+AMB_TD,
 06530+I_NPN, 06531+I_NPN, 06532+I_NPN, 06533+I_NPN,    /* AD */
 06534+I_NPN, 06535+I_NPN, 06536+I_NPN, 06537+I_NPN,
 06660+I_NPN, 06601+I_NPN, 06603+I_NPN, 06605+I_NPN,                 /* DF/RF */
 06611+I_NPN, 06612+I_NPN, 06615+I_NPN, 06616+I_NPN,
 06611+I_NPN,              06615+I_NPN, 06616+I_NPN,
 06621+I_NPN, 06622+I_NPN, 06623+I_NPN, 06626+I_NPN,
 06641+I_NPN, 06643+I_NPN, 06645+I_NPN,
 06661+I_NPN, 06662+I_NPN, 06663+I_NPN,                 /* LPT */
 06664+I_NPN, 06665+I_NPN, 06666+I_NPN, 06667+I_NPN,
 06701+I_NPN, 06702+I_NPN, 06703+I_NPN,                 /* MT */
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
    };

/* Operate decode

   Inputs:
        *of     =       output stream
        inst    =       mask bits
        class   =       instruction class code
        sp      =       space needed?
   Outputs:
        status  =       space needed
*/

/* Use scp.c provided fprintf function */
#define fprintf Fprintf
#define fputs(_s,f) Fprintf(f,"%s",_s)
#define fputc(_c,f) Fprintf(f,"%c",_c)

int32 fprint_opr (FILE *of, int32 inst, int32 class, int32 sp)
{
int32 i, j;

for (i = 0; opc_val[i] >= 0; i++) {                     /* loop thru ops */
    j = (opc_val[i] >> I_V_FL) & I_M_FL;                /* get class */
    if ((j == class) && (opc_val[i] & inst)) {          /* same class? */
        inst = inst & ~opc_val[i];                      /* mask bit set? */
        fprintf (of, (sp? " %s": "%s"), opcode[i]);
        sp = 1;
        }
    }
return sp;
}







|










|





|







515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
    };

/* Operate decode

   Inputs:
        *of     =       output stream
        inst    =       mask bits
        Class   =       instruction class code
        sp      =       space needed?
   Outputs:
        status  =       space needed
*/

/* Use scp.c provided fprintf function */
#define fprintf Fprintf
#define fputs(_s,f) Fprintf(f,"%s",_s)
#define fputc(_c,f) Fprintf(f,"%c",_c)

int32 fprint_opr (FILE *of, int32 inst, int32 Class, int32 sp)
{
int32 i, j;

for (i = 0; opc_val[i] >= 0; i++) {                     /* loop thru ops */
    j = (opc_val[i] >> I_V_FL) & I_M_FL;                /* get class */
    if ((j == Class) && (opc_val[i] & inst)) {          /* same class? */
        inst = inst & ~opc_val[i];                      /* mask bit set? */
        fprintf (of, (sp? " %s": "%s"), opcode[i]);
        sp = 1;
        }
    }
return sp;
}
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
        *uptr   =       pointer to unit
        *val    =       pointer to output values
        sw      =       switches
   Outputs:
        status  =       error status
*/

t_stat parse_sym (char *cptr, t_addr addr, UNIT *uptr, t_value *val, int32 sw)
{
uint32 cflag, d, i, j, k;
t_stat r;
char gbuf[CBUFSIZE];

cflag = (uptr == NULL) || (uptr == &cpu_unit);
while (isspace (*cptr)) cptr++;                         /* absorb spaces */







|







675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
        *uptr   =       pointer to unit
        *val    =       pointer to output values
        sw      =       switches
   Outputs:
        status  =       error status
*/

t_stat parse_sym (CONST char *cptr, t_addr addr, UNIT *uptr, t_value *val, int32 sw)
{
uint32 cflag, d, i, j, k;
t_stat r;
char gbuf[CBUFSIZE];

cflag = (uptr == NULL) || (uptr == &cpu_unit);
while (isspace (*cptr)) cptr++;                         /* absorb spaces */
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        }                                               /* end if */
    }                                                   /* end for */
return SCPE_ARG;
}

/* FPP8 instruction parse */

t_stat parse_sym_fpp (char *cptr, t_value *val)
{
uint32 i, j, ad, xr;
int32 broff, nwd;
char gbuf[CBUFSIZE];

cptr = get_glyph (cptr, gbuf, 0);                       /* get opcode */
for (i = 0; (fopcode[i] != NULL) && (strcmp (fopcode[i], gbuf) != 0) ; i++) ;







|







865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
        }                                               /* end if */
    }                                                   /* end for */
return SCPE_ARG;
}

/* FPP8 instruction parse */

t_stat parse_sym_fpp (CONST char *cptr, t_value *val)
{
uint32 i, j, ad, xr;
int32 broff, nwd;
char gbuf[CBUFSIZE];

cptr = get_glyph (cptr, gbuf, 0);                       /* get opcode */
for (i = 0; (fopcode[i] != NULL) && (strcmp (fopcode[i], gbuf) != 0) ; i++) ;
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993

if (*cptr != 0) return SCPE_ARG;                        /* junk at end? */
return -nwd;
}

/* Parse field */

char *parse_field (char *cptr, uint32 max, uint32 *val, uint32 c)
{
char gbuf[CBUFSIZE];
t_stat r;

cptr = get_glyph (cptr, gbuf, c);                       /* get field */
*val = get_uint (gbuf, 8, max, &r);
if (r != SCPE_OK)
    return NULL;
return cptr;
}

/* Parse index register */

char *parse_fpp_xr (char *cptr, uint32 *xr, t_bool inc)
{
char gbuf[CBUFSIZE];
uint32 len;
t_stat r;

cptr = get_glyph (cptr, gbuf, 0);                      /* get field */
len = strlen (gbuf);







|













|







966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994

if (*cptr != 0) return SCPE_ARG;                        /* junk at end? */
return -nwd;
}

/* Parse field */

CONST char *parse_field (CONST char *cptr, uint32 max, uint32 *val, uint32 c)
{
char gbuf[CBUFSIZE];
t_stat r;

cptr = get_glyph (cptr, gbuf, c);                       /* get field */
*val = get_uint (gbuf, 8, max, &r);
if (r != SCPE_OK)
    return NULL;
return cptr;
}

/* Parse index register */

CONST char *parse_fpp_xr (CONST char *cptr, uint32 *xr, t_bool inc)
{
char gbuf[CBUFSIZE];
uint32 len;
t_stat r;

cptr = get_glyph (cptr, gbuf, 0);                      /* get field */
len = strlen (gbuf);
Changes to src/PDP8/pdp8_td.c.
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
int32 td_csum = 0;                                      /* save check sum */
int32 td_qlctr = 0;                                     /* quad line ctr */
int32 td_ltime = 20;                                    /* interline time */
int32 td_dctime = 40000;                                /* decel time */
int32 td_stopoffr = 0;
static uint8 tdb_mtk[DT_NUMDR][D18_LPERB];              /* mark track bits */

DEVICE td_dev;
int32 td77 (int32 IR, int32 AC);
t_stat td_svc (UNIT *uptr);
t_stat td_reset (DEVICE *dptr);
t_stat td_attach (UNIT *uptr, char *cptr);
void td_flush (UNIT *uptr);
t_stat td_detach (UNIT *uptr);
t_stat td_boot (int32 unitno, DEVICE *dptr);
t_bool td_newsa (int32 newf);
t_bool td_setpos (UNIT *uptr);
int32 td_header (UNIT *uptr, int32 blk, int32 line);
int32 td_trailer (UNIT *uptr, int32 blk, int32 line);
int32 td_read (UNIT *uptr, int32 blk, int32 line);
void td_write (UNIT *uptr, int32 blk, int32 line, int32 datb);
int32 td_set_mtk (int32 code, int32 u, int32 k);
t_stat td_show_pos (FILE *st, UNIT *uptr, int32 val, void *desc);

extern uint16 M[];

/* TD data structures

   td_dev       DT device descriptor
   td_unit      DT unit list







<



|










|







189
190
191
192
193
194
195

196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
int32 td_csum = 0;                                      /* save check sum */
int32 td_qlctr = 0;                                     /* quad line ctr */
int32 td_ltime = 20;                                    /* interline time */
int32 td_dctime = 40000;                                /* decel time */
int32 td_stopoffr = 0;
static uint8 tdb_mtk[DT_NUMDR][D18_LPERB];              /* mark track bits */


int32 td77 (int32 IR, int32 AC);
t_stat td_svc (UNIT *uptr);
t_stat td_reset (DEVICE *dptr);
t_stat td_attach (UNIT *uptr, CONST char *cptr);
void td_flush (UNIT *uptr);
t_stat td_detach (UNIT *uptr);
t_stat td_boot (int32 unitno, DEVICE *dptr);
t_bool td_newsa (int32 newf);
t_bool td_setpos (UNIT *uptr);
int32 td_header (UNIT *uptr, int32 blk, int32 line);
int32 td_trailer (UNIT *uptr, int32 blk, int32 line);
int32 td_read (UNIT *uptr, int32 blk, int32 line);
void td_write (UNIT *uptr, int32 blk, int32 line, int32 datb);
int32 td_set_mtk (int32 code, int32 u, int32 k);
t_stat td_show_pos (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

extern uint16 M[];

/* TD data structures

   td_dev       DT device descriptor
   td_unit      DT unit list
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    { UDATA (&td_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) },
    { UDATA (&td_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) }
    };

REG td_reg[] = {
    { GRDATA (TDCMD, td_cmd, 8, 4, 8) },
    { ORDATA (TDDAT, td_dat, 12) },
    { ORDATA (TDMTK, td_mtk, 6) },
    { FLDATA (TDSLF, td_slf, 0) },
    { FLDATA (TDQLF, td_qlf, 0) },
    { FLDATA (TDTME, td_tme, 0) },
    { ORDATA (TDQL, td_qlctr, 2) },
    { ORDATA (TDCSUM, td_csum, 6), REG_RO },
    { DRDATA (LTIME, td_ltime, 31), REG_NZ | PV_LEFT },
    { DRDATA (DCTIME, td_dctime, 31), REG_NZ | PV_LEFT },
    { URDATA (POS, td_unit[0].pos, 10, T_ADDR_W, 0,
              DT_NUMDR, PV_LEFT | REG_RO) },
    { URDATA (STATT, td_unit[0].STATE, 8, 18, 0,
              DT_NUMDR, REG_RO) },
    { URDATA (LASTT, td_unit[0].LASTT, 10, 32, 0,
              DT_NUMDR, REG_HRO) },
    { FLDATA (STOP_OFFR, td_stopoffr, 0) },
    { ORDATA (DEVNUM, td_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB td_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL }, 







|
|
|
|
|
|
|

|
|
|
|
|
|


|







225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    { UDATA (&td_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) },
    { UDATA (&td_svc, UNIT_8FMT+UNIT_FIX+UNIT_ATTABLE+
             UNIT_DISABLE+UNIT_ROABLE, DT_CAPAC) }
    };

REG td_reg[] = {
    { GRDATAD (TDCMD, td_cmd, 8, 4, 8, "command register") },
    { ORDATAD (TDDAT, td_dat, 12, "data register") },
    { ORDATAD (TDMTK, td_mtk, 6, "mark track register") },
    { FLDATAD (TDSLF, td_slf, 0, "single line flag") },
    { FLDATAD (TDQLF, td_qlf, 0, "quad line flag") },
    { FLDATAD (TDTME, td_tme, 0, "timing error flag") },
    { ORDATAD (TDQL, td_qlctr, 2, "quad line counter") },
    { ORDATA (TDCSUM, td_csum, 6), REG_RO },
    { DRDATAD (LTIME, td_ltime, 31, "time between lines"), REG_NZ | PV_LEFT },
    { DRDATAD (DCTIME, td_dctime, 31, "time to decelerate to a full stop"), REG_NZ | PV_LEFT },
    { URDATAD (POS, td_unit[0].pos, 10, T_ADDR_W, 0,
              DT_NUMDR, PV_LEFT | REG_RO, "positions, in lines, units 0 and 1") },
    { URDATAD (STATT, td_unit[0].STATE, 8, 18, 0,
              DT_NUMDR, REG_RO, "unit state, units 0 and 1") },
    { URDATA (LASTT, td_unit[0].LASTT, 10, 32, 0,
              DT_NUMDR, REG_HRO) },
    { FLDATAD (STOP_OFFR, td_stopoffr, 0, "stop on off-reel error") },
    { ORDATA (DEVNUM, td_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB td_mod[] = {
    { UNIT_WLK, 0, "write enabled", "WRITEENABLED", NULL },
    { UNIT_WLK, UNIT_WLK, "write locked", "LOCKED", NULL }, 
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
   Determine 12b, 16b, or 18b/36b format
   Allocate buffer
   If 16b or 18b, read 16b or 18b format and convert to 12b in buffer
   If 12b, read data into buffer
   Set up mark track bit array
*/

t_stat td_attach (UNIT *uptr, char *cptr)
{
uint32 pdp18b[D18_NBSIZE];
uint16 pdp11b[D18_NBSIZE], *fbuf;
int32 i, k, mtkpb;
int32 u = uptr - td_dev.units;
t_stat r;
uint32 ba, sz;







|







761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
   Determine 12b, 16b, or 18b/36b format
   Allocate buffer
   If 16b or 18b, read 16b or 18b format and convert to 12b in buffer
   If 12b, read data into buffer
   Set up mark track bit array
*/

t_stat td_attach (UNIT *uptr, CONST char *cptr)
{
uint32 pdp18b[D18_NBSIZE];
uint16 pdp11b[D18_NBSIZE], *fbuf;
int32 i, k, mtkpb;
int32 u = uptr - td_dev.units;
t_stat r;
uint32 ba, sz;
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
for (i = 5; i >= 0; i--)
    tdb_mtk[u][k++] = (code >> i) & 1;
return k;
}

/* Show position */

t_stat td_show_pos (FILE *st, UNIT *uptr, int32 val, void *desc)
{
if ((uptr->flags & UNIT_ATT) == 0) return SCPE_UNATT;
if (uptr->pos < DT_EZLIN)                               /* rev end zone? */
    fprintf (st, "Reverse end zone\n");
else if (uptr->pos < ((uint32) DTU_FWDEZ (uptr))) {     /* data zone? */
    int32 blkno = DT_LIN2BL (uptr->pos, uptr);          /* block # */
    int32 lineno = DT_LIN2OF (uptr->pos, uptr);         /* line # within block */







|







926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
for (i = 5; i >= 0; i--)
    tdb_mtk[u][k++] = (code >> i) & 1;
return k;
}

/* Show position */

t_stat td_show_pos (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
if ((uptr->flags & UNIT_ATT) == 0) return SCPE_UNATT;
if (uptr->pos < DT_EZLIN)                               /* rev end zone? */
    fprintf (st, "Reverse end zone\n");
else if (uptr->pos < ((uint32) DTU_FWDEZ (uptr))) {     /* data zone? */
    int32 blkno = DT_LIN2BL (uptr->pos, uptr);          /* block # */
    int32 lineno = DT_LIN2OF (uptr->pos, uptr);         /* line # within block */
Changes to src/PDP8/pdp8_tsc.c.
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
extern int32 tsc_pc;                                    /* "ERTB" */
extern int32 tsc_cdf;                                   /* "ECDF" */
extern int32 tsc_enb;                                   /* enable */

#define UNIT_V_SN699    (UNIT_V_UF + 0)                 /* SN 699 or above */
#define UNIT_SN699      (1 << UNIT_V_SN699)

DEVICE tsc_dev;
int32 tsc (int32 IR, int32 AC);
t_stat tsc_reset (DEVICE *dptr);

/* TSC data structures

   tsc_dev      TSC device descriptor
   tsc_unit     TSC unit descriptor
   tsc_reg      TSC register list
*/

DIB tsc_dib = { DEV_TSC, 1, { &tsc } };

UNIT tsc_unit = { UDATA (NULL, UNIT_SN699, 0) };

REG tsc_reg[] = {
    { ORDATA (IR, tsc_ir, 12) },
    { ORDATA (PC, tsc_pc, 12) },
    { FLDATA (CDF, tsc_cdf, 0) },
    { FLDATA (ENB, tsc_enb, 0) },
    { FLDATA (INT, int_req, INT_V_TSC) },
    { NULL }
    };

MTAB tsc_mod[] = {
    { UNIT_SN699, UNIT_SN699, "ESME", "ESME", NULL },
    { UNIT_SN699, 0, "no ESME", "NOESME", NULL },
    { 0 }







<















|
|
|
|
|







56
57
58
59
60
61
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
extern int32 tsc_pc;                                    /* "ERTB" */
extern int32 tsc_cdf;                                   /* "ECDF" */
extern int32 tsc_enb;                                   /* enable */

#define UNIT_V_SN699    (UNIT_V_UF + 0)                 /* SN 699 or above */
#define UNIT_SN699      (1 << UNIT_V_SN699)


int32 tsc (int32 IR, int32 AC);
t_stat tsc_reset (DEVICE *dptr);

/* TSC data structures

   tsc_dev      TSC device descriptor
   tsc_unit     TSC unit descriptor
   tsc_reg      TSC register list
*/

DIB tsc_dib = { DEV_TSC, 1, { &tsc } };

UNIT tsc_unit = { UDATA (NULL, UNIT_SN699, 0) };

REG tsc_reg[] = {
    { ORDATAD (IR, tsc_ir, 12, "most recently trapped instruction") },
    { ORDATAD (PC, tsc_pc, 12, "PC of most recently trapped instruction") },
    { FLDATAD (CDF, tsc_cdf, 0, "1 if trapped instruction is CDF, 0 otherwise") },
    { FLDATAD (ENB, tsc_enb, 0, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_TSC, "interrupt pending flag") },
    { NULL }
    };

MTAB tsc_mod[] = {
    { UNIT_SN699, UNIT_SN699, "ESME", "ESME", NULL },
    { UNIT_SN699, 0, "no ESME", "NOESME", NULL },
    { 0 }
Changes to src/PDP8/pdp8_tt.c.
1
2
3
4
5
6
7
8
9
10
/* pdp8_tt.c: PDP-8 console terminal simulator

   Copyright (c) 1993-2012, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_tt.c: PDP-8 console terminal simulator

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97


98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

int32 tti (int32 IR, int32 AC);
int32 tto (int32 IR, int32 AC);
t_stat tti_svc (UNIT *uptr);
t_stat tto_svc (UNIT *uptr);
t_stat tti_reset (DEVICE *dptr);
t_stat tto_reset (DEVICE *dptr);
t_stat tty_set_mode (UNIT *uptr, int32 val, char *cptr, void *desc);

/* TTI data structures

   tti_dev      TTI device descriptor
   tti_unit     TTI unit descriptor
   tti_reg      TTI register list
   tti_mod      TTI modifiers list
*/

DIB tti_dib = { DEV_TTI, 1, { &tti } };

UNIT tti_unit = { UDATA (&tti_svc, UNIT_IDLE|TT_MODE_KSR, 0), SERIAL_IN_WAIT };

REG tti_reg[] = {
    { ORDATA (BUF, tti_unit.buf, 8) },
    { FLDATA (DONE, dev_done, INT_V_TTI) },
    { FLDATA (ENABLE, int_enable, INT_V_TTI) },
    { FLDATA (INT, int_req, INT_V_TTI) },
    { DRDATA (POS, tti_unit.pos, T_ADDR_W), PV_LEFT },
    { DRDATA (TIME, tti_unit.wait, 24), PV_LEFT },
    { NULL }
    };

MTAB tti_mod[] = {
    { TT_MODE, TT_MODE_KSR, "KSR", "KSR", &tty_set_mode },
    { TT_MODE, TT_MODE_7B,  "7b",  "7B",  &tty_set_mode },
    { TT_MODE, TT_MODE_8B,  "8b",  "8B",  &tty_set_mode },
    { TT_MODE, TT_MODE_7P,  "7b",  NULL,  NULL },
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev, NULL },
    { 0 }
    };

DEVICE tti_dev = {
    "TTI", &tti_unit, tti_reg, tti_mod,
    1, 10, 31, 1, 8, 8,
    NULL, NULL, &tti_reset,
    NULL, NULL, NULL,
    &tti_dib, 0
    };



/* TTO data structures

   tto_dev      TTO device descriptor
   tto_unit     TTO unit descriptor
   tto_reg      TTO register list
*/

DIB tto_dib = { DEV_TTO, 1, { &tto } };

UNIT tto_unit = { UDATA (&tto_svc, TT_MODE_KSR, 0), SERIAL_OUT_WAIT };

REG tto_reg[] = {
    { ORDATA (BUF, tto_unit.buf, 8) },
    { FLDATA (DONE, dev_done, INT_V_TTO) },
    { FLDATA (ENABLE, int_enable, INT_V_TTO) },
    { FLDATA (INT, int_req, INT_V_TTO) },
    { DRDATA (POS, tto_unit.pos, T_ADDR_W), PV_LEFT },
    { DRDATA (TIME, tto_unit.wait, 24), PV_LEFT },
    { NULL }
    };

MTAB tto_mod[] = {
    { TT_MODE, TT_MODE_KSR, "KSR", "KSR", &tty_set_mode },
    { TT_MODE, TT_MODE_7B,  "7b",  "7B",  &tty_set_mode },
    { TT_MODE, TT_MODE_8B,  "8b",  "8B",  &tty_set_mode },







|














|
|
|
|
|
|




















>
>












|
|
|
|
|
|







50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124

int32 tti (int32 IR, int32 AC);
int32 tto (int32 IR, int32 AC);
t_stat tti_svc (UNIT *uptr);
t_stat tto_svc (UNIT *uptr);
t_stat tti_reset (DEVICE *dptr);
t_stat tto_reset (DEVICE *dptr);
t_stat tty_set_mode (UNIT *uptr, int32 val, CONST char *cptr, void *desc);

/* TTI data structures

   tti_dev      TTI device descriptor
   tti_unit     TTI unit descriptor
   tti_reg      TTI register list
   tti_mod      TTI modifiers list
*/

DIB tti_dib = { DEV_TTI, 1, { &tti } };

UNIT tti_unit = { UDATA (&tti_svc, UNIT_IDLE|TT_MODE_KSR, 0), SERIAL_IN_WAIT };

REG tti_reg[] = {
    { ORDATAD (BUF, tti_unit.buf, 8, "last data item processed") },
    { FLDATAD (DONE, dev_done, INT_V_TTI, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_TTI, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_TTI, "interrupt pending flag") },
    { DRDATAD (POS, tti_unit.pos, T_ADDR_W, "number of characters input"), PV_LEFT },
    { DRDATAD (TIME, tti_unit.wait, 24, "input polling interval (if 0, the keyboard is polled synchronously with the clock)"), PV_LEFT+REG_NZ },
    { NULL }
    };

MTAB tti_mod[] = {
    { TT_MODE, TT_MODE_KSR, "KSR", "KSR", &tty_set_mode },
    { TT_MODE, TT_MODE_7B,  "7b",  "7B",  &tty_set_mode },
    { TT_MODE, TT_MODE_8B,  "8b",  "8B",  &tty_set_mode },
    { TT_MODE, TT_MODE_7P,  "7b",  NULL,  NULL },
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", NULL, NULL, &show_dev, NULL },
    { 0 }
    };

DEVICE tti_dev = {
    "TTI", &tti_unit, tti_reg, tti_mod,
    1, 10, 31, 1, 8, 8,
    NULL, NULL, &tti_reset,
    NULL, NULL, NULL,
    &tti_dib, 0
    };

uint32 tti_buftime;                                     /* time input character arrived */

/* TTO data structures

   tto_dev      TTO device descriptor
   tto_unit     TTO unit descriptor
   tto_reg      TTO register list
*/

DIB tto_dib = { DEV_TTO, 1, { &tto } };

UNIT tto_unit = { UDATA (&tto_svc, TT_MODE_KSR, 0), SERIAL_OUT_WAIT };

REG tto_reg[] = {
    { ORDATAD (BUF, tto_unit.buf, 8, "last date item processed") },
    { FLDATAD (DONE, dev_done, INT_V_TTO, "device done flag") },
    { FLDATAD (ENABLE, int_enable, INT_V_TTO, "interrupt enable flag") },
    { FLDATAD (INT, int_req, INT_V_TTO, "interrupt pending flag") },
    { DRDATAD (POS, tto_unit.pos, T_ADDR_W, "number of characters output"), PV_LEFT },
    { DRDATAD (TIME, tto_unit.wait, 24, "time form I/O initiation to interrupt"), PV_LEFT },
    { NULL }
    };

MTAB tto_mod[] = {
    { TT_MODE, TT_MODE_KSR, "KSR", "KSR", &tty_set_mode },
    { TT_MODE, TT_MODE_7B,  "7b",  "7B",  &tty_set_mode },
    { TT_MODE, TT_MODE_8B,  "8b",  "8B",  &tty_set_mode },
175
176
177
178
179
180
181
182

183
184
185
186
187
188

189
190
191
192
193
194
195
/* Unit service */

t_stat tti_svc (UNIT *uptr)
{
int32 c;

sim_clock_coschedule (uptr, tmxr_poll);                 /* continue poll */
if (dev_done & INT_TTI)                                 /* prior character still pending? */

    return SCPE_OK;
if ((c = sim_poll_kbd ()) < SCPE_KFLAG)                 /* no char or error? */
    return c;
if (c & SCPE_BREAK)                                     /* break? */
    uptr->buf = 0;
else uptr->buf = sim_tt_inpcvt (c, TT_GET_MODE (uptr->flags) | TTUF_KSR);

uptr->pos = uptr->pos + 1;
dev_done = dev_done | INT_TTI;                          /* set done */
int_req = INT_UPDATE;                                   /* update interrupts */
return SCPE_OK;
}

/* Reset routine */







|
>






>







177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* Unit service */

t_stat tti_svc (UNIT *uptr)
{
int32 c;

sim_clock_coschedule (uptr, tmxr_poll);                 /* continue poll */
if ((dev_done & INT_TTI) &&                             /* prior character still pending and < 500ms? */
    ((sim_os_msec () - tti_buftime) < 500))
    return SCPE_OK;
if ((c = sim_poll_kbd ()) < SCPE_KFLAG)                 /* no char or error? */
    return c;
if (c & SCPE_BREAK)                                     /* break? */
    uptr->buf = 0;
else uptr->buf = sim_tt_inpcvt (c, TT_GET_MODE (uptr->flags) | TTUF_KSR);
tti_buftime = sim_os_msec ();
uptr->pos = uptr->pos + 1;
dev_done = dev_done | INT_TTI;                          /* set done */
int_req = INT_UPDATE;                                   /* update interrupts */
return SCPE_OK;
}

/* Reset routine */
269
270
271
272
273
274
275
276
277
278
279
280
281
dev_done = dev_done & ~INT_TTO;                         /* clear done, int */
int_req = int_req & ~INT_TTO;
int_enable = int_enable | INT_TTO;                      /* set enable */
sim_cancel (&tto_unit);                                 /* deactivate unit */
return SCPE_OK;
}

t_stat tty_set_mode (UNIT *uptr, int32 val, char *cptr, void *desc)
{
tti_unit.flags = (tti_unit.flags & ~TT_MODE) | val;
tto_unit.flags = (tto_unit.flags & ~TT_MODE) | val;
return SCPE_OK;
}







|





273
274
275
276
277
278
279
280
281
282
283
284
285
dev_done = dev_done & ~INT_TTO;                         /* clear done, int */
int_req = int_req & ~INT_TTO;
int_enable = int_enable | INT_TTO;                      /* set enable */
sim_cancel (&tto_unit);                                 /* deactivate unit */
return SCPE_OK;
}

t_stat tty_set_mode (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
tti_unit.flags = (tti_unit.flags & ~TT_MODE) | val;
tto_unit.flags = (tto_unit.flags & ~TT_MODE) | val;
return SCPE_OK;
}
Changes to src/PDP8/pdp8_ttx.c.
1
2
3
4
5
6
7
8
9
10
/* pdp8_ttx.c: PDP-8 additional terminals simulator

   Copyright (c) 1993-2013, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* pdp8_ttx.c: PDP-8 additional terminals simulator

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51





52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69


70
71

72
73
74
75
76
77
78


79
80
81



82









83
84
85
86
87
88
89
90
91


















92
93
94
95
96
97
98


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   ttix,ttox    PT08/KL8JA terminal input/output


   11-Oct-13    RMS     Poll TTIX immediately to pick up initial connect (Mark Pizzolato)
   18-Apr-12    RMS     Revised to use clock coscheduling
   19-Nov-08    RMS     Revised for common TMXR show routines
   07-Jun-06    RMS     Added UNIT_IDLE flag
   06-Jul-06    RMS     Fixed bug in DETACH routine
   22-Nov-05    RMS     Revised for new terminal processing routines
   29-Jun-05    RMS     Added SET TTOXn DISCONNECT
                        Fixed bug in SET LOG/NOLOG
   21-Jun-05    RMS     Fixed bug in SHOW CONN/STATS
   05-Jan-04    RMS     Revised for tmxr library changes
   09-May-03    RMS     Added network device flag
   25-Apr-03    RMS     Revised for extended file support
   22-Dec-02    RMS     Added break support
   02-Nov-02    RMS     Added 7B/8B support
   04-Oct-02    RMS     Added DIB, device number support
   22-Aug-02    RMS     Updated for changes to sim_tmxr.c
   06-Jan-02    RMS     Added device enable/disable support
   30-Dec-01    RMS     Complete rebuild
   30-Nov-01    RMS     Added extended SET/SHOW support

   This module implements four individual serial interfaces similar in function
   to the console.  These interfaces are mapped to Telnet based connections as
   though they were the four lines of a terminal multiplexor.  The connection
   polling mechanism is superimposed onto the keyboard of the first interface.





*/

#include "pdp8_defs.h"
#include "sim_sock.h"
#include "sim_tmxr.h"
#include <ctype.h>

#define TTX_LINES       4
#define TTX_MASK        (TTX_LINES - 1)

#define TTX_GETLN(x)    (((x) >> 4) & TTX_MASK)

extern int32 int_req, int_enable, dev_done, stop_inst;
extern int32 tmxr_poll;

uint8 ttix_buf[TTX_LINES] = { 0 };                      /* input buffers */
uint8 ttox_buf[TTX_LINES] = { 0 };                      /* output buffers */
int32 ttx_tps = 100;                                    /* polls per second */


TMLN ttx_ldsc[TTX_LINES] = { {0} };                     /* line descriptors */
TMXR ttx_desc = { TTX_LINES, 0, 0, ttx_ldsc };          /* mux descriptor */


DEVICE ttix_dev, ttox_dev;
int32 ttix (int32 IR, int32 AC);
int32 ttox (int32 IR, int32 AC);
t_stat ttix_svc (UNIT *uptr);
t_stat ttix_reset (DEVICE *dptr);
t_stat ttox_svc (UNIT *uptr);


t_stat ttox_reset (DEVICE *dptr);
t_stat ttx_attach (UNIT *uptr, char *cptr);
t_stat ttx_detach (UNIT *uptr);



void ttx_enbdis (int32 dis);










/* TTIx data structures

   ttix_dev     TTIx device descriptor
   ttix_unit    TTIx unit descriptor
   ttix_reg     TTIx register list
   ttix_mod     TTIx modifiers list
*/



















DIB ttix_dib = { DEV_KJ8, 8,
             { &ttix, &ttox, &ttix, &ttox, &ttix, &ttox, &ttix, &ttox } };

UNIT ttix_unit = { UDATA (&ttix_svc, UNIT_IDLE|UNIT_ATTABLE, 0), SERIAL_IN_WAIT };

REG ttix_reg[] = {
    { BRDATA (BUF, ttix_buf, 8, 8, TTX_LINES) },


    { GRDATA (DONE, dev_done, 8, TTX_LINES, INT_V_TTI1) },
    { GRDATA (ENABLE, int_enable, 8, TTX_LINES, INT_V_TTI1) },
    { GRDATA (INT, int_req, 8, TTX_LINES, INT_V_TTI1) },
    { DRDATA (TIME, ttix_unit.wait, 24), REG_NZ + PV_LEFT },
    { DRDATA (TPS, ttx_tps, 10), REG_NZ + PV_LEFT },
    { ORDATA (DEVNUM, ttix_dib.dev, 6), REG_HRO },
    { NULL }
    };

MTAB ttix_mod[] = {
    { UNIT_ATT, UNIT_ATT, "summary", NULL,
      NULL, &tmxr_show_summ, (void *) &ttx_desc },
    { MTAB_XTD | MTAB_VDV, 1, NULL, "DISCONNECT",
      &tmxr_dscln, NULL, (void *) &ttx_desc },
    { MTAB_XTD | MTAB_VDV | MTAB_NMO, 1, "CONNECTIONS", NULL,
      NULL, &tmxr_show_cstat, (void *) &ttx_desc },
    { MTAB_XTD | MTAB_VDV | MTAB_NMO, 0, "STATISTICS", NULL,
      NULL, &tmxr_show_cstat, (void *) &ttx_desc },
    { MTAB_XTD|MTAB_VDV, 0, "DEVNO", "DEVNO",
      &set_dev, &show_dev, NULL },
    { 0 }
    };

/* debugging bitmaps */
#define DBG_XMT  TMXR_DBG_XMT                           /* display Transmitted Data */
#define DBG_RCV  TMXR_DBG_RCV                           /* display Received Data */
#define DBG_RET  TMXR_DBG_RET                           /* display Returned Received Data */







>




















|



>
>
>
>
>







|
|






|
|
|
>
>
|
|
>

<



<

>
>
|
|

>
>
>
|
>
>
>
>
>
>
>
>
>









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|




|
>
>
|
|
<
|
<
|




<
|
|
|
|
|
<
|
<
<







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

82
83
84

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

142

143
144
145
146
147

148
149
150
151
152

153


154
155
156
157
158
159
160

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   ttix,ttox    PT08/KL8JA terminal input/output

   18-Sep-16    RMS     Expanded support to 16 terminals
   11-Oct-13    RMS     Poll TTIX immediately to pick up initial connect (Mark Pizzolato)
   18-Apr-12    RMS     Revised to use clock coscheduling
   19-Nov-08    RMS     Revised for common TMXR show routines
   07-Jun-06    RMS     Added UNIT_IDLE flag
   06-Jul-06    RMS     Fixed bug in DETACH routine
   22-Nov-05    RMS     Revised for new terminal processing routines
   29-Jun-05    RMS     Added SET TTOXn DISCONNECT
                        Fixed bug in SET LOG/NOLOG
   21-Jun-05    RMS     Fixed bug in SHOW CONN/STATS
   05-Jan-04    RMS     Revised for tmxr library changes
   09-May-03    RMS     Added network device flag
   25-Apr-03    RMS     Revised for extended file support
   22-Dec-02    RMS     Added break support
   02-Nov-02    RMS     Added 7B/8B support
   04-Oct-02    RMS     Added DIB, device number support
   22-Aug-02    RMS     Updated for changes to sim_tmxr.c
   06-Jan-02    RMS     Added device enable/disable support
   30-Dec-01    RMS     Complete rebuild
   30-Nov-01    RMS     Added extended SET/SHOW support

   This module implements 1-16 individual serial interfaces similar in function
   to the console.  These interfaces are mapped to Telnet based connections as
   though they were the four lines of a terminal multiplexor.  The connection
   polling mechanism is superimposed onto the keyboard of the first interface.

   The done and enable flags are maintained locally, and only a master interrupt
   request is maintained in global register dev_done. Because this is actually
   an interrupt request flag, the corresponding bit in int_enable must always
   be set to 1.
*/

#include "pdp8_defs.h"
#include "sim_sock.h"
#include "sim_tmxr.h"
#include <ctype.h>

#define TTX_MAXL        16
#define TTX_INIL        4

#define TTX_GETLN(x)    (((x) >> 4) & TTX_MASK)

extern int32 int_req, int_enable, dev_done, stop_inst;
extern int32 tmxr_poll;

uint32 ttix_done = 0;                                   /* input ready flags */
uint32 ttox_done = 0;                                   /* output ready flags */
uint32 ttx_enbl = 0;                                    /* intr enable flags */
uint8 ttix_buf[TTX_MAXL] = { 0 };                       /* input buffers */
uint8 ttox_buf[TTX_MAXL] = { 0 };                       /* output buffers */
TMLN ttx_ldsc[TTX_MAXL] = { {0} };                      /* line descriptors */
TMXR ttx_desc = { TTX_INIL, 0, 0, ttx_ldsc };           /* mux descriptor */
#define ttx_lines	ttx_desc.lines


int32 ttix (int32 IR, int32 AC);
int32 ttox (int32 IR, int32 AC);
t_stat ttix_svc (UNIT *uptr);

t_stat ttox_svc (UNIT *uptr);
int32 ttx_getln (int32 inst);
void ttx_new_flags (uint32 newi, uint32 newo, uint32 newe);
t_stat ttx_reset (DEVICE *dptr);
t_stat ttx_attach (UNIT *uptr, CONST char *cptr);
t_stat ttx_detach (UNIT *uptr);
void ttx_reset_ln (int32 i);
t_stat ttx_vlines (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat ttx_show_devno (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

#define TTIX_SET_DONE(ln)       ttx_new_flags (ttix_done | (1u << (ln)), ttox_done, ttx_enbl)
#define TTIX_CLR_DONE(ln)       ttx_new_flags (ttix_done & ~(1u << (ln)), ttox_done, ttx_enbl)
#define TTIX_TST_DONE(ln)       ((ttix_done & (1u << (ln))) != 0)
#define TTOX_SET_DONE(ln)       ttx_new_flags (ttix_done, ttox_done | (1u << (ln)), ttx_enbl)
#define TTOX_CLR_DONE(ln)       ttx_new_flags (ttix_done, ttox_done & ~(1u << (ln)), ttx_enbl)
#define TTOX_TST_DONE(ln)       ((ttox_done & (1u << (ln))) != 0)
#define TTX_SET_ENBL(ln)        ttx_new_flags (ttix_done, ttox_done, ttx_enbl | (1u << (ln)))
#define TTX_CLR_ENBL(ln)        ttx_new_flags (ttix_done, ttox_done, ttx_enbl & ~(1u << (ln)))
#define TTX_TST_ENBL(ln)        ((ttx_enbl & (1u << (ln))) != 0)

/* TTIx data structures

   ttix_dev     TTIx device descriptor
   ttix_unit    TTIx unit descriptor
   ttix_reg     TTIx register list
   ttix_mod     TTIx modifiers list
*/

DIB_DSP ttx_dsp[TTX_MAXL * 2] = {
    { DEV_TTI1,  &ttix }, { DEV_TTO1,  &ttox },
    { DEV_TTI2,  &ttix }, { DEV_TTO2,  &ttox },
    { DEV_TTI3,  &ttix }, { DEV_TTO3,  &ttox },
    { DEV_TTI4,  &ttix }, { DEV_TTO4,  &ttox },
    { DEV_TTI5,  &ttix }, { DEV_TTO5,  &ttox },
    { DEV_TTI6,  &ttix }, { DEV_TTO6,  &ttox },
    { DEV_TTI7,  &ttix }, { DEV_TTO7,  &ttox },
    { DEV_TTI8,  &ttix }, { DEV_TTO8,  &ttox },
    { DEV_TTI9,  &ttix }, { DEV_TTO9,  &ttox },
    { DEV_TTI10, &ttix }, { DEV_TTO10, &ttox },
    { DEV_TTI11, &ttix }, { DEV_TTO11, &ttox },
    { DEV_TTI12, &ttix }, { DEV_TTO12, &ttox },
    { DEV_TTI13, &ttix }, { DEV_TTO13, &ttox },
    { DEV_TTI14, &ttix }, { DEV_TTO14, &ttox },
    { DEV_TTI15, &ttix }, { DEV_TTO15, &ttox },
    { DEV_TTI16, &ttix }, { DEV_TTO16, &ttox }
    };

DIB ttx_dib = { DEV_TTI1, TTX_INIL * 2, { &ttix, &ttox }, ttx_dsp };

UNIT ttix_unit = { UDATA (&ttix_svc, UNIT_IDLE|UNIT_ATTABLE, 0), SERIAL_IN_WAIT };

REG ttix_reg[] = {
    { BRDATAD (BUF, ttix_buf, 8, 8, TTX_MAXL, "input buffer, lines 0 to 15") },
    { ORDATAD (DONE, ttix_done, TTX_MAXL, "device done flag (line 0 rightmost)") },
    { ORDATAD (ENABLE, ttx_enbl, TTX_MAXL, "interrupt enable flag") },
    { FLDATA  (SUMDONE, dev_done, INT_V_TTI1), REG_HRO },
    { FLDATA  (SUMENABLE, int_enable, INT_V_TTI1), REG_HRO },

    { DRDATAD (TIME, ttix_unit.wait, 24, "initial polling interval"), REG_NZ + PV_LEFT },

    { DRDATA  (LINES, ttx_desc.lines, 6), REG_HRO },
    { NULL }
    };

MTAB ttix_mod[] = {

    { MTAB_VDV,            0,       "LINES",      "LINES", &ttx_vlines,  &tmxr_show_lines, (void *) &ttx_desc },
    { MTAB_VDV,            0,      "DEVNO",          NULL, NULL,         &ttx_show_devno, (void *) &ttx_desc },
    { UNIT_ATT,     UNIT_ATT,     "SUMMARY",         NULL, NULL,         &tmxr_show_summ,  (void *) &ttx_desc },
    { MTAB_VDV,            1,          NULL, "DISCONNECT", &tmxr_dscln,  NULL,             (void *) &ttx_desc },
    { MTAB_VDV | MTAB_NMO, 1, "CONNECTIONS",         NULL, NULL,         &tmxr_show_cstat, (void *) &ttx_desc },

    { MTAB_VDV | MTAB_NMO, 0, "STATISTICS",          NULL, NULL,         &tmxr_show_cstat, (void *) &ttx_desc },


    { 0 }
    };

/* debugging bitmaps */
#define DBG_XMT  TMXR_DBG_XMT                           /* display Transmitted Data */
#define DBG_RCV  TMXR_DBG_RCV                           /* display Received Data */
#define DBG_RET  TMXR_DBG_RET                           /* display Returned Received Data */
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158












159
160
161
162


163
164
165
166
167
168
169
170
171
172
173
174
175

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
  {"TRC",    DBG_TRC},
  {0}
};

DEVICE ttix_dev = {
    "TTIX", &ttix_unit, ttix_reg, ttix_mod,
    1, 10, 31, 1, 8, 8,
    &tmxr_ex, &tmxr_dep, &ttix_reset,
    NULL, &ttx_attach, &ttx_detach,
    &ttix_dib, DEV_MUX | DEV_DISABLE | DEV_DEBUG,
    0, ttx_debug
    };

/* TTOx data structures

   ttox_dev     TTOx device descriptor
   ttox_unit    TTOx unit descriptor
   ttox_reg     TTOx register list
*/

UNIT ttox_unit[] = {
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT }












    };

REG ttox_reg[] = {
    { BRDATA (BUF, ttox_buf, 8, 8, TTX_LINES) },


    { GRDATA (DONE, dev_done, 8, TTX_LINES, INT_V_TTO1) },
    { GRDATA (ENABLE, int_enable, 8, TTX_LINES, INT_V_TTO1) },
    { GRDATA (INT, int_req, 8, TTX_LINES, INT_V_TTO1) },
    { URDATA (TIME, ttox_unit[0].wait, 10, 24, 0,
              TTX_LINES, PV_LEFT) },
    { NULL }
    };

MTAB ttox_mod[] = {
    { TT_MODE, TT_MODE_UC, "UC", "UC", NULL },
    { TT_MODE, TT_MODE_7B, "7b", "7B", NULL },
    { TT_MODE, TT_MODE_8B, "8b", "8B", NULL },
    { TT_MODE, TT_MODE_7P, "7p", "7P", NULL },

    { MTAB_XTD|MTAB_VUN, 0, NULL, "DISCONNECT",
      &tmxr_dscln, NULL, &ttx_desc },
    { MTAB_XTD|MTAB_VUN|MTAB_NC, 0, "LOG", "LOG",
      &tmxr_set_log, &tmxr_show_log, &ttx_desc },
    { MTAB_XTD|MTAB_VUN|MTAB_NC, 0, NULL, "NOLOG",
      &tmxr_set_nolog, NULL, &ttx_desc },
    { 0 }
    };

DEVICE ttox_dev = {
    "TTOX", ttox_unit, ttox_reg, ttox_mod,
    4, 10, 31, 1, 8, 8,
    NULL, NULL, &ttox_reset, 
    NULL, NULL, NULL,
    NULL, DEV_DISABLE | DEV_DEBUG,
    0, ttx_debug
    };

/* Terminal input: IOT routine */

int32 ttix (int32 inst, int32 AC)
{
int32 pulse = inst & 07;                                /* IOT pulse */
int32 ln = TTX_GETLN (inst);                            /* line # */
int32 itti = (INT_TTI1 << ln);                          /* rx intr */
int32 itto = (INT_TTO1 << ln);                          /* tx intr */


switch (pulse) {                                        /* case IR<9:11> */

    case 0:                                             /* KCF */
        dev_done = dev_done & ~itti;                    /* clear flag */
        int_req = int_req & ~itti;
        break;

    case 1:                                             /* KSF */
        return (dev_done & itti)? IOT_SKP + AC: AC;

    case 2:                                             /* KCC */
        dev_done = dev_done & ~itti;                    /* clear flag */
        int_req = int_req & ~itti;
        sim_activate_abs (&ttix_unit, ttix_unit.wait);  /* check soon for more input */
        return 0;                                       /* clear AC */

    case 4:                                             /* KRS */
        return (AC | ttix_buf[ln]);                     /* return buf */

    case 5:                                             /* KIE */
        if (AC & 1)
            int_enable = int_enable | (itti + itto);
        else int_enable = int_enable & ~(itti + itto);
        int_req = INT_UPDATE;                           /* update intr */
        break;

    case 6:                                             /* KRB */
        dev_done = dev_done & ~itti;                    /* clear flag */
        int_req = int_req & ~itti;
        sim_activate_abs (&ttix_unit, ttix_unit.wait);  /* check soon for more input */
        return ttix_buf[ln];                            /* return buf */

    default:
        return (stop_inst << IOT_V_REASON) + AC;
        }                                               /* end switch */

return AC;
}

/* Unit service */

t_stat ttix_svc (UNIT *uptr)
{
int32 ln, c, temp;

if ((uptr->flags & UNIT_ATT) == 0)                      /* attached? */
    return SCPE_OK;
sim_clock_coschedule (uptr, tmxr_poll);                 /* continue poll */
ln = tmxr_poll_conn (&ttx_desc);                        /* look for connect */
if (ln >= 0)                                            /* got one? rcv enb*/
    ttx_ldsc[ln].rcve = 1;
tmxr_poll_rx (&ttx_desc);                               /* poll for input */
for (ln = 0; ln < TTX_LINES; ln++) {                    /* loop thru lines */
    if (ttx_ldsc[ln].conn) {                            /* connected? */
        if (dev_done & (INT_TTI1 << ln))                /* Last character still pending? */
            continue;
        if ((temp = tmxr_getc_ln (&ttx_ldsc[ln]))) {    /* get char */
            if (temp & SCPE_BREAK)                      /* break? */
                c = 0;
            else c = sim_tt_inpcvt (temp, TT_GET_MODE (ttox_unit[ln].flags));
            ttix_buf[ln] = c;
            dev_done = dev_done | (INT_TTI1 << ln);
            int_req = INT_UPDATE;
            }
        }
    }
return SCPE_OK;
}

/* Reset routine */

t_stat ttix_reset (DEVICE *dptr)
{
int32 ln, itto;

ttx_enbdis (dptr->flags & DEV_DIS);                     /* sync enables */
if (ttix_unit.flags & UNIT_ATT)                         /* if attached, */
    sim_activate (&ttix_unit, tmxr_poll);               /* activate */
else sim_cancel (&ttix_unit);                           /* else stop */
for (ln = 0; ln < TTX_LINES; ln++) {                    /* for all lines */
    ttix_buf[ln] = 0;                                   /* clear buf, */
    itto = (INT_TTI1 << ln);                            /* interrupt */
    dev_done = dev_done & ~itto;                        /* clr done, int */
    int_req = int_req & ~itto;
    int_enable = int_enable | itto;                     /* set enable */
    }
return SCPE_OK;
}

/* Terminal output: IOT routine */

int32 ttox (int32 inst, int32 AC)
{
int32 pulse = inst & 07;                                /* pulse */
int32 ln = TTX_GETLN (inst);                            /* line # */
int32 itti = (INT_TTI1 << ln);                          /* rx intr */
int32 itto = (INT_TTO1 << ln);                          /* tx intr */


switch (pulse) {                                        /* case IR<9:11> */

    case 0:                                             /* TLF */
        dev_done = dev_done | itto;                     /* set flag */
        int_req = INT_UPDATE;                           /* update intr */
        break;

    case 1:                                             /* TSF */
        return (dev_done & itto)? IOT_SKP + AC: AC;

    case 2:                                             /* TCF */
        dev_done = dev_done & ~itto;                    /* clear flag */
        int_req = int_req & ~itto;                      /* clear intr */
        break;

    case 5:                                             /* SPI */



        return (int_req & (itti | itto))? IOT_SKP + AC: AC;

    case 6:                                             /* TLS */
        dev_done = dev_done & ~itto;                    /* clear flag */
        int_req = int_req & ~itto;                      /* clear int req */
    case 4:                                             /* TPC */
        sim_activate (&ttox_unit[ln], ttox_unit[ln].wait); /* activate */
        ttox_buf[ln] = AC & 0377;                       /* load buffer */
        break;

   default:
        return (stop_inst << IOT_V_REASON) + AC;
        }                                               /* end switch */

return AC;
}

/* Unit service */








|

|














|
>
>
>
>
>
>
>
>
>
>
>
>



|
>
>
|
|
<
|
|








>











|
|










|
|
|
>




|
<



|


|
<








|
|
<



|
<




|















|
|

|

|






<
<
<
<
<
<
<
|
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<









|
|
|
>




<
|



|


<
|



>
>
>
|


<
|






|







169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

257
258
259
260
261
262
263

264
265
266
267
268
269
270
271
272
273

274
275
276
277

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309







310

311



312










313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

330
331
332
333
334
335
336

337
338
339
340
341
342
343
344
345
346

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
  {"TRC",    DBG_TRC},
  {0}
};

DEVICE ttix_dev = {
    "TTIX", &ttix_unit, ttix_reg, ttix_mod,
    1, 10, 31, 1, 8, 8,
    &tmxr_ex, &tmxr_dep, &ttx_reset,
    NULL, &ttx_attach, &ttx_detach,
    &ttx_dib, DEV_MUX | DEV_DISABLE | DEV_DEBUG,
    0, ttx_debug
    };

/* TTOx data structures

   ttox_dev     TTOx device descriptor
   ttox_unit    TTOx unit descriptor
   ttox_reg     TTOx register list
*/

UNIT ttox_unit[] = {
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT },
    { UDATA (&ttox_svc, TT_MODE_UC+UNIT_DIS, 0), SERIAL_OUT_WAIT }
    };

REG ttox_reg[] = {
    { BRDATAD (BUF, ttox_buf, 8, 8, TTX_MAXL, "last data item processed, lines 0 to 3") },
    { ORDATAD  (DONE, ttox_done, TTX_MAXL, "device done flag (line 0 rightmost)") },
    { ORDATAD  (ENABLE, ttx_enbl, TTX_MAXL, "interrupt enable flag") },
    { FLDATA  (SUMDONE, dev_done, INT_V_TTO1), REG_HRO },
    { FLDATA  (SUMENABLE, int_enable, INT_V_TTO1), REG_HRO },

    { URDATAD (TIME, ttox_unit[0].wait, 10, 24, 0,
              TTX_MAXL, PV_LEFT, "line from I/O initiation to interrupt, lines 0 to 3") },
    { NULL }
    };

MTAB ttox_mod[] = {
    { TT_MODE, TT_MODE_UC, "UC", "UC", NULL },
    { TT_MODE, TT_MODE_7B, "7b", "7B", NULL },
    { TT_MODE, TT_MODE_8B, "8b", "8B", NULL },
    { TT_MODE, TT_MODE_7P, "7p", "7P", NULL },
    { MTAB_VDV, 0, "DEVNO", NULL, NULL, &ttx_show_devno, &ttx_desc },
    { MTAB_XTD|MTAB_VUN, 0, NULL, "DISCONNECT",
      &tmxr_dscln, NULL, &ttx_desc },
    { MTAB_XTD|MTAB_VUN|MTAB_NC, 0, "LOG", "LOG",
      &tmxr_set_log, &tmxr_show_log, &ttx_desc },
    { MTAB_XTD|MTAB_VUN|MTAB_NC, 0, NULL, "NOLOG",
      &tmxr_set_nolog, NULL, &ttx_desc },
    { 0 }
    };

DEVICE ttox_dev = {
    "TTOX", ttox_unit, ttox_reg, ttox_mod,
    TTX_MAXL, 10, 31, 1, 8, 8,
    NULL, NULL, &ttx_reset, 
    NULL, NULL, NULL,
    NULL, DEV_DISABLE | DEV_DEBUG,
    0, ttx_debug
    };

/* Terminal input: IOT routine */

int32 ttix (int32 inst, int32 AC)
{
int32 pulse = inst & 07;                                /* IOT pulse */
int32 ln = ttx_getln (inst);                            /* line # */

if (ln < 0)                                             /* bad line #? */
    return (SCPE_IERR << IOT_V_REASON) | AC;

switch (pulse) {                                        /* case IR<9:11> */

    case 0:                                             /* KCF */
        TTIX_CLR_DONE (ln);                             /* clear flag */

        break;

    case 1:                                             /* KSF */
        return (TTIX_TST_DONE (ln))? IOT_SKP | AC: AC;

    case 2:                                             /* KCC */
        TTIX_CLR_DONE (ln);                             /* clear flag */

        sim_activate_abs (&ttix_unit, ttix_unit.wait);  /* check soon for more input */
        return 0;                                       /* clear AC */

    case 4:                                             /* KRS */
        return (AC | ttix_buf[ln]);                     /* return buf */

    case 5:                                             /* KIE */
        if (AC & 1)
            TTX_SET_ENBL (ln);
        else TTX_CLR_ENBL (ln);

        break;

    case 6:                                             /* KRB */
        TTIX_CLR_DONE (ln);                             /* clear flag */

        sim_activate_abs (&ttix_unit, ttix_unit.wait);  /* check soon for more input */
        return ttix_buf[ln];                            /* return buf */

    default:
        return (stop_inst << IOT_V_REASON) | AC;
        }                                               /* end switch */

return AC;
}

/* Unit service */

t_stat ttix_svc (UNIT *uptr)
{
int32 ln, c, temp;

if ((uptr->flags & UNIT_ATT) == 0)                      /* attached? */
    return SCPE_OK;
sim_clock_coschedule (uptr, tmxr_poll);                 /* continue poll */
ln = tmxr_poll_conn (&ttx_desc);                        /* look for connect */
if (ln >= 0)                                            /* got one? */
    ttx_ldsc[ln].rcve = 1;                              /* set rcv enable */
tmxr_poll_rx (&ttx_desc);                               /* poll for input */
for (ln = 0; ln < ttx_lines; ln++) {                    /* loop thru lines */
    if (ttx_ldsc[ln].conn) {                            /* connected? */
        if (TTIX_TST_DONE (ln))                         /* last char still pending? */
            continue;
        if ((temp = tmxr_getc_ln (&ttx_ldsc[ln]))) {    /* get char */
            if (temp & SCPE_BREAK)                      /* break? */
                c = 0;
            else c = sim_tt_inpcvt (temp, TT_GET_MODE (ttox_unit[ln].flags));
            ttix_buf[ln] = c;







            TTIX_SET_DONE (ln);                         /* set flag */

            }



        }










    }
return SCPE_OK;
}

/* Terminal output: IOT routine */

int32 ttox (int32 inst, int32 AC)
{
int32 pulse = inst & 07;                                /* pulse */
int32 ln = ttx_getln (inst);                            /* line # */

if (ln < 0)                                             /* bad line #? */
    return (SCPE_IERR << IOT_V_REASON) | AC;

switch (pulse) {                                        /* case IR<9:11> */

    case 0:                                             /* TLF */

        TTOX_SET_DONE (ln);                             /* set flag */
        break;

    case 1:                                             /* TSF */
        return (TTOX_TST_DONE (ln))? IOT_SKP | AC: AC;

    case 2:                                             /* TCF */

        TTOX_CLR_DONE (ln);                             /* clear flag */
        break;

    case 5:                                             /* SPI */
        if ((TTIX_TST_DONE (ln) || TTOX_TST_DONE (ln))  /* either done set */
            && TTX_TST_ENBL (ln))                       /* and enabled? */
            return IOT_SKP | AC;
        return AC;

    case 6:                                             /* TLS */

        TTOX_CLR_DONE (ln);                             /* clear flag */
    case 4:                                             /* TPC */
        sim_activate (&ttox_unit[ln], ttox_unit[ln].wait); /* activate */
        ttox_buf[ln] = AC & 0377;                       /* load buffer */
        break;

   default:
        return (stop_inst << IOT_V_REASON) | AC;
        }                                               /* end switch */

return AC;
}

/* Unit service */

347
348
349
350
351
352
353



354


















355














356
357
358
359
360
361
362
363
364
365










366
367



368

369



370
371


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403

404

405
406

407





408



409







410

411

412









413





414










415





416
417

        }
    else {
        tmxr_poll_tx (&ttx_desc);                       /* poll xmt */
        sim_activate (uptr, ttox_unit[ln].wait);        /* wait */
        return SCPE_OK;
        }
    }



dev_done = dev_done | (INT_TTO1 << ln);                 /* set done */


















int_req = INT_UPDATE;                                   /* update intr */














return SCPE_OK;
}

/* Reset routine */

t_stat ttox_reset (DEVICE *dptr)
{
int32 ln, itto;

ttx_enbdis (dptr->flags & DEV_DIS);                     /* sync enables */










for (ln = 0; ln < TTX_LINES; ln++) {                    /* for all lines */
    ttox_buf[ln] = 0;                                   /* clear buf */



    itto = (INT_TTO1 << ln);                            /* interrupt */

    dev_done = dev_done & ~itto;                        /* clr done, int */



    int_req = int_req & ~itto;
    int_enable = int_enable | itto;                     /* set enable */


    sim_cancel (&ttox_unit[ln]);                        /* deactivate */
    }
return SCPE_OK;
}

/* Attach master unit */

t_stat ttx_attach (UNIT *uptr, char *cptr)
{
t_stat r;

r = tmxr_attach (&ttx_desc, uptr, cptr);                /* attach */
if (r != SCPE_OK)                                       /* error */
    return r;
sim_activate (uptr, 0);                                 /* start poll at once */
return SCPE_OK;
}

/* Detach master unit */

t_stat ttx_detach (UNIT *uptr)
{
int32 i;
t_stat r;

r = tmxr_detach (&ttx_desc, uptr);                      /* detach */
for (i = 0; i < TTX_LINES; i++)                         /* all lines, */
    ttx_ldsc[i].rcve = 0;                               /* disable rcv */
sim_cancel (uptr);                                      /* stop poll */
return r;
}


/* Enable/disable device */


void ttx_enbdis (int32 dis)

{





if (dis) {



    ttix_dev.flags = ttix_dev.flags | DEV_DIS;







    ttox_dev.flags = ttox_dev.flags | DEV_DIS;

    }

else {









    ttix_dev.flags = ttix_dev.flags & ~DEV_DIS;





    ttox_dev.flags = ttox_dev.flags & ~DEV_DIS;










    }





return;
}








>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|




|

|

|
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
|
>
|
>
>
>
|
|
>
>
|
<
|




|


















|





>
|
>
|
|
>
|
>
>
>
>
>
|
>
>
>
|
>
>
>
>
>
>
>
|
>
|
>

>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
|

>
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        }
    else {
        tmxr_poll_tx (&ttx_desc);                       /* poll xmt */
        sim_activate (uptr, ttox_unit[ln].wait);        /* wait */
        return SCPE_OK;
        }
    }
TTOX_SET_DONE (ln);                                     /* set done */
return SCPE_OK;
}

/* Flag routine

   Global dev_done is used as a master interrupt; therefore, global
   int_enable must always be set
*/

void ttx_new_flags (uint32 newidone, uint32 newodone, uint32 newenbl)
{
ttix_done = newidone;
ttox_done = newodone;
ttx_enbl = newenbl;
if ((ttix_done & ttx_enbl) != 0)
    dev_done |= INT_TTI1;
else dev_done &= ~INT_TTI1;
if ((ttox_done & ttx_enbl) != 0)
    dev_done |= INT_TTO1;
else dev_done &= ~INT_TTO1;
int_enable |= (INT_TTI1 | INT_TTO1);
int_req = INT_UPDATE;
return;
}

/* Compute relative line number, based on table of device numbers */

int32 ttx_getln (int32 inst)
{
int32 i;
int32 device = (inst >> 3) & 077;                       /* device = IR<3:8> */

for (i = 0; i < (ttx_lines * 2); i++) {                 /* loop thru disp tbl */
    if (device == ttx_dsp[i].dev)                       /* dev # match? */
        return (i >> 1);                                /* return line # */
    }
return -1;
}

/* Reset routine */

t_stat ttx_reset (DEVICE *dptr)
{
int32 ln;

if (dptr->flags & DEV_DIS) {                            /* sync enables */
    ttix_dev.flags |= DEV_DIS;
    ttox_dev.flags |= DEV_DIS;
    }
else {
    ttix_dev.flags &= ~DEV_DIS;
    ttox_dev.flags &= ~DEV_DIS;
    }
if (ttix_unit.flags & UNIT_ATT)                         /* if attached, */
    sim_activate (&ttix_unit, tmxr_poll);               /* activate */
else sim_cancel (&ttix_unit);                           /* else stop */
for (ln = 0; ln < TTX_MAXL; ln++)                       /* for all lines */
    ttx_reset_ln (ln);                                  /* reset line */
int_enable |= (INT_TTI1 | INT_TTO1);                    /* set master enable */
return SCPE_OK;
}

/* Reset line n */

void ttx_reset_ln (int32 ln)
{
uint32 mask = (1u << ln);

ttix_buf[ln] = 0;                                       /* clr buf */
ttox_buf[ln] = 0;                                       /* clr done, set enbl */
ttx_new_flags (ttix_done & ~mask, ttox_done & ~mask, ttx_enbl | mask);
sim_cancel (&ttox_unit[ln]);                            /* stop output */

return;
}

/* Attach master unit */

t_stat ttx_attach (UNIT *uptr, CONST char *cptr)
{
t_stat r;

r = tmxr_attach (&ttx_desc, uptr, cptr);                /* attach */
if (r != SCPE_OK)                                       /* error */
    return r;
sim_activate (uptr, 0);                                 /* start poll at once */
return SCPE_OK;
}

/* Detach master unit */

t_stat ttx_detach (UNIT *uptr)
{
int32 i;
t_stat r;

r = tmxr_detach (&ttx_desc, uptr);                      /* detach */
for (i = 0; i < TTX_MAXL; i++)                         /* all lines, */
    ttx_ldsc[i].rcve = 0;                               /* disable rcv */
sim_cancel (uptr);                                      /* stop poll */
return r;
}

/* Change number of lines */

t_stat ttx_vlines (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
int32 newln, i, t;
t_stat r;

if (cptr == NULL)
    return SCPE_ARG;
newln = get_uint (cptr, 10, TTX_MAXL, &r);
if ((r != SCPE_OK) || (newln == ttx_lines))
    return r;
if (newln == 0)
    return SCPE_ARG;
if (newln < ttx_lines) {
    for (i = newln, t = 0; i < ttx_lines; i++)
        t = t | ttx_ldsc[i].conn;
    if (t && !get_yn ("This will disconnect users; proceed [N]?", FALSE))
        return SCPE_OK;
    for (i = newln; i < ttx_lines; i++) {
        if (ttx_ldsc[i].conn) {
            tmxr_linemsg (&ttx_ldsc[i], "\r\nOperator disconnected line\r\n");
            tmxr_reset_ln (&ttx_ldsc[i]);               /* reset line */
            }
        ttox_unit[i].flags |= UNIT_DIS;
        ttx_reset_ln (i);
        }
    }
else {
    for (i = ttx_lines; i < newln; i++) {
        ttox_unit[i].flags &= ~UNIT_DIS;
        ttx_reset_ln (i);
        }
    }
ttx_lines = newln;
ttx_dib.num = newln * 2;
return SCPE_OK;
}

/* Show device numbers */
t_stat ttx_show_devno (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
int32 i, dev_offset;
DEVICE *dptr;

if (uptr == NULL)
    return SCPE_IERR;
dptr = find_dev_from_unit (uptr);
if (dptr == NULL)
    return SCPE_IERR;
/* Select correct devno entry for Input or Output device */
if (dptr->name[2] == 'O')
    dev_offset = 1;
else
    dev_offset = 0;

fprintf(st, "devno=");
for (i = 0; i < ttx_lines; i++) {
    fprintf(st, "%02o%s", ttx_dsp[i*2+dev_offset].dev, i < ttx_lines-1 ? 
         "," : "");
}
return SCPE_OK;
}

Changes to src/gpio.c.
206
207
208
209
210
211
212

213
214

215
216
217
218
219
220
221
	pss->stable_state = ss;
	pss->last_change = na_ms;

	int mask = 1 << col;
	if (ss) switchstatus[row] |=  mask;
	else    switchstatus[row] &= ~mask;


	//printf("%cSS[%d][%02d] = %d  ", gss_initted ? 'N' : 'I',
	//		row, col, ss);

}


// Given the state of the switch at (row,col), work out if this requires
// a change in our exported switch state.
static void debounce_switch(int row, int col, int ss, ms_time_t now_ms)
{







>
|
<
>







206
207
208
209
210
211
212
213
214

215
216
217
218
219
220
221
222
	pss->stable_state = ss;
	pss->last_change = na_ms;

	int mask = 1 << col;
	if (ss) switchstatus[row] |=  mask;
	else    switchstatus[row] &= ~mask;

	#ifdef DEBUG
		printf("%cSS[%d][%02d] = %d  ", gss_initted ? 'N' : 'I',row, col, ss);

	#endif
}


// Given the state of the switch at (row,col), work out if this requires
// a change in our exported switch state.
static void debounce_switch(int row, int col, int ss, ms_time_t now_ms)
{
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
	int i,j,k;
	const us_time_t intervl = 5;	// light each row of leds 5 µs
	ms_time_t now_ms;

	// Find gpio address (different for Pi 2) ----------
	gpio.addr_p = bcm_host_get_peripheral_address() + 0x200000;
	if (gpio.addr_p== 0x20200000) printf("RPi Plus detected - ");
	else printf("RPi 2 detected - ");
#ifdef SERIALSETUP
	printf(" Serial mod version\n");
#else
	printf(" Default version using gpiomem\n");
#endif

	// set thread to real time priority -----------------







|







257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
	int i,j,k;
	const us_time_t intervl = 5;	// light each row of leds 5 µs
	ms_time_t now_ms;

	// Find gpio address (different for Pi 2) ----------
	gpio.addr_p = bcm_host_get_peripheral_address() + 0x200000;
	if (gpio.addr_p== 0x20200000) printf("RPi Plus detected - ");
	else printf("RPi 2/3 detected - ");
#ifdef SERIALSETUP
	printf(" Serial mod version\n");
#else
	printf(" Default version using gpiomem\n");
#endif

	// set thread to real time priority -----------------
Changes to src/scp.c.in.
1
2
3
4
5
6
7
8
9
10
/* scp.c: simulator control program

   Copyright (c) 1993-2012, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:


|







1
2
3
4
5
6
7
8
9
10
/* scp.c: simulator control program

   Copyright (c) 1993-2016, Robert M Supnik

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:
19
20
21
22
23
24
25

26
27
28
29
30
31
32
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.


   20-Mar-12    MP      Fixes to "SHOW <x> SHOW" commands
   06-Jan-12    JDB     Fixed "SHOW DEVICE" with only one enabled unit (Dave Bryan)
   25-Sep-11    MP      Added the ability for a simulator built with
                        SIM_ASYNCH_IO to change whether I/O is actually done
                        asynchronously by the new scp command SET ASYNCH and
                        SET NOASYNCH
   22-Sep-11    MP      Added signal catching of SIGHUP and SIGTERM to cause







>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

   Except as contained in this notice, the name of Robert M Supnik shall not be
   used in advertising or otherwise to promote the sale, use or other dealings
   in this Software without prior written authorization from Robert M Supnik.

   08-Mar-16    RMS     Added shutdown flag for detach_all
   20-Mar-12    MP      Fixes to "SHOW <x> SHOW" commands
   06-Jan-12    JDB     Fixed "SHOW DEVICE" with only one enabled unit (Dave Bryan)
   25-Sep-11    MP      Added the ability for a simulator built with
                        SIM_ASYNCH_IO to change whether I/O is actually done
                        asynchronously by the new scp command SET ASYNCH and
                        SET NOASYNCH
   22-Sep-11    MP      Added signal catching of SIGHUP and SIGTERM to cause
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240

241
242
243
244
245
246
247

/* Macros and data structures */

#ifdef PIDP8I
#include <pthread.h>
#include <time.h>
#include <stdint.h>
#include <unistd.h>	// for sleep()

extern void *blink(void *ptr);	// the real-time multiplexing process to start up
#endif

#define NOT_MUX_USING_CODE /* sim_tmxr library provider or agnostic */

#include "sim_defs.h"
#include "sim_rev.h"
#include "sim_disk.h"
#include "sim_tape.h"
#include "sim_ether.h"
#include "sim_serial.h"
#if defined (USE_SIM_VIDEO)
#include "sim_video.h"
#endif
#include "sim_sock.h"
#include "sim_frontpanel.h"
#include <signal.h>
#include <ctype.h>
#include <time.h>

#if defined(_WIN32)
#include <direct.h>
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif







|

|


















>







214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

/* Macros and data structures */

#ifdef PIDP8I
#include <pthread.h>
#include <time.h>
#include <stdint.h>
#include <unistd.h> // for sleep()

extern void *blink(void *ptr);  // the real-time multiplexing process to start up
#endif

#define NOT_MUX_USING_CODE /* sim_tmxr library provider or agnostic */

#include "sim_defs.h"
#include "sim_rev.h"
#include "sim_disk.h"
#include "sim_tape.h"
#include "sim_ether.h"
#include "sim_serial.h"
#if defined (USE_SIM_VIDEO)
#include "sim_video.h"
#endif
#include "sim_sock.h"
#include "sim_frontpanel.h"
#include <signal.h>
#include <ctype.h>
#include <time.h>
#include <math.h>
#if defined(_WIN32)
#include <direct.h>
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif
337
338
339
340
341
342
343
344
345
346
347
348
349
350























































351
352
353
354
355
356
357
358
359
360
361

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412


413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486

487
488

489


490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506

507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
pthread_mutex_t sim_timer_lock     = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sim_timer_wake      = PTHREAD_COND_INITIALIZER;
pthread_mutex_t sim_tmxr_poll_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sim_tmxr_poll_cond  = PTHREAD_COND_INITIALIZER;
int32 sim_tmxr_poll_count;
pthread_t sim_asynch_main_threadid;
UNIT * volatile sim_asynch_queue;
UNIT * volatile sim_wallclock_queue;
UNIT * volatile sim_wallclock_entry;
UNIT * volatile sim_clock_cosched_queue[SIM_NTIMERS];
t_bool sim_asynch_enabled = TRUE;
int32 sim_asynch_check;
int32 sim_asynch_latency = 4000;      /* 4 usec interrupt latency */
int32 sim_asynch_inst_latency = 20;   /* assume 5 mip simulator */























































#else
t_bool sim_asynch_enabled = FALSE;
#endif

/* The per-simulator init routine is a weak global that defaults to NULL
   The other per-simulator pointers can be overrriden by the init routine */

void (*sim_vm_init) (void);
char* (*sim_vm_read) (char *ptr, int32 size, FILE *stream) = NULL;
void (*sim_vm_post) (t_bool from_scp) = NULL;
CTAB *sim_vm_cmd = NULL;

void (*sim_vm_fprint_addr) (FILE *st, DEVICE *dptr, t_addr addr) = NULL;
t_addr (*sim_vm_parse_addr) (DEVICE *dptr, char *cptr, char **tptr) = NULL;
t_value (*sim_vm_pc_value) (void) = NULL;
t_bool (*sim_vm_is_subroutine_call) (t_addr **ret_addrs) = NULL;
t_bool (*sim_vm_fprint_stopped) (FILE *st, t_stat reason) = NULL;

/* Prototypes */

/* Set and show command processors */

t_stat set_dev_radix (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat set_dev_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat set_unit_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat ssh_break (FILE *st, char *cptr, int32 flg);
t_stat show_cmd_fi (FILE *ofile, int32 flag, char *cptr);
t_stat show_config (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_queue (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_time (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_mod_names (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_log_names (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_radix (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_logicals (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_modifiers (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_default (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_break (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_on (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_send (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_device (FILE *st, DEVICE *dptr, int32 flag);
t_stat show_unit (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag);
t_stat show_all_mods (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flg, int32 *toks);
t_stat show_one_mod (FILE *st, DEVICE *dptr, UNIT *uptr, MTAB *mptr, char *cptr, int32 flag);
t_stat sim_save (FILE *sfile);
t_stat sim_rest (FILE *rfile);

/* Breakpoint package */

t_stat sim_brk_init (void);
t_stat sim_brk_set (t_addr loc, int32 sw, int32 ncnt, char *act);
t_stat sim_brk_clr (t_addr loc, int32 sw);
t_stat sim_brk_clrall (int32 sw);
t_stat sim_brk_show (FILE *st, t_addr loc, int32 sw);
t_stat sim_brk_showall (FILE *st, int32 sw);
char *sim_brk_getact (char *buf, int32 size);
void sim_brk_npc (uint32 cnt);
BRKTAB *sim_brk_new (t_addr loc);


FILE *stdnul;

/* Command support routines */

SCHTAB *get_rsearch (const char *cptr, int32 radix, SCHTAB *schptr);
SCHTAB *get_asearch (const char *cptr, int32 radix, SCHTAB *schptr);
int32 test_search (t_value *val, SCHTAB *schptr);
static const char *get_glyph_gen (const char *iptr, char *optr, char mchar, t_bool uc, t_bool quote, char escape_char);
int32 get_switches (char *cptr);
char *get_sim_sw (char *cptr);
t_stat get_aval (t_addr addr, DEVICE *dptr, UNIT *uptr);
t_value get_rval (REG *rptr, uint32 idx);
void put_rval (REG *rptr, uint32 idx, t_value val);
void fprint_help (FILE *st);
void fprint_stopped (FILE *st, t_stat r);
void fprint_capac (FILE *st, DEVICE *dptr, UNIT *uptr);
void fprint_sep (FILE *st, int32 *tokens);
char *read_line (char *ptr, int32 size, FILE *stream);
char *read_line_p (const char *prompt, char *ptr, int32 size, FILE *stream);
REG *find_reg_glob (const char *ptr, const char **optr, DEVICE **gdptr);
char *sim_trim_endspc (char *cptr);

/* Forward references */

t_stat scp_attach_unit (DEVICE *dptr, UNIT *uptr, char *cptr);
t_stat scp_detach_unit (DEVICE *dptr, UNIT *uptr);
t_bool qdisable (DEVICE *dptr);
t_stat attach_err (UNIT *uptr, t_stat stat);
t_stat detach_all (int32 start_device, t_bool shutdown);
t_stat assign_device (DEVICE *dptr, char *cptr);
t_stat deassign_device (DEVICE *dptr);
t_stat ssh_break_one (FILE *st, int32 flg, t_addr lo, int32 cnt, char *aptr);
t_stat exdep_reg_loop (FILE *ofile, SCHTAB *schptr, int32 flag, char *cptr,
    REG *lowr, REG *highr, uint32 lows, uint32 highs);
t_stat ex_reg (FILE *ofile, t_value val, int32 flag, REG *rptr, uint32 idx);
t_stat dep_reg (int32 flag, char *cptr, REG *rptr, uint32 idx);
t_stat exdep_addr_loop (FILE *ofile, SCHTAB *schptr, int32 flag, char *cptr,
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr);
t_stat ex_addr (FILE *ofile, int32 flag, t_addr addr, DEVICE *dptr, UNIT *uptr);
t_stat dep_addr (int32 flag, char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc);
void fprint_fields (FILE *stream, t_value before, t_value after, BITFIELD* bitdefs);
t_stat step_svc (UNIT *ptr);
t_stat expect_svc (UNIT *ptr);
t_stat shift_args (char *do_arg[], size_t arg_count);
t_stat set_on (int32 flag, char *cptr);
t_stat set_verify (int32 flag, char *cptr);
t_stat set_message (int32 flag, char *cptr);
t_stat set_quiet (int32 flag, char *cptr);
t_stat set_asynch (int32 flag, char *cptr);
t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat do_cmd_label (int32 flag, char *cptr, char *label);
void int_handler (int signal);
t_stat set_prompt (int32 flag, char *cptr);
t_stat sim_set_asynch (int32 flag, char *cptr);
t_stat sim_set_environment (int32 flag, char *cptr);
static const char *get_dbg_verb (uint32 dbits, DEVICE* dptr);

/* Global data */

DEVICE *sim_dflt_dev = NULL;
UNIT *sim_clock_queue = QUEUE_LIST_END;
int32 sim_interval = 0;
int32 sim_switches = 0;
FILE *sim_ofile = NULL;
TMLN *sim_oline = NULL;
SCHTAB *sim_schrptr = FALSE;
SCHTAB *sim_schaptr = FALSE;
DEVICE *sim_dfdev = NULL;
UNIT *sim_dfunit = NULL;
DEVICE **sim_internal_devices = NULL;
uint32 sim_internal_device_count = 0;
int32 sim_opt_out = 0;
int32 sim_is_running = 0;

uint32 sim_brk_summ = 0;
uint32 sim_brk_types = 0;

uint32 sim_brk_dflt = 0;


char *sim_brk_act[MAX_DO_NEST_LVL];
char *sim_brk_act_buf[MAX_DO_NEST_LVL];
BRKTAB *sim_brk_tab = NULL;
int32 sim_brk_ent = 0;
int32 sim_brk_lnt = 0;
int32 sim_brk_ins = 0;
t_bool sim_brk_pend[SIM_BKPT_N_SPC] = { FALSE };
t_addr sim_brk_ploc[SIM_BKPT_N_SPC] = { 0 };
int32 sim_quiet = 0;
int32 sim_step = 0;
static double sim_time;
static uint32 sim_rtime;
static int32 noqueue_time;
volatile int32 stop_cpu = 0;
static char **sim_argv;
t_value *sim_eval = NULL;
static t_value sim_last_val;

FILE *sim_log = NULL;                                   /* log file */
FILEREF *sim_log_ref = NULL;                            /* log file file reference */
FILE *sim_deb = NULL;                                   /* debug file */
FILEREF *sim_deb_ref = NULL;                            /* debug file file reference */
int32 sim_deb_switches = 0;                             /* debug switches */
struct timespec sim_deb_basetime;                       /* debug timestamp relative base time */
char *sim_prompt = NULL;                                /* prompt string */
static FILE *sim_gotofile;                              /* the currently open do file */
static int32 sim_goto_line[MAX_DO_NEST_LVL+1];          /* the current line number in the currently open do file */
static int32 sim_do_echo = 0;                           /* the echo status of the currently open do file */
static int32 sim_show_message = 1;                      /* the message display status of the currently open do file */
static int32 sim_on_inherit = 0;                        /* the inherit status of on state and conditions when executing do files */
static int32 sim_do_depth = 0;

static int32 sim_on_check[MAX_DO_NEST_LVL+1];
static char *sim_on_actions[MAX_DO_NEST_LVL+1][SCPE_MAX_ERR+1];
static char sim_do_filename[MAX_DO_NEST_LVL+1][CBUFSIZE];
static char *sim_do_ocptr[MAX_DO_NEST_LVL+1];
static char *sim_do_label[MAX_DO_NEST_LVL+1];

t_stat sim_last_cmd_stat;                               /* Command Status */

static SCHTAB sim_stabr;                                /* Register search specifier */
static SCHTAB sim_staba;                                /* Memory search specifier */

static UNIT sim_step_unit = { UDATA (&step_svc, 0, 0)  };







<
<
<




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







|



>

|








|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|



|






|




|
<
|
>
>




|
|


|
|









|




|




|

|
|


|
|


|





|
|
|
|
|
|
|

|
|
|


















>


>

>
>


|



<
<









>

















|
|







339
340
341
342
343
344
345



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555


556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
pthread_mutex_t sim_timer_lock     = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sim_timer_wake      = PTHREAD_COND_INITIALIZER;
pthread_mutex_t sim_tmxr_poll_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sim_tmxr_poll_cond  = PTHREAD_COND_INITIALIZER;
int32 sim_tmxr_poll_count;
pthread_t sim_asynch_main_threadid;
UNIT * volatile sim_asynch_queue;



t_bool sim_asynch_enabled = TRUE;
int32 sim_asynch_check;
int32 sim_asynch_latency = 4000;      /* 4 usec interrupt latency */
int32 sim_asynch_inst_latency = 20;   /* assume 5 mip simulator */

int sim_aio_update_queue (void)
{
int migrated = 0;

if (AIO_QUEUE_VAL != QUEUE_LIST_END) {  /* List !Empty */
    UNIT *q, *uptr;
    int32 a_event_time;
    do
        q = AIO_QUEUE_VAL;
        while (q != AIO_QUEUE_SET(QUEUE_LIST_END, q));  /* Grab current queue */
    while (q != QUEUE_LIST_END) {       /* List !Empty */
        sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Migrating Asynch event for %s after %d instructions\n", sim_uname(q), q->a_event_time);
        ++migrated;
        uptr = q;
        q = q->a_next;
        uptr->a_next = NULL;        /* hygiene */
        if (uptr->a_activate_call != &sim_activate_notbefore) {
            a_event_time = uptr->a_event_time-((sim_asynch_inst_latency+1)/2);
            if (a_event_time < 0)
                a_event_time = 0;
            }
        else
            a_event_time = uptr->a_event_time;
        uptr->a_activate_call (uptr, a_event_time);
        if (uptr->a_check_completion) {
            sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Calling Completion Check for asynch event on %s\n", sim_uname(uptr));
            uptr->a_check_completion (uptr);
            }
        }
    }
return migrated;
}

void sim_aio_activate (ACTIVATE_API caller, UNIT *uptr, int32 event_time)
{
sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch event for %s after %d instructions\n", sim_uname(uptr), event_time);
if (uptr->a_next) {
    uptr->a_activate_call = sim_activate_abs;
    }
else {
    UNIT *q;
    uptr->a_event_time = event_time;
    uptr->a_activate_call = caller;
    do {
        q = AIO_QUEUE_VAL;
        uptr->a_next = q;                               /* Mark as on list */
        } while (q != AIO_QUEUE_SET(uptr, q));
    }
sim_asynch_check = 0;                             /* try to force check */
if (sim_idle_wait) {
    sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(uptr), event_time);
    pthread_cond_signal (&sim_asynch_wake);
    }
}
#else
t_bool sim_asynch_enabled = FALSE;
#endif

/* The per-simulator init routine is a weak global that defaults to NULL
   The other per-simulator pointers can be overrriden by the init routine */

WEAK void (*sim_vm_init) (void);
char* (*sim_vm_read) (char *ptr, int32 size, FILE *stream) = NULL;
void (*sim_vm_post) (t_bool from_scp) = NULL;
CTAB *sim_vm_cmd = NULL;
void (*sim_vm_sprint_addr) (char *buf, DEVICE *dptr, t_addr addr) = NULL;
void (*sim_vm_fprint_addr) (FILE *st, DEVICE *dptr, t_addr addr) = NULL;
t_addr (*sim_vm_parse_addr) (DEVICE *dptr, CONST char *cptr, CONST char **tptr) = NULL;
t_value (*sim_vm_pc_value) (void) = NULL;
t_bool (*sim_vm_is_subroutine_call) (t_addr **ret_addrs) = NULL;
t_bool (*sim_vm_fprint_stopped) (FILE *st, t_stat reason) = NULL;

/* Prototypes */

/* Set and show command processors */

t_stat set_dev_radix (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_dev_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_unit_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat ssh_break (FILE *st, const char *cptr, int32 flg);
t_stat show_cmd_fi (FILE *ofile, int32 flag, CONST char *cptr);
t_stat show_config (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_queue (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_time (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_mod_names (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_log_names (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_radix (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_logicals (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_modifiers (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_default (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_break (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_on (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_send (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_device (FILE *st, DEVICE *dptr, int32 flag);
t_stat show_unit (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag);
t_stat show_all_mods (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flg, int32 *toks);
t_stat show_one_mod (FILE *st, DEVICE *dptr, UNIT *uptr, MTAB *mptr, CONST char *cptr, int32 flag);
t_stat sim_save (FILE *sfile);
t_stat sim_rest (FILE *rfile);

/* Breakpoint package */

t_stat sim_brk_init (void);
t_stat sim_brk_set (t_addr loc, int32 sw, int32 ncnt, CONST char *act);
t_stat sim_brk_clr (t_addr loc, int32 sw);
t_stat sim_brk_clrall (int32 sw);
t_stat sim_brk_show (FILE *st, t_addr loc, int32 sw);
t_stat sim_brk_showall (FILE *st, int32 sw);
CONST char *sim_brk_getact (char *buf, int32 size);

BRKTAB *sim_brk_new (t_addr loc, uint32 btyp);
char *sim_brk_clract (void);

FILE *stdnul;

/* Command support routines */

SCHTAB *get_rsearch (CONST char *cptr, int32 radix, SCHTAB *schptr);
SCHTAB *get_asearch (CONST char *cptr, int32 radix, SCHTAB *schptr);
int32 test_search (t_value *val, SCHTAB *schptr);
static const char *get_glyph_gen (const char *iptr, char *optr, char mchar, t_bool uc, t_bool quote, char escape_char);
int32 get_switches (const char *cptr);
CONST char *get_sim_sw (CONST char *cptr);
t_stat get_aval (t_addr addr, DEVICE *dptr, UNIT *uptr);
t_value get_rval (REG *rptr, uint32 idx);
void put_rval (REG *rptr, uint32 idx, t_value val);
void fprint_help (FILE *st);
void fprint_stopped (FILE *st, t_stat r);
void fprint_capac (FILE *st, DEVICE *dptr, UNIT *uptr);
void fprint_sep (FILE *st, int32 *tokens);
char *read_line (char *ptr, int32 size, FILE *stream);
char *read_line_p (const char *prompt, char *ptr, int32 size, FILE *stream);
REG *find_reg_glob (CONST char *ptr, CONST char **optr, DEVICE **gdptr);
char *sim_trim_endspc (char *cptr);

/* Forward references */

t_stat scp_attach_unit (DEVICE *dptr, UNIT *uptr, const char *cptr);
t_stat scp_detach_unit (DEVICE *dptr, UNIT *uptr);
t_bool qdisable (DEVICE *dptr);
t_stat attach_err (UNIT *uptr, t_stat stat);
t_stat detach_all (int32 start_device, t_bool shutdown);
t_stat assign_device (DEVICE *dptr, const char *cptr);
t_stat deassign_device (DEVICE *dptr);
t_stat ssh_break_one (FILE *st, int32 flg, t_addr lo, int32 cnt, CONST char *aptr);
t_stat exdep_reg_loop (FILE *ofile, SCHTAB *schptr, int32 flag, CONST char *cptr,
    REG *lowr, REG *highr, uint32 lows, uint32 highs);
t_stat ex_reg (FILE *ofile, t_value val, int32 flag, REG *rptr, uint32 idx);
t_stat dep_reg (int32 flag, CONST char *cptr, REG *rptr, uint32 idx);
t_stat exdep_addr_loop (FILE *ofile, SCHTAB *schptr, int32 flag, const char *cptr,
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr);
t_stat ex_addr (FILE *ofile, int32 flag, t_addr addr, DEVICE *dptr, UNIT *uptr);
t_stat dep_addr (int32 flag, const char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc);
void fprint_fields (FILE *stream, t_value before, t_value after, BITFIELD* bitdefs);
t_stat step_svc (UNIT *ptr);
t_stat expect_svc (UNIT *ptr);
t_stat shift_args (char *do_arg[], size_t arg_count);
t_stat set_on (int32 flag, CONST char *cptr);
t_stat set_verify (int32 flag, CONST char *cptr);
t_stat set_message (int32 flag, CONST char *cptr);
t_stat set_quiet (int32 flag, CONST char *cptr);
t_stat set_asynch (int32 flag, CONST char *cptr);
t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat do_cmd_label (int32 flag, CONST char *cptr, CONST char *label);
void int_handler (int signal);
t_stat set_prompt (int32 flag, CONST char *cptr);
t_stat sim_set_asynch (int32 flag, CONST char *cptr);
t_stat sim_set_environment (int32 flag, CONST char *cptr);
static const char *get_dbg_verb (uint32 dbits, DEVICE* dptr);

/* Global data */

DEVICE *sim_dflt_dev = NULL;
UNIT *sim_clock_queue = QUEUE_LIST_END;
int32 sim_interval = 0;
int32 sim_switches = 0;
FILE *sim_ofile = NULL;
TMLN *sim_oline = NULL;
SCHTAB *sim_schrptr = FALSE;
SCHTAB *sim_schaptr = FALSE;
DEVICE *sim_dfdev = NULL;
UNIT *sim_dfunit = NULL;
DEVICE **sim_internal_devices = NULL;
uint32 sim_internal_device_count = 0;
int32 sim_opt_out = 0;
int32 sim_is_running = 0;
t_bool sim_processing_event = FALSE;
uint32 sim_brk_summ = 0;
uint32 sim_brk_types = 0;
BRKTYPTAB *sim_brk_type_desc = NULL;                  /* type descriptions */
uint32 sim_brk_dflt = 0;
uint32 sim_brk_match_type;
t_addr sim_brk_match_addr;
char *sim_brk_act[MAX_DO_NEST_LVL];
char *sim_brk_act_buf[MAX_DO_NEST_LVL];
BRKTAB **sim_brk_tab = NULL;
int32 sim_brk_ent = 0;
int32 sim_brk_lnt = 0;
int32 sim_brk_ins = 0;


int32 sim_quiet = 0;
int32 sim_step = 0;
static double sim_time;
static uint32 sim_rtime;
static int32 noqueue_time;
volatile int32 stop_cpu = 0;
static char **sim_argv;
t_value *sim_eval = NULL;
static t_value sim_last_val;
static t_addr sim_last_addr;
FILE *sim_log = NULL;                                   /* log file */
FILEREF *sim_log_ref = NULL;                            /* log file file reference */
FILE *sim_deb = NULL;                                   /* debug file */
FILEREF *sim_deb_ref = NULL;                            /* debug file file reference */
int32 sim_deb_switches = 0;                             /* debug switches */
struct timespec sim_deb_basetime;                       /* debug timestamp relative base time */
char *sim_prompt = NULL;                                /* prompt string */
static FILE *sim_gotofile;                              /* the currently open do file */
static int32 sim_goto_line[MAX_DO_NEST_LVL+1];          /* the current line number in the currently open do file */
static int32 sim_do_echo = 0;                           /* the echo status of the currently open do file */
static int32 sim_show_message = 1;                      /* the message display status of the currently open do file */
static int32 sim_on_inherit = 0;                        /* the inherit status of on state and conditions when executing do files */
static int32 sim_do_depth = 0;

static int32 sim_on_check[MAX_DO_NEST_LVL+1];
static char *sim_on_actions[MAX_DO_NEST_LVL+1][SCPE_MAX_ERR+1];
static char sim_do_filename[MAX_DO_NEST_LVL+1][CBUFSIZE];
static const char *sim_do_ocptr[MAX_DO_NEST_LVL+1];
static const char *sim_do_label[MAX_DO_NEST_LVL+1];

t_stat sim_last_cmd_stat;                               /* Command Status */

static SCHTAB sim_stabr;                                /* Register search specifier */
static SCHTAB sim_staba;                                /* Memory search specifier */

static UNIT sim_step_unit = { UDATA (&step_svc, 0, 0)  };
878
879
880
881
882
883
884


885
886
887
888
889
890
891
      " Except for main memory and network devices, units are simulated as\n"
      " unstructured binary disk files in the host file system.  Before using a\n"
      " simulated unit, the user must specify the file to be accessed by that unit.\n"
#define HLP_ATTACH      "*Commands Connecting_and_Disconnecting_Devices ATTACH"
      "3ATTACH\n"
      " The ATTACH (abbreviation AT) command associates a unit and a file:\n"
      "++ATTACH <unit> <filename>\n\n"


      "4Switches\n"
      "5-n\n"
      " If the -n switch is specified when an attach is executed, a new file is\n"
      " created, and an appropriate message is printed.\n"
      "5-e\n"
      " If the file does not exist, and the -e switch was not specified, a new\n"
      " file is created, and an appropriate message is printed.  If the -e switch\n"







>
>







937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
      " Except for main memory and network devices, units are simulated as\n"
      " unstructured binary disk files in the host file system.  Before using a\n"
      " simulated unit, the user must specify the file to be accessed by that unit.\n"
#define HLP_ATTACH      "*Commands Connecting_and_Disconnecting_Devices ATTACH"
      "3ATTACH\n"
      " The ATTACH (abbreviation AT) command associates a unit and a file:\n"
      "++ATTACH <unit> <filename>\n\n"
      " Some devices have more detailed or specific help available with:\n\n"
      "++HELP <device> ATTACH\n\n"
      "4Switches\n"
      "5-n\n"
      " If the -n switch is specified when an attach is executed, a new file is\n"
      " created, and an appropriate message is printed.\n"
      "5-e\n"
      " If the file does not exist, and the -e switch was not specified, a new\n"
      " file is created, and an appropriate message is printed.  If the -e switch\n"
957
958
959
960
961
962
963







964
965
966
967
968
969
970
971
972
973


974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999



1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011


1012
1013
1014
1015
1016
1017
1018
      "2Listing Files\n"
#define HLP_DIR         "*Commands Listing_Files DIR"
      "3DIR\n"
      "++DIR {path}                list directory files\n"
#define HLP_LS          "*Commands Listing_Files LS"
      "3LS\n"
      "++LS {path}                 list directory files\n"







#define HLP_SET         "*Commands SET"
      "2SET\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_CONSOLE "*Commands SET CONSOLE"
      "3Console\n"
      "+set console arg{,arg...}    set console options\n"
      "+set console WRU             specify console drop to simh character\n"
      "+set console BRK             specify console Break character\n"
      "+set console DEL             specify console delete character\n"
      "+set console PCHAR           specify console printable characters\n"


      "+set console TELNET=port     specify console telnet port\n"
      "+set console TELNET=LOG=log_file\n"
      "++++++++                     specify console telnet logging to the\n"
      "++++++++                     specified destination {LOG,STDOUT,STDERR,\n"
      "++++++++                     DEBUG or filename)\n"
      "+set console TELNET=NOLOG    disables console telnet logging\n"
      "+set console TELNET=BUFFERED[=bufsize]\n"
      "++++++++                     specify console telnet buffering\n"
      "+set console TELNET=NOBUFFERED\n"
      "++++++++                     disables console telnet buffering\n"
      "+set console TELNET=UNBUFFERED\n"
      "++++++++                     disables console telnet buffering\n"
      "+set console NOTELNET        disable console telnet\n"
      "+set console SERIAL=serialport[;config]\n"
      "++++++++                     specify console serial port and optionally\n"
      "++++++++                     the port config (i.e. ;9600-8n1)\n"
      "+set console NOSERIAL        disable console serial session\n"
      "+set console LOG=log_file    enable console logging to the\n"
      "++++++++                     specified destination {STDOUT,STDERR,DEBUG\n"
      "++++++++                     or filename)\n"
      "+set console NOLOG           disable console logging\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_REMOTE "*Commands SET REMOTE"
      "3Remote\n"
      "+set remote TELNET=port      specify remote console telnet port\n"
      "+set remote NOTELNET         disables remote console\n"



      "+set remote CONNECTIONS=n    specify number of concurrent remote\n"
      "++++++++                     console sessions\n"
      "+set remote TIMEOUT=n        specify number of seconds without input\n"
      "++++++++                     before automatic continue\n"
      "+set remote MASTER           enable master mode remote console\n"
      "+set remote NOMASTER         disable remote master mode console\n"
#define HLP_SET_DEFAULT "*Commands SET Working_Directory"
      "3Working Directory\n"
      "+set default <dir>           set the current directory\n"
      "+cd <dir>                    set the current directory\n"
#define HLP_SET_LOG    "*Commands SET Log"
      "3Log\n"


      "+set log log_file            specify the log destination\n"
      "++++++++                     (STDOUT,DEBUG or filename)\n"
      "+set nolog                   disables any currently active logging\n"
      "4Switches\n"
      " By default, log output is written at the end of the specified log file.\n"
      " A new log file can created if the -N switch is used on the command line.\n"
#define HLP_SET_DEBUG  "*Commands SET Debug"







>
>
>
>
>
>
>










>
>

















<
<
<
|





>
>
>












>
>







1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
      "2Listing Files\n"
#define HLP_DIR         "*Commands Listing_Files DIR"
      "3DIR\n"
      "++DIR {path}                list directory files\n"
#define HLP_LS          "*Commands Listing_Files LS"
      "3LS\n"
      "++LS {path}                 list directory files\n"
      "2Displaying Files\n"
#define HLP_TYPE         "*Commands Displaying_Files TYPE"
      "3TYPE\n"
      "++TYPE {file}               display a file contents\n"
#define HLP_CAT          "*Commands Displaying_Files CAT"
      "3CAT\n"
      "++CAT {file}                display a file contents\n"
#define HLP_SET         "*Commands SET"
      "2SET\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_CONSOLE "*Commands SET CONSOLE"
      "3Console\n"
      "+set console arg{,arg...}    set console options\n"
      "+set console WRU             specify console drop to simh character\n"
      "+set console BRK             specify console Break character\n"
      "+set console DEL             specify console delete character\n"
      "+set console PCHAR           specify console printable characters\n"
      "+set console SPEED=speed{*factor}\n"
      "++++++++                     specify console input data rate\n"
      "+set console TELNET=port     specify console telnet port\n"
      "+set console TELNET=LOG=log_file\n"
      "++++++++                     specify console telnet logging to the\n"
      "++++++++                     specified destination {LOG,STDOUT,STDERR,\n"
      "++++++++                     DEBUG or filename)\n"
      "+set console TELNET=NOLOG    disables console telnet logging\n"
      "+set console TELNET=BUFFERED[=bufsize]\n"
      "++++++++                     specify console telnet buffering\n"
      "+set console TELNET=NOBUFFERED\n"
      "++++++++                     disables console telnet buffering\n"
      "+set console TELNET=UNBUFFERED\n"
      "++++++++                     disables console telnet buffering\n"
      "+set console NOTELNET        disable console telnet\n"
      "+set console SERIAL=serialport[;config]\n"
      "++++++++                     specify console serial port and optionally\n"
      "++++++++                     the port config (i.e. ;9600-8n1)\n"
      "+set console NOSERIAL        disable console serial session\n"



      "+set console SPEED=nn{*fac}  specifies the maximum console port input rate\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_REMOTE "*Commands SET REMOTE"
      "3Remote\n"
      "+set remote TELNET=port      specify remote console telnet port\n"
      "+set remote NOTELNET         disables remote console\n"
      "+set remote BUFFERSIZE=bufsize\n"
      "++++++++                     specify remote console command output buffer\n"
      "++++++++                     size\n"
      "+set remote CONNECTIONS=n    specify number of concurrent remote\n"
      "++++++++                     console sessions\n"
      "+set remote TIMEOUT=n        specify number of seconds without input\n"
      "++++++++                     before automatic continue\n"
      "+set remote MASTER           enable master mode remote console\n"
      "+set remote NOMASTER         disable remote master mode console\n"
#define HLP_SET_DEFAULT "*Commands SET Working_Directory"
      "3Working Directory\n"
      "+set default <dir>           set the current directory\n"
      "+cd <dir>                    set the current directory\n"
#define HLP_SET_LOG    "*Commands SET Log"
      "3Log\n"
      " Interactions with the simulator session (at the \"sim>\" prompt\n"
      " can be recorded to a log file\n\n"
      "+set log log_file            specify the log destination\n"
      "++++++++                     (STDOUT,DEBUG or filename)\n"
      "+set nolog                   disables any currently active logging\n"
      "4Switches\n"
      " By default, log output is written at the end of the specified log file.\n"
      " A new log file can created if the -N switch is used on the command line.\n"
#define HLP_SET_DEBUG  "*Commands SET Debug"
1038
1039
1040
1041
1042
1043
1044






1045
1046
1047
1048
1049
1050
1051
1052
1053
1054









1055
1056
1057
1058
1059
1060
1061
      " -T or -A is explicitly specified, -T is implied.\n"
      "5-P\n"
      " The -P switch adds the output of the PC (Program Counter) to each debug\n"
      " message.\n"
      "5-N\n"
      " The -N switch causes a new/empty file to be written to.  The default\n"
      " is to append to an existing debug log file.\n"






#define HLP_SET_BREAK  "*Commands SET Breakpoints"
      "3Breakpoints\n"
      "+set break <list>            set breakpoints\n"
      "+set nobreak <list>          clear breakpoints\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_THROTTLE "*Commands SET Throttle"
      "3Throttle\n"
      "+set throttle {x{M|K|%%}}|{x/t}\n"
      "++++++++                     set simulation rate\n"
      "+set nothrottle              set simulation rate to maximum\n"









#define HLP_SET_ASYNCH "*Commands SET Asynch"
      "3Asynch\n"
      "+set asynch                  enable asynchronous I/O\n"
      "+set noasynch                disable asynchronous I/O\n"
#define HLP_SET_ENVIRON "*Commands SET Asynch"
      "3Environment\n"
      "+set environment name=val    set environment variable\n"







>
>
>
>
>
>










>
>
>
>
>
>
>
>
>







1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
      " -T or -A is explicitly specified, -T is implied.\n"
      "5-P\n"
      " The -P switch adds the output of the PC (Program Counter) to each debug\n"
      " message.\n"
      "5-N\n"
      " The -N switch causes a new/empty file to be written to.  The default\n"
      " is to append to an existing debug log file.\n"
      "5-D\n"
      " The -D switch causes data blob output to also display the data as\n"
      " RADIX-50 characters.\n"
      "5-E\n"
      " The -E switch causes data blob output to also display the data as\n"
      " EBCDIC characters.\n"
#define HLP_SET_BREAK  "*Commands SET Breakpoints"
      "3Breakpoints\n"
      "+set break <list>            set breakpoints\n"
      "+set nobreak <list>          clear breakpoints\n"
       /***************** 80 character line width template *************************/
#define HLP_SET_THROTTLE "*Commands SET Throttle"
      "3Throttle\n"
      "+set throttle {x{M|K|%%}}|{x/t}\n"
      "++++++++                     set simulation rate\n"
      "+set nothrottle              set simulation rate to maximum\n"
#define HLP_SET_CLOCKS "*Commands SET Clocks"
      "3Clock\n"
#if defined (SIM_ASYNCH_CLOCKS)
      "+set clock asynch            enable asynchronous clocks\n"
      "+set clock noasynch          disable asynchronous clocks\n"
#endif
      "+set clock nocatchup         disable catchup clock ticks\n"
      "+set clock catchup           enable catchup clock ticks\n"
      "+set clock calib=n%%          specify idle calibration skip %%\n"
#define HLP_SET_ASYNCH "*Commands SET Asynch"
      "3Asynch\n"
      "+set asynch                  enable asynchronous I/O\n"
      "+set noasynch                disable asynchronous I/O\n"
#define HLP_SET_ENVIRON "*Commands SET Asynch"
      "3Environment\n"
      "+set environment name=val    set environment variable\n"
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
      "++++++++                     available\n"
       /***************** 80 character line width template *************************/
#define HLP_SHOW        "*Commands SHOW"
      "2SHOW\n"
      "+sh{ow} {-c} br{eak} <list>  show breakpoints\n"
      "+sh{ow} con{figuration}      show configuration\n"
      "+sh{ow} cons{ole} {arg}      show console options\n"
      "+sh{ow} dev{ices}            show devices\n"
      "+sh{ow} fea{tures}           show system devices with descriptions\n"
      "+sh{ow} m{odifiers}          show modifiers for all devices\n"
      "+sh{ow} s{how}               show SHOW commands for all devices\n"
      "+sh{ow} n{ames}              show logical names\n"
      "+sh{ow} q{ueue}              show event queue\n"
      "+sh{ow} ti{me}               show simulated time\n"
      "+sh{ow} th{rottle}           show simulation rate\n"







|







1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
      "++++++++                     available\n"
       /***************** 80 character line width template *************************/
#define HLP_SHOW        "*Commands SHOW"
      "2SHOW\n"
      "+sh{ow} {-c} br{eak} <list>  show breakpoints\n"
      "+sh{ow} con{figuration}      show configuration\n"
      "+sh{ow} cons{ole} {arg}      show console options\n"
      "+sh{ow} {-ei} dev{ices}      show devices\n"
      "+sh{ow} fea{tures}           show system devices with descriptions\n"
      "+sh{ow} m{odifiers}          show modifiers for all devices\n"
      "+sh{ow} s{how}               show SHOW commands for all devices\n"
      "+sh{ow} n{ames}              show logical names\n"
      "+sh{ow} q{ueue}              show event queue\n"
      "+sh{ow} ti{me}               show simulated time\n"
      "+sh{ow} th{rottle}           show simulation rate\n"
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
      "+sh{ow} <unit> {arg,...}     show unit parameters\n"
      "+sh{ow} ethernet             show ethernet devices\n"
      "+sh{ow} serial               show serial devices\n"
      "+sh{ow} multiplexer          show open multiplexer devices\n"
#if defined(USE_SIM_VIDEO)
      "+sh{ow} video                show video capabilities\n"
#endif
      "+sh{ow} clocks               show calibrated timers\n"
      "+sh{ow} throttle             show throttle info\n"
      "+sh{ow} on                   show on condition actions\n"
      "+h{elp} <dev> show           displays the device specific show commands\n"
      "++++++++                     available\n"
#define HLP_SHOW_CONFIG         "*Commands SHOW"
#define HLP_SHOW_DEVICES        "*Commands SHOW"
#define HLP_SHOW_FEATURES       "*Commands SHOW"







|







1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
      "+sh{ow} <unit> {arg,...}     show unit parameters\n"
      "+sh{ow} ethernet             show ethernet devices\n"
      "+sh{ow} serial               show serial devices\n"
      "+sh{ow} multiplexer          show open multiplexer devices\n"
#if defined(USE_SIM_VIDEO)
      "+sh{ow} video                show video capabilities\n"
#endif
      "+sh{ow} clocks               show calibrated timer information\n"
      "+sh{ow} throttle             show throttle info\n"
      "+sh{ow} on                   show on condition actions\n"
      "+h{elp} <dev> show           displays the device specific show commands\n"
      "++++++++                     available\n"
#define HLP_SHOW_CONFIG         "*Commands SHOW"
#define HLP_SHOW_DEVICES        "*Commands SHOW"
#define HLP_SHOW_FEATURES       "*Commands SHOW"
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484




1485
1486
1487
1488
1489
1490
1491
      " units of microseconds rather than instructions.\n"
       /***************** 80 character line width template *************************/
#define HLP_EXPECT      "*Commands Executing_Command_Files Reacting_To_Console_Output"
       /***************** 80 character line width template *************************/
      "3Reacting To Console Output\n"
      " The EXPECT command provides a way to stop execution and take actions\n"
      " when specific output has been generated by the simulated system.\n"
      "++EXPECT {dev:line} {HALTAFTER=n,}\"<string>\" {actioncommand {; actioncommand}...}\n\n"
      " The string argument must be delimited by quote characters.  Quotes may\n"
      " be either single or double but the opening and closing quote characters\n"
      " must match.  Data in the string may contain escaped character strings.\n\n"




      " When expect rules are defined, they are evaluated agains recently\n"
      " produced output as each character is output to the device.  Since this\n"
      " evaluation processing is done on each output character, rule matching\n"
      " is not specifically line oriented.  If line oriented matching is desired\n"
      " then rules should be defined which contain the simulated system's line\n"
      " ending character sequence (i.e. \"\\r\\n\").\n"
      " Once data has matched any expect rule, that data is no longer eligible\n"







|


|
>
>
>
>







1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
      " units of microseconds rather than instructions.\n"
       /***************** 80 character line width template *************************/
#define HLP_EXPECT      "*Commands Executing_Command_Files Reacting_To_Console_Output"
       /***************** 80 character line width template *************************/
      "3Reacting To Console Output\n"
      " The EXPECT command provides a way to stop execution and take actions\n"
      " when specific output has been generated by the simulated system.\n"
      "++EXPECT {dev:line} {[count]} {HALTAFTER=n,}\"<string>\" {actioncommand {; actioncommand}...}\n\n"
      " The string argument must be delimited by quote characters.  Quotes may\n"
      " be either single or double but the opening and closing quote characters\n"
      " must match.  Data in the string may contain escaped character strings.\n"
      " If a [count] is specified, the rule will match after the match string\n"
      " has matched count times.\n\n"
      " When multiple expect rules are defined with the same match string, they\n"
      " will match in the same order they were defined in.\n\n"
      " When expect rules are defined, they are evaluated agains recently\n"
      " produced output as each character is output to the device.  Since this\n"
      " evaluation processing is done on each output character, rule matching\n"
      " is not specifically line oriented.  If line oriented matching is desired\n"
      " then rules should be defined which contain the simulated system's line\n"
      " ending character sequence (i.e. \"\\r\\n\").\n"
      " Once data has matched any expect rule, that data is no longer eligible\n"
1678
1679
1680
1681
1682
1683
1684
1685





1686
1687
1688
1689
1690
1691
1692
      " EXIT (synonyms QUIT and BYE) returns control to the operating system.\n"
       /***************** 80 character line width template *************************/
#define HLP_SCREENSHOT  "*Commands Screenshot_Video_Window"
      "2Screenshot Video Window\n"
      " Simulators with Video devices display the simulated video in a window\n"
      " on the local system.  The contents of that display can be saved in a\n"
      " file with the SCREENSHOT command:\n\n"
      " SCREENSHOT screenshotfile.bmp\n"





#define HLP_SPAWN       "*Commands Executing_System_Commands"
      "2Executing System Commands\n"
      " The simulator can execute operating system commands with the ! (spawn)\n"
      " command:\n\n"
      "++!                    execute local command interpreter\n"
      "++! <command>          execute local host command\n"
      " If no operating system command is provided, the simulator attempts to\n"







|
>
>
>
>
>







1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
      " EXIT (synonyms QUIT and BYE) returns control to the operating system.\n"
       /***************** 80 character line width template *************************/
#define HLP_SCREENSHOT  "*Commands Screenshot_Video_Window"
      "2Screenshot Video Window\n"
      " Simulators with Video devices display the simulated video in a window\n"
      " on the local system.  The contents of that display can be saved in a\n"
      " file with the SCREENSHOT command:\n\n"
      " +SCREENSHOT screenshotfile\n\n"
#if defined(HAVE_LIBPNG)
      " which will create a screen shot file called screenshotfile.png\n"
#else
      " which will create a screen shot file called screenshotfile.bmp\n"
#endif
#define HLP_SPAWN       "*Commands Executing_System_Commands"
      "2Executing System Commands\n"
      " The simulator can execute operating system commands with the ! (spawn)\n"
      " command:\n\n"
      "++!                    execute local command interpreter\n"
      "++! <command>          execute local host command\n"
      " If no operating system command is provided, the simulator attempts to\n"
1723
1724
1725
1726
1727
1728
1729


1730
1731
1732
1733
1734
1735
1736
    { "EXIT",       &exit_cmd,      0,          HLP_EXIT },
    { "QUIT",       &exit_cmd,      0,          NULL },
    { "BYE",        &exit_cmd,      0,          NULL },
    { "CD",         &set_default_cmd, 0,        HLP_CD },
    { "PWD",        &pwd_cmd,       0,          HLP_PWD },
    { "DIR",        &dir_cmd,       0,          HLP_DIR },
    { "LS",         &dir_cmd,       0,          HLP_LS },


    { "SET",        &set_cmd,       0,          HLP_SET },
    { "SHOW",       &show_cmd,      0,          HLP_SHOW },
    { "DO",         &do_cmd,        1,          HLP_DO },
    { "GOTO",       &goto_cmd,      1,          HLP_GOTO },
    { "RETURN",     &return_cmd,    0,          HLP_RETURN },
    { "SHIFT",      &shift_cmd,     0,          HLP_SHIFT },
    { "CALL",       &call_cmd,      0,          HLP_CALL },







>
>







1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
    { "EXIT",       &exit_cmd,      0,          HLP_EXIT },
    { "QUIT",       &exit_cmd,      0,          NULL },
    { "BYE",        &exit_cmd,      0,          NULL },
    { "CD",         &set_default_cmd, 0,        HLP_CD },
    { "PWD",        &pwd_cmd,       0,          HLP_PWD },
    { "DIR",        &dir_cmd,       0,          HLP_DIR },
    { "LS",         &dir_cmd,       0,          HLP_LS },
    { "TYPE",       &type_cmd,      0,          HLP_TYPE },
    { "CAT",        &type_cmd,      0,          HLP_CAT },
    { "SET",        &set_cmd,       0,          HLP_SET },
    { "SHOW",       &show_cmd,      0,          HLP_SHOW },
    { "DO",         &do_cmd,        1,          HLP_DO },
    { "GOTO",       &goto_cmd,      1,          HLP_GOTO },
    { "RETURN",     &return_cmd,    0,          HLP_RETURN },
    { "SHIFT",      &shift_cmd,     0,          HLP_SHIFT },
    { "CALL",       &call_cmd,      0,          HLP_CALL },
1761
1762
1763
1764
1765
1766
1767

1768
1769
1770
1771
1772
1773
1774
    { "NOTELNET",   &sim_set_notelnet,          0 },            /* deprecated */
    { "LOG",        &sim_set_logon,             0, HLP_SET_LOG  },
    { "NOLOG",      &sim_set_logoff,            0, HLP_SET_LOG  },
    { "DEBUG",      &sim_set_debon,             0, HLP_SET_DEBUG  },
    { "NODEBUG",    &sim_set_deboff,            0, HLP_SET_DEBUG  },
    { "THROTTLE",   &sim_set_throt,             1, HLP_SET_THROTTLE },
    { "NOTHROTTLE", &sim_set_throt,             0, HLP_SET_THROTTLE },

    { "ASYNCH",     &sim_set_asynch,            1, HLP_SET_ASYNCH },
    { "NOASYNCH",   &sim_set_asynch,            0, HLP_SET_ASYNCH },
    { "ENVIRONMENT", &sim_set_environment,      1, HLP_SET_ENVIRON },
    { "ON",         &set_on,                    1, HLP_SET_ON },
    { "NOON",       &set_on,                    0, HLP_SET_ON },
    { "VERIFY",     &set_verify,                1, HLP_SET_VERIFY },
    { "VERBOSE",    &set_verify,                1, HLP_SET_VERIFY },







>







1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
    { "NOTELNET",   &sim_set_notelnet,          0 },            /* deprecated */
    { "LOG",        &sim_set_logon,             0, HLP_SET_LOG  },
    { "NOLOG",      &sim_set_logoff,            0, HLP_SET_LOG  },
    { "DEBUG",      &sim_set_debon,             0, HLP_SET_DEBUG  },
    { "NODEBUG",    &sim_set_deboff,            0, HLP_SET_DEBUG  },
    { "THROTTLE",   &sim_set_throt,             1, HLP_SET_THROTTLE },
    { "NOTHROTTLE", &sim_set_throt,             0, HLP_SET_THROTTLE },
    { "CLOCKS",     &sim_set_timers,            1, HLP_SET_CLOCKS },
    { "ASYNCH",     &sim_set_asynch,            1, HLP_SET_ASYNCH },
    { "NOASYNCH",   &sim_set_asynch,            0, HLP_SET_ASYNCH },
    { "ENVIRONMENT", &sim_set_environment,      1, HLP_SET_ENVIRON },
    { "ON",         &set_on,                    1, HLP_SET_ON },
    { "NOON",       &set_on,                    0, HLP_SET_ON },
    { "VERIFY",     &set_verify,                1, HLP_SET_VERIFY },
    { "VERBOSE",    &set_verify,                1, HLP_SET_VERIFY },
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
t_stat stat;

#ifdef PIDP8I
// PiDP-8/I hack here
 pthread_t thread1;
 const char *message="Thread 1";
 int terminate=0, iret1;
//	printf("\nPiDP FP driver 3\n");

 // create thread
 iret1 = pthread_create( &thread1, NULL, blink, &terminate);

 if (iret1) {
   fprintf(stderr, "Error creating thread, return code %d\n", iret1);
   exit (EXIT_FAILURE);
 }
//	printf("Created thread, return code %d\n", iret1);

 sleep(2);			// allow 2 sec for multiplex to start
// ------------------------------------------------------------------------
#endif

#if defined (__MWERKS__) && defined (macintosh)
argc = ccommand (&argv);
#endif








|








|

|







1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
t_stat stat;

#ifdef PIDP8I
// PiDP-8/I hack here
 pthread_t thread1;
 const char *message="Thread 1";
 int terminate=0, iret1;
//  printf("\nPiDP FP driver 3\n");

 // create thread
 iret1 = pthread_create( &thread1, NULL, blink, &terminate);

 if (iret1) {
   fprintf(stderr, "Error creating thread, return code %d\n", iret1);
   exit (EXIT_FAILURE);
 }
//  printf("Created thread, return code %d\n", iret1);

 sleep(2);          // allow 2 sec for multiplex to start
// ------------------------------------------------------------------------
#endif

#if defined (__MWERKS__) && defined (macintosh)
argc = ccommand (&argv);
#endif

1980
1981
1982
1983
1984
1985
1986


1987











1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
    }
if (!sim_quiet) {
    printf ("\n");
    show_version (stdout, NULL, NULL, 0, NULL);
    }
if (sim_dflt_dev == NULL)                               /* if no default */
    sim_dflt_dev = sim_devices[0];














sim_argv = argv;
cptr = getenv("HOME");
if (cptr == NULL) {
    cptr = getenv("HOMEPATH");
    cptr2 = getenv("HOMEDRIVE");
    }
else
    cptr2 = NULL;
if (cptr && sizeof (nbuf) > strlen (cptr) + strlen ("/simh.ini") + 1) {
    sprintf(nbuf, "\"%s%s%ssimh.ini\"", cptr2 ? cptr2 : "", cptr, strchr (cptr, '/') ? "/" : "\\");
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* simh.ini proc cmd file */
    }
if (stat == SCPE_OPENERR)
    stat = do_cmd (-1, "simh.ini");                     /* simh.ini proc cmd file */
if (*cbuf)                                              /* cmd file arg? */
    stat = do_cmd (0, cbuf);                            /* proc cmd file */
else if (*argv[0]) {                                    /* sim name arg? */
    char *np;                                           /* "path.ini" */
    nbuf[0] = '"';                                      /* starting " */
    strncpy (nbuf + 1, argv[0], PATH_MAX + 1);          /* copy sim name */
    if ((np = match_ext (nbuf, "EXE")))                 /* remove .exe */
        *np = 0;
    strcat (nbuf, ".ini\"");                            /* add .ini" */
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* proc default cmd file */
    if (stat == SCPE_OPENERR) {                         /* didn't exist/can't open? */
        np = strrchr (nbuf, '/');                       /* stript path and try again in cwd */
        if (np == NULL)
            np = strrchr (nbuf, '\\');                  /* windows path separator */







>
>

>
>
>
>
>
>
>
>
>
>
>




















|







2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
    }
if (!sim_quiet) {
    printf ("\n");
    show_version (stdout, NULL, NULL, 0, NULL);
    }
if (sim_dflt_dev == NULL)                               /* if no default */
    sim_dflt_dev = sim_devices[0];
if (*argv[0]) {                                         /* sim name arg? */
    char *np;                                           /* "path.ini" */

    strncpy (nbuf, argv[0], PATH_MAX + 1);              /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    np = strrchr (nbuf, '/');                           /* stript path and try again in cwd */
    if (np == NULL)
        np = strrchr (nbuf, '\\');                      /* windows path separator */
    if (np == NULL)
        np = strrchr (nbuf, ']');                       /* VMS path separator */
    if (np != NULL)
        setenv ("SIM_BIN_NAME", np+1, 1);               /* Publish simulator binary name */
    }
sim_argv = argv;
cptr = getenv("HOME");
if (cptr == NULL) {
    cptr = getenv("HOMEPATH");
    cptr2 = getenv("HOMEDRIVE");
    }
else
    cptr2 = NULL;
if (cptr && sizeof (nbuf) > strlen (cptr) + strlen ("/simh.ini") + 1) {
    sprintf(nbuf, "\"%s%s%ssimh.ini\"", cptr2 ? cptr2 : "", cptr, strchr (cptr, '/') ? "/" : "\\");
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* simh.ini proc cmd file */
    }
if (stat == SCPE_OPENERR)
    stat = do_cmd (-1, "simh.ini");                     /* simh.ini proc cmd file */
if (*cbuf)                                              /* cmd file arg? */
    stat = do_cmd (0, cbuf);                            /* proc cmd file */
else if (*argv[0]) {                                    /* sim name arg? */
    char *np;                                           /* "path.ini" */
    nbuf[0] = '"';                                      /* starting " */
    strncpy (nbuf + 1, argv[0], PATH_MAX + 1);          /* copy sim name */
    if ((np = (char *)match_ext (nbuf, "EXE")))         /* remove .exe */
        *np = 0;
    strcat (nbuf, ".ini\"");                            /* add .ini" */
    stat = do_cmd (-1, nbuf) & ~SCPE_NOMESSAGE;         /* proc default cmd file */
    if (stat == SCPE_OPENERR) {                         /* didn't exist/can't open? */
        np = strrchr (nbuf, '/');                       /* stript path and try again in cwd */
        if (np == NULL)
            np = strrchr (nbuf, '\\');                  /* windows path separator */
2041
2042
2043
2044
2045
2046
2047
2048

2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
#endif

return 0;
}

t_stat process_stdin_commands (t_stat stat, char *argv[])
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *cptr;

t_stat stat_nomessage;
CTAB *cmdp;

stat = SCPE_BARE_STATUS(stat);                          /* remove possible flag */
while (stat != SCPE_EXIT) {                             /* in case exit */
#ifdef PIDP8I
if (awfulHackFlag!=0) {
  if (awfulHackFlag==8)
    sprintf(cbuf, "exit");	// inject command into command line processor.
  else {
    char path[256];
    snprintf(path, sizeof(path), "@BOOTDIR@/%d.script", awfulHackFlag);
    if (access(path, R_OK) == 0) {
      sprintf(cbuf, "do %s", path);
    }
		else {
			// Give up; can't find that boot script.  Have to exit, or we'll
			// spam the console with errors, since we can write errors faster
			// than the user can flip the offending switch back, particularly
			// with a slow serial console.
			char cwd[256];
			getcwd(cwd, sizeof(cwd));
			printf("Cannot read %s from %s: %s!\n", path, cwd, strerror(errno));
			sprintf(cbuf, "exit");
    }
  }
  cptr = cbuf;
 }
 else if ((cptr = sim_brk_getact (cbuf, sizeof(cbuf))))   /* pending action? */
   printf ("%s%s\n", sim_prompt, cptr);            /* echo */
 else if (sim_vm_read != NULL) {                     /* sim routine? */







|
>








|






|
|
|
|
|
|
|
|
|







2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
#endif

return 0;
}

t_stat process_stdin_commands (t_stat stat, char *argv[])
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE];
CONST char *cptr;
t_stat stat_nomessage;
CTAB *cmdp;

stat = SCPE_BARE_STATUS(stat);                          /* remove possible flag */
while (stat != SCPE_EXIT) {                             /* in case exit */
#ifdef PIDP8I
if (awfulHackFlag!=0) {
  if (awfulHackFlag==8)
    sprintf(cbuf, "exit");  // inject command into command line processor.
  else {
    char path[256];
    snprintf(path, sizeof(path), "@BOOTDIR@/%d.script", awfulHackFlag);
    if (access(path, R_OK) == 0) {
      sprintf(cbuf, "do %s", path);
    }
        else {
            // Give up; can't find that boot script.  Have to exit, or we'll
            // spam the console with errors, since we can write errors faster
            // than the user can flip the offending switch back, particularly
            // with a slow serial console.
            char cwd[256];
            getcwd(cwd, sizeof(cwd));
            printf("Cannot read %s from %s: %s!\n", path, cwd, strerror(errno));
            sprintf(cbuf, "exit");
    }
  }
  cptr = cbuf;
 }
 else if ((cptr = sim_brk_getact (cbuf, sizeof(cbuf))))   /* pending action? */
   printf ("%s%s\n", sim_prompt, cptr);            /* echo */
 else if (sim_vm_read != NULL) {                     /* sim routine? */
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107

2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    sim_sub_args (cbuf, sizeof(cbuf), argv);
    if (sim_log)                                        /* log cmd */
        fprintf (sim_log, "%s%s\n", sim_prompt, cptr);
    if (sim_deb && (sim_deb != sim_log) && (sim_deb != stdout))
        fprintf (sim_deb, "%s%s\n", sim_prompt, cptr);
    cptr = get_glyph (cptr, gbuf, 0);                   /* get command glyph */
    sim_switches = 0;                                   /* init switches */
    if ((cmdp = find_cmd (gbuf)))                       /* lookup command */
        stat = cmdp->action (cmdp->arg, cptr);          /* if found, exec */

    else stat = SCPE_UNK;
    stat_nomessage = stat & SCPE_NOMESSAGE;             /* extract possible message supression flag */
    stat_nomessage = stat_nomessage || (!sim_show_message);/* Apply global suppression */
    stat = SCPE_BARE_STATUS(stat);                      /* remove possible flag */
    sim_last_cmd_stat = stat;                           /* save command error status */
    if (!stat_nomessage) {                              /* displaying message status? */
        if (cmdp && (cmdp->message))                    /* special message handler? */
            cmdp->message (NULL, stat);                 /* let it deal with display */
        else
            if (stat >= SCPE_BASE)                      /* error? */
                sim_printf ("%s\n", sim_error_text (stat));
        }
    if (sim_vm_post != NULL)
        (*sim_vm_post) (TRUE);
    }                                                   /* end while */
return stat;
}

/* Set prompt routine */

t_stat set_prompt (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];

if ((!cptr) || (*cptr == '\0'))
    return SCPE_ARG;

cptr = get_glyph_nc (cptr, gbuf, '"');                  /* get quote delimited token */
if (gbuf[0] == '\0') {                                  /* Token started with quote */
    gbuf[sizeof (gbuf)-1] = '\0';
    strncpy (gbuf, cptr, sizeof (gbuf)-1);
    cptr = strchr (gbuf, '"');
    if (cptr)
        *cptr = '\0';
    }
sim_prompt = (char *)realloc (sim_prompt, strlen (gbuf) + 2);   /* nul terminator and trailing blank */
sprintf (sim_prompt, "%s ", gbuf);
return SCPE_OK;
}

/* Find command routine */







|



>
|



















|

|








|
|
|







2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    sim_sub_args (cbuf, sizeof(cbuf), argv);
    if (sim_log)                                        /* log cmd */
        fprintf (sim_log, "%s%s\n", sim_prompt, cptr);
    if (sim_deb && (sim_deb != sim_log) && (sim_deb != stdout))
        fprintf (sim_deb, "%s%s\n", sim_prompt, cptr);
    cptr = get_glyph_cmd (cptr, gbuf);                  /* get command glyph */
    sim_switches = 0;                                   /* init switches */
    if ((cmdp = find_cmd (gbuf)))                       /* lookup command */
        stat = cmdp->action (cmdp->arg, cptr);          /* if found, exec */
    else
        stat = SCPE_UNK;
    stat_nomessage = stat & SCPE_NOMESSAGE;             /* extract possible message supression flag */
    stat_nomessage = stat_nomessage || (!sim_show_message);/* Apply global suppression */
    stat = SCPE_BARE_STATUS(stat);                      /* remove possible flag */
    sim_last_cmd_stat = stat;                           /* save command error status */
    if (!stat_nomessage) {                              /* displaying message status? */
        if (cmdp && (cmdp->message))                    /* special message handler? */
            cmdp->message (NULL, stat);                 /* let it deal with display */
        else
            if (stat >= SCPE_BASE)                      /* error? */
                sim_printf ("%s\n", sim_error_text (stat));
        }
    if (sim_vm_post != NULL)
        (*sim_vm_post) (TRUE);
    }                                                   /* end while */
return stat;
}

/* Set prompt routine */

t_stat set_prompt (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE], *gptr;

if ((!cptr) || (*cptr == '\0'))
    return SCPE_ARG;

cptr = get_glyph_nc (cptr, gbuf, '"');                  /* get quote delimited token */
if (gbuf[0] == '\0') {                                  /* Token started with quote */
    gbuf[sizeof (gbuf)-1] = '\0';
    strncpy (gbuf, cptr, sizeof (gbuf)-1);
    gptr = strchr (gbuf, '"');
    if (gptr)
        *gptr = '\0';
    }
sim_prompt = (char *)realloc (sim_prompt, strlen (gbuf) + 2);   /* nul terminator and trailing blank */
sprintf (sim_prompt, "%s ", gbuf);
return SCPE_OK;
}

/* Find command routine */
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
if (cmdp == NULL)                                       /* try regular cmds */
    cmdp = find_ctab (cmd_table, gbuf);
return cmdp;
}

/* Exit command */

t_stat exit_cmd (int32 flag, char *cptr)
{
return SCPE_EXIT;
}

/* Help command */


/* Used when sorting a list of command names */
static int _cmd_name_compare (const void *pa, const void *pb)
{
CTAB **a = (CTAB **)pa;
CTAB **b = (CTAB **)pb;

return strcmp((*a)->name, (*b)->name);
}

void fprint_help (FILE *st)
{
CTAB *cmdp;







|










|
|







2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
if (cmdp == NULL)                                       /* try regular cmds */
    cmdp = find_ctab (cmd_table, gbuf);
return cmdp;
}

/* Exit command */

t_stat exit_cmd (int32 flag, CONST char *cptr)
{
return SCPE_EXIT;
}

/* Help command */


/* Used when sorting a list of command names */
static int _cmd_name_compare (const void *pa, const void *pb)
{
CTAB * const *a = (CTAB * const *)pa;
CTAB * const *b = (CTAB * const *)pb;

return strcmp((*a)->name, (*b)->name);
}

void fprint_help (FILE *st)
{
CTAB *cmdp;
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
void fprint_reg_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
REG *rptr, *trptr;
t_bool found = FALSE;
t_bool all_unique = TRUE;
size_t max_namelen = 0;
DEVICE *tdptr;
const char *tptr;
char *namebuf;
char rangebuf[32];

if (dptr->registers)
    for (rptr = dptr->registers; rptr->name != NULL; rptr++) {
        if (rptr->flags & REG_HIDDEN)
            continue;







|







2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
void fprint_reg_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
REG *rptr, *trptr;
t_bool found = FALSE;
t_bool all_unique = TRUE;
size_t max_namelen = 0;
DEVICE *tdptr;
CONST char *tptr;
char *namebuf;
char rangebuf[32];

if (dptr->registers)
    for (rptr = dptr->registers; rptr->name != NULL; rptr++) {
        if (rptr->flags & REG_HIDDEN)
            continue;
2343
2344
2345
2346
2347
2348
2349

2350


2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367


2368
2369
2370
2371


2372
2373
2374
2375
2376
2377
2378





2379
2380
2381
2382
2383
2384
2385
        if (!MODMASK(mptr,MTAB_VDV) && MODMASK(mptr,MTAB_VUN) && (dptr->numunits != 1))
            continue;                                       /* skip unit only extended modifiers */
        if ((dptr->numunits != 1) && !(mptr->mask & MTAB_XTD))
            continue;                                       /* skip unit only simple modifiers */
        if (mptr->mstring) {
            fprint_header (st, &found, header);
            sprintf (buf, "set %s %s%s", sim_dname (dptr), mptr->mstring, (strchr(mptr->mstring, '=')) ? "" : (MODMASK(mptr,MTAB_VALR) ? "=val" : (MODMASK(mptr,MTAB_VALO) ? "{=val}" : "")));

            fprintf (st, "%-30s\t%s\n", buf, (strchr(mptr->mstring, '=')) ? "" : (mptr->help ? mptr->help : ""));


            }
        }
    }
if (dptr->flags & DEV_DISABLE) {
    fprint_header (st, &found, header);
    sprintf (buf, "set %s ENABLE", sim_dname (dptr));
    fprintf (st,  "%-30s\tEnables device %s\n", buf, sim_dname (dptr));
    sprintf (buf, "set %s DISABLE", sim_dname (dptr));
    fprintf (st,  "%-30s\tDisables device %s\n", buf, sim_dname (dptr));
    }
if (dptr->flags & DEV_DEBUG) {
    fprint_header (st, &found, header);
    sprintf (buf, "set %s DEBUG", sim_dname (dptr));
    fprintf (st,  "%-30s\tEnables debugging for device %s\n", buf, sim_dname (dptr));
    sprintf (buf, "set %s NODEBUG", sim_dname (dptr));
    fprintf (st,  "%-30s\tDisables debugging for device %s\n", buf, sim_dname (dptr));
    if (dptr->debflags) {


        strcpy (buf, "");
        fprintf (st, "set %s DEBUG=", sim_dname (dptr));
        for (dep = dptr->debflags; dep->name != NULL; dep++)
            fprintf (st, "%s%s", ((dep == dptr->debflags) ? "" : ";"), dep->name);


        fprintf (st, "\n");
        fprintf (st,  "%-30s\tEnables specific debugging for device %s\n", buf, sim_dname (dptr));
        fprintf (st, "set %s NODEBUG=", sim_dname (dptr));
        for (dep = dptr->debflags; dep->name != NULL; dep++)
            fprintf (st, "%s%s", ((dep == dptr->debflags) ? "" : ";"), dep->name);
        fprintf (st, "\n");
        fprintf (st,  "%-30s\tDisables specific debugging for device %s\n", buf, sim_dname (dptr));





        }
    }
if ((dptr->modifiers) && (dptr->units) && (dptr->numunits != 1)) {
    if (dptr->units->flags & UNIT_DISABLE) {
        fprint_header (st, &found, header);
        sprintf (buf, "set %sn ENABLE", sim_dname (dptr));
        fprintf (st,  "%-30s\tEnables unit %sn\n", buf, sim_dname (dptr));







>
|
>
>

















>
>


|

>
>







>
>
>
>
>







2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
        if (!MODMASK(mptr,MTAB_VDV) && MODMASK(mptr,MTAB_VUN) && (dptr->numunits != 1))
            continue;                                       /* skip unit only extended modifiers */
        if ((dptr->numunits != 1) && !(mptr->mask & MTAB_XTD))
            continue;                                       /* skip unit only simple modifiers */
        if (mptr->mstring) {
            fprint_header (st, &found, header);
            sprintf (buf, "set %s %s%s", sim_dname (dptr), mptr->mstring, (strchr(mptr->mstring, '=')) ? "" : (MODMASK(mptr,MTAB_VALR) ? "=val" : (MODMASK(mptr,MTAB_VALO) ? "{=val}" : "")));
            if ((strlen (buf) < 30) || (!mptr->help))
                fprintf (st, "%-30s\t%s\n", buf, mptr->help ? mptr->help : "");
            else
                fprintf (st, "%s\n%-30s\t%s\n", buf, "", mptr->help);
            }
        }
    }
if (dptr->flags & DEV_DISABLE) {
    fprint_header (st, &found, header);
    sprintf (buf, "set %s ENABLE", sim_dname (dptr));
    fprintf (st,  "%-30s\tEnables device %s\n", buf, sim_dname (dptr));
    sprintf (buf, "set %s DISABLE", sim_dname (dptr));
    fprintf (st,  "%-30s\tDisables device %s\n", buf, sim_dname (dptr));
    }
if (dptr->flags & DEV_DEBUG) {
    fprint_header (st, &found, header);
    sprintf (buf, "set %s DEBUG", sim_dname (dptr));
    fprintf (st,  "%-30s\tEnables debugging for device %s\n", buf, sim_dname (dptr));
    sprintf (buf, "set %s NODEBUG", sim_dname (dptr));
    fprintf (st,  "%-30s\tDisables debugging for device %s\n", buf, sim_dname (dptr));
    if (dptr->debflags) {
        t_bool desc_available = FALSE;

        strcpy (buf, "");
        fprintf (st, "set %s DEBUG=", sim_dname (dptr));
        for (dep = dptr->debflags; dep->name != NULL; dep++) {
            fprintf (st, "%s%s", ((dep == dptr->debflags) ? "" : ";"), dep->name);
            desc_available |= ((dep->desc != NULL) && (dep->desc[0] != '\0'));
            }
        fprintf (st, "\n");
        fprintf (st,  "%-30s\tEnables specific debugging for device %s\n", buf, sim_dname (dptr));
        fprintf (st, "set %s NODEBUG=", sim_dname (dptr));
        for (dep = dptr->debflags; dep->name != NULL; dep++)
            fprintf (st, "%s%s", ((dep == dptr->debflags) ? "" : ";"), dep->name);
        fprintf (st, "\n");
        fprintf (st,  "%-30s\tDisables specific debugging for device %s\n", buf, sim_dname (dptr));
        if (desc_available) {
            fprintf (st, "\n*%s device DEBUG settings:\n", sim_dname (dptr));
            for (dep = dptr->debflags; dep->name != NULL; dep++)
                fprintf (st, "%4s%-12s%s\n", "", dep->name, dep->desc ? dep->desc : "");
            }
        }
    }
if ((dptr->modifiers) && (dptr->units) && (dptr->numunits != 1)) {
    if (dptr->units->flags & UNIT_DISABLE) {
        fprint_header (st, &found, header);
        sprintf (buf, "set %sn ENABLE", sim_dname (dptr));
        fprintf (st,  "%-30s\tEnables unit %sn\n", buf, sim_dname (dptr));
2448
2449
2450
2451
2452
2453
2454




































2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480




2481
2482
2483
2484
2485
2486
2487
}

void fprint_show_help (FILE *st, DEVICE *dptr)
    {
    fprint_show_help_ex (st, dptr, TRUE);
    }





































t_stat help_dev_help (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
CTAB *cmdp;

if (*cptr) {
    char *gptr = get_glyph (cptr, gbuf, 0);
    if ((cmdp = find_cmd (gbuf))) {
        if (cmdp->action == &exdep_cmd) {
            if (dptr->help) /* Shouldn't this pass cptr so the device knows which command invoked? */
                return dptr->help (st, dptr, uptr, flag, gptr);
            else
                fprintf (st, "No help available for the %s %s command\n", cmdp->name, sim_dname(dptr));
            return SCPE_OK;
            }
        if (cmdp->action == &set_cmd) {
            fprint_set_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (cmdp->action == &show_cmd) {
            fprint_show_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (cmdp->action == &attach_cmd) {
            fprint_attach_help_ex (st, dptr, FALSE);
            return SCPE_OK;




            }
        if (dptr->help)
            return dptr->help (st, dptr, uptr, flag, cptr);
        fprintf (st, "No %s help is available for the %s device\n", cmdp->name, dptr->name);
        return SCPE_OK;
        }
    if (MATCH_CMD (gbuf, "REGISTERS") == 0) {







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|





|



















>
>
>
>







2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
}

void fprint_show_help (FILE *st, DEVICE *dptr)
    {
    fprint_show_help_ex (st, dptr, TRUE);
    }

void fprint_brk_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
BRKTYPTAB *brkt = dptr->brk_types;
char gbuf[CBUFSIZE];

if (sim_brk_types == 0) {
    if ((dptr != sim_dflt_dev) && (!silent)) {
        fprintf (st, "Breakpoints are not supported in the %s simulator\n", sim_name);
        if (dptr->help)
            dptr->help (st, dptr, NULL, 0, NULL);
        }
    return;
    }
if (brkt == NULL) {
    int i;

    if (dptr == sim_dflt_dev) {
        if (sim_brk_types & ~sim_brk_dflt) {
            fprintf (st, "%s supports the following breakpoint types:\n", sim_dname (dptr));
            for (i=0; i<26; i++) {
                if (sim_brk_types & (1<<i))
                    fprintf (st, "  -%c\n", 'A'+i);
                }
            }
        fprintf (st, "The default breakpoint type is: %s\n", put_switches (gbuf, sizeof(gbuf), sim_brk_dflt));
        }
    return;
    }
fprintf (st, "%s supports the following breakpoint types:\n", sim_dname (dptr));
while (brkt->btyp) {
    fprintf (st, "  %s     %s\n", put_switches (gbuf, sizeof(gbuf), brkt->btyp), brkt->desc);
    ++brkt;
    }
fprintf (st, "The default breakpoint type is: %s\n", put_switches (gbuf, sizeof(gbuf), sim_brk_dflt));
}

t_stat help_dev_help (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
char gbuf[CBUFSIZE];
CTAB *cmdp;

if (*cptr) {
    const char *gptr = get_glyph (cptr, gbuf, 0);
    if ((cmdp = find_cmd (gbuf))) {
        if (cmdp->action == &exdep_cmd) {
            if (dptr->help) /* Shouldn't this pass cptr so the device knows which command invoked? */
                return dptr->help (st, dptr, uptr, flag, gptr);
            else
                fprintf (st, "No help available for the %s %s command\n", cmdp->name, sim_dname(dptr));
            return SCPE_OK;
            }
        if (cmdp->action == &set_cmd) {
            fprint_set_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (cmdp->action == &show_cmd) {
            fprint_show_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (cmdp->action == &attach_cmd) {
            fprint_attach_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (cmdp->action == &brk_cmd) {
            fprint_brk_help_ex (st, dptr, FALSE);
            return SCPE_OK;
            }
        if (dptr->help)
            return dptr->help (st, dptr, uptr, flag, cptr);
        fprintf (st, "No %s help is available for the %s device\n", cmdp->name, dptr->name);
        return SCPE_OK;
        }
    if (MATCH_CMD (gbuf, "REGISTERS") == 0) {
2500
2501
2502
2503
2504
2505
2506

2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
    fprintf (st, "%s %s help\n", dptr->description (dptr), dptr->name);
else
    fprintf (st, "%s help\n", dptr->name);
fprint_set_help_ex (st, dptr, TRUE);
fprint_show_help_ex (st, dptr, TRUE);
fprint_attach_help_ex (st, dptr, TRUE);
fprint_reg_help_ex (st, dptr, TRUE);

return SCPE_OK;
}

t_stat help_cmd_output (int32 flag, const char *help, const char *help_base)
{
switch (help[0]) {
    case '*':
        scp_help (stdout, NULL, NULL, flag, help_base ? help_base : simh_help, help+1);
        if (sim_log)
            scp_help (sim_log, NULL, NULL, flag | SCP_HELP_FLAT, help_base ? help_base : simh_help, help+1);
        break;
    default:
        fputs (help, stdout);
        if (sim_log)
            fputs (help, sim_log);
        break;
    }
return SCPE_OK;
}

t_stat help_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
CTAB *cmdp;

GET_SWITCHES (cptr);
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;







>




















|







2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
    fprintf (st, "%s %s help\n", dptr->description (dptr), dptr->name);
else
    fprintf (st, "%s help\n", dptr->name);
fprint_set_help_ex (st, dptr, TRUE);
fprint_show_help_ex (st, dptr, TRUE);
fprint_attach_help_ex (st, dptr, TRUE);
fprint_reg_help_ex (st, dptr, TRUE);
fprint_brk_help_ex (st, dptr, TRUE);
return SCPE_OK;
}

t_stat help_cmd_output (int32 flag, const char *help, const char *help_base)
{
switch (help[0]) {
    case '*':
        scp_help (stdout, NULL, NULL, flag, help_base ? help_base : simh_help, help+1);
        if (sim_log)
            scp_help (sim_log, NULL, NULL, flag | SCP_HELP_FLAT, help_base ? help_base : simh_help, help+1);
        break;
    default:
        fputs (help, stdout);
        if (sim_log)
            fputs (help, sim_log);
        break;
    }
return SCPE_OK;
}

t_stat help_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CTAB *cmdp;

GET_SWITCHES (cptr);
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
        fprint_help (sim_log);
    }
return SCPE_OK;
}

/* Spawn command */

t_stat spawn_cmd (int32 flag, char *cptr)
{
t_stat status;
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = getenv("SHELL");
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = getenv("ComSpec");
#if defined (VMS)







|







2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
        fprint_help (sim_log);
    }
return SCPE_OK;
}

/* Spawn command */

t_stat spawn_cmd (int32 flag, CONST char *cptr)
{
t_stat status;
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = getenv("SHELL");
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = getenv("ComSpec");
#if defined (VMS)
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
#endif

return status;
}

/* Screenshot command */

t_stat screenshot_cmd (int32 flag, char *cptr)
{
if ((cptr == NULL) || (strlen (cptr) == 0))
    return SCPE_ARG;
#if defined (USE_SIM_VIDEO)
return vid_screenshot (cptr);
#else
sim_printf ("No video device\n");
return SCPE_UNK|SCPE_NOMESSAGE;
#endif
}

/* Echo command */

t_stat echo_cmd (int32 flag, char *cptr)
{
sim_printf ("%s\n", cptr);
return SCPE_OK;
}

/* Do command








|













|







2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
#endif

return status;
}

/* Screenshot command */

t_stat screenshot_cmd (int32 flag, CONST char *cptr)
{
if ((cptr == NULL) || (strlen (cptr) == 0))
    return SCPE_ARG;
#if defined (USE_SIM_VIDEO)
return vid_screenshot (cptr);
#else
sim_printf ("No video device\n");
return SCPE_UNK|SCPE_NOMESSAGE;
#endif
}

/* Echo command */

t_stat echo_cmd (int32 flag, CONST char *cptr)
{
sim_printf ("%s\n", cptr);
return SCPE_OK;
}

/* Do command

2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740

2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760


2761
2762
2763
2764
2765
2766
2767
2768

        -1      =   initialization file (no error if not found)
         0      =   command line file
         1      =   "DO" command
        >1      =   nested "DO" command
*/

t_stat do_cmd (int32 flag, char *fcptr)
{
return do_cmd_label (flag, fcptr, NULL);
}

static char *do_position(void)
{
static char cbuf[CBUFSIZE];

sprintf (cbuf, "%s%s%s-%d", sim_do_filename[sim_do_depth], sim_do_label[sim_do_depth] ? "::" : "", sim_do_label[sim_do_depth] ? sim_do_label[sim_do_depth] : "", sim_goto_line[sim_do_depth]);
return cbuf;
}

t_stat do_cmd_label (int32 flag, char *fcptr, char *label)
{
char *cptr, cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *c, quote, *do_arg[11];

FILE *fpin;
CTAB *cmdp = NULL;
int32 echo, nargs, errabort, i;
int32 saved_sim_do_echo = sim_do_echo,
      saved_sim_show_message = sim_show_message,
      saved_sim_on_inherit = sim_on_inherit,
      saved_sim_quiet = sim_quiet;
t_bool staying;
t_stat stat, stat_nomessage;

stat = SCPE_OK;
staying = TRUE;
if (flag > 0)                                           /* need switches? */
    GET_SWITCHES (fcptr);                               /* get switches */
echo = (sim_switches & SWMASK ('V')) || sim_do_echo;    /* -v means echo */
sim_quiet = (sim_switches & SWMASK ('Q')) || sim_quiet; /* -q means quiet */
sim_on_inherit =(sim_switches & SWMASK ('O')) || sim_on_inherit; /* -o means inherit ON condition actions */

errabort = sim_switches & SWMASK ('E');                 /* -e means abort on error */



c = fcptr;
do_arg[10] = NULL;                                      /* make sure the argument list always ends with a NULL */
for (nargs = 0; nargs < 10; ) {                         /* extract arguments */
    while (sim_isspace (*c))                                /* skip blanks */
        c++;
    if (*c == 0)                                        /* all done? */
        do_arg [nargs++] = NULL;                        /* null argument */
    else {







|












|

|
>




















>
>
|







2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938

        -1      =   initialization file (no error if not found)
         0      =   command line file
         1      =   "DO" command
        >1      =   nested "DO" command
*/

t_stat do_cmd (int32 flag, CONST char *fcptr)
{
return do_cmd_label (flag, fcptr, NULL);
}

static char *do_position(void)
{
static char cbuf[CBUFSIZE];

sprintf (cbuf, "%s%s%s-%d", sim_do_filename[sim_do_depth], sim_do_label[sim_do_depth] ? "::" : "", sim_do_label[sim_do_depth] ? sim_do_label[sim_do_depth] : "", sim_goto_line[sim_do_depth]);
return cbuf;
}

t_stat do_cmd_label (int32 flag, CONST char *fcptr, CONST char *label)
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], abuf[4*CBUFSIZE], quote, *c, *do_arg[11];
CONST char *cptr;
FILE *fpin;
CTAB *cmdp = NULL;
int32 echo, nargs, errabort, i;
int32 saved_sim_do_echo = sim_do_echo,
      saved_sim_show_message = sim_show_message,
      saved_sim_on_inherit = sim_on_inherit,
      saved_sim_quiet = sim_quiet;
t_bool staying;
t_stat stat, stat_nomessage;

stat = SCPE_OK;
staying = TRUE;
if (flag > 0)                                           /* need switches? */
    GET_SWITCHES (fcptr);                               /* get switches */
echo = (sim_switches & SWMASK ('V')) || sim_do_echo;    /* -v means echo */
sim_quiet = (sim_switches & SWMASK ('Q')) || sim_quiet; /* -q means quiet */
sim_on_inherit =(sim_switches & SWMASK ('O')) || sim_on_inherit; /* -o means inherit ON condition actions */

errabort = sim_switches & SWMASK ('E');                 /* -e means abort on error */

abuf[sizeof(abuf)-1] = '\0';
strncpy (abuf, fcptr, sizeof(abuf)-1);
c = abuf;
do_arg[10] = NULL;                                      /* make sure the argument list always ends with a NULL */
for (nargs = 0; nargs < 10; ) {                         /* extract arguments */
    while (sim_isspace (*c))                                /* skip blanks */
        c++;
    if (*c == 0)                                        /* all done? */
        do_arg [nargs++] = NULL;                        /* null argument */
    else {
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
        }
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    if (echo)                                           /* echo if -v */
        sim_printf("%s> %s\n", do_position(), cptr);
    if (*cptr == ':')                                   /* ignore label */
        continue;
    cptr = get_glyph (cptr, gbuf, 0);                   /* get command glyph */
    sim_switches = 0;                                   /* init switches */
    sim_gotofile = fpin;
    sim_do_echo = echo;
    if ((cmdp = find_cmd (gbuf))) {                     /* lookup command */
        if (cmdp->action == &return_cmd)                /* RETURN command? */
            break;                                      /*    done! */
        if (cmdp->action == &do_cmd) {                  /* DO command? */







|







3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
        }
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    if (echo)                                           /* echo if -v */
        sim_printf("%s> %s\n", do_position(), cptr);
    if (*cptr == ':')                                   /* ignore label */
        continue;
    cptr = get_glyph_cmd (cptr, gbuf);                  /* get command glyph */
    sim_switches = 0;                                   /* init switches */
    sim_gotofile = fpin;
    sim_do_echo = echo;
    if ((cmdp = find_cmd (gbuf))) {                     /* lookup command */
        if (cmdp->action == &return_cmd)                /* RETURN command? */
            break;                                      /*    done! */
        if (cmdp->action == &do_cmd) {                  /* DO command? */
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
                stat = cmdp->action (cmdp->arg, cptr);  /* exec other cmd */
        }
    else stat = SCPE_UNK;                               /* bad cmd given */
    echo = sim_do_echo;                                 /* Allow for SET VERIFY */
    stat_nomessage = stat & SCPE_NOMESSAGE;             /* extract possible message supression flag */
    stat_nomessage = stat_nomessage || (!sim_show_message);/* Apply global suppression */
    stat = SCPE_BARE_STATUS(stat);                      /* remove possible flag */
    if ((stat != SCPE_OK) ||
        ((cmdp->action != &return_cmd) &&
         (cmdp->action != &goto_cmd) &&
         (cmdp->action != &on_cmd) &&
         (cmdp->action != &echo_cmd)))
        sim_last_cmd_stat = stat;                       /* save command error status */
    switch (stat) {
        case SCPE_AFAIL:







|







3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
                stat = cmdp->action (cmdp->arg, cptr);  /* exec other cmd */
        }
    else stat = SCPE_UNK;                               /* bad cmd given */
    echo = sim_do_echo;                                 /* Allow for SET VERIFY */
    stat_nomessage = stat & SCPE_NOMESSAGE;             /* extract possible message supression flag */
    stat_nomessage = stat_nomessage || (!sim_show_message);/* Apply global suppression */
    stat = SCPE_BARE_STATUS(stat);                      /* remove possible flag */
    if (((stat != SCPE_OK) && (stat != SCPE_EXPECT)) ||
        ((cmdp->action != &return_cmd) &&
         (cmdp->action != &goto_cmd) &&
         (cmdp->action != &on_cmd) &&
         (cmdp->action != &echo_cmd)))
        sim_last_cmd_stat = stat;                       /* save command error status */
    switch (stat) {
        case SCPE_AFAIL:
2899
2900
2901
2902
2903
2904
2905


2906
2907
2908
2909
2910
2911
2912
    if (!stat_nomessage) {                              /* report error if not suppressed */
        if (cmdp && cmdp->message)                      /* special message handler */
            cmdp->message ((!echo && !sim_quiet) ? sim_do_ocptr[sim_do_depth] : NULL, stat);
        else
            if (stat >= SCPE_BASE)                      /* report error if not suppressed */
                sim_printf ("%s\n", sim_error_text (stat));
        }


    if (staying &&
        (sim_on_check[sim_do_depth]) &&
        (stat != SCPE_OK) &&
        (stat != SCPE_STEP)) {
        if ((stat <= SCPE_MAX_ERR) && sim_on_actions[sim_do_depth][stat])
            sim_brk_setact (sim_on_actions[sim_do_depth][stat]);
        else







>
>







3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
    if (!stat_nomessage) {                              /* report error if not suppressed */
        if (cmdp && cmdp->message)                      /* special message handler */
            cmdp->message ((!echo && !sim_quiet) ? sim_do_ocptr[sim_do_depth] : NULL, stat);
        else
            if (stat >= SCPE_BASE)                      /* report error if not suppressed */
                sim_printf ("%s\n", sim_error_text (stat));
        }
    if (stat == SCPE_EXPECT)                            /* EXPECT status is non actionable */
        stat = SCPE_OK;                                 /* so adjust it to SCPE_OK */
    if (staying &&
        (sim_on_check[sim_do_depth]) &&
        (stat != SCPE_OK) &&
        (stat != SCPE_STEP)) {
        if ((stat <= SCPE_MAX_ERR) && sim_on_actions[sim_do_depth][stat])
            sim_brk_setact (sim_on_actions[sim_do_depth][stat]);
        else
2984
2985
2986
2987
2988
2989
2990
2991

2992
2993
2994
2995
2996
2997
2998
   it is not found, then the original beginning token on the line is left
   untouched.
*/

void sim_sub_args (char *instr, size_t instr_size, char *do_arg[])
{
char gbuf[CBUFSIZE];
char *ip = instr, *op, *ap, *oend, *istart, *tmpbuf;

char rbuf[CBUFSIZE];
int i;
time_t now;
struct tm *tmnow;

time(&now);
tmnow = localtime(&now);







|
>







3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
   it is not found, then the original beginning token on the line is left
   untouched.
*/

void sim_sub_args (char *instr, size_t instr_size, char *do_arg[])
{
char gbuf[CBUFSIZE];
char *ip = instr, *op, *oend, *istart, *tmpbuf;
const char *ap;
char rbuf[CBUFSIZE];
int i;
time_t now;
struct tm *tmnow;

time(&now);
tmnow = localtime(&now);
3099
3100
3101
3102
3103
3104
3105

















3106
3107
3108
3109








3110
3111
3112
3113
3114
3115
3116
                    else if (!strcmp ("DATE_YY", gbuf)) {/* Year (00-99) */
                        strftime (rbuf, sizeof(rbuf), "%y", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_YC", gbuf)) {/* Century (year/100) */
                        sprintf (rbuf, "%d", (tmnow->tm_year + 1900)/100);
                        ap = rbuf;

















                        }
                    else if (!strcmp ("DATE_MM", gbuf)) {/* Month number (01-12) */
                        strftime (rbuf, sizeof(rbuf), "%m", tmnow);
                        ap = rbuf;








                        }
                    else if (!strcmp ("DATE_DD", gbuf)) {/* Day of Month (01-31) */
                        strftime (rbuf, sizeof(rbuf), "%d", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_D", gbuf)) { /* ISO 8601 weekday number (1-7) */
                        sprintf (rbuf, "%d", (tmnow->tm_wday ? tmnow->tm_wday : 7));







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>
>
>
>
>
>
>
>







3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
                    else if (!strcmp ("DATE_YY", gbuf)) {/* Year (00-99) */
                        strftime (rbuf, sizeof(rbuf), "%y", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_YC", gbuf)) {/* Century (year/100) */
                        sprintf (rbuf, "%d", (tmnow->tm_year + 1900)/100);
                        ap = rbuf;
                        }
                    else if ((!strcmp ("DATE_19XX_YY", gbuf)) || /* Year with same calendar */
                             (!strcmp ("DATE_19XX_YYYY", gbuf))) {
                        int year = tmnow->tm_year + 1900;
                        int days = year - 2001;
                        int leaps = days/4 - days/100 + days/400;
                        int lyear = ((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0));
                        int selector = ((days + leaps + 7) % 7) + lyear * 7;
                        static int years[] = {90, 91, 97, 98, 99, 94, 89,
                                              96, 80, 92, 76, 88, 72, 84};
                        int cal_year = years[selector];

                        if (!strcmp ("DATE_19XX_YY", gbuf))
                            sprintf (rbuf, "%d", cal_year);        /* 2 digit year */
                        else
                            sprintf (rbuf, "%d", cal_year + 1900); /* 4 digit year */
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_MM", gbuf)) {/* Month number (01-12) */
                        strftime (rbuf, sizeof(rbuf), "%m", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_MMM", gbuf)) {/* abbreviated Month name */
                        strftime (rbuf, sizeof(rbuf), "%b", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_MONTH", gbuf)) {/* full Month name */
                        strftime (rbuf, sizeof(rbuf), "%B", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_DD", gbuf)) {/* Day of Month (01-31) */
                        strftime (rbuf, sizeof(rbuf), "%d", tmnow);
                        ap = rbuf;
                        }
                    else if (!strcmp ("DATE_D", gbuf)) { /* ISO 8601 weekday number (1-7) */
                        sprintf (rbuf, "%d", (tmnow->tm_wday ? tmnow->tm_wday : 7));
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281

3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313

3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328

3329
3330
3331
3332
3333
3334
3335
            <=  - less than or equal
            LEQ - less than or equal
            >   - greater than
            GTR - greater than
            >=  - greater than or equal
            GEQ - greater than or equal
*/
t_stat assert_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE], gbuf2[CBUFSIZE];
const char *tptr, *gptr;
REG *rptr;
uint32 idx;
t_value val;
t_stat r;
t_bool not = FALSE;
t_bool result;
t_addr addr;
t_stat reason;

cptr = get_sim_opt (CMD_OPT_SW|CMD_OPT_DFT, cptr, &r);  /* get sw, default */

sim_stabr.boolop = sim_staba.boolop = -1;               /* no relational op dflt */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
tptr = get_glyph (cptr, gbuf, 0);                       /* get token */
if (!strcmp (gbuf, "NOT")) {                            /* Conditional Inversion? */
    not = TRUE;                                         /* remember that, and */
    cptr = (char *)tptr;
    }
if (*cptr == '"') {                                     /* quoted string comparison? */
    char op[CBUFSIZE];
    static struct {
        const char *op;
        int aval;
        int bval;
        t_bool invert;
        } *optr, compare_ops[] =
        {
            {"==",   0,  0, FALSE},
            {"EQU",  0,  0, FALSE},
            {"!=",   0,  0, TRUE},
            {"NEQ",  0,  0, TRUE},
            {"<",   -1, -1, FALSE},
            {"LSS", -1, -1, FALSE},
            {"<=",   0, -1, FALSE},
            {"LEQ",  0, -1, FALSE},
            {">",    1,  1, FALSE},
            {"GTR",  1,  1, FALSE},
            {">=",   0,  1, FALSE},
            {"GEQ",  0,  1, FALSE},
            {NULL}};

    tptr = (char *)get_glyph_gen (cptr, gbuf, '=', (sim_switches & SWMASK ('I')), TRUE, '\\');/* get first string */

    if (!*tptr)
        return SCPE_2FARG;
    cptr += strlen (gbuf);
    while (sim_isspace (*cptr))                         /* skip spaces */
        ++cptr;
    get_glyph (cptr, op, '"');
    for (optr = compare_ops; optr->op; optr++)
        if (0 == strcmp (op, optr->op))
            break;
    if (!optr->op)
        return sim_messagef (SCPE_ARG, "Invalid operator: %s\n", op);
    cptr += strlen (op);
    while (sim_isspace (*cptr))                         /* skip spaces */
        ++cptr;
    cptr = (char *)get_glyph_gen (cptr, gbuf2, 0, (sim_switches & SWMASK ('I')), TRUE, '\\');/* get second string */

    if (*cptr) {                                        /* more? */
        if (flag)                                       /* ASSERT has no more args */
            return SCPE_2MARG;
        }
    else {
        if (!flag)
            return SCPE_2FARG;                          /* IF needs actions! */







|


|




|




|
>





|
|



















|




|
>














|
>







3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
            <=  - less than or equal
            LEQ - less than or equal
            >   - greater than
            GTR - greater than
            >=  - greater than or equal
            GEQ - greater than or equal
*/
t_stat assert_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE], gbuf2[CBUFSIZE];
CONST char *tptr, *gptr;
REG *rptr;
uint32 idx;
t_value val;
t_stat r;
t_bool Not = FALSE;
t_bool result;
t_addr addr;
t_stat reason;

cptr = (CONST char *)get_sim_opt (CMD_OPT_SW|CMD_OPT_DFT, (CONST char *)cptr, &r);
                                                        /* get sw, default */
sim_stabr.boolop = sim_staba.boolop = -1;               /* no relational op dflt */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
tptr = get_glyph (cptr, gbuf, 0);                       /* get token */
if (!strcmp (gbuf, "NOT")) {                            /* Conditional Inversion? */
    Not = TRUE;                                         /* remember that, and */
    cptr = (CONST char *)tptr;
    }
if (*cptr == '"') {                                     /* quoted string comparison? */
    char op[CBUFSIZE];
    static struct {
        const char *op;
        int aval;
        int bval;
        t_bool invert;
        } *optr, compare_ops[] =
        {
            {"==",   0,  0, FALSE},
            {"EQU",  0,  0, FALSE},
            {"!=",   0,  0, TRUE},
            {"NEQ",  0,  0, TRUE},
            {"<",   -1, -1, FALSE},
            {"LSS", -1, -1, FALSE},
            {"<=",   0, -1, FALSE},
            {"LEQ",  0, -1, FALSE},
            {">",    1,  1, FALSE},
            {"GTR",  1,      1, FALSE},
            {">=",   0,  1, FALSE},
            {"GEQ",  0,  1, FALSE},
            {NULL}};

    tptr = (CONST char *)get_glyph_gen (cptr, gbuf, '=', (sim_switches & SWMASK ('I')), TRUE, '\\');
                                                    /* get first string */
    if (!*tptr)
        return SCPE_2FARG;
    cptr += strlen (gbuf);
    while (sim_isspace (*cptr))                         /* skip spaces */
        ++cptr;
    get_glyph (cptr, op, '"');
    for (optr = compare_ops; optr->op; optr++)
        if (0 == strcmp (op, optr->op))
            break;
    if (!optr->op)
        return sim_messagef (SCPE_ARG, "Invalid operator: %s\n", op);
    cptr += strlen (op);
    while (sim_isspace (*cptr))                         /* skip spaces */
        ++cptr;
    cptr = (CONST char *)get_glyph_gen (cptr, gbuf2, 0, (sim_switches & SWMASK ('I')), TRUE, '\\');
                                                        /* get second string */
    if (*cptr) {                                        /* more? */
        if (flag)                                       /* ASSERT has no more args */
            return SCPE_2MARG;
        }
    else {
        if (!flag)
            return SCPE_2FARG;                          /* IF needs actions! */
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
            }
        else idx = 0;                                   /* not array */
        if (idx >= rptr->depth)                         /* validate subscript */
            return SCPE_SUB;
        }
    else {                                              /* not reg, check for memory */
        if (sim_dfdev && sim_vm_parse_addr)             /* get addr */
            addr = sim_vm_parse_addr (sim_dfdev, (char *)gbuf, (char **)&gptr);
        else addr = (t_addr) strtotv (gbuf, &gptr, sim_dfdev->dradix);
        if (gbuf == gptr)                               /* error? */
            return SCPE_NXREG;
        }
    if (*gptr != 0)                                     /* more? must be search */
        get_glyph (gptr, gbuf, 0);
    else {







|







3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
            }
        else idx = 0;                                   /* not array */
        if (idx >= rptr->depth)                         /* validate subscript */
            return SCPE_SUB;
        }
    else {                                              /* not reg, check for memory */
        if (sim_dfdev && sim_vm_parse_addr)             /* get addr */
            addr = sim_vm_parse_addr (sim_dfdev, gbuf, &gptr);
        else addr = (t_addr) strtotv (gbuf, &gptr, sim_dfdev->dradix);
        if (gbuf == gptr)                               /* error? */
            return SCPE_NXREG;
        }
    if (*gptr != 0)                                     /* more? must be search */
        get_glyph (gptr, gbuf, 0);
    else {
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
            return SCPE_MISVAL;
        reason = get_aval (addr, sim_dfdev, sim_dfunit);/* get data */
        if (reason != SCPE_OK)                          /* return if error */
            return reason;
        result = test_search (sim_eval, &sim_staba);    /* test condition */
        }
    }
if (not ^ result) {
    if (!flag)
        sim_brk_setact (cptr);                          /* set up IF actions */
    }
else
    if (flag)
        return SCPE_AFAIL;                              /* return assert status */
return SCPE_OK;







|







3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
            return SCPE_MISVAL;
        reason = get_aval (addr, sim_dfdev, sim_dfunit);/* get data */
        if (reason != SCPE_OK)                          /* return if error */
            return reason;
        result = test_search (sim_eval, &sim_staba);    /* test condition */
        }
    }
if (Not ^ result) {
    if (!flag)
        sim_brk_setact (cptr);                          /* set up IF actions */
    }
else
    if (flag)
        return SCPE_AFAIL;                              /* return assert status */
return SCPE_OK;
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442

3443
3444
3445
3446
3447
3448
3449
        \e  Sends the ASCII Escape character (Decimal value 27)
     as well as octal character values of the form:
        \n{n{n}} where each n is an octal digit (0-7)
     and hext character values of the form:
        \xh{h} where each h is a hex digit (0-9A-Fa-f)
   */

t_stat send_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE], *tptr;

uint8 dbuf[CBUFSIZE];
uint32 dsize = 0;
uint32 delay = 0;
uint32 after = 0;
t_stat r;
SEND *snd;








|

|
>







3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
        \e  Sends the ASCII Escape character (Decimal value 27)
     as well as octal character values of the form:
        \n{n{n}} where each n is an octal digit (0-7)
     and hext character values of the form:
        \xh{h} where each h is a hex digit (0-9A-Fa-f)
   */

t_stat send_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *tptr;
uint8 dbuf[CBUFSIZE];
uint32 dsize = 0;
uint32 delay = 0;
uint32 after = 0;
t_stat r;
SEND *snd;

3491
3492
3493
3494
3495
3496
3497
3498
3499
3500

3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520

3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542

3543
3544
3545
3546
3547
3548
3549
        return sim_messagef (SCPE_ARG, "Invalid String\n");
    }
if ((dsize == 0) && (delay == 0) && (after == 0))
    return SCPE_2FARG;
return sim_send_input (snd, dbuf, dsize, after, delay);
}

t_stat sim_show_send (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char gbuf[CBUFSIZE], *tptr;

t_stat r;
SEND *snd;

tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_send (gbuf, &snd);
    if (r != SCPE_OK)
        return r;
    cptr = tptr;
    }
else
    snd = sim_cons_get_send ();
if (*cptr)
    return SCPE_2MARG;
return sim_show_send_input (st, snd);
}

t_stat expect_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE], *tptr;

t_stat r;
EXPECT *exp;

GET_SWITCHES (cptr);                                    /* get switches */
tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_expect (gbuf, &exp);
    if (r != SCPE_OK)
        return r;
    cptr = tptr;
    }
else
    exp = sim_cons_get_expect ();
if (flag)
    return sim_set_expect (exp, cptr);
else
    return sim_set_noexpect (exp, cptr);
}

t_stat sim_show_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char gbuf[CBUFSIZE], *tptr;

t_stat r;
EXPECT *exp;

tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_expect (gbuf, &exp);
    if (r != SCPE_OK)







|

|
>

















|

|
>



















|

|
>







3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
        return sim_messagef (SCPE_ARG, "Invalid String\n");
    }
if ((dsize == 0) && (delay == 0) && (after == 0))
    return SCPE_2FARG;
return sim_send_input (snd, dbuf, dsize, after, delay);
}

t_stat sim_show_send (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *tptr;
t_stat r;
SEND *snd;

tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_send (gbuf, &snd);
    if (r != SCPE_OK)
        return r;
    cptr = tptr;
    }
else
    snd = sim_cons_get_send ();
if (*cptr)
    return SCPE_2MARG;
return sim_show_send_input (st, snd);
}

t_stat expect_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *tptr;
t_stat r;
EXPECT *exp;

GET_SWITCHES (cptr);                                    /* get switches */
tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_expect (gbuf, &exp);
    if (r != SCPE_OK)
        return r;
    cptr = tptr;
    }
else
    exp = sim_cons_get_expect ();
if (flag)
    return sim_set_expect (exp, cptr);
else
    return sim_set_noexpect (exp, cptr);
}

t_stat sim_show_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *tptr;
t_stat r;
EXPECT *exp;

tptr = get_glyph (cptr, gbuf, ',');
if (sim_isalpha(gbuf[0]) && (strchr (gbuf, ':'))) {
    r = tmxr_locate_line_expect (gbuf, &exp);
    if (r != SCPE_OK)
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570

3571
3572
3573
3574
3575
3576
3577
    return SCPE_ARG;            /* String must be quote delimited */
return sim_exp_show (st, exp, gbuf);
}


/* Goto command */

t_stat goto_cmd (int32 flag, char *fcptr)
{
char *cptr, cbuf[CBUFSIZE], gbuf[CBUFSIZE], gbuf1[CBUFSIZE];

long fpos;
int32 saved_do_echo = sim_do_echo;
int32 saved_goto_line = sim_goto_line[sim_do_depth];

if (NULL == sim_gotofile) return SCPE_UNK;              /* only valid inside of do_cmd */
get_glyph (fcptr, gbuf1, 0);
if ('\0' == gbuf1[0]) return SCPE_ARG;                  /* unspecified goto target */







|

|
>







3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
    return SCPE_ARG;            /* String must be quote delimited */
return sim_exp_show (st, exp, gbuf);
}


/* Goto command */

t_stat goto_cmd (int32 flag, CONST char *fcptr)
{
char cbuf[CBUFSIZE], gbuf[CBUFSIZE], gbuf1[CBUFSIZE];
const char *cptr;
long fpos;
int32 saved_do_echo = sim_do_echo;
int32 saved_goto_line = sim_goto_line[sim_do_depth];

if (NULL == sim_gotofile) return SCPE_UNK;              /* only valid inside of do_cmd */
get_glyph (fcptr, gbuf1, 0);
if ('\0' == gbuf1[0]) return SCPE_ARG;                  /* unspecified goto target */
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636

3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655

/* Return command */
/* The return command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a return has been issued from */
/* interactive input */

t_stat return_cmd (int32 flag, char *fcptr)
{
return SCPE_UNK;                                        /* only valid inside of do_cmd */
}

/* Shift command */
/* The shift command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a shift has been issued from */
/* interactive input (it is not valid interactively since it would have to */
/* mess with the program's argv which is owned by the C runtime library */

t_stat shift_cmd (int32 flag, char *fcptr)
{
return SCPE_UNK;                                        /* only valid inside of do_cmd */
}

/* Call command */
/* The call command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a call has been issued from */
/* interactive input */

t_stat call_cmd (int32 flag, char *fcptr)
{
char *cptr, cbuf[CBUFSIZE], gbuf[CBUFSIZE];


if (NULL == sim_gotofile) return SCPE_UNK;              /* only valid inside of do_cmd */
cptr = get_glyph (fcptr, gbuf, 0);
if ('\0' == gbuf[0]) return SCPE_ARG;                   /* unspecified goto target */
sprintf(cbuf, "%s %s", sim_do_filename[sim_do_depth], cptr);
sim_switches |= SWMASK ('O');                           /* inherit ON state and actions */
return do_cmd_label (flag, cbuf, gbuf);
}

/* On command */

t_stat on_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
t_stat cond;

cptr = get_glyph (cptr, gbuf, 0);
if ('\0' == gbuf[0]) return SCPE_ARG;                   /* unspecified condition */
if (0 == strcmp("ERROR", gbuf))







|











|










|

|
>











|







3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862

/* Return command */
/* The return command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a return has been issued from */
/* interactive input */

t_stat return_cmd (int32 flag, CONST char *fcptr)
{
return SCPE_UNK;                                        /* only valid inside of do_cmd */
}

/* Shift command */
/* The shift command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a shift has been issued from */
/* interactive input (it is not valid interactively since it would have to */
/* mess with the program's argv which is owned by the C runtime library */

t_stat shift_cmd (int32 flag, CONST char *fcptr)
{
return SCPE_UNK;                                        /* only valid inside of do_cmd */
}

/* Call command */
/* The call command is invalid unless encountered in a do_cmd context, */
/* and in that context, it is handled as a special case inside of do_cmd() */
/* and not dispatched here, so if we get here a call has been issued from */
/* interactive input */

t_stat call_cmd (int32 flag, CONST char *fcptr)
{
char cbuf[CBUFSIZE], gbuf[CBUFSIZE];
const char *cptr;

if (NULL == sim_gotofile) return SCPE_UNK;              /* only valid inside of do_cmd */
cptr = get_glyph (fcptr, gbuf, 0);
if ('\0' == gbuf[0]) return SCPE_ARG;                   /* unspecified goto target */
sprintf(cbuf, "%s %s", sim_do_filename[sim_do_depth], cptr);
sim_switches |= SWMASK ('O');                           /* inherit ON state and actions */
return do_cmd_label (flag, cbuf, gbuf);
}

/* On command */

t_stat on_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
t_stat cond;

cptr = get_glyph (cptr, gbuf, 0);
if ('\0' == gbuf[0]) return SCPE_ARG;                   /* unspecified condition */
if (0 == strcmp("ERROR", gbuf))
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
    }
return SCPE_OK;
}

/* noop command */
/* The noop command (IGNORE, PROCEED) does nothing */

t_stat noop_cmd (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
return SCPE_OK;                                         /* we're happy doing nothing */
}

/* Set on/noon routine */

t_stat set_on (int32 flag, char *cptr)
{
if ((flag) && (cptr) && (*cptr)) {                      /* Set ON with arg */
    char gbuf[CBUFSIZE];

    cptr = get_glyph (cptr, gbuf, 0);                   /* get command glyph */
    if (((MATCH_CMD(gbuf,"INHERIT")) &&
         (MATCH_CMD(gbuf,"NOINHERIT"))) ||







|








|







3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
    }
return SCPE_OK;
}

/* noop command */
/* The noop command (IGNORE, PROCEED) does nothing */

t_stat noop_cmd (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
return SCPE_OK;                                         /* we're happy doing nothing */
}

/* Set on/noon routine */

t_stat set_on (int32 flag, CONST char *cptr)
{
if ((flag) && (cptr) && (*cptr)) {                      /* Set ON with arg */
    char gbuf[CBUFSIZE];

    cptr = get_glyph (cptr, gbuf, 0);                   /* get command glyph */
    if (((MATCH_CMD(gbuf,"INHERIT")) &&
         (MATCH_CMD(gbuf,"NOINHERIT"))) ||
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
    strcpy(sim_on_actions[sim_do_depth][SCPE_AFAIL], "RETURN");
    }
return SCPE_OK;
}

/* Set verify/noverify routine */

t_stat set_verify (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_do_echo)                                /* already set correctly? */
    return SCPE_OK;
sim_do_echo = flag;
return SCPE_OK;
}

/* Set message/nomessage routine */

t_stat set_message (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_show_message)                           /* already set correctly? */
    return SCPE_OK;
sim_show_message = flag;
return SCPE_OK;
}

/* Set quiet/noquiet routine */

t_stat set_quiet (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_quiet)                                  /* already set correctly? */
    return SCPE_OK;
sim_quiet = flag;
return SCPE_OK;
}

/* Set asynch/noasynch routine */

t_stat sim_set_asynch (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
#ifdef SIM_ASYNCH_IO
if (flag == sim_asynch_enabled)                         /* already set correctly? */
    return SCPE_OK;
sim_asynch_enabled = flag;







|











|











|











|







3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
    strcpy(sim_on_actions[sim_do_depth][SCPE_AFAIL], "RETURN");
    }
return SCPE_OK;
}

/* Set verify/noverify routine */

t_stat set_verify (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_do_echo)                                /* already set correctly? */
    return SCPE_OK;
sim_do_echo = flag;
return SCPE_OK;
}

/* Set message/nomessage routine */

t_stat set_message (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_show_message)                           /* already set correctly? */
    return SCPE_OK;
sim_show_message = flag;
return SCPE_OK;
}

/* Set quiet/noquiet routine */

t_stat set_quiet (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (flag == sim_quiet)                                  /* already set correctly? */
    return SCPE_OK;
sim_quiet = flag;
return SCPE_OK;
}

/* Set asynch/noasynch routine */

t_stat sim_set_asynch (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
#ifdef SIM_ASYNCH_IO
if (flag == sim_asynch_enabled)                         /* already set correctly? */
    return SCPE_OK;
sim_asynch_enabled = flag;
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833

3834
3835
3836
3837
3838
3839
3840
    fprintf (sim_log, "Asynchronous I/O is not available in this simulator\n");
return SCPE_NOFNC;
#endif
}

/* Show asynch routine */

t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
#ifdef SIM_ASYNCH_IO
fprintf (st, "Asynchronous I/O is %sabled, %s\n", (sim_asynch_enabled) ? "en" : "dis", AIO_QUEUE_MODE);
#if defined(SIM_ASYNCH_MUX)
fprintf (st, "Asynchronous Multiplexer support is available\n");
#endif
#if defined(SIM_ASYNCH_CLOCKS)
fprintf (st, "Asynchronous Clock is %sabled\n", (sim_asynch_timer) ? "en" : "dis");
#endif
#else
fprintf (st, "Asynchronous I/O is not available in this simulator\n");
#endif
return SCPE_OK;
}

/* Set environment routine */

t_stat sim_set_environment (int32 flag, char *cptr)
{
char varname[CBUFSIZE];

if ((!cptr) || (*cptr == 0))                            /* now eol? */
    return SCPE_2FARG;
cptr = get_glyph (cptr, varname, '=');                  /* get environment variable name */
setenv(varname, cptr, 1);
return SCPE_OK;
}

/* Set command */

t_stat set_cmd (int32 flag, char *cptr)
{
uint32 lvl = 0;
t_stat r;
char gbuf[CBUFSIZE], *cvptr, *svptr;

DEVICE *dptr;
UNIT *uptr;
MTAB *mptr;
CTAB *gcmdp;
C1TAB *ctbr = NULL, *glbr;

GET_SWITCHES (cptr);                                    /* get switches */







|



















|












|



|
>







3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
    fprintf (sim_log, "Asynchronous I/O is not available in this simulator\n");
return SCPE_NOFNC;
#endif
}

/* Show asynch routine */

t_stat sim_show_asynch (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
#ifdef SIM_ASYNCH_IO
fprintf (st, "Asynchronous I/O is %sabled, %s\n", (sim_asynch_enabled) ? "en" : "dis", AIO_QUEUE_MODE);
#if defined(SIM_ASYNCH_MUX)
fprintf (st, "Asynchronous Multiplexer support is available\n");
#endif
#if defined(SIM_ASYNCH_CLOCKS)
fprintf (st, "Asynchronous Clock is %sabled\n", (sim_asynch_timer) ? "en" : "dis");
#endif
#else
fprintf (st, "Asynchronous I/O is not available in this simulator\n");
#endif
return SCPE_OK;
}

/* Set environment routine */

t_stat sim_set_environment (int32 flag, CONST char *cptr)
{
char varname[CBUFSIZE];

if ((!cptr) || (*cptr == 0))                            /* now eol? */
    return SCPE_2FARG;
cptr = get_glyph (cptr, varname, '=');                  /* get environment variable name */
setenv(varname, cptr, 1);
return SCPE_OK;
}

/* Set command */

t_stat set_cmd (int32 flag, CONST char *cptr)
{
uint32 lvl = 0;
t_stat r;
char gbuf[CBUFSIZE], *cvptr;
CONST char *svptr;
DEVICE *dptr;
UNIT *uptr;
MTAB *mptr;
CTAB *gcmdp;
C1TAB *ctbr = NULL, *glbr;

GET_SWITCHES (cptr);                                    /* get switches */
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
                        }
                    r = mptr->valid (uptr, mptr->match, cvptr, mptr->desc);
                    if (r != SCPE_OK)
                        return r;
                    }
                else if (!mptr->desc)                   /* value desc? */
                    break;
//                else if (mptr->mask & MTAB_VAL) {       /* take a value? */
//                    if (!cvptr) return SCPE_MISVAL;     /* none? error */
//                    r = dep_reg (0, cvptr, (REG *) mptr->desc, 0);
//                    if (r != SCPE_OK) return r;
//                    }
                else if (cvptr)                         /* = value? */
                    return SCPE_ARG;
                else *((int32 *) mptr->desc) = mptr->match;
                }                                       /* end if xtd */







|
|







4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
                        }
                    r = mptr->valid (uptr, mptr->match, cvptr, mptr->desc);
                    if (r != SCPE_OK)
                        return r;
                    }
                else if (!mptr->desc)                   /* value desc? */
                    break;
//                else if (mptr->mask & MTAB_VAL) {     /* take a value? */
//                    if (!cvptr) return SCPE_MISVAL;   /* none? error */
//                    r = dep_reg (0, cvptr, (REG *) mptr->desc, 0);
//                    if (r != SCPE_OK) return r;
//                    }
                else if (cvptr)                         /* = value? */
                    return SCPE_ARG;
                else *((int32 *) mptr->desc) = mptr->match;
                }                                       /* end if xtd */
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
        return tab;
    }
return NULL;
}

/* Set device data radix routine */

t_stat set_dev_radix (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (cptr)
    return SCPE_ARG;
dptr->dradix = flag & 037;
return SCPE_OK;
}

/* Set device enabled/disabled routine */

t_stat set_dev_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
UNIT *up;
uint32 i;

if (cptr)
    return SCPE_ARG;
if ((dptr->flags & DEV_DISABLE) == 0)                   /* allowed? */







|









|







4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
        return tab;
    }
return NULL;
}

/* Set device data radix routine */

t_stat set_dev_radix (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (cptr)
    return SCPE_ARG;
dptr->dradix = flag & 037;
return SCPE_OK;
}

/* Set device enabled/disabled routine */

t_stat set_dev_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
UNIT *up;
uint32 i;

if (cptr)
    return SCPE_ARG;
if ((dptr->flags & DEV_DISABLE) == 0)                   /* allowed? */
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
if (dptr->reset)                                        /* reset device */
    return dptr->reset (dptr);
else return SCPE_OK;
}

/* Set unit enabled/disabled routine */

t_stat set_unit_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (cptr)
    return SCPE_ARG;
if (!(uptr->flags & UNIT_DISABLE))                      /* allowed? */
    return SCPE_NOFNC;
if (flag)                                               /* enb? enable */
    uptr->flags = uptr->flags & ~UNIT_DIS;
else {
    if ((uptr->flags & UNIT_ATT) ||                     /* dsb */
        sim_is_active (uptr))                           /* more tests */
        return SCPE_NOFNC;
    uptr->flags = uptr->flags | UNIT_DIS;               /* disable */
    }
return SCPE_OK;
}

/* Set device debug enabled/disabled routine */

t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEBTAB *dep;

if ((dptr->flags & DEV_DEBUG) == 0)
    return SCPE_NOFNC;
if (cptr == NULL) {                                     /* no arguments? */







|


















|







4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
if (dptr->reset)                                        /* reset device */
    return dptr->reset (dptr);
else return SCPE_OK;
}

/* Set unit enabled/disabled routine */

t_stat set_unit_enbdis (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (cptr)
    return SCPE_ARG;
if (!(uptr->flags & UNIT_DISABLE))                      /* allowed? */
    return SCPE_NOFNC;
if (flag)                                               /* enb? enable */
    uptr->flags = uptr->flags & ~UNIT_DIS;
else {
    if ((uptr->flags & UNIT_ATT) ||                     /* dsb */
        sim_is_active (uptr))                           /* more tests */
        return SCPE_NOFNC;
    uptr->flags = uptr->flags | UNIT_DIS;               /* disable */
    }
return SCPE_OK;
}

/* Set device debug enabled/disabled routine */

t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
DEBTAB *dep;

if ((dptr->flags & DEV_DEBUG) == 0)
    return SCPE_NOFNC;
if (cptr == NULL) {                                     /* no arguments? */
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078

4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098

4099
4100
4101
4102
4103
4104
4105
        return SCPE_ARG;
    }                                                   /* end while */
return SCPE_OK;
}

/* Show command */

t_stat show_cmd (int32 flag, char *cptr)
{
t_stat r;

cptr = get_sim_opt (CMD_OPT_SW|CMD_OPT_OF, cptr, &r);   /* get sw, ofile */

if (!cptr)                                              /* error? */
    return r;
if (sim_ofile) {                                        /* output file? */
    r = show_cmd_fi (sim_ofile, flag, cptr);            /* do show */
    fclose (sim_ofile);
    }
else {
    r = show_cmd_fi (stdout, flag, cptr);               /* no, stdout, log */
    if (sim_log && (sim_log != stdout))
        show_cmd_fi (sim_log, flag, cptr);
    if (sim_deb && (sim_deb != stdout) && (sim_deb != sim_log))
        show_cmd_fi (sim_deb, flag, cptr);
    }
return r;
}

t_stat show_cmd_fi (FILE *ofile, int32 flag, char *cptr)
{
uint32 lvl = 0xFFFFFFFF;
char gbuf[CBUFSIZE], *cvptr, *svptr;

DEVICE *dptr;
UNIT *uptr;
MTAB *mptr;
SHTAB *shtb = NULL, *shptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */







|



|
>
















|


|
>







4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
        return SCPE_ARG;
    }                                                   /* end while */
return SCPE_OK;
}

/* Show command */

t_stat show_cmd (int32 flag, CONST char *cptr)
{
t_stat r;

cptr = get_sim_opt (CMD_OPT_SW|CMD_OPT_OF, cptr, &r);
                                                        /* get sw, ofile */
if (!cptr)                                              /* error? */
    return r;
if (sim_ofile) {                                        /* output file? */
    r = show_cmd_fi (sim_ofile, flag, cptr);            /* do show */
    fclose (sim_ofile);
    }
else {
    r = show_cmd_fi (stdout, flag, cptr);               /* no, stdout, log */
    if (sim_log && (sim_log != stdout))
        show_cmd_fi (sim_log, flag, cptr);
    if (sim_deb && (sim_deb != stdout) && (sim_deb != sim_log))
        show_cmd_fi (sim_deb, flag, cptr);
    }
return r;
}

t_stat show_cmd_fi (FILE *ofile, int32 flag, CONST char *cptr)
{
uint32 lvl = 0xFFFFFFFF;
char gbuf[CBUFSIZE], *cvptr;
CONST char *svptr;
DEVICE *dptr;
UNIT *uptr;
MTAB *mptr;
SHTAB *shtb = NULL, *shptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
4213
4214
4215
4216
4217
4218
4219




4220
4221
4222
4223
4224
4225
4226
UNIT *uptr;
int32 toks = 0;

fprintf (st, "%s", sim_dname (dptr));                   /* print dev name */
if ((flag == 2) && dptr->description) {
    fprintf (st, "\t%s\n", dptr->description(dptr));
    }




if (qdisable (dptr)) {                                  /* disabled? */
    fprintf (st, "\tdisabled\n");
    return SCPE_OK;
    }
for (j = ucnt = udbl = 0; j < dptr->numunits; j++) {    /* count units */
    uptr = dptr->units + j;
    if (!(uptr->flags & UNIT_DIS))                      /* count enabled units */







>
>
>
>







4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
UNIT *uptr;
int32 toks = 0;

fprintf (st, "%s", sim_dname (dptr));                   /* print dev name */
if ((flag == 2) && dptr->description) {
    fprintf (st, "\t%s\n", dptr->description(dptr));
    }
else {
    if ((sim_switches & SWMASK ('D')) && dptr->description)
        fprintf (st, "\t%s\n", dptr->description(dptr));
    }
if (qdisable (dptr)) {                                  /* disabled? */
    fprintf (st, "\tdisabled\n");
    return SCPE_OK;
    }
for (j = ucnt = udbl = 0; j < dptr->numunits; j++) {    /* count units */
    uptr = dptr->units + j;
    if (!(uptr->flags & UNIT_DIS))                      /* count enabled units */
4290
4291
4292
4293
4294
4295
4296
4297
4298

4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312

4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328





4329
4330
4331
4332
4333
4334
4335



4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346

4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
    }
show_all_mods (st, dptr, uptr, MTAB_VUN, &toks);        /* show unit mods */
if (toks || (flag < 0) || (flag > 1))
    fprintf (st, "\n");
return SCPE_OK;
}

void fprint_capac (FILE *st, DEVICE *dptr, UNIT *uptr)
{

t_addr kval = (uptr->flags & UNIT_BINK)? 1024: 1000;
t_addr mval;
t_addr psize = uptr->capac;
char scale, width;

if (sim_switches & SWMASK ('B'))
    kval = 1024;
mval = kval * kval;
if (dptr->flags & DEV_SECTORS) {
    kval = kval / 512;
    mval = mval / 512;
    }
if ((dptr->dwidth / dptr->aincr) > 8)
    width = 'W';

else width = 'B';
if (uptr->capac < (kval * 10))
    scale = 0;
else if (uptr->capac < (mval * 10)) {
    scale = 'K';
    psize = psize / kval;
    }
else {
    scale = 'M';
    psize = psize / mval;
    }
fprint_val (st, (t_value) psize, 10, T_ADDR_W, PV_LEFT);
if (scale)
    fputc (scale, st);
fputc (width, st);
return;





}

/* Show <global name> processors  */

t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
int32 vmaj = SIM_MAJOR, vmin = SIM_MINOR, vpat = SIM_PATCH, vdelt = SIM_DELTA;




if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "%s simulator V%d.%d-%d", sim_name, vmaj, vmin, vpat);
if (vdelt)
    fprintf (st, " delta %d", vdelt);
#if defined (SIM_VERSION_MODE)
fprintf (st, " %s", SIM_VERSION_MODE);
#endif
if (flag) {
    uint32 idle_capable, os_tick_size;


    fprintf (st, "\n\tSimulator Framework Capabilities:");
    fprintf (st, "\n\t\t%s", sim_si64);
    fprintf (st, "\n\t\t%s", sim_sa64);
    fprintf (st, "\n\t\t%s", eth_capabilities());
    idle_capable = sim_timer_idle_capable (&os_tick_size);
    fprintf (st, "\n\t\tIdle/Throttling support is %savailable", ((idle_capable == 0) ? "NOT " : ""));
    if (sim_disk_vhd_support())
        fprintf (st, "\n\t\tVirtual Hard Disk (VHD) support");
    if (sim_disk_raw_support())
        fprintf (st, "\n\t\tRAW disk and CD/DVD ROM support");
#if defined (SIM_ASYNCH_IO)
    fprintf (st, "\n\t\tAsynchronous I/O support");
#endif







|

>



|









|
>
|

|

|



|


|
<
<
|
|
>
>
>
>
>




|


>
>
>










|
>





|
|







4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540


4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
    }
show_all_mods (st, dptr, uptr, MTAB_VUN, &toks);        /* show unit mods */
if (toks || (flag < 0) || (flag > 1))
    fprintf (st, "\n");
return SCPE_OK;
}

const char *sprint_capac (DEVICE *dptr, UNIT *uptr)
{
static char capac_buf[((CHAR_BIT * sizeof (t_value) * 4 + 3)/3) + 8];
t_addr kval = (uptr->flags & UNIT_BINK)? 1024: 1000;
t_addr mval;
t_addr psize = uptr->capac;
const char *scale, *width;

if (sim_switches & SWMASK ('B'))
    kval = 1024;
mval = kval * kval;
if (dptr->flags & DEV_SECTORS) {
    kval = kval / 512;
    mval = mval / 512;
    }
if ((dptr->dwidth / dptr->aincr) > 8)
    width = "W";
else
    width = "B";
if (uptr->capac < (kval * 10))
    scale = "";
else if (uptr->capac < (mval * 10)) {
    scale = "K";
    psize = psize / kval;
    }
else {
    scale = "M";
    psize = psize / mval;
    }
sprint_val (capac_buf, (t_value) psize, 10, T_ADDR_W, PV_LEFT);


sprintf (&capac_buf[strlen (capac_buf)], "%s%s", scale, width);
return capac_buf;
}

void fprint_capac (FILE *st, DEVICE *dptr, UNIT *uptr)
{
fprintf (st, "%s", sprint_capac (dptr, uptr));
}

/* Show <global name> processors  */

t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 vmaj = SIM_MAJOR, vmin = SIM_MINOR, vpat = SIM_PATCH, vdelt = SIM_DELTA;
const char *cpp = "";
const char *build = "";
const char *arch = "";

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "%s simulator V%d.%d-%d", sim_name, vmaj, vmin, vpat);
if (vdelt)
    fprintf (st, " delta %d", vdelt);
#if defined (SIM_VERSION_MODE)
fprintf (st, " %s", SIM_VERSION_MODE);
#endif
if (flag) {
    t_bool idle_capable;
    uint32 os_ms_sleep_1, os_tick_size;

    fprintf (st, "\n\tSimulator Framework Capabilities:");
    fprintf (st, "\n\t\t%s", sim_si64);
    fprintf (st, "\n\t\t%s", sim_sa64);
    fprintf (st, "\n\t\t%s", eth_capabilities());
    idle_capable = sim_timer_idle_capable (&os_ms_sleep_1, &os_tick_size);
    fprintf (st, "\n\t\tIdle/Throttling support is %savailable", idle_capable ? "" : "NOT ");
    if (sim_disk_vhd_support())
        fprintf (st, "\n\t\tVirtual Hard Disk (VHD) support");
    if (sim_disk_raw_support())
        fprintf (st, "\n\t\tRAW disk and CD/DVD ROM support");
#if defined (SIM_ASYNCH_IO)
    fprintf (st, "\n\t\tAsynchronous I/O support");
#endif
4370
4371
4372
4373
4374
4375
4376





4377
4378
4379
4380
4381
4382
4383
4384
4385


















4386





4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402

4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415



















4416
4417
4418
4419



4420













4421
4422
4423

4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455






4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491


4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508

4509


4510
4511
4512
4513
4514
4515
4516
    fprintf (st, "\n\tHost Platform:");
#if defined (__GNUC__) && defined (__VERSION__)
    fprintf (st, "\n\t\tCompiler: GCC %s", __VERSION__);
#elif defined (__clang_version__)
    fprintf (st, "\n\t\tCompiler: clang %s", __clang_version__);
#elif defined (_MSC_FULL_VER) && defined (_MSC_BUILD)
    fprintf (st, "\n\t\tCompiler: Microsoft Visual C++ %d.%02d.%05d.%02d", _MSC_FULL_VER/10000000, (_MSC_FULL_VER/100000)%100, _MSC_FULL_VER%100000, _MSC_BUILD);





#elif defined (__DECC_VER)
    fprintf (st, "\n\t\tCompiler: DEC C %c%d.%d-%03d", ("T SV")[((__DECC_VER/10000)%10)-6], __DECC_VER/10000000, (__DECC_VER/100000)%100, __DECC_VER%10000);
#elif defined (SIM_COMPILER)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
    fprintf (st, "\n\t\tCompiler: %s", S_xstr(SIM_COMPILER));
#undef S_str
#undef S_xstr
#endif


















#if defined (__DATE__) && defined (__TIME__)





    fprintf (st, "\n\t\tSimulator Compiled: %s at %s", __DATE__, __TIME__);
#endif
    fprintf (st, "\n\t\tMemory Access: %s Endian", sim_end ? "Little" : "Big");
    fprintf (st, "\n\t\tMemory Pointer Size: %d bits", (int)sizeof(dptr)*8);
    fprintf (st, "\n\t\t%s", sim_toffset_64 ? "Large File (>2GB) support" : "No Large File support");
#if defined (USE_SIM_VIDEO)
    fprintf (st, "\n\t\tSDL Video support: %s", vid_version());
#endif
#if defined (HAVE_PCREPOSIX_H)
    fprintf (st, "\n\t\tPCRE RegEx support for EXPECT commands");
#elif defined (HAVE_REGEX_H)
    fprintf (st, "\n\t\tRegEx support for EXPECT commands");
#else
    fprintf (st, "\n\t\tNo RegEx support for EXPECT commands");
#endif
    fprintf (st, "\n\t\tOS clock tick size (time taken by msleep(1)): %dms", os_tick_size);

#if defined(__VMS)
    if (1) {
        char *arch =
#if defined(__ia64)
            "I64";
#elif defined(__ALPHA)
            "Alpha";
#else
            "VAX";
#endif
        fprintf (st, "\n\t\tOS: OpenVMS %s %s", arch, __VMS_VERSION);
        }
#elif defined(_WIN32)



















    fprintf (st, "\n\t\tOS: Windows: ");
    fflush (st);
    system ("ver");
    system ("echo \t\t%PROCESSOR_IDENTIFIER% - %PROCESSOR_ARCHITECTURE%-%PROCESSOR_ARCHITEW6432%");



#else













    fprintf (st, "\n\t\tOS: ");
    fflush (st);
    system ("uname -a");

#endif
    }
#if defined(SIM_GIT_COMMIT_ID)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
fprintf (st, "%sgit commit id: %8.8s", flag ? "\n        " : "        ", S_xstr(SIM_GIT_COMMIT_ID));
#undef S_str
#undef S_xstr
#endif
#if defined(SIM_BUILD)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
fprintf (st, "%sBuild: %s", flag ? "\n        " : "        ", S_xstr(SIM_BUILD));
#undef S_str
#undef S_xstr
#endif
fprintf (st, "\n");
return SCPE_OK;
}

t_stat show_config (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
int32 i;
DEVICE *dptr;
t_bool only_enabled = (sim_switches & SWMASK ('E'));

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "%s simulator configuration%s\n\n", sim_name, only_enabled ? " (enabled devices)" : "");
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    if (!only_enabled || !qdisable (dptr))
        show_device (st, dptr, flag);






return SCPE_OK;
}

t_stat show_log_names (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_logicals (st, dptr, NULL, 1, cptr);
return SCPE_OK;
}

t_stat show_dev_logicals (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (dptr->lname)
    fprintf (st, "%s -> %s\n", dptr->lname, dptr->name);
else if (!flag)
    fputs ("no logical name assigned\n", st);
return SCPE_OK;
}

t_stat show_queue (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
DEVICE *dptr;
UNIT *uptr;
int32 accum;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %.0f instructios/sec\n",
             sim_name, sim_time, sim_timer_inst_per_sec ());
else {


    fprintf (st, "%s event queue status, time = %.0f, executing %.0f instructions/sec\n",
             sim_name, sim_time, sim_timer_inst_per_sec ());
    accum = 0;
    for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = uptr->next) {
        if (uptr == &sim_step_unit)
            fprintf (st, "  Step timer");
        else
            if (uptr == &sim_expect_unit)
                fprintf (st, "  Expect fired");
            else
                if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                    fprintf (st, "  %s", sim_dname (dptr));
                    if (dptr->numunits > 1)
                        fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                    }
                else
                    fprintf (st, "  Unknown");

        fprintf (st, " at %d\n", accum + uptr->time);


        accum = accum + uptr->time;
        }
    }
sim_show_clock_queues (st, dnotused, unotused, flag, cptr);
#if defined (SIM_ASYNCH_IO)
pthread_mutex_lock (&sim_asynch_lock);
fprintf (st, "asynchronous pending event queue\n");







>
>
>
>
>









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
|














|
>













>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
<
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
>




















|











>
>
>
>
>
>



|











|








|











>
>

















>
|
>
>







4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687



4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705


4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
    fprintf (st, "\n\tHost Platform:");
#if defined (__GNUC__) && defined (__VERSION__)
    fprintf (st, "\n\t\tCompiler: GCC %s", __VERSION__);
#elif defined (__clang_version__)
    fprintf (st, "\n\t\tCompiler: clang %s", __clang_version__);
#elif defined (_MSC_FULL_VER) && defined (_MSC_BUILD)
    fprintf (st, "\n\t\tCompiler: Microsoft Visual C++ %d.%02d.%05d.%02d", _MSC_FULL_VER/10000000, (_MSC_FULL_VER/100000)%100, _MSC_FULL_VER%100000, _MSC_BUILD);
#if defined(_DEBUG)
    build = " (Debug Build)";
#else
    build = " (Release Build)";
#endif
#elif defined (__DECC_VER)
    fprintf (st, "\n\t\tCompiler: DEC C %c%d.%d-%03d", ("T SV")[((__DECC_VER/10000)%10)-6], __DECC_VER/10000000, (__DECC_VER/100000)%100, __DECC_VER%10000);
#elif defined (SIM_COMPILER)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
    fprintf (st, "\n\t\tCompiler: %s", S_xstr(SIM_COMPILER));
#undef S_str
#undef S_xstr
#endif
#if defined(__GNUC__)
#if defined(__OPTIMIZE__)
    build = " (Release Build)";
#else
    build = " (Debug Build)";
#endif
#endif
#if defined(_M_X64) || defined(_M_AMD64) || defined(__amd64__) || defined(__x86_64__)
    arch = " arch: x64";
#elif defined(_M_IX86) || defined(__i386)
    arch = " arch: x86";
#elif defined(_M_ARM64) || defined(__aarch64_)
    arch = " arch: ARM64";
#elif defined(_M_ARM) || defined(__arm__)
    arch = " arch: ARM";
#elif defined(__ia64__) || defined(_M_IA64) || defined(__itanium__)
    arch = " arch: IA-64";
#endif
#if defined (__DATE__) && defined (__TIME__)
#ifdef  __cplusplus
    cpp = "C++";
#else
    cpp = "C";
#endif
    fprintf (st, "\n\t\tSimulator Compiled as %s%s%s on %s at %s", cpp, arch, build, __DATE__, __TIME__);
#endif
    fprintf (st, "\n\t\tMemory Access: %s Endian", sim_end ? "Little" : "Big");
    fprintf (st, "\n\t\tMemory Pointer Size: %d bits", (int)sizeof(dptr)*8);
    fprintf (st, "\n\t\t%s", sim_toffset_64 ? "Large File (>2GB) support" : "No Large File support");
#if defined (USE_SIM_VIDEO)
    fprintf (st, "\n\t\tSDL Video support: %s", vid_version());
#endif
#if defined (HAVE_PCREPOSIX_H)
    fprintf (st, "\n\t\tPCRE RegEx support for EXPECT commands");
#elif defined (HAVE_REGEX_H)
    fprintf (st, "\n\t\tRegEx support for EXPECT commands");
#else
    fprintf (st, "\n\t\tNo RegEx support for EXPECT commands");
#endif
    fprintf (st, "\n\t\tOS clock resolution: %dms", os_tick_size);
    fprintf (st, "\n\t\tTime taken by msleep(1): %dms", os_ms_sleep_1);
#if defined(__VMS)
    if (1) {
        char *arch =
#if defined(__ia64)
            "I64";
#elif defined(__ALPHA)
            "Alpha";
#else
            "VAX";
#endif
        fprintf (st, "\n\t\tOS: OpenVMS %s %s", arch, __VMS_VERSION);
        }
#elif defined(_WIN32)
    if (1) {
        char *proc_id = getenv ("PROCESSOR_IDENTIFIER");
        char *arch = getenv ("PROCESSOR_ARCHITECTURE");
        char *procs = getenv ("NUMBER_OF_PROCESSORS");
        char *proc_level = getenv ("PROCESSOR_LEVEL");
        char *proc_rev = getenv ("PROCESSOR_REVISION");
        char *proc_arch3264 = getenv ("PROCESSOR_ARCHITEW6432");
        char osversion[PATH_MAX+1] = "";
        FILE *f;

        if ((f = _popen ("ver", "r"))) {
            memset (osversion, 0, sizeof(osversion));
            do {
                if (NULL == fgets (osversion, sizeof(osversion)-1, f))
                    break;
                sim_trim_endspc (osversion);
                } while (osversion[0] == '\0');
            _pclose (f);
            }
        fprintf (st, "\n\t\tOS: %s", osversion);



        fprintf (st, "\n\t\tArchitecture: %s%s%s, Processors: %s", arch, proc_arch3264 ? " on " : "", proc_arch3264 ? proc_arch3264  : "", procs);
        fprintf (st, "\n\t\tProcessor Id: %s, Level: %s, Revision: %s", proc_id ? proc_id : "", proc_level ? proc_level : "", proc_rev ? proc_rev : "");
        }
#else
    if (1) {
        char osversion[2*PATH_MAX+1] = "";
        FILE *f;

        if ((f = popen ("uname -a", "r"))) {
            memset (osversion, 0, sizeof(osversion));
            do {
                if (NULL == fgets (osversion, sizeof(osversion)-1, f))
                    break;
                sim_trim_endspc (osversion);
                } while (osversion[0] == '\0');
            pclose (f);
            }
        fprintf (st, "\n\t\tOS: %s", osversion);


        }
#endif
    }
#if defined(SIM_GIT_COMMIT_ID)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
fprintf (st, "%sgit commit id: %8.8s", flag ? "\n        " : "        ", S_xstr(SIM_GIT_COMMIT_ID));
#undef S_str
#undef S_xstr
#endif
#if defined(SIM_BUILD)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
fprintf (st, "%sBuild: %s", flag ? "\n        " : "        ", S_xstr(SIM_BUILD));
#undef S_str
#undef S_xstr
#endif
fprintf (st, "\n");
return SCPE_OK;
}

t_stat show_config (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
int32 i;
DEVICE *dptr;
t_bool only_enabled = (sim_switches & SWMASK ('E'));

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "%s simulator configuration%s\n\n", sim_name, only_enabled ? " (enabled devices)" : "");
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    if (!only_enabled || !qdisable (dptr))
        show_device (st, dptr, flag);
if (sim_switches & SWMASK ('I')) {
    fprintf (st, "\nInternal Devices%s\n\n", only_enabled ? " (enabled devices)" : "");
    for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i)
        if (!only_enabled || !qdisable (dptr))
            show_device (st, dptr, flag);
    }
return SCPE_OK;
}

t_stat show_log_names (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_logicals (st, dptr, NULL, 1, cptr);
return SCPE_OK;
}

t_stat show_dev_logicals (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (dptr->lname)
    fprintf (st, "%s -> %s\n", dptr->lname, dptr->name);
else if (!flag)
    fputs ("no logical name assigned\n", st);
return SCPE_OK;
}

t_stat show_queue (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
DEVICE *dptr;
UNIT *uptr;
int32 accum;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %.0f instructios/sec\n",
             sim_name, sim_time, sim_timer_inst_per_sec ());
else {
    const char *tim;

    fprintf (st, "%s event queue status, time = %.0f, executing %.0f instructions/sec\n",
             sim_name, sim_time, sim_timer_inst_per_sec ());
    accum = 0;
    for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = uptr->next) {
        if (uptr == &sim_step_unit)
            fprintf (st, "  Step timer");
        else
            if (uptr == &sim_expect_unit)
                fprintf (st, "  Expect fired");
            else
                if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                    fprintf (st, "  %s", sim_dname (dptr));
                    if (dptr->numunits > 1)
                        fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                    }
                else
                    fprintf (st, "  Unknown");
        tim = sim_fmt_secs((accum + uptr->time)/sim_timer_inst_per_sec ());
        fprintf (st, " at %d%s%s%s%s\n", accum + uptr->time,
                                        (*tim) ? " (" : "", tim, (*tim) ? ")" : "",
                                        (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");
        accum = accum + uptr->time;
        }
    }
sim_show_clock_queues (st, dnotused, unotused, flag, cptr);
#if defined (SIM_ASYNCH_IO)
pthread_mutex_lock (&sim_asynch_lock);
fprintf (st, "asynchronous pending event queue\n");
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550

4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571


4572
4573
4574

4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
fprintf (st, "asynch latency: %d nanoseconds\n", sim_asynch_latency);
fprintf (st, "asynch instruction latency: %d instructions\n", sim_asynch_inst_latency);
pthread_mutex_unlock (&sim_asynch_lock);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}

t_stat show_time (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "Time:\t%.0f\n", sim_gtime());
return SCPE_OK;
}

t_stat show_break (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
t_stat r;

if (cptr && (*cptr != 0))
    r = ssh_break (st, cptr, 1);  /* more? */

else r = sim_brk_showall (st, sim_switches);
return r;
}

t_stat show_dev_radix (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
fprintf (st, "Radix=%d\n", dptr->dradix);
return SCPE_OK;
}

t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
int32 any = 0;
DEBTAB *dep;

if (dptr->flags & DEV_DEBUG) {
    if (dptr->dctrl == 0)
        fputs ("Debugging disabled", st);
    else if (dptr->debflags == NULL)
        fputs ("Debugging enabled", st);
    else {


        fputs ("Debug=", st);
        for (dep = dptr->debflags; dep->name != NULL; dep++) {
            if ((dptr->dctrl & dep->mask) == dep->mask) {

                if (any)
                    fputc (';', st);
                fputs (dep->name, st);
                any = 1;
                }
            }
        }
    fputc ('\n', st);
    return SCPE_OK;
    }
else return SCPE_NOFNC;
}

/* Show On actions */

t_stat show_on (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
int32 lvl, i;

if (cptr && (*cptr != 0)) return SCPE_2MARG;            /* now eol? */
for (lvl=sim_do_depth; lvl >= 0; --lvl) {
    if (lvl > 0)
        fprintf(st, "On Processing at Do Nest Level: %d", lvl);







|







|





>
|



|





|










>
>

|
|
>















|







4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
fprintf (st, "asynch latency: %d nanoseconds\n", sim_asynch_latency);
fprintf (st, "asynch instruction latency: %d instructions\n", sim_asynch_inst_latency);
pthread_mutex_unlock (&sim_asynch_lock);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}

t_stat show_time (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
fprintf (st, "Time:\t%.0f\n", sim_gtime());
return SCPE_OK;
}

t_stat show_break (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
t_stat r;

if (cptr && (*cptr != 0))
    r = ssh_break (st, cptr, 1);  /* more? */
else
    r = sim_brk_showall (st, sim_switches);
return r;
}

t_stat show_dev_radix (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
fprintf (st, "Radix=%d\n", dptr->dradix);
return SCPE_OK;
}

t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 any = 0;
DEBTAB *dep;

if (dptr->flags & DEV_DEBUG) {
    if (dptr->dctrl == 0)
        fputs ("Debugging disabled", st);
    else if (dptr->debflags == NULL)
        fputs ("Debugging enabled", st);
    else {
        uint32 dctrl = dptr->dctrl;

        fputs ("Debug=", st);
        for (dep = dptr->debflags; (dctrl != 0) && (dep->name != NULL); dep++) {
            if ((dctrl & dep->mask) == dep->mask) {
                dctrl &= ~dep->mask;
                if (any)
                    fputc (';', st);
                fputs (dep->name, st);
                any = 1;
                }
            }
        }
    fputc ('\n', st);
    return SCPE_OK;
    }
else return SCPE_NOFNC;
}

/* Show On actions */

t_stat show_on (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 lvl, i;

if (cptr && (*cptr != 0)) return SCPE_2MARG;            /* now eol? */
for (lvl=sim_do_depth; lvl >= 0; --lvl) {
    if (lvl > 0)
        fprintf(st, "On Processing at Do Nest Level: %d", lvl);
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
if (sim_on_inherit)
    fprintf(st, "on state and actions are inherited by nested do commands and subroutines\n");
return SCPE_OK;
}

/* Show modifiers */

t_stat show_mod_names (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_modifiers (st, dptr, NULL, flag, cptr);
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i)
    show_dev_modifiers (st, dptr, NULL, flag, cptr);
return SCPE_OK;
}

t_stat show_dev_modifiers (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
fprint_set_help (st, dptr);
return SCPE_OK;
}

t_stat show_all_mods (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, int32 *toks)
{







|













|







4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
if (sim_on_inherit)
    fprintf(st, "on state and actions are inherited by nested do commands and subroutines\n");
return SCPE_OK;
}

/* Show modifiers */

t_stat show_mod_names (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_modifiers (st, dptr, NULL, flag, cptr);
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i)
    show_dev_modifiers (st, dptr, NULL, flag, cptr);
return SCPE_OK;
}

t_stat show_dev_modifiers (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
fprint_set_help (st, dptr);
return SCPE_OK;
}

t_stat show_all_mods (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, int32 *toks)
{
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716


4717
4718
4719
4720


4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750

4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
        r = show_one_mod (st, dptr, uptr, mptr, NULL, 0);
        }
    }
return SCPE_OK;
}

t_stat show_one_mod (FILE *st, DEVICE *dptr, UNIT *uptr, MTAB *mptr,
    char *cptr, int32 flag)
{
t_stat r = SCPE_OK;
//t_value val;

if (mptr->disp)
    r = mptr->disp (st, uptr, mptr->match, cptr? cptr: mptr->desc);
//else if ((mptr->mask & MTAB_XTD) && (mptr->mask & MTAB_VAL)) {
//    REG *rptr = (REG *) mptr->desc;
//    fprintf (st, "%s=", mptr->pstring);
//    val = get_rval (rptr, 0);
//    fprint_val (st, val, rptr->radix, rptr->width,
//        rptr->flags & REG_FMT);
//    }
else fputs (mptr->pstring, st);
if ((r == SCPE_OK) && (flag && !((mptr->mask & MTAB_XTD) && MODMASK(mptr,MTAB_NMO))))
    fputc ('\n', st);
return r;
}

/* Show show commands */

t_stat show_show_commands (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_show_commands (st, dptr, NULL, flag, cptr);
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i)
    show_dev_show_commands (st, dptr, NULL, flag, cptr);
return SCPE_OK;
}

t_stat show_dev_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
fprint_show_help (st, dptr);
return SCPE_OK;
}

/* Show/change the current working directiory commands */

t_stat show_default (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char buffer[PATH_MAX];
char *wd = getcwd(buffer, PATH_MAX);
fprintf (st, "%s\n", wd);
return SCPE_OK;
}

t_stat set_default_cmd (int32 flg, char *cptr)
{


if (sim_is_running)
    return SCPE_INVREM;
if ((!cptr) || (*cptr == 0))
    return SCPE_2FARG;


sim_trim_endspc(cptr);
if (chdir(cptr) != 0)
    return sim_messagef(SCPE_IOERR, "Unable to directory change to: %s\n", cptr);
return SCPE_OK;
}

t_stat pwd_cmd (int32 flg, char *cptr)
{
return show_cmd (0, "DEFAULT");
}

#if defined (_WIN32)

t_stat dir_cmd (int32 flg, char *cptr)
{
HANDLE hFind;
WIN32_FIND_DATAA File;
struct stat filestat;
char WildName[PATH_MAX + 1];

if (*cptr == '\0')
    cptr = "./*";
if ((!stat (cptr, &filestat)) && (filestat.st_mode & S_IFDIR)) {
    sprintf (WildName, "%s%c*", cptr, strchr (cptr, '/') ? '/' : '\\');
    cptr = WildName;
    }
if ((hFind =  FindFirstFileA (cptr, &File)) != INVALID_HANDLE_VALUE) {
    t_int64 FileSize, TotalSize = 0;
    int DirCount = 0, FileCount = 0;
    char DirName[PATH_MAX + 1], FileName[PATH_MAX + 1];

    char *c, pathsep = '/';
    struct tm *local;

    GetFullPathNameA(cptr, sizeof(DirName), DirName, &c);
    c = strrchr(DirName, pathsep);
    if (NULL == c) {
        pathsep = '\\';
        c = strrchr(cptr, pathsep);
        }
    if (c) {
        memcpy(DirName, cptr, c - cptr);







|





|















|













|







|







|

>
>




>
>
|
|
|



|






|
















>
|


|







4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
        r = show_one_mod (st, dptr, uptr, mptr, NULL, 0);
        }
    }
return SCPE_OK;
}

t_stat show_one_mod (FILE *st, DEVICE *dptr, UNIT *uptr, MTAB *mptr,
    CONST char *cptr, int32 flag)
{
t_stat r = SCPE_OK;
//t_value val;

if (mptr->disp)
    r = mptr->disp (st, uptr, mptr->match, (CONST void *)(cptr? cptr: mptr->desc));
//else if ((mptr->mask & MTAB_XTD) && (mptr->mask & MTAB_VAL)) {
//    REG *rptr = (REG *) mptr->desc;
//    fprintf (st, "%s=", mptr->pstring);
//    val = get_rval (rptr, 0);
//    fprint_val (st, val, rptr->radix, rptr->width,
//        rptr->flags & REG_FMT);
//    }
else fputs (mptr->pstring, st);
if ((r == SCPE_OK) && (flag && !((mptr->mask & MTAB_XTD) && MODMASK(mptr,MTAB_NMO))))
    fputc ('\n', st);
return r;
}

/* Show show commands */

t_stat show_show_commands (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++)
    show_dev_show_commands (st, dptr, NULL, flag, cptr);
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i)
    show_dev_show_commands (st, dptr, NULL, flag, cptr);
return SCPE_OK;
}

t_stat show_dev_show_commands (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
fprint_show_help (st, dptr);
return SCPE_OK;
}

/* Show/change the current working directiory commands */

t_stat show_default (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
char buffer[PATH_MAX];
char *wd = getcwd(buffer, PATH_MAX);
fprintf (st, "%s\n", wd);
return SCPE_OK;
}

t_stat set_default_cmd (int32 flg, CONST char *cptr)
{
char gbuf[4*CBUFSIZE];

if (sim_is_running)
    return SCPE_INVREM;
if ((!cptr) || (*cptr == 0))
    return SCPE_2FARG;
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
sim_trim_endspc(gbuf);
if (chdir(gbuf) != 0)
    return sim_messagef(SCPE_IOERR, "Unable to directory change to: %s\n", gbuf);
return SCPE_OK;
}

t_stat pwd_cmd (int32 flg, CONST char *cptr)
{
return show_cmd (0, "DEFAULT");
}

#if defined (_WIN32)

t_stat dir_cmd (int32 flg, CONST char *cptr)
{
HANDLE hFind;
WIN32_FIND_DATAA File;
struct stat filestat;
char WildName[PATH_MAX + 1];

if (*cptr == '\0')
    cptr = "./*";
if ((!stat (cptr, &filestat)) && (filestat.st_mode & S_IFDIR)) {
    sprintf (WildName, "%s%c*", cptr, strchr (cptr, '/') ? '/' : '\\');
    cptr = WildName;
    }
if ((hFind =  FindFirstFileA (cptr, &File)) != INVALID_HANDLE_VALUE) {
    t_int64 FileSize, TotalSize = 0;
    int DirCount = 0, FileCount = 0;
    char DirName[PATH_MAX + 1], FileName[PATH_MAX + 1];
    const char *c;
    char pathsep = '/';
    struct tm *local;

    GetFullPathNameA(cptr, sizeof(DirName), DirName, (char **)&c);
    c = strrchr(DirName, pathsep);
    if (NULL == c) {
        pathsep = '\\';
        c = strrchr(cptr, pathsep);
        }
    if (c) {
        memcpy(DirName, cptr, c - cptr);
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826

4827
4828
4829
4830
4831
4832
4833
4834
#else /* !defined (HAVE_GLOB) */
#include <dirent.h>
#if defined (HAVE_FNMATCH)
#include <fnmatch.h>
#endif
#endif /* defined (HAVE_GLOB) */

t_stat dir_cmd (int32 flg, char *cptr)
{
#if defined (HAVE_GLOB)
glob_t  paths;
#else
DIR *dir;
#endif
struct stat filestat;
char *c;
char DirName[PATH_MAX + 1], WholeName[PATH_MAX + 1], WildName[PATH_MAX + 1];

if (*cptr == '\0')
    cptr = "./*";

strcpy (WildName, cptr);
cptr = WildName;
while (strlen(WildName) && sim_isspace(WildName[strlen(WildName)-1]))
    WildName[strlen(WildName)-1] = '\0';
if ((!stat (WildName, &filestat)) && (filestat.st_mode & S_IFDIR))
    strcat (WildName, "/*");
if ((*cptr != '/') || (0 == memcmp (cptr, "./", 2)) || (0 == memcmp (cptr, "../", 3))) {
#if defined (VMS)







|











|
>
|







5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
#else /* !defined (HAVE_GLOB) */
#include <dirent.h>
#if defined (HAVE_FNMATCH)
#include <fnmatch.h>
#endif
#endif /* defined (HAVE_GLOB) */

t_stat dir_cmd (int32 flg, CONST char *cptr)
{
#if defined (HAVE_GLOB)
glob_t  paths;
#else
DIR *dir;
#endif
struct stat filestat;
char *c;
char DirName[PATH_MAX + 1], WholeName[PATH_MAX + 1], WildName[PATH_MAX + 1];

if (*cptr == '\0')
    strcpy (WildName, "./*");
else
    strcpy (WildName, cptr);
cptr = WildName;
while (strlen(WildName) && sim_isspace(WildName[strlen(WildName)-1]))
    WildName[strlen(WildName)-1] = '\0';
if ((!stat (WildName, &filestat)) && (filestat.st_mode & S_IFDIR))
    strcat (WildName, "/*");
if ((*cptr != '/') || (0 == memcmp (cptr, "./", 2)) || (0 == memcmp (cptr, "../", 3))) {
#if defined (VMS)
4939
4940
4941
4942
4943
4944
4945





















4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967



4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993

4994
4995

4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010


5011
5012
5013
5014
5015
5016
5017
    return SCPE_ARG;
    }
return SCPE_OK;
}

#endif /* !defined(_WIN32) */






















/* Breakpoint commands */

t_stat brk_cmd (int32 flg, char *cptr)
{
GET_SWITCHES (cptr);                                    /* get switches */
return ssh_break (NULL, cptr, flg);                     /* call common code */
}

t_stat ssh_break (FILE *st, char *cptr, int32 flg)
{
char gbuf[CBUFSIZE], *aptr;
const char *tptr, *t1ptr;
DEVICE *dptr = sim_dflt_dev;
UNIT *uptr = dptr->units;
t_stat r;
t_addr lo, hi, max = uptr->capac - 1;
int32 cnt;

if (sim_brk_types == 0)
    return SCPE_NOFNC;
if ((dptr == NULL) || (uptr == NULL))
    return SCPE_IERR;



if ((aptr = strchr (cptr, ';'))) {                      /* ;action? */
    if (flg != SSH_ST)                                  /* only on SET */
        return SCPE_ARG;
    *aptr++ = 0;                                        /* separate strings */
    }
if (*cptr == 0) {                                       /* no argument? */
    lo = (t_addr) get_rval (sim_PC, 0);                 /* use PC */
    return ssh_break_one (st, flg, lo, 0, aptr);
    }
while (*cptr) {
    cptr = get_glyph (cptr, gbuf, ',');
    tptr = get_range (dptr, gbuf, &lo, &hi, dptr->aradix, max, 0);
    if (tptr == NULL)
        return SCPE_ARG;
    if (*tptr == '[') {
        cnt = (int32) strtotv (tptr + 1, &t1ptr, 10);
        if ((tptr == t1ptr) || (*t1ptr != ']') || (flg != SSH_ST))
            return SCPE_ARG;
        tptr = t1ptr + 1;
        }
    else cnt = 0;
    if (*tptr != 0)
        return SCPE_ARG;
    if ((lo == 0) && (hi == max)) {
        if (flg == SSH_CL)
            sim_brk_clrall (sim_switches);

        else if (flg == SSH_SH)
            sim_brk_showall (st, sim_switches);

        else return SCPE_ARG;
        }
    else {
        for ( ; lo <= hi; lo = lo + 1) {
            r = ssh_break_one (st, flg, lo, cnt, aptr);
            if (r != SCPE_OK)
                return r;
            }
        }
    }
return SCPE_OK;
}

t_stat ssh_break_one (FILE *st, int32 flg, t_addr lo, int32 cnt, char *aptr)
{


switch (flg) {

    case SSH_ST:
        return sim_brk_set (lo, sim_switches, cnt, aptr);
        break;

    case SSH_CL:







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|





|

|
|







|


>
>
>
|

|










|



|




|



>
|
|
>
|












|

>
>







5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
    return SCPE_ARG;
    }
return SCPE_OK;
}

#endif /* !defined(_WIN32) */


t_stat type_cmd (int32 flg, CONST char *cptr)
{
FILE *file;
char lbuf[4*CBUFSIZE];

if ((!cptr) || (*cptr == 0))
    return SCPE_2FARG;
lbuf[sizeof(lbuf)-1] = '\0';
strncpy (lbuf, cptr, sizeof(lbuf)-1);
sim_trim_endspc(lbuf);
file = sim_fopen (lbuf, "r");
if (file == NULL)                           /* open failed? */
    return SCPE_OPENERR;
lbuf[sizeof(lbuf)-1] = '\0';
while (fgets (lbuf, sizeof(lbuf)-1, file))
    sim_printf ("%s", lbuf);
fclose (file);
return SCPE_OK;
}

/* Breakpoint commands */

t_stat brk_cmd (int32 flg, CONST char *cptr)
{
GET_SWITCHES (cptr);                                    /* get switches */
return ssh_break (NULL, cptr, flg);                     /* call common code */
}

t_stat ssh_break (FILE *st, const char *cptr, int32 flg)
{
char gbuf[CBUFSIZE], *aptr, abuf[4*CBUFSIZE];
CONST char *tptr, *t1ptr;
DEVICE *dptr = sim_dflt_dev;
UNIT *uptr = dptr->units;
t_stat r;
t_addr lo, hi, max = uptr->capac - 1;
int32 cnt;

if (sim_brk_types == 0)
    return sim_messagef (SCPE_NOFNC, "No breakpoint support in this simulator\n");
if ((dptr == NULL) || (uptr == NULL))
    return SCPE_IERR;
abuf[sizeof(abuf)-1] = '\0';
strncpy (abuf, cptr, sizeof(abuf)-1);
cptr = abuf;
if ((aptr = strchr (abuf, ';'))) {                      /* ;action? */
    if (flg != SSH_ST)                                  /* only on SET */
        return sim_messagef (SCPE_ARG, "Invalid argument: %s\n", aptr);
    *aptr++ = 0;                                        /* separate strings */
    }
if (*cptr == 0) {                                       /* no argument? */
    lo = (t_addr) get_rval (sim_PC, 0);                 /* use PC */
    return ssh_break_one (st, flg, lo, 0, aptr);
    }
while (*cptr) {
    cptr = get_glyph (cptr, gbuf, ',');
    tptr = get_range (dptr, gbuf, &lo, &hi, dptr->aradix, max, 0);
    if (tptr == NULL)
        return sim_messagef (SCPE_ARG, "Invalid address specifier: %s\n", gbuf);
    if (*tptr == '[') {
        cnt = (int32) strtotv (tptr + 1, &t1ptr, 10);
        if ((tptr == t1ptr) || (*t1ptr != ']') || (flg != SSH_ST))
            return sim_messagef (SCPE_ARG, "Invalid repeat count specifier: %s\n", tptr + 1);
        tptr = t1ptr + 1;
        }
    else cnt = 0;
    if (*tptr != 0)
        return sim_messagef (SCPE_ARG, "Unexpected argument: %s\n", tptr);
    if ((lo == 0) && (hi == max)) {
        if (flg == SSH_CL)
            sim_brk_clrall (sim_switches);
        else
            if (flg == SSH_SH)
                sim_brk_showall (st, sim_switches);
            else
                return SCPE_ARG;
        }
    else {
        for ( ; lo <= hi; lo = lo + 1) {
            r = ssh_break_one (st, flg, lo, cnt, aptr);
            if (r != SCPE_OK)
                return r;
            }
        }
    }
return SCPE_OK;
}

t_stat ssh_break_one (FILE *st, int32 flg, t_addr lo, int32 cnt, CONST char *aptr)
{
if (!sim_brk_types)
    return sim_messagef (SCPE_NOFNC, "No breakpoint support in this simulator\n");
switch (flg) {

    case SSH_ST:
        return sim_brk_set (lo, sim_switches, cnt, aptr);
        break;

    case SSH_CL:
5030
5031
5032
5033
5034
5035
5036


5037
5038
5039
5040
5041
5042

5043
5044
5045
5046
5047
5048
5049
/* Reset command and routines

   re[set]              reset all devices
   re[set] all          reset all devices
   re[set] device       reset specific device
*/



t_stat reset_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */

if (*cptr == 0)                                         /* reset(cr) */
    return (reset_all (0));
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
if (strcmp (gbuf, "ALL") == 0)
    return (reset_all (0));







>
>
|





>







5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
/* Reset command and routines

   re[set]              reset all devices
   re[set] all          reset all devices
   re[set] device       reset specific device
*/

static t_bool run_cmd_did_reset = FALSE;

t_stat reset_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */
run_cmd_did_reset = FALSE;
if (*cptr == 0)                                         /* reset(cr) */
    return (reset_all (0));
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
if (strcmp (gbuf, "ALL") == 0)
    return (reset_all (0));
5111
5112
5113
5114
5115
5116
5117






























5118
5119
5120
5121
5122
5123
5124
5125
5126
5127

5128
5129
5130

5131
5132

5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151

/* Load and dump commands

   lo[ad] filename {arg}        load specified file
   du[mp] filename {arg}        dump to specified file
*/































t_stat load_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
FILE *loadfile;
t_stat reason;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph_nc (cptr, gbuf, 0);                    /* get file name */

loadfile = sim_fopen (gbuf, flag? "wb": "rb");          /* open for wr/rd */
if (loadfile == NULL)
    return SCPE_OPENERR;

GET_SWITCHES (cptr);                                    /* get switches */
reason = sim_load (loadfile, cptr, gbuf, flag);         /* load or dump */

fclose (loadfile);
return reason;
}

/* Attach command

   at[tach] unit file   attach specified unit to file
*/

t_stat attach_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;
UNIT *uptr;
t_stat r;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|


|






>
|
|
|
>

|
>
|








|

|







5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519

/* Load and dump commands

   lo[ad] filename {arg}        load specified file
   du[mp] filename {arg}        dump to specified file
*/

/* Memory File use (for internal memory static ROM images)

    when used to read ROM image with internally generated
    load commands, calling code setups with sim_set_memory_file()
    sim_load uses Fgetc() instead of fgetc() or getc()
*/

static const unsigned char *mem_data = NULL;
static size_t mem_data_size = 0;

t_stat sim_set_memory_load_file (const unsigned char *data, size_t size)
{
mem_data = data;
mem_data_size = size;
return SCPE_OK;
}

int Fgetc (FILE *f)
{
if (mem_data) {
    if (mem_data_size == 0)
        return EOF;
    --mem_data_size;
    return (int)(*mem_data++);
    }
else
    return fgetc (f);
}


t_stat load_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
FILE *loadfile = NULL;
t_stat reason;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph_nc (cptr, gbuf, 0);                    /* get file name */
if (!mem_data) {
    loadfile = sim_fopen (gbuf, flag? "wb": "rb");      /* open for wr/rd */
    if (loadfile == NULL)
        return SCPE_OPENERR;
    }
GET_SWITCHES (cptr);                                    /* get switches */
reason = sim_load (loadfile, (CONST char *)cptr, gbuf, flag);/* load or dump */
if (loadfile)
    fclose (loadfile);
return reason;
}

/* Attach command

   at[tach] unit file   attach specified unit to file
*/

t_stat attach_cmd (int32 flag, CONST char *cptr)
{
char gbuf[4*CBUFSIZE];
DEVICE *dptr;
UNIT *uptr;
t_stat r;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
5166
5167
5168
5169
5170
5171
5172


5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202

5203

5204
5205
5206
5207
5208
5209
5210
            return r;
        }
    else {
        if (!(uptr->dynflags & UNIT_ATTMULT))
            return SCPE_ALATT;                          /* Already attached */
        }
    }


sim_trim_endspc (cptr);                                 /* trim trailing spc */
return scp_attach_unit (dptr, uptr, cptr);              /* attach */
}

/* Call device-specific or file-oriented attach unit routine */

t_stat scp_attach_unit (DEVICE *dptr, UNIT *uptr, char *cptr)
{
if (dptr->attach != NULL)                               /* device routine? */
    return dptr->attach (uptr, cptr);                   /* call it */
return attach_unit (uptr, cptr);                        /* no, std routine */
}

/* Attach unit to file */

t_stat attach_unit (UNIT *uptr, char *cptr)
{
DEVICE *dptr;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;
if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char)); /* alloc name buf */
if (uptr->filename == NULL)
    return SCPE_MEM;
strncpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
if (sim_switches & SWMASK ('R')) {                      /* read only? */

    if ((uptr->flags & UNIT_ROABLE) == 0)               /* allowed? */

        return attach_err (uptr, SCPE_NORO);            /* no, error */
    uptr->fileref = sim_fopen (cptr, "rb");             /* open rd only */
    if (uptr->fileref == NULL)                          /* open fail? */
        return attach_err (uptr, SCPE_OPENERR);         /* yes, error */
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    if (!sim_quiet && !(sim_switches & SWMASK ('Q'))) {
        sim_printf ("%s: unit is read only\n", sim_dname (dptr));







>
>
|
|




|


|
|




|













|
>
|
>







5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
            return r;
        }
    else {
        if (!(uptr->dynflags & UNIT_ATTMULT))
            return SCPE_ALATT;                          /* Already attached */
        }
    }
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
sim_trim_endspc (gbuf);                                 /* trim trailing spc */
return scp_attach_unit (dptr, uptr, gbuf);              /* attach */
}

/* Call device-specific or file-oriented attach unit routine */

t_stat scp_attach_unit (DEVICE *dptr, UNIT *uptr, const char *cptr)
{
if (dptr->attach != NULL)                               /* device routine? */
    return dptr->attach (uptr, (CONST char *)cptr);     /* call it */
return attach_unit (uptr, (CONST char *)cptr);          /* no, std routine */
}

/* Attach unit to file */

t_stat attach_unit (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;
if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char)); /* alloc name buf */
if (uptr->filename == NULL)
    return SCPE_MEM;
strncpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
if ((sim_switches & SWMASK ('R')) ||                    /* read only? */
    ((uptr->flags & UNIT_RO) != 0)) {
    if (((uptr->flags & UNIT_ROABLE) == 0) &&           /* allowed? */
        ((uptr->flags & UNIT_RO) == 0))
        return attach_err (uptr, SCPE_NORO);            /* no, error */
    uptr->fileref = sim_fopen (cptr, "rb");             /* open rd only */
    if (uptr->fileref == NULL)                          /* open fail? */
        return attach_err (uptr, SCPE_OPENERR);         /* yes, error */
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    if (!sim_quiet && !(sim_switches & SWMASK ('Q'))) {
        sim_printf ("%s: unit is read only\n", sim_dname (dptr));
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308

/* Detach command

   det[ach] all         detach all units
   det[ach] unit        detach specified unit
*/

t_stat detach_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;
UNIT *uptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
if (strcmp (gbuf, "ALL") == 0)
    return (detach_all (0, FALSE));
dptr = find_unit (gbuf, &uptr);                         /* locate unit */
if (dptr == NULL)                                       /* found dev? */
    return SCPE_NXDEV;
if (uptr == NULL)                                        /* valid unit? */
    return SCPE_NXUN;
return scp_detach_unit (dptr, uptr);                    /* detach */
}

/* Detach devices start..end

   Inputs:







|
















|







5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680

/* Detach command

   det[ach] all         detach all units
   det[ach] unit        detach specified unit
*/

t_stat detach_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;
UNIT *uptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
if (strcmp (gbuf, "ALL") == 0)
    return (detach_all (0, FALSE));
dptr = find_unit (gbuf, &uptr);                         /* locate unit */
if (dptr == NULL)                                       /* found dev? */
    return SCPE_NXDEV;
if (uptr == NULL)                                       /* valid unit? */
    return SCPE_NXUN;
return scp_detach_unit (dptr, uptr);                    /* detach */
}

/* Detach devices start..end

   Inputs:
5321
5322
5323
5324
5325
5326
5327


5328
5329
5330
5331
5332
5333
5334
uint32 i, j;
DEVICE *dptr;
UNIT *uptr;
t_stat r;

if ((start < 0) || (start > 1))
    return SCPE_IERR;


for (i = start; (dptr = sim_devices[i]) != NULL; i++) { /* loop thru dev */
    for (j = 0; j < dptr->numunits; j++) {              /* loop thru units */
        uptr = (dptr->units) + j;
        if ((uptr->flags & UNIT_ATT) ||                 /* attached? */
            (shutdown && dptr->detach &&                /* shutdown, spec rtn, */
            !(uptr->flags & UNIT_ATTABLE))) {           /* !attachable? */
            r = scp_detach_unit (dptr, uptr);           /* detach unit */







>
>







5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
uint32 i, j;
DEVICE *dptr;
UNIT *uptr;
t_stat r;

if ((start < 0) || (start > 1))
    return SCPE_IERR;
if (shutdown)
    sim_switches = sim_switches | SIM_SW_SHUT;          /* flag shutdown */
for (i = start; (dptr = sim_devices[i]) != NULL; i++) { /* loop thru dev */
    for (j = 0; j < dptr->numunits; j++) {              /* loop thru units */
        uptr = (dptr->units) + j;
        if ((uptr->flags & UNIT_ATT) ||                 /* attached? */
            (shutdown && dptr->detach &&                /* shutdown, spec rtn, */
            !(uptr->flags & UNIT_ATTABLE))) {           /* !attachable? */
            r = scp_detach_unit (dptr, uptr);           /* detach unit */
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
}

/* Assign command

   as[sign] device name assign logical name to device
*/

t_stat assign_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;







|







5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
}

/* Assign command

   as[sign] device name assign logical name to device
*/

t_stat assign_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
    return SCPE_2MARG;
if (find_dev (gbuf))                                    /* name in use */
    return SCPE_ARG;
deassign_device (dptr);                                 /* release current */
return assign_device (dptr, gbuf);
}

t_stat assign_device (DEVICE *dptr, char *cptr)
{
dptr->lname = (char *) calloc (CBUFSIZE, sizeof (char));
if (dptr->lname == NULL)
    return SCPE_MEM;
strncpy (dptr->lname, cptr, CBUFSIZE);
return SCPE_OK;
}

/* Deassign command

   dea[ssign] device    deassign logical name
*/

t_stat deassign_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
dptr = find_dev (gbuf);                                 /* locate device */
if (dptr == NULL)                                       /* found dev? */
    return SCPE_NXDEV;
return deassign_device (dptr);
}

t_stat deassign_device (DEVICE *dptr)
{
if (dptr->lname)
    free (dptr->lname);
dptr->lname = NULL;
return SCPE_OK;
}

/* Get device display name */

const char *sim_dname (DEVICE *dptr)
{
return (dptr->lname? dptr->lname: dptr->name);
}

/* Get unit display name */

const char *sim_uname (UNIT *uptr)
{
DEVICE *d = find_dev_from_unit(uptr);







|

|


|








|


















<
|








|







5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832

5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
    return SCPE_2MARG;
if (find_dev (gbuf))                                    /* name in use */
    return SCPE_ARG;
deassign_device (dptr);                                 /* release current */
return assign_device (dptr, gbuf);
}

t_stat assign_device (DEVICE *dptr, const char *cptr)
{
dptr->lname = (char *) calloc (1 + strlen (cptr), sizeof (char));
if (dptr->lname == NULL)
    return SCPE_MEM;
strcpy (dptr->lname, cptr);
return SCPE_OK;
}

/* Deassign command

   dea[ssign] device    deassign logical name
*/

t_stat deassign_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
DEVICE *dptr;

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
cptr = get_glyph (cptr, gbuf, 0);                       /* get next glyph */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
dptr = find_dev (gbuf);                                 /* locate device */
if (dptr == NULL)                                       /* found dev? */
    return SCPE_NXDEV;
return deassign_device (dptr);
}

t_stat deassign_device (DEVICE *dptr)
{

free (dptr->lname);
dptr->lname = NULL;
return SCPE_OK;
}

/* Get device display name */

const char *sim_dname (DEVICE *dptr)
{
return (dptr ? (dptr->lname? dptr->lname: dptr->name) : "");
}

/* Get unit display name */

const char *sim_uname (UNIT *uptr)
{
DEVICE *d = find_dev_from_unit(uptr);
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495


5496
5497
5498


5499
5500
5501
5502
5503
5504
5505
5506
5507
}

/* Save command

   sa[ve] filename              save state to specified file
*/

t_stat save_cmd (int32 flag, char *cptr)
{
FILE *sfile;
t_stat r;


GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;


sim_trim_endspc (cptr);
if ((sfile = sim_fopen (cptr, "wb")) == NULL)
    return SCPE_OPENERR;
r = sim_save (sfile);
fclose (sfile);
return r;
}

t_stat sim_save (FILE *sfile)







|



>
>



>
>
|
|







5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
}

/* Save command

   sa[ve] filename              save state to specified file
*/

t_stat save_cmd (int32 flag, CONST char *cptr)
{
FILE *sfile;
t_stat r;
char gbuf[4*CBUFSIZE];

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
sim_trim_endspc (gbuf);
if ((sfile = sim_fopen (gbuf, "wb")) == NULL)
    return SCPE_OPENERR;
r = sim_save (sfile);
fclose (sfile);
return r;
}

t_stat sim_save (FILE *sfile)
5559
5560
5561
5562
5563
5564
5565


5566
5567
5568
5569
5570
5571
5572
        WRITE_I (t);                                    /* activation time */
        WRITE_I (uptr->u3);                             /* unit specific */
        WRITE_I (uptr->u4);
        WRITE_I (uptr->u5);                             /* [V3.0] more unit */
        WRITE_I (uptr->u6);
        WRITE_I (uptr->flags);                          /* [V2.10] flags */
        WRITE_I (uptr->dynflags);


        WRITE_I (uptr->capac);                          /* [V3.5] capacity */
        if (uptr->flags & UNIT_ATT) {
            fputs (uptr->filename, sfile);
            if ((uptr->flags & UNIT_BUF) &&             /* writable buffered */
                uptr->hwmark &&                         /* files need to be */
                ((uptr->flags & UNIT_RO) == 0)) {       /* written on save */
                uint32 cap = (uptr->hwmark + dptr->aincr - 1) / dptr->aincr;







>
>







5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
        WRITE_I (t);                                    /* activation time */
        WRITE_I (uptr->u3);                             /* unit specific */
        WRITE_I (uptr->u4);
        WRITE_I (uptr->u5);                             /* [V3.0] more unit */
        WRITE_I (uptr->u6);
        WRITE_I (uptr->flags);                          /* [V2.10] flags */
        WRITE_I (uptr->dynflags);
        WRITE_I (uptr->wait);
        WRITE_I (uptr->buf);
        WRITE_I (uptr->capac);                          /* [V3.5] capacity */
        if (uptr->flags & UNIT_ATT) {
            fputs (uptr->filename, sfile);
            if ((uptr->flags & UNIT_BUF) &&             /* writable buffered */
                uptr->hwmark &&                         /* files need to be */
                ((uptr->flags & UNIT_RO) == 0)) {       /* written on save */
                uint32 cap = (uptr->hwmark + dptr->aincr - 1) / dptr->aincr;
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643

5644
5645
5646
5647


5648
5649
5650
5651
5652
5653
5654
5655
5656
}

/* Restore command

   re[store] filename           restore state from specified file
*/

t_stat restore_cmd (int32 flag, char *cptr)
{
FILE *rfile;
t_stat r;


GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;


sim_trim_endspc (cptr);
if ((rfile = sim_fopen (cptr, "rb")) == NULL)
    return SCPE_OPENERR;
r = sim_rest (rfile);
fclose (rfile);
return r;
}

t_stat sim_rest (FILE *rfile)







|



>




>
>
|
|







6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
}

/* Restore command

   re[store] filename           restore state from specified file
*/

t_stat restore_cmd (int32 flag, CONST char *cptr)
{
FILE *rfile;
t_stat r;
char gbuf[4*CBUFSIZE];

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
sim_trim_endspc (gbuf);
if ((rfile = sim_fopen (gbuf, "rb")) == NULL)
    return SCPE_OPENERR;
r = sim_rest (rfile);
fclose (rfile);
return r;
}

t_stat sim_rest (FILE *rfile)
5791
5792
5793
5794
5795
5796
5797


5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
        READ_I (uptr->u3);                              /* device specific */
        READ_I (uptr->u4);
        READ_I (uptr->u5);                              /* [V3.0+] more dev spec */
        READ_I (uptr->u6);
        READ_I (flg);                                   /* [V2.10+] unit flags */
        if (v40) {                                      /* [V4.0+] dynflags */
            READ_I (uptr->dynflags);


            }
        old_capac = uptr->capac;                        /* save current capacity */
        if (v35) {                                      /* [V3.5+] capacity */
            READ_I (uptr->capac);
            }
        if (!v32)
            flg = ((flg & UNIT_UFMASK_31) << (UNIT_V_UF - UNIT_V_UF_31)) |
                (flg & ~UNIT_UFMASK_31);                /* [V3.2+] flags moved */
        uptr->flags = (uptr->flags & ~UNIT_RFLAGS) |
            (flg & UNIT_RFLAGS);                        /* restore */
        READ_S (buf);                                   /* attached file */
        if ((uptr->flags & UNIT_ATT) &&                 /* unit currently attached? */
            (!dont_detach_attach)) {
            r = scp_detach_unit (dptr, uptr);           /* detach it */
            if (r != SCPE_OK)
                return r;
            }
        if ((buf[0] != '\0') &&                         /* unit to be reattached? */
            ((uptr->flags & UNIT_ATTABLE) ||            /*  and unit is attachable */
             (dptr->attach != NULL))) {                 /*    or VM attach routine provided? */
            uptr->flags = uptr->flags & ~UNIT_DIS;      /* ensure device is enabled */
            if (flg & UNIT_RO)                          /* [V2.10+] saved flgs & RO? */
                sim_switches |= SWMASK ('R');           /* RO attach */







>
>















|







6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
        READ_I (uptr->u3);                              /* device specific */
        READ_I (uptr->u4);
        READ_I (uptr->u5);                              /* [V3.0+] more dev spec */
        READ_I (uptr->u6);
        READ_I (flg);                                   /* [V2.10+] unit flags */
        if (v40) {                                      /* [V4.0+] dynflags */
            READ_I (uptr->dynflags);
            READ_I (uptr->wait);
            READ_I (uptr->buf);
            }
        old_capac = uptr->capac;                        /* save current capacity */
        if (v35) {                                      /* [V3.5+] capacity */
            READ_I (uptr->capac);
            }
        if (!v32)
            flg = ((flg & UNIT_UFMASK_31) << (UNIT_V_UF - UNIT_V_UF_31)) |
                (flg & ~UNIT_UFMASK_31);                /* [V3.2+] flags moved */
        uptr->flags = (uptr->flags & ~UNIT_RFLAGS) |
            (flg & UNIT_RFLAGS);                        /* restore */
        READ_S (buf);                                   /* attached file */
        if ((uptr->flags & UNIT_ATT) &&                 /* unit currently attached? */
            (!dont_detach_attach)) {
            r = scp_detach_unit (dptr, uptr);           /* detach it */
            if (r != SCPE_OK)
                return sim_messagef (r, "Error detaching %s from %s: %s\n", sim_uname (uptr), uptr->filename, sim_error_text (r));
            }
        if ((buf[0] != '\0') &&                         /* unit to be reattached? */
            ((uptr->flags & UNIT_ATTABLE) ||            /*  and unit is attachable */
             (dptr->attach != NULL))) {                 /*    or VM attach routine provided? */
            uptr->flags = uptr->flags & ~UNIT_DIS;      /* ensure device is enabled */
            if (flg & UNIT_RO)                          /* [V2.10+] saved flgs & RO? */
                sim_switches |= SWMASK ('R');           /* RO attach */
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962


5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985

5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997

5998
5999

6000



























6001
6002
6003
6004
6005
6006
6007
free (attunits);
free (attswitches);
if (warned)
    sim_printf ("restore with the -Q switch to suppress warning messages\n");
return r;
}

/* Run, go, cont, step commands

   ru[n] [new PC]       reset and start simulation
   go [new PC]          start simulation
   co[nt]               start simulation
   s[tep] [step limit]  start simulation for 'limit' instructions


   b[oot] device        bootstrap from device and start simulation

   switches:
    -Q                  quiet return status
    -T                  (only for step), causes the step limit to
                        be a number of microseconds to run for
*/

t_stat run_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
const char *tptr;
uint32 i, j;
int32 sim_next;
int32 unitno;
t_value pcv;
t_stat r;
DEVICE *dptr;
UNIT *uptr;

GET_SWITCHES (cptr);                                    /* get switches */
sim_step = 0;
if ((flag == RU_RUN) || (flag == RU_GO)) {              /* run or go */

    if (*cptr != 0) {                                   /* argument? */
        cptr = get_glyph (cptr, gbuf, 0);               /* get next glyph */
        if (*cptr != 0)                                 /* should be end */
            return SCPE_2MARG;
        if (sim_vm_parse_addr)                          /* address parser? */
            pcv = sim_vm_parse_addr (sim_dflt_dev, gbuf, (char **)&tptr);
        else pcv = strtotv (gbuf, &tptr, sim_PC->radix);/* parse PC */
        if ((tptr == gbuf) || (*tptr != 0) ||           /* error? */
            (pcv > width_mask[sim_PC->width]))
            return SCPE_ARG;
        put_rval (sim_PC, 0, pcv);
        }

    if ((flag == RU_RUN) &&                             /* run? */
        ((r = sim_run_boot_prep ()) != SCPE_OK))        /* reset sim */

        return r;



























    }

else if ((flag == RU_STEP) ||
         ((flag == RU_NEXT) && !sim_vm_is_subroutine_call)) { /* step */
    static t_bool not_implemented_message = FALSE;

    if ((!not_implemented_message) && (flag == RU_NEXT)) {







|





>
>








|

|
|



|







>


|
<
|
|
|
|
|
|
|
|
>

|
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375

6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
free (attunits);
free (attswitches);
if (warned)
    sim_printf ("restore with the -Q switch to suppress warning messages\n");
return r;
}

/* Run, go, boot, cont, step, next commands

   ru[n] [new PC]       reset and start simulation
   go [new PC]          start simulation
   co[nt]               start simulation
   s[tep] [step limit]  start simulation for 'limit' instructions
   next                 start simulation for 1 instruction
                        stepping over subroutine calls
   b[oot] device        bootstrap from device and start simulation

   switches:
    -Q                  quiet return status
    -T                  (only for step), causes the step limit to
                        be a number of microseconds to run for
*/

t_stat run_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE] = "";
CONST char *tptr;
uint32 i, j;
int32 sim_next;
int32 unitno;
t_value pcv, orig_pcv;
t_stat r;
DEVICE *dptr;
UNIT *uptr;

GET_SWITCHES (cptr);                                    /* get switches */
sim_step = 0;
if ((flag == RU_RUN) || (flag == RU_GO)) {              /* run or go */
    orig_pcv = get_rval (sim_PC, 0);                    /* get current PC value */
    if (*cptr != 0) {                                   /* argument? */
        cptr = get_glyph (cptr, gbuf, 0);               /* get next glyph */
        if (MATCH_CMD (gbuf, "UNTIL") != 0) {

            if (sim_vm_parse_addr)                      /* address parser? */
                pcv = sim_vm_parse_addr (sim_dflt_dev, gbuf, &tptr);
            else pcv = strtotv (gbuf, &tptr, sim_PC->radix);/* parse PC */
            if ((tptr == gbuf) || (*tptr != 0) ||       /* error? */
                (pcv > width_mask[sim_PC->width]))
                return SCPE_ARG;
            put_rval (sim_PC, 0, pcv);                  /* Save in PC */
            }
        }
    if ((flag == RU_RUN) &&                             /* run? */
        ((r = sim_run_boot_prep (flag)) != SCPE_OK)) {  /* reset sim */
        put_rval (sim_PC, 0, orig_pcv);                 /* restore original PC */
        return r;
        }
    if ((*cptr) || (MATCH_CMD (gbuf, "UNTIL") == 0)) {  /* should be end */
        int32 saved_switches = sim_switches;

        if (MATCH_CMD (gbuf, "UNTIL") != 0)
            cptr = get_glyph (cptr, gbuf, 0);           /* get next glyph */
        if (MATCH_CMD (gbuf, "UNTIL") != 0)
            return sim_messagef (SCPE_2MARG, "Unexpected %s command argument: %s %s\n",
                                             (flag == RU_RUN) ? "RUN" : "GO", gbuf, cptr);
        sim_switches = 0;
        GET_SWITCHES (cptr);
        if ((*cptr == '\'') || (*cptr == '"')) {        /* Expect UNTIL condition */
            r = expect_cmd (1, cptr);
            if (r != SCPE_OK)
                return r;
            }
        else {                                          /* BREAK UNTIL condition */
            if (sim_switches == 0)
                sim_switches = sim_brk_dflt;
            sim_switches |= BRK_TYP_TEMP;               /* make this a one-shot breakpoint */
            sim_brk_types |= BRK_TYP_TEMP;
            r = ssh_break (NULL, cptr, SSH_ST);
            if (r != SCPE_OK)
                return sim_messagef (r, "Unable to establish breakpoint at: %s\n", cptr);
            }
        sim_switches = saved_switches;
        }
    }

else if ((flag == RU_STEP) ||
         ((flag == RU_NEXT) && !sim_vm_is_subroutine_call)) { /* step */
    static t_bool not_implemented_message = FALSE;

    if ((!not_implemented_message) && (flag == RU_NEXT)) {
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068

6069
6070



6071
6072
6073
6074
6075
6076
6077
        return SCPE_NOFNC;
    if (uptr->flags & UNIT_DIS)                         /* disabled? */
        return SCPE_UDIS;
    if ((uptr->flags & UNIT_ATTABLE) &&                 /* if attable, att? */
        !(uptr->flags & UNIT_ATT))
        return SCPE_UNATT;
    unitno = (int32) (uptr - dptr->units);              /* recover unit# */
    if ((r = sim_run_boot_prep ()) != SCPE_OK)          /* reset sim */
        return r;
    if ((r = dptr->boot (unitno, dptr)) != SCPE_OK)     /* boot device */
        return r;
    }


else if (flag != RU_CONT)                               /* must be cont */
    return SCPE_IERR;




if (sim_switches & SIM_SW_HIDE)                         /* Setup only for Remote Console Mode */
    return SCPE_OK;

for (i = 1; (dptr = sim_devices[i]) != NULL; i++) {     /* reposition all */
    for (j = 0; j < dptr->numunits; j++) {              /* seq devices */
        uptr = dptr->units + j;







|





>
|
|
>
>
>







6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
        return SCPE_NOFNC;
    if (uptr->flags & UNIT_DIS)                         /* disabled? */
        return SCPE_UDIS;
    if ((uptr->flags & UNIT_ATTABLE) &&                 /* if attable, att? */
        !(uptr->flags & UNIT_ATT))
        return SCPE_UNATT;
    unitno = (int32) (uptr - dptr->units);              /* recover unit# */
    if ((r = sim_run_boot_prep (flag)) != SCPE_OK)      /* reset sim */
        return r;
    if ((r = dptr->boot (unitno, dptr)) != SCPE_OK)     /* boot device */
        return r;
    }

else
    if (flag != RU_CONT)                                /* must be cont */
        return SCPE_IERR;
    else                                                /* CONTINUE command */
        if (*cptr != 0)                                 /* should be end (no arguments allowed) */
            return sim_messagef (SCPE_2MARG, "CONTINUE command takes no arguments\n");

if (sim_switches & SIM_SW_HIDE)                         /* Setup only for Remote Console Mode */
    return SCPE_OK;

for (i = 1; (dptr = sim_devices[i]) != NULL; i++) {     /* reposition all */
    for (j = 0; j < dptr->numunits; j++) {              /* seq devices */
        uptr = dptr->units + j;
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220

6221
6222
6223
6224
6225
6226
6227
6228








6229
6230
6231
6232
6233
6234
6235
6236
    fprint_stopped (sim_log, r);
if (sim_deb && (sim_deb != stdout) && (sim_deb != sim_log))/* debug if enabled */
    fprint_stopped (sim_deb, r);
}

/* Common setup for RUN or BOOT */

t_stat sim_run_boot_prep (void)
{
UNIT *uptr;


sim_interval = 0;                                       /* reset queue */
sim_time = sim_rtime = 0;
noqueue_time = 0;
for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = sim_clock_queue) {
    sim_clock_queue = uptr->next;
    uptr->next = NULL;
    }








return reset_all (0);
}

/* Print stopped message
 * For VM stops, if a VM-specific "sim_vm_fprint_stopped" pointer is defined,
 * call the indicated routine to print additional information after the message
 * and before the PC value is printed.  If the routine returns FALSE, skip
 * printing the PC and its related instruction.







|


>








>
>
>
>
>
>
>
>
|







6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
    fprint_stopped (sim_log, r);
if (sim_deb && (sim_deb != stdout) && (sim_deb != sim_log))/* debug if enabled */
    fprint_stopped (sim_deb, r);
}

/* Common setup for RUN or BOOT */

t_stat sim_run_boot_prep (int32 flag)
{
UNIT *uptr;
t_stat r;

sim_interval = 0;                                       /* reset queue */
sim_time = sim_rtime = 0;
noqueue_time = 0;
for (uptr = sim_clock_queue; uptr != QUEUE_LIST_END; uptr = sim_clock_queue) {
    sim_clock_queue = uptr->next;
    uptr->next = NULL;
    }
r = reset_all (0);
if ((r == SCPE_OK) && (flag == RU_RUN)) {
    if ((run_cmd_did_reset) && (0 == (sim_switches & SWMASK ('Q')))) {
        sim_printf ("Resetting all devices...  This may not have been your intention.\n");
        sim_printf ("The GO and CONTINUE commands do not reset devices.\n");
        }
    run_cmd_did_reset = TRUE;
    }
return r;
}

/* Print stopped message
 * For VM stops, if a VM-specific "sim_vm_fprint_stopped" pointer is defined,
 * call the indicated routine to print additional information after the message
 * and before the PC value is printed.  If the routine returns FALSE, skip
 * printing the PC and its related instruction.
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
        ALL                             all addresses
        register[:register|-register]   register range
        register[index]                 register array element
        register[start:end]             register array range
        STATE                           all registers
*/

t_stat exdep_cmd (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
const char *gptr;
const char *tptr = NULL;
int32 opt;
t_addr low, high;
t_stat reason;
DEVICE *tdptr;
REG *lowr, *highr;
FILE *ofile;








|


|
|







6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
        ALL                             all addresses
        register[:register|-register]   register range
        register[index]                 register array element
        register[start:end]             register array range
        STATE                           all registers
*/

t_stat exdep_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *gptr;
CONST char *tptr = NULL;
int32 opt;
t_addr low, high;
t_stat reason;
DEVICE *tdptr;
REG *lowr, *highr;
FILE *ofile;

6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440

/* Loop controllers for examine/deposit

   exdep_reg_loop       examine/deposit range of registers
   exdep_addr_loop      examine/deposit range of addresses
*/

t_stat exdep_reg_loop (FILE *ofile, SCHTAB *schptr, int32 flag, char *cptr,
    REG *lowr, REG *highr, uint32 lows, uint32 highs)
{
t_stat reason;
uint32 idx, val_start=lows;
t_value val, last_val;
REG *rptr;








|







6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868

/* Loop controllers for examine/deposit

   exdep_reg_loop       examine/deposit range of registers
   exdep_addr_loop      examine/deposit range of addresses
*/

t_stat exdep_reg_loop (FILE *ofile, SCHTAB *schptr, int32 flag, CONST char *cptr,
    REG *lowr, REG *highr, uint32 lows, uint32 highs)
{
t_stat reason;
uint32 idx, val_start=lows;
t_value val, last_val;
REG *rptr;

6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
                }
            }
        }
    }
return SCPE_OK;
}

t_stat exdep_addr_loop (FILE *ofile, SCHTAB *schptr, int32 flag, char *cptr,
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr)
{
t_addr i, mask;
t_stat reason;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;







|







6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
                }
            }
        }
    }
return SCPE_OK;
}

t_stat exdep_addr_loop (FILE *ofile, SCHTAB *schptr, int32 flag, const char *cptr,
    t_addr low, t_addr high, DEVICE *dptr, UNIT *uptr)
{
t_addr i, mask;
t_stat reason;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624










6625
6626
6627
6628
6629
6630
6631
        return  =       register value
*/

t_value get_rval (REG *rptr, uint32 idx)
{
size_t sz;
t_value val;
UNIT *uptr;

sz = SZ_R (rptr);
if ((rptr->depth > 1) && (rptr->flags & REG_CIRC)) {
    idx = idx + rptr->qptr;
    if (idx >= rptr->depth) idx = idx - rptr->depth;
    }
if ((rptr->depth > 1) && (rptr->flags & REG_UNIT)) {
    uptr = ((UNIT *) rptr->loc) + idx;
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        val = *((uint32 *) uptr);
    else val = *((t_uint64 *) uptr);
#else
    val = *((uint32 *) uptr);










#endif
    }
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint8)))
    val = *(((uint8 *) rptr->loc) + idx);
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint16)))







|







|


|
|

|
>
>
>
>
>
>
>
>
>
>







7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
        return  =       register value
*/

t_value get_rval (REG *rptr, uint32 idx)
{
size_t sz;
t_value val;
uint32 *ptr;

sz = SZ_R (rptr);
if ((rptr->depth > 1) && (rptr->flags & REG_CIRC)) {
    idx = idx + rptr->qptr;
    if (idx >= rptr->depth) idx = idx - rptr->depth;
    }
if ((rptr->depth > 1) && (rptr->flags & REG_UNIT)) {
    ptr = (uint32 *)(((UNIT *) rptr->loc) + idx);
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        val = *ptr;
    else val = *((t_uint64 *) ptr);
#else
    val = *ptr;
#endif
    }
else if ((rptr->depth > 1) && (rptr->flags & REG_STRUCT)) {
    ptr = (uint32 *)(((size_t) rptr->loc) + (idx * rptr->str_size));
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        val = *ptr;
    else val = *((t_uint64 *) ptr);
#else
    val = *ptr;
#endif
    }
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint8)))
    val = *(((uint8 *) rptr->loc) + idx);
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint16)))
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659

6660
6661
6662
6663
6664
6665
6666
6667
        cptr    =       pointer to input string
        rptr    =       pointer to register descriptor
        idx     =       index
   Outputs:
        return  =       error status
*/

t_stat dep_reg (int32 flag, char *cptr, REG *rptr, uint32 idx)
{
t_stat r;
t_value val, mask;
int32 rdx;

char *tptr, gbuf[CBUFSIZE];

if ((cptr == NULL) || (rptr == NULL))
    return SCPE_IERR;
if (rptr->flags & REG_RO)
    return SCPE_RO;
if (flag & EX_I) {
    cptr = read_line (gbuf, sizeof(gbuf), stdin);







|




>
|







7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
        cptr    =       pointer to input string
        rptr    =       pointer to register descriptor
        idx     =       index
   Outputs:
        return  =       error status
*/

t_stat dep_reg (int32 flag, CONST char *cptr, REG *rptr, uint32 idx)
{
t_stat r;
t_value val, mask;
int32 rdx;
CONST char *tptr;
char gbuf[CBUFSIZE];

if ((cptr == NULL) || (rptr == NULL))
    return SCPE_IERR;
if (rptr->flags & REG_RO)
    return SCPE_RO;
if (flag & EX_I) {
    cptr = read_line (gbuf, sizeof(gbuf), stdin);
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
if ((rptr->flags & REG_VMAD) && sim_vm_parse_addr) {    /* address form? */
    val = sim_vm_parse_addr (sim_dflt_dev, cptr, &tptr);
    if ((tptr == cptr) || (*tptr != 0) || (val > mask))
        return SCPE_ARG;
    }
else
    if (!(rptr->flags & REG_VMFLAGS) ||                 /* dont use sym? */
        (parse_sym (cptr, (rptr->flags & REG_UFMASK) | rdx, NULL,
                    &val, sim_switches | SIM_SW_REG) > SCPE_OK)) {
    val = get_uint (cptr, rdx, mask, &r);
    if (r != SCPE_OK)
        return SCPE_ARG;
    }
if ((rptr->flags & REG_NZ) && (val == 0))
    return SCPE_ARG;







|







7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
if ((rptr->flags & REG_VMAD) && sim_vm_parse_addr) {    /* address form? */
    val = sim_vm_parse_addr (sim_dflt_dev, cptr, &tptr);
    if ((tptr == cptr) || (*tptr != 0) || (val > mask))
        return SCPE_ARG;
    }
else
    if (!(rptr->flags & REG_VMFLAGS) ||                 /* dont use sym? */
        (parse_sym ((CONST char *)cptr, (rptr->flags & REG_UFMASK) | rdx, NULL,
                    &val, sim_switches | SIM_SW_REG) > SCPE_OK)) {
    val = get_uint (cptr, rdx, mask, &r);
    if (r != SCPE_OK)
        return SCPE_ARG;
    }
if ((rptr->flags & REG_NZ) && (val == 0))
    return SCPE_ARG;
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736









6737






6738
6739
6740
6741
6742
6743
6744
        none
*/

void put_rval (REG *rptr, uint32 idx, t_value val)
{
size_t sz;
t_value mask;
UNIT *uptr;

#define PUT_RVAL(sz,rp,id,v,m) \
    *(((sz *) rp->loc) + id) = \
            (sz)((*(((sz *) rp->loc) + id) & \
            ~((m) << (rp)->offset)) | ((v) << (rp)->offset))

if (rptr == sim_PC)
    sim_brk_npc (0);
sz = SZ_R (rptr);
mask = width_mask[rptr->width];
if ((rptr->depth > 1) && (rptr->flags & REG_CIRC)) {
    idx = idx + rptr->qptr;
    if (idx >= rptr->depth)
        idx = idx - rptr->depth;
    }
if ((rptr->depth > 1) && (rptr->flags & REG_UNIT)) {
    uptr = ((UNIT *) rptr->loc) + idx;
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        *((uint32 *) uptr) = (*((uint32 *) uptr) &
        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
    else *((t_uint64 *) uptr) = (*((t_uint64 *) uptr)
        & ~(mask << rptr->offset)) | (val << rptr->offset);
#else









    *((uint32 *) uptr) = (*((uint32 *) uptr) &






        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
#endif
    }
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint8)))
    PUT_RVAL (uint8, rptr, idx, (uint32) val, (uint32) mask);







|
















|


|


|


>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>







7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
        none
*/

void put_rval (REG *rptr, uint32 idx, t_value val)
{
size_t sz;
t_value mask;
uint32 *ptr;

#define PUT_RVAL(sz,rp,id,v,m) \
    *(((sz *) rp->loc) + id) = \
            (sz)((*(((sz *) rp->loc) + id) & \
            ~((m) << (rp)->offset)) | ((v) << (rp)->offset))

if (rptr == sim_PC)
    sim_brk_npc (0);
sz = SZ_R (rptr);
mask = width_mask[rptr->width];
if ((rptr->depth > 1) && (rptr->flags & REG_CIRC)) {
    idx = idx + rptr->qptr;
    if (idx >= rptr->depth)
        idx = idx - rptr->depth;
    }
if ((rptr->depth > 1) && (rptr->flags & REG_UNIT)) {
    ptr = (uint32 *)(((UNIT *) rptr->loc) + idx);
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        *ptr = (*ptr &
        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
    else *((t_uint64 *) ptr) = (*((t_uint64 *) ptr)
        & ~(mask << rptr->offset)) | (val << rptr->offset);
#else
    *ptr = (*ptr &
        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
#endif
    }
else if ((rptr->depth > 1) && (rptr->flags & REG_STRUCT)) {
    ptr = (uint32 *)(((size_t) rptr->loc) + (idx * rptr->str_size));
#if defined (USE_INT64)
    if (sz <= sizeof (uint32))
        *((uint32 *) ptr) = (*((uint32 *) ptr) &
        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
    else *((t_uint64 *) ptr) = (*((t_uint64 *) ptr)
        & ~(mask << rptr->offset)) | (val << rptr->offset);
#else
    *ptr = (*ptr &
        ~(((uint32) mask) << rptr->offset)) |
        (((uint32) val) << rptr->offset);
#endif
    }
else if (((rptr->depth > 1) || (rptr->flags & REG_FIT)) &&
    (sz == sizeof (uint8)))
    PUT_RVAL (uint8, rptr, idx, (uint32) val, (uint32) mask);
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
        uptr    =       pointer to unit
        dfltinc =       value to return on cr input
   Outputs:
        return  =       if > 0, error status
                        if <= 0, -number of extra address units retired
*/

t_stat dep_addr (int32 flag, char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc)
{
int32 i, count, rdx;
t_addr j, loc;
t_stat r, reason;
t_value mask;
size_t sz;







|







7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
        uptr    =       pointer to unit
        dfltinc =       value to return on cr input
   Outputs:
        return  =       if > 0, error status
                        if <= 0, -number of extra address units retired
*/

t_stat dep_addr (int32 flag, const char *cptr, t_addr addr, DEVICE *dptr,
    UNIT *uptr, int32 dfltinc)
{
int32 i, count, rdx;
t_addr j, loc;
t_stat r, reason;
t_value mask;
size_t sz;
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
        return dfltinc;
    }
if (uptr->flags & UNIT_RO)                              /* read only? */
    return SCPE_RO;
mask = width_mask[dptr->dwidth];

GET_RADIX (rdx, dptr->dradix);
if ((reason = parse_sym (cptr, addr, uptr, sim_eval, sim_switches)) > 0) {
    sim_eval[0] = get_uint (cptr, rdx, mask, &reason);
    if (reason != SCPE_OK)
        return reason;
    reason = dfltinc;
    }
count = (1 - reason + (dptr->aincr - 1)) / dptr->aincr;








|







7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
        return dfltinc;
    }
if (uptr->flags & UNIT_RO)                              /* read only? */
    return SCPE_RO;
mask = width_mask[dptr->dwidth];

GET_RADIX (rdx, dptr->dradix);
if ((reason = parse_sym ((CONST char *)cptr, addr, uptr, sim_eval, sim_switches)) > 0) {
    sim_eval[0] = get_uint (cptr, rdx, mask, &reason);
    if (reason != SCPE_OK)
        return reason;
    reason = dfltinc;
    }
count = (1 - reason + (dptr->aincr - 1)) / dptr->aincr;

6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
        }
    }
return reason;
}

/* Evaluate command */

t_stat eval_cmd (int32 flg, char *cptr)
{
DEVICE *dptr = sim_dflt_dev;
int32 i, rdx, a, lim;
t_stat r;

GET_SWITCHES (cptr);
GET_RADIX (rdx, dptr->dradix);
for (i = 0; i < sim_emax; i++)
sim_eval[i] = 0;
if (*cptr == 0)
    return SCPE_2FARG;
if ((r = parse_sym (cptr, 0, dptr->units, sim_eval, sim_switches)) > 0) {
    sim_eval[0] = get_uint (cptr, rdx, width_mask[dptr->dwidth], &r);
    if (r != SCPE_OK)
        return r;
    }
lim = 1 - r;
for (i = a = 0; a < lim; ) {
    sim_printf ("%d:\t", a);







|











|







7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
        }
    }
return reason;
}

/* Evaluate command */

t_stat eval_cmd (int32 flg, CONST char *cptr)
{
DEVICE *dptr = sim_dflt_dev;
int32 i, rdx, a, lim;
t_stat r;

GET_SWITCHES (cptr);
GET_RADIX (rdx, dptr->dradix);
for (i = 0; i < sim_emax; i++)
sim_eval[i] = 0;
if (*cptr == 0)
    return SCPE_2FARG;
if ((r = parse_sym ((CONST char *)cptr, 0, dptr->units, sim_eval, sim_switches)) > 0) {
    sim_eval[0] = get_uint (cptr, rdx, width_mask[dptr->dwidth], &r);
    if (r != SCPE_OK)
        return r;
    }
lim = 1 - r;
for (i = a = 0; a < lim; ) {
    sim_printf ("%d:\t", a);
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
#if defined(HAVE_DLOPEN)
static int initialized = 0;
typedef char *(*readline_func)(const char *);
static readline_func p_readline = NULL;
typedef void (*add_history_func)(const char *);
static add_history_func p_add_history = NULL;

if (!initialized) {
    initialized = 1;
    void *handle;

#define S__STR_QUOTE(tok) #tok
#define S__STR(tok) S__STR_QUOTE(tok)
    handle = dlopen("libncurses." S__STR(HAVE_DLOPEN), RTLD_NOW|RTLD_GLOBAL);
    handle = dlopen("libcurses." S__STR(HAVE_DLOPEN), RTLD_NOW|RTLD_GLOBAL);







|







7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
#if defined(HAVE_DLOPEN)
static int initialized = 0;
typedef char *(*readline_func)(const char *);
static readline_func p_readline = NULL;
typedef void (*add_history_func)(const char *);
static add_history_func p_add_history = NULL;

if (prompt && (!initialized)) {
    initialized = 1;
    void *handle;

#define S__STR_QUOTE(tok) #tok
#define S__STR(tok) S__STR_QUOTE(tok)
    handle = dlopen("libncurses." S__STR(HAVE_DLOPEN), RTLD_NOW|RTLD_GLOBAL);
    handle = dlopen("libcurses." S__STR(HAVE_DLOPEN), RTLD_NOW|RTLD_GLOBAL);
7084
7085
7086
7087
7088
7089
7090

7091
7092
7093
7094
7095
7096
7097

return cptr;
}

/* get_glyph            get next glyph (force upper case)
   get_glyph_nc         get next glyph (no conversion)
   get_glyph_quoted     get next glyph (potentially enclosed in quotes, no conversion)

   get_glyph_gen        get next glyph (general case)

   Inputs:
        iptr        =   pointer to input string
        optr        =   pointer to output string
        mchar       =   optional end of glyph character
        uc          =   TRUE for convert to upper case (_gen only)







>







7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552

return cptr;
}

/* get_glyph            get next glyph (force upper case)
   get_glyph_nc         get next glyph (no conversion)
   get_glyph_quoted     get next glyph (potentially enclosed in quotes, no conversion)
   get_glyph_cmd        get command glyph (force upper case, extract leading !)
   get_glyph_gen        get next glyph (general case)

   Inputs:
        iptr        =   pointer to input string
        optr        =   pointer to output string
        mchar       =   optional end of glyph character
        uc          =   TRUE for convert to upper case (_gen only)
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157










7158
7159
7160
7161
7162
7163
7164
if (mchar && (*iptr == mchar))                          /* skip terminator */
    iptr++;
while (sim_isspace (*iptr))                             /* absorb spaces */
    iptr++;
return iptr;
}

char *get_glyph (const char *iptr, char *optr, char mchar)
{
return (char *)get_glyph_gen (iptr, optr, mchar, TRUE, FALSE, 0);
}

char *get_glyph_nc (const char *iptr, char *optr, char mchar)
{
return (char *)get_glyph_gen (iptr, optr, mchar, FALSE, FALSE, 0);
}

char *get_glyph_quoted (const char *iptr, char *optr, char mchar)
{
return (char *)get_glyph_gen (iptr, optr, mchar, FALSE, TRUE, '\\');










}

/* Trim trailing spaces from a string

    Inputs:
        cptr    =       pointer to string
    Outputs:







|

|


|

|


|

|
>
>
>
>
>
>
>
>
>
>







7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
if (mchar && (*iptr == mchar))                          /* skip terminator */
    iptr++;
while (sim_isspace (*iptr))                             /* absorb spaces */
    iptr++;
return iptr;
}

CONST char *get_glyph (const char *iptr, char *optr, char mchar)
{
return (CONST char *)get_glyph_gen (iptr, optr, mchar, TRUE, FALSE, 0);
}

CONST char *get_glyph_nc (const char *iptr, char *optr, char mchar)
{
return (CONST char *)get_glyph_gen (iptr, optr, mchar, FALSE, FALSE, 0);
}

CONST char *get_glyph_quoted (const char *iptr, char *optr, char mchar)
{
return (CONST char *)get_glyph_gen (iptr, optr, mchar, FALSE, TRUE, '\\');
}

CONST char *get_glyph_cmd (const char *iptr, char *optr)
{
/* Tolerate "!subprocess" vs. requiring "! subprocess" */
if ((iptr[0] == '!') && (!sim_isspace(iptr[1]))) {
    strcpy (optr, "!");                     /* return ! as command glyph */
    return (CONST char *)(iptr + 1);        /* and skip over the leading ! */
    }
return (CONST char *)get_glyph_gen (iptr, optr, 0, TRUE, FALSE, 0);
}

/* Trim trailing spaces from a string

    Inputs:
        cptr    =       pointer to string
    Outputs:
7205
7206
7207
7208
7209
7210
7211























7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224

7225




7226
7227
7228
7229
7230
7231
7232
return (c & 0x80) ? 0 : isgraph (c);
}

int sim_isalnum (char c)
{
return (c & 0x80) ? 0 : isalnum (c);
}
























/* get_yn               yes/no question

   Inputs:
        ques    =       pointer to question
        deflt   =       default answer
   Outputs:
        result  =       true if yes, false if no
*/

t_stat get_yn (const char *ques, t_stat deflt)
{
char cbuf[CBUFSIZE], *cptr;






if (sim_rem_cmd_active_line != -1)
    return deflt;
cptr = read_line_p (ques, cbuf, sizeof(cbuf), stdin);
if ((cptr == NULL) || (*cptr == 0))
    return deflt;
if ((*cptr == 'Y') || (*cptr == 'y'))
    return TRUE;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












|
>

>
>
>
>







7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
return (c & 0x80) ? 0 : isgraph (c);
}

int sim_isalnum (char c)
{
return (c & 0x80) ? 0 : isalnum (c);
}

/* strncasecmp() is not available on all platforms */
int sim_strncasecmp (const char* string1, const char* string2, size_t len)
{
size_t i;
unsigned char s1, s2;

for (i=0; i<len; i++) {
    s1 = (unsigned char)string1[i];
    s2 = (unsigned char)string2[i];
    if (sim_islower (s1))
        s1 = (unsigned char)toupper (s1);
    if (sim_islower (s2))
        s2 = (unsigned char)toupper (s2);
    if (s1 < s2)
        return -1;
    if (s1 > s2)
        return 1;
    if (s1 == 0)
        return 0;
    }
return 0;
}

/* get_yn               yes/no question

   Inputs:
        ques    =       pointer to question
        deflt   =       default answer
   Outputs:
        result  =       true if yes, false if no
*/

t_stat get_yn (const char *ques, t_stat deflt)
{
char cbuf[CBUFSIZE];
const char *cptr;

if (sim_switches & SWMASK ('Y'))
    return TRUE;
if (sim_switches & SWMASK ('N'))
    return FALSE;
if (sim_rem_cmd_active_line != -1)
    return deflt;
cptr = read_line_p (ques, cbuf, sizeof(cbuf), stdin);
if ((cptr == NULL) || (*cptr == 0))
    return deflt;
if ((*cptr == 'Y') || (*cptr == 'y'))
    return TRUE;
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
   Outputs:
        val     =       value
*/

t_value get_uint (const char *cptr, uint32 radix, t_value max, t_stat *status)
{
t_value val;
const char *tptr;

*status = SCPE_OK;
val = strtotv (cptr, &tptr, radix);
if ((cptr == tptr) || (val > max))
    *status = SCPE_ARG;
else {
    while (sim_isspace (*tptr)) tptr++;
    if (*tptr != 0)
        *status = SCPE_ARG;
    }







|


|







7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
   Outputs:
        val     =       value
*/

t_value get_uint (const char *cptr, uint32 radix, t_value max, t_stat *status)
{
t_value val;
CONST char *tptr;

*status = SCPE_OK;
val = strtotv ((CONST char *)cptr, &tptr, radix);
if ((cptr == tptr) || (val > max))
    *status = SCPE_ARG;
else {
    while (sim_isspace (*tptr)) tptr++;
    if (*tptr != 0)
        *status = SCPE_ARG;
    }
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290




7291
7292
7293
7294





7295
7296
7297
7298
7299
7300


7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320

7321
7322
7323
7324
7325
7326
7327
        max     =       default high value
        term    =       terminating character, 0 if none
   Outputs:
        tptr    =       input pointer after processing
                        NULL if error
*/

const char *get_range (DEVICE *dptr, const char *cptr, t_addr *lo, t_addr *hi,
    uint32 rdx, t_addr max, char term)
{
const char *tptr;

if (max && strncmp (cptr, "ALL", strlen ("ALL")) == 0) {    /* ALL? */
    tptr = cptr + strlen ("ALL");
    *lo = 0;
    *hi = max;
    }
else {
    if (strncmp (cptr, "$", strlen ("$")) == 0) {           /* $? */




        tptr = cptr + strlen ("$");
        *hi = *lo = (t_addr)sim_last_val;
        }
    else {





        if (dptr && sim_vm_parse_addr)                      /* get low */
            *lo = sim_vm_parse_addr (dptr, (char *)cptr, (char **)&tptr);
        else
            *lo = (t_addr) strtotv (cptr, &tptr, rdx);
        if (cptr == tptr)                                   /* error? */
                return NULL;


        if ((*tptr == '-') || (*tptr == ':')) {             /* range? */
            cptr = tptr + 1;
            if (dptr && sim_vm_parse_addr)                  /* get high */
                *hi = sim_vm_parse_addr (dptr, (char *)cptr, (char **)&tptr);
            else *hi = (t_addr) strtotv (cptr, &tptr, rdx);
            if (cptr == tptr)
                return NULL;
            if (*lo > *hi)
                return NULL;
            }
        else if (*tptr == '/') {                            /* relative? */
            cptr = tptr + 1;
            *hi = (t_addr) strtotv (cptr, &tptr, rdx);      /* get high */
            if ((cptr == tptr) || (*hi == 0))
                return NULL;
            *hi = *lo + *hi - 1;
            }
        else *hi = *lo;
        }
    }

if (term && (*tptr++ != term))
    return NULL;
return tptr;
}

/* sim_decode_quoted_string








|


|







|
>
>
>
>
|
|


>
>
>
>
>
|
|
|
|
|
|
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>







7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823

7824
7825
7826
7827
7828
7829
7830
7831
        max     =       default high value
        term    =       terminating character, 0 if none
   Outputs:
        tptr    =       input pointer after processing
                        NULL if error
*/

CONST char *get_range (DEVICE *dptr, CONST char *cptr, t_addr *lo, t_addr *hi,
    uint32 rdx, t_addr max, char term)
{
CONST char *tptr;

if (max && strncmp (cptr, "ALL", strlen ("ALL")) == 0) {    /* ALL? */
    tptr = cptr + strlen ("ALL");
    *lo = 0;
    *hi = max;
    }
else {
    if ((strncmp (cptr, ".", strlen (".")) == 0) &&             /* .? */
        ((cptr[1] == '\0') ||
         (cptr[1] == '-')  ||
         (cptr[1] == ':')  ||
         (cptr[1] == '/'))) {
        tptr = cptr + strlen (".");
        *lo = *hi = sim_last_addr;
        }
    else {
        if (strncmp (cptr, "$", strlen ("$")) == 0) {           /* $? */
            tptr = cptr + strlen ("$");
            *hi = *lo = (t_addr)sim_last_val;
            }
        else {
            if (dptr && sim_vm_parse_addr)                      /* get low */
                *lo = sim_vm_parse_addr (dptr, cptr, &tptr);
            else
                *lo = (t_addr) strtotv (cptr, &tptr, rdx);
            if (cptr == tptr)                                   /* error? */
                    return NULL;
            }
        }
    if ((*tptr == '-') || (*tptr == ':')) {             /* range? */
        cptr = tptr + 1;
        if (dptr && sim_vm_parse_addr)                  /* get high */
            *hi = sim_vm_parse_addr (dptr, cptr, &tptr);
        else *hi = (t_addr) strtotv (cptr, &tptr, rdx);
        if (cptr == tptr)
            return NULL;
        if (*lo > *hi)
            return NULL;
        }
    else if (*tptr == '/') {                            /* relative? */
        cptr = tptr + 1;
        *hi = (t_addr) strtotv (cptr, &tptr, rdx);      /* get high */
        if ((cptr == tptr) || (*hi == 0))
            return NULL;
        *hi = *lo + *hi - 1;
        }
    else *hi = *lo;
    }

sim_last_addr = *hi;
if (term && (*tptr++ != term))
    return NULL;
return tptr;
}

/* sim_decode_quoted_string

7504
7505
7506
7507
7508
7509
7510

7511
7512
7513
7514
7515
7516
7517
7518
            break;
        }
if (double_quote_found && (!single_quote_found))
    quote = '\'';
*tptr++ = quote;
while (size--) {
    switch (*iptr) {

        case '\r':  *tptr++ = '\\'; *tptr++ = 'r'; break;
        case '\n':
            *tptr++ = '\\'; *tptr++ = 'n'; break;
        case '\f':
            *tptr++ = '\\'; *tptr++ = 'f'; break;
        case '\t':
            *tptr++ = '\\'; *tptr++ = 't'; break;
        case '\v':







>
|







8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
            break;
        }
if (double_quote_found && (!single_quote_found))
    quote = '\'';
*tptr++ = quote;
while (size--) {
    switch (*iptr) {
        case '\r':
            *tptr++ = '\\'; *tptr++ = 'r'; break;
        case '\n':
            *tptr++ = '\\'; *tptr++ = 'n'; break;
        case '\f':
            *tptr++ = '\\'; *tptr++ = 'f'; break;
        case '\t':
            *tptr++ = '\\'; *tptr++ = 't'; break;
        case '\v':
7560
7561
7562
7563
7564
7565
7566


7567
7568
7569
7570
7571
7572
7573
*/

DEVICE *find_dev (const char *cptr)
{
int32 i;
DEVICE *dptr;



for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    if ((strcmp (cptr, dptr->name) == 0) ||
        (dptr->lname &&
        (strcmp (cptr, dptr->lname) == 0)))
        return dptr;
    }
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i) {







>
>







8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
*/

DEVICE *find_dev (const char *cptr)
{
int32 i;
DEVICE *dptr;

if (cptr == NULL)
    return NULL;
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    if ((strcmp (cptr, dptr->name) == 0) ||
        (dptr->lname &&
        (strcmp (cptr, dptr->lname) == 0)))
        return dptr;
    }
for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i) {
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
        gdptr   =       pointer to global device
   Outputs:
        result  =       pointer to register, NULL if error
        *optr   =       pointer to next character in input string
        *gdptr  =       pointer to device where found
*/

REG *find_reg_glob (const char *cptr, const char **optr, DEVICE **gdptr)
{
int32 i;
DEVICE *dptr;
REG *rptr, *srptr = NULL;

*gdptr = NULL;
for (i = 0; (dptr = sim_devices[i]) != 0; i++) {        /* all dev */







|







8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
        gdptr   =       pointer to global device
   Outputs:
        result  =       pointer to register, NULL if error
        *optr   =       pointer to next character in input string
        *gdptr  =       pointer to device where found
*/

REG *find_reg_glob (CONST char *cptr, CONST char **optr, DEVICE **gdptr)
{
int32 i;
DEVICE *dptr;
REG *rptr, *srptr = NULL;

*gdptr = NULL;
for (i = 0; (dptr = sim_devices[i]) != 0; i++) {        /* all dev */
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
        optr    =       pointer to output pointer (can be null)
        dptr    =       pointer to device
   Outputs:
        result  =       pointer to register, NULL if error
        *optr   =       pointer to next character in input string
*/

REG *find_reg (const char *cptr, const char **optr, DEVICE *dptr)
{
const char *tptr;
REG *rptr;
size_t slnt;

if ((cptr == NULL) || (dptr == NULL) || (dptr->registers == NULL))
    return NULL;
tptr = cptr;
do {







|

|







8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
        optr    =       pointer to output pointer (can be null)
        dptr    =       pointer to device
   Outputs:
        result  =       pointer to register, NULL if error
        *optr   =       pointer to next character in input string
*/

REG *find_reg (CONST char *cptr, CONST char **optr, DEVICE *dptr)
{
CONST char *tptr;
REG *rptr;
size_t slnt;

if ((cptr == NULL) || (dptr == NULL) || (dptr->registers == NULL))
    return NULL;
tptr = cptr;
do {
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
   Inputs:
        cptr    =       pointer to input string
   Outputs:
        sw      =       switch bit mask
                        0 if no switches, -1 if error
*/

int32 get_switches (char *cptr)
{
int32 sw;

if (*cptr != '-')
    return 0;
sw = 0;
for (cptr++; (sim_isspace (*cptr) == 0) && (*cptr != 0); cptr++) {







|







8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
   Inputs:
        cptr    =       pointer to input string
   Outputs:
        sw      =       switch bit mask
                        0 if no switches, -1 if error
*/

int32 get_switches (const char *cptr)
{
int32 sw;

if (*cptr != '-')
    return 0;
sw = 0;
for (cptr++; (sim_isspace (*cptr) == 0) && (*cptr != 0); cptr++) {
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
   Inputs:
        cptr    =       pointer to input string
   Outputs:
        ptr     =       pointer to first non-string glyph
                        NULL if error
*/

char *get_sim_sw (char *cptr)
{
int32 lsw;
char gbuf[CBUFSIZE];

while (*cptr == '-') {                                  /* while switches */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get switch glyph */
    lsw = get_switches (gbuf);                          /* parse */







|







8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
   Inputs:
        cptr    =       pointer to input string
   Outputs:
        ptr     =       pointer to first non-string glyph
                        NULL if error
*/

CONST char *get_sim_sw (CONST char *cptr)
{
int32 lsw;
char gbuf[CBUFSIZE];

while (*cptr == '-') {                                  /* while switches */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get switch glyph */
    lsw = get_switches (gbuf);                          /* parse */
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821

7822
7823
7824
7825
7826
7827
7828
        opt     =       command options
        cptr    =       pointer to input string
   Outputs:
        ptr     =       pointer to next glypsh, NULL if error
        *stat   =       error status
*/

char *get_sim_opt (int32 opt, char *cptr, t_stat *st)
{
int32 t;
char *svptr, gbuf[CBUFSIZE];

DEVICE *tdptr;
UNIT *tuptr;

sim_switches = 0;                                       /* no switches */
sim_ofile = NULL;                                       /* no output file */
sim_schrptr = NULL;                                     /* no search */
sim_schaptr = NULL;                                     /* no search */







|


|
>







8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
        opt     =       command options
        cptr    =       pointer to input string
   Outputs:
        ptr     =       pointer to next glypsh, NULL if error
        *stat   =       error status
*/

CONST char *get_sim_opt (int32 opt, CONST char *cptr, t_stat *st)
{
int32 t;
char gbuf[CBUFSIZE];
CONST char *svptr;
DEVICE *tdptr;
UNIT *tuptr;

sim_switches = 0;                                       /* no switches */
sim_ofile = NULL;                                       /* no output file */
sim_schrptr = NULL;                                     /* no search */
sim_schaptr = NULL;                                     /* no search */
7881
7882
7883
7884
7885
7886
7887




























7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
        sim_dfunit = tuptr;
        sim_opt_out |= CMD_OPT_DFT;                     /* got default */
        }
    else return svptr;                                  /* not rec, break out */
    }
return cptr;
}





























/* Match file extension

   Inputs:
        fnam    =       file name
        ext     =       extension, without period
   Outputs:
        cp      =       pointer to final '.' if match, NULL if not
*/

char *match_ext (char *fnam, const char *ext)
{
char *pptr, *fptr;
const char *eptr;

if ((fnam == NULL) || (ext == NULL))                    /* bad arguments? */
     return NULL;
pptr = strrchr (fnam, '.');                             /* find last . */
if (pptr) {                                             /* any? */
    for (fptr = pptr + 1, eptr = ext;                   /* match characters */







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|

|







8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
        sim_dfunit = tuptr;
        sim_opt_out |= CMD_OPT_DFT;                     /* got default */
        }
    else return svptr;                                  /* not rec, break out */
    }
return cptr;
}

/* put_switches         put switches into string

   Inputs:
        buf     =       pointer to string buffer
        bufsize =       size of string buffer
        sw      =       switch bit mask
   Outputs:
        buf     =       buffer with switches converted to text
*/

const char *put_switches (char *buf, size_t bufsize, uint32 sw)
{
char *optr = buf;
int32 bit;

memset (buf, 0, bufsize);
if ((sw == 0) || (bufsize < 3))
    return buf;
--bufsize;                          /* leave room for terminating NUL */
*optr++ = '-';
for (bit=0; bit <= ('Z'-'A'); bit++)
    if (sw & (1 << bit))
        if ((size_t)(optr - buf) < bufsize)
            *optr++ = 'A' + bit;
return buf;
}


/* Match file extension

   Inputs:
        fnam    =       file name
        ext     =       extension, without period
   Outputs:
        cp      =       pointer to final '.' if match, NULL if not
*/

CONST char *match_ext (CONST char *fnam, const char *ext)
{
CONST char *pptr, *fptr;
const char *eptr;

if ((fnam == NULL) || (ext == NULL))                    /* bad arguments? */
     return NULL;
pptr = strrchr (fnam, '.');                             /* find last . */
if (pptr) {                                             /* any? */
    for (fptr = pptr + 1, eptr = ext;                   /* match characters */
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
        radix   =       radix for numbers
        schptr =        pointer to search table
   Outputs:
        return =        NULL if error
                        schptr if valid search specification
*/

SCHTAB *get_rsearch (const char *cptr, int32 radix, SCHTAB *schptr)
{
int32 c, logop, cmpop;
t_value logval, cmpval;
const char *sptr;
const char *tptr;
const char logstr[] = "|&^", cmpstr[] = "=!><";

logval = cmpval = 0;
if (*cptr == 0)                                         /* check for clause */
    return NULL;
for (logop = cmpop = -1; (c = *cptr++); ) {             /* loop thru clauses */
    if ((sptr = strchr (logstr, c))) {                  /* check for mask */
        logop = (int32)(sptr - logstr);
        logval = strtotv (cptr, &tptr, radix);
        if (cptr == tptr)
            return NULL;
        cptr = (char *)tptr;
        }
    else if ((sptr = strchr (cmpstr, c))) {             /* check for boolop */
        cmpop = (int32)(sptr - cmpstr);
        if (*cptr == '=') {
            cmpop = cmpop + strlen (cmpstr);
            cptr++;
            }
        cmpval = strtotv (cptr, &tptr, radix);
        if (cptr == tptr)
            return NULL;
        cptr = (char *)tptr;
        }
    else return NULL;
    }                                                   /* end for */
if (schptr->count != 1) {
    free (schptr->mask);
    schptr->mask = (t_value *)calloc (sim_emax, sizeof(*schptr->mask));
    free (schptr->comp);







|




|











|










|







8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
        radix   =       radix for numbers
        schptr =        pointer to search table
   Outputs:
        return =        NULL if error
                        schptr if valid search specification
*/

SCHTAB *get_rsearch (CONST char *cptr, int32 radix, SCHTAB *schptr)
{
int32 c, logop, cmpop;
t_value logval, cmpval;
const char *sptr;
CONST char *tptr;
const char logstr[] = "|&^", cmpstr[] = "=!><";

logval = cmpval = 0;
if (*cptr == 0)                                         /* check for clause */
    return NULL;
for (logop = cmpop = -1; (c = *cptr++); ) {             /* loop thru clauses */
    if ((sptr = strchr (logstr, c))) {                  /* check for mask */
        logop = (int32)(sptr - logstr);
        logval = strtotv (cptr, &tptr, radix);
        if (cptr == tptr)
            return NULL;
        cptr = tptr;
        }
    else if ((sptr = strchr (cmpstr, c))) {             /* check for boolop */
        cmpop = (int32)(sptr - cmpstr);
        if (*cptr == '=') {
            cmpop = cmpop + strlen (cmpstr);
            cptr++;
            }
        cmpval = strtotv (cptr, &tptr, radix);
        if (cptr == tptr)
            return NULL;
        cptr = tptr;
        }
    else return NULL;
    }                                                   /* end for */
if (schptr->count != 1) {
    free (schptr->mask);
    schptr->mask = (t_value *)calloc (sim_emax, sizeof(*schptr->mask));
    free (schptr->comp);
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
        radix   =       radix for numbers
        schptr =        pointer to search table
   Outputs:
        return =        NULL if error
                        schptr if valid search specification
*/

SCHTAB *get_asearch (const char *cptr, int32 radix, SCHTAB *schptr)
{
int32 c, logop, cmpop;
t_value *logval, *cmpval;
t_stat reason;
const char *ocptr = cptr;
const char *sptr;
char gbuf[CBUFSIZE];
const char logstr[] = "|&^", cmpstr[] = "=!><";

if (*cptr == 0)                                         /* check for clause */
    return NULL;
logval = (t_value *)calloc (sim_emax, sizeof(*logval));







|




|







8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
        radix   =       radix for numbers
        schptr =        pointer to search table
   Outputs:
        return =        NULL if error
                        schptr if valid search specification
*/

SCHTAB *get_asearch (CONST char *cptr, int32 radix, SCHTAB *schptr)
{
int32 c, logop, cmpop;
t_value *logval, *cmpval;
t_stat reason;
CONST char *ocptr = cptr;
const char *sptr;
char gbuf[CBUFSIZE];
const char logstr[] = "|&^", cmpstr[] = "=!><";

if (*cptr == 0)                                         /* check for clause */
    return NULL;
logval = (t_value *)calloc (sim_emax, sizeof(*logval));
8045
8046
8047
8048
8049
8050
8051



8052
8053
8054
8055
8056



8057
8058
8059
8060
8061
8062
8063
    schptr->comp = (t_value *)calloc (sim_emax, sizeof(*schptr->comp));
    }
if (logop >= 0) {
    schptr->logic = logop;
    free (schptr->mask);
    schptr->mask = logval;
    }



if (cmpop >= 0) {
    schptr->boolop = cmpop;
    free (schptr->comp);
    schptr->comp = cmpval;
    }



return schptr;
}

/* Test value against search specification

   Inputs:
        val    =        value list to test







>
>
>





>
>
>







8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
    schptr->comp = (t_value *)calloc (sim_emax, sizeof(*schptr->comp));
    }
if (logop >= 0) {
    schptr->logic = logop;
    free (schptr->mask);
    schptr->mask = logval;
    }
else {
    free (logval);
    }
if (cmpop >= 0) {
    schptr->boolop = cmpop;
    free (schptr->comp);
    schptr->comp = cmpval;
    }
else {
    free (cmpval);
    }
return schptr;
}

/* Test value against search specification

   Inputs:
        val    =        value list to test
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
        radix   =       radix for input
   Outputs:
        value   =       converted value

   On an error, the endptr will equal the inptr.
*/

t_value strtotv (const char *inptr, const char **endptr, uint32 radix)
{
int32 nodigit;
t_value val;
uint32 c, digit;

*endptr = (char *)inptr;                                /* assume fails */
if ((radix < 2) || (radix > 36))
    return 0;
while (sim_isspace (*inptr))                                /* bypass white space */
    inptr++;
val = 0;
nodigit = 1;
for (c = *inptr; sim_isalnum(c); c = *++inptr) {        /* loop through char */
    if (sim_islower (c))
        c = toupper (c);
    if (sim_isdigit (c))                                /* digit? */
        digit = c - (uint32) '0';
    else if (radix <= 10)                               /* stop if not expected */
        break;
    else digit = c + 10 - (uint32) 'A';                 /* convert letter */
    if (digit >= radix)                                 /* valid in radix? */
        return 0;
    val = (val * radix) + digit;                        /* add to value */
    nodigit = 0;
    }
if (nodigit)                                            /* no digits? */
    return 0;
*endptr = (char *)inptr;                                /* result pointer */
return val;
}

/* fprint_val - general radix printing routine

   Inputs:
        stream  =       stream designator







|





|


|


















|







8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
        radix   =       radix for input
   Outputs:
        value   =       converted value

   On an error, the endptr will equal the inptr.
*/

t_value strtotv (CONST char *inptr, CONST char **endptr, uint32 radix)
{
int32 nodigit;
t_value val;
uint32 c, digit;

*endptr = inptr;                                        /* assume fails */
if ((radix < 2) || (radix > 36))
    return 0;
while (sim_isspace (*inptr))                            /* bypass white space */
    inptr++;
val = 0;
nodigit = 1;
for (c = *inptr; sim_isalnum(c); c = *++inptr) {        /* loop through char */
    if (sim_islower (c))
        c = toupper (c);
    if (sim_isdigit (c))                                /* digit? */
        digit = c - (uint32) '0';
    else if (radix <= 10)                               /* stop if not expected */
        break;
    else digit = c + 10 - (uint32) 'A';                 /* convert letter */
    if (digit >= radix)                                 /* valid in radix? */
        return 0;
    val = (val * radix) + digit;                        /* add to value */
    nodigit = 0;
    }
if (nodigit)                                            /* no digits? */
    return 0;
*endptr = inptr;                                        /* result pointer */
return val;
}

/* fprint_val - general radix printing routine

   Inputs:
        stream  =       stream designator
8256
8257
8258
8259
8260
8261
8262

8263
8264
8265
8266
8267
8268
8269
            }
        if ((MAX_WIDTH - (ndigits + commas)) < d)
            d = MAX_WIDTH - (ndigits + commas);
        break;
    }
if (!buffer)
    return strlen(dbuf+d);

if (width < strlen(dbuf+d))
    return SCPE_IOERR;
strcpy(buffer, dbuf+d);
return SCPE_OK;
}

t_stat fprint_val (FILE *stream, t_value val, uint32 radix,







>







8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
            }
        if ((MAX_WIDTH - (ndigits + commas)) < d)
            d = MAX_WIDTH - (ndigits + commas);
        break;
    }
if (!buffer)
    return strlen(dbuf+d);
*buffer = '\0';
if (width < strlen(dbuf+d))
    return SCPE_IOERR;
strcpy(buffer, dbuf+d);
return SCPE_OK;
}

t_stat fprint_val (FILE *stream, t_value val, uint32 radix,
8295
8296
8297
8298
8299
8300
8301




















































































8302
8303
8304
8305
8306
8307
8308
    if (fputs (dbuf, sim_log) == EOF)
        return SCPE_IOERR;
if (sim_deb && (sim_deb != stdout))
    if (fputs (dbuf, sim_deb) == EOF)
        return SCPE_IOERR;
return SCPE_OK;
}





















































































/* Event queue package

        sim_activate            add entry to event queue
        sim_activate_abs        add entry to event queue even if event already scheduled
        sim_activate_notbefore  add entry to event queue even if event already scheduled
                                but not before the specified time







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
    if (fputs (dbuf, sim_log) == EOF)
        return SCPE_IOERR;
if (sim_deb && (sim_deb != stdout))
    if (fputs (dbuf, sim_deb) == EOF)
        return SCPE_IOERR;
return SCPE_OK;
}

const char *sim_fmt_secs (double seconds)
{
static char buf[60];
char frac[16] = "";
const char *sign = "";
double val = seconds;
double days, hours, mins, secs, msecs, usecs;

if (val == 0.0)
    return "";
if (val < 0.0) {
    sign = "-";
    val = -val;
    }
days = floor (val / (24.0*60.0*60.0));
val -= (days * 24.0*60.0*60.0);
hours = floor (val / (60.0*60.0));
val -= (hours * 60.0 * 60.0);
mins = floor (val / 60.0);
val -= (mins * 60.0);
secs = floor (val);
val -= secs;
val *= 1000.0;
msecs = floor (val);
val -= msecs;
val *= 1000.0;
usecs = floor (val+0.5);
if (usecs == 1000.0) {
    usecs = 0.0;
    msecs += 1;
    }
if ((msecs > 0.0) || (usecs > 0.0)) {
    sprintf (frac, ".%03.0f%03.0f", msecs, usecs);
    while (frac[strlen (frac) - 1] == '0')
        frac[strlen (frac) - 1] = '\0';
    if (strlen (frac) == 1)
        frac[0] = '\0';
    }
if (days > 0)
    sprintf (buf, "%s%.0f day%s %02.0f:%02.0f:%02.0f%s hour%s", sign, days, (days != 1)? "s" : "", hours, mins, secs, frac, (days == 1) ? "s" : "");
else
    if (hours > 0)
        sprintf (buf, "%s%.0f:%02.0f:%02.0f%s hour", sign, hours, mins, secs, frac);
    else
        if (mins > 0)
            sprintf (buf, "%s%.0f:%02.0f%s minute", sign, mins, secs, frac);
        else
            if (secs > 0)
                sprintf (buf, "%s%.0f%s second", sign, secs, frac);
            else
                if (msecs > 0) {
                    if (usecs > 0)
                        sprintf (buf, "%s%.0f.%s msec", sign, msecs, frac+4);
                    else
                        sprintf (buf, "%s%.0f msec", sign, msecs);
                    }
                else
                    sprintf (buf, "%s%.0f usec", sign, usecs);
if (0 != strncmp ("1 ", buf, 2))
    strcpy (&buf[strlen (buf)], "s");
return buf;
}

const char *sim_fmt_numeric (double number)
{
static char buf[60];
char tmpbuf[60];
size_t len;
uint32 c;
char *p;

sprintf (tmpbuf, "%.0f", number);
len = strlen (tmpbuf);
for (c=0, p=buf; c < len; c++) {
    if ((c > 0) &&
        (sim_isdigit (tmpbuf[c])) &&
        (0 == ((len - c) % 3)))
        *(p++) = ',';
    *(p++) = tmpbuf[c];
    }
*p = '\0';
return buf;
}

/* Event queue package

        sim_activate            add entry to event queue
        sim_activate_abs        add entry to event queue even if event already scheduled
        sim_activate_notbefore  add entry to event queue even if event already scheduled
                                but not before the specified time
8346
8347
8348
8349
8350
8351
8352

8353
8354
8355
8356
8357
8358
8359
UPDATE_SIM_TIME;                                        /* update sim time */

if (sim_clock_queue == QUEUE_LIST_END) {                /* queue empty? */
    sim_interval = noqueue_time = NOQUEUE_WAIT;         /* flag queue empty */
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Queue Empty New Interval = %d\n", sim_interval);
    return SCPE_OK;
    }

do {
    uptr = sim_clock_queue;                             /* get first */
    sim_clock_queue = uptr->next;                       /* remove first */
    uptr->next = NULL;                                  /* hygiene */
    uptr->time = 0;
    if (sim_clock_queue != QUEUE_LIST_END)
        sim_interval = sim_clock_queue->time;







>







8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
UPDATE_SIM_TIME;                                        /* update sim time */

if (sim_clock_queue == QUEUE_LIST_END) {                /* queue empty? */
    sim_interval = noqueue_time = NOQUEUE_WAIT;         /* flag queue empty */
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Queue Empty New Interval = %d\n", sim_interval);
    return SCPE_OK;
    }
sim_processing_event = TRUE;
do {
    uptr = sim_clock_queue;                             /* get first */
    sim_clock_queue = uptr->next;                       /* remove first */
    uptr->next = NULL;                                  /* hygiene */
    uptr->time = 0;
    if (sim_clock_queue != QUEUE_LIST_END)
        sim_interval = sim_clock_queue->time;
8376
8377
8378
8379
8380
8381
8382

8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396


8397
8398
8399
8400
8401
8402
8403
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Processing Queue Complete New Interval = %d\n", sim_interval);
    }
else
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Processing Queue Complete New Interval = %d(%s)\n", sim_interval, sim_uname(sim_clock_queue));

if ((reason == SCPE_OK) && stop_cpu)
    reason = SCPE_STOP;

return reason;
}

/* sim_activate - activate (queue) event

   Inputs:
        uptr    =       pointer to unit
        event_time =    relative timeout
   Outputs:
        reason  =       result (SCPE_OK if ok)
*/

t_stat sim_activate (UNIT *uptr, int32 event_time)
{


return _sim_activate (uptr, event_time);
}

t_stat _sim_activate (UNIT *uptr, int32 event_time)
{
UNIT *cptr, *prvptr;
int32 accum;







>














>
>







9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Processing Queue Complete New Interval = %d\n", sim_interval);
    }
else
    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Processing Queue Complete New Interval = %d(%s)\n", sim_interval, sim_uname(sim_clock_queue));

if ((reason == SCPE_OK) && stop_cpu)
    reason = SCPE_STOP;
sim_processing_event = FALSE;
return reason;
}

/* sim_activate - activate (queue) event

   Inputs:
        uptr    =       pointer to unit
        event_time =    relative timeout
   Outputs:
        reason  =       result (SCPE_OK if ok)
*/

t_stat sim_activate (UNIT *uptr, int32 event_time)
{
if (uptr->dynflags & UNIT_TMR_UNIT)
    return sim_timer_activate (uptr, event_time);
return _sim_activate (uptr, event_time);
}

t_stat _sim_activate (UNIT *uptr, int32 event_time)
{
UNIT *cptr, *prvptr;
int32 accum;
8477
8478
8479
8480
8481
8482
8483
8484
8485







8486
8487
8488





8489
8490
8491
8492
8493
8494
8495
8496
   Inputs:
        uptr    =       pointer to unit
        usec_delay =    relative timeout (in microseconds)
   Outputs:
        reason  =       result (SCPE_OK if ok)
*/

t_stat sim_activate_after (UNIT *uptr, int32 event_time)
{







return _sim_activate_after (uptr, event_time);
}






t_stat _sim_activate_after (UNIT *uptr, int32 usec_delay)
{
if (sim_is_active (uptr))                               /* already active? */
    return SCPE_OK;
AIO_ACTIVATE (_sim_activate_after, uptr, usec_delay);
return sim_timer_activate_after (uptr, usec_delay);
}








|

>
>
>
>
>
>
>



>
>
>
>
>
|







9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
   Inputs:
        uptr    =       pointer to unit
        usec_delay =    relative timeout (in microseconds)
   Outputs:
        reason  =       result (SCPE_OK if ok)
*/

t_stat sim_activate_after_abs (UNIT *uptr, uint32 event_time)
{
return _sim_activate_after_abs (uptr, event_time);
}

t_stat _sim_activate_after_abs (UNIT *uptr, uint32 event_time)
{
AIO_ACTIVATE (_sim_activate_after_abs, uptr, event_time);
sim_cancel (uptr);
return _sim_activate_after (uptr, event_time);
}

t_stat sim_activate_after (UNIT *uptr, uint32 usec_delay)
{
return _sim_activate_after (uptr, usec_delay);
}

t_stat _sim_activate_after (UNIT *uptr, uint32 usec_delay)
{
if (sim_is_active (uptr))                               /* already active? */
    return SCPE_OK;
AIO_ACTIVATE (_sim_activate_after, uptr, usec_delay);
return sim_timer_activate_after (uptr, usec_delay);
}

8535
8536
8537
8538
8539
8540
8541

8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580



8581
8582
8583
8584
8585

8586
8587
8588
8589
8590
8591
8592
8593
    nptr->time += (uptr->next) ? 0 : uptr->time;
if (!uptr->next)
    uptr->time = 0;
if (sim_clock_queue != QUEUE_LIST_END)
    sim_interval = sim_clock_queue->time;
else sim_interval = noqueue_time = NOQUEUE_WAIT;
if (uptr->next) {

    if (sim_deb) {
        sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Cancel failed for %s\n", sim_uname(uptr));
        fclose(sim_deb);
        }
    abort ();
    }
return SCPE_OK;
}

/* sim_is_active - test for entry in queue

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        TRUE if unit is busy, FALSE inactive
*/

t_bool sim_is_active (UNIT *uptr)
{
AIO_VALIDATE;
AIO_UPDATE_QUEUE;
return (((uptr->next) || AIO_IS_ACTIVE(uptr)) ? TRUE : FALSE);
}

/* sim_activate_time - return activation time

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        absolute activation time + 1, 0 if inactive
*/

int32 sim_activate_time (UNIT *uptr)
{
UNIT *cptr;
int32 accum = 0;

AIO_VALIDATE;
AIO_RETURN_TIME(uptr);



for (cptr = sim_clock_queue; cptr != QUEUE_LIST_END; cptr = cptr->next) {
    if (cptr == sim_clock_queue) {
        if (sim_interval > 0)
            accum = accum + sim_interval;
        }

    else accum = accum + cptr->time;
    if (cptr == uptr)
        return accum + 1;
    }
return 0;
}

/* sim_gtime - return global time







>
|
<

<

















|













|


|
>
>
>





>
|







9178
9179
9180
9181
9182
9183
9184
9185
9186

9187

9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
    nptr->time += (uptr->next) ? 0 : uptr->time;
if (!uptr->next)
    uptr->time = 0;
if (sim_clock_queue != QUEUE_LIST_END)
    sim_interval = sim_clock_queue->time;
else sim_interval = noqueue_time = NOQUEUE_WAIT;
if (uptr->next) {
    sim_printf ("Cancel failed for %s\n", sim_uname(uptr));
    if (sim_deb)

        fclose(sim_deb);

    abort ();
    }
return SCPE_OK;
}

/* sim_is_active - test for entry in queue

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        TRUE if unit is busy, FALSE inactive
*/

t_bool sim_is_active (UNIT *uptr)
{
AIO_VALIDATE;
AIO_UPDATE_QUEUE;
return (((uptr->next) || AIO_IS_ACTIVE(uptr) || ((uptr->dynflags & UNIT_TMR_UNIT) ? sim_timer_is_active (uptr) : FALSE)) ? TRUE : FALSE);
}

/* sim_activate_time - return activation time

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        absolute activation time + 1, 0 if inactive
*/

int32 sim_activate_time (UNIT *uptr)
{
UNIT *cptr;
int32 accum;

AIO_VALIDATE;
accum = sim_timer_activate_time (uptr);             \
if (accum >= 0)                                           \
    return accum;                                         \
accum = 0;
for (cptr = sim_clock_queue; cptr != QUEUE_LIST_END; cptr = cptr->next) {
    if (cptr == sim_clock_queue) {
        if (sim_interval > 0)
            accum = accum + sim_interval;
        }
    else
        accum = accum + cptr->time;
    if (cptr == uptr)
        return accum + 1;
    }
return 0;
}

/* sim_gtime - return global time
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644


8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667














8668
8669
8670
8671

8672
8673
8674
8675
8676
8677
8678
return cnt;
}

/* Breakpoint package.  This module replaces the VM-implemented one
   instruction breakpoint capability.

   Breakpoints are stored in table sim_brk_tab, which is ordered by address for
   efficient binary searching.  A breakpoint consists of a four entry structure:

        addr                    address of the breakpoint
        type                    types of breakpoints set on the address
                                a bit mask representing letters A-Z
        cnt                     number of iterations before breakp is taken
        action                  pointer command string to be executed
                                when break is taken



   sim_brk_summ is a summary of the types of breakpoints that are currently set (it
   is the bitwise OR of all the type fields).  A simulator need only check for
   a breakpoint of type X if bit SWMASK('X') is set in sim_brk_sum.

   The package contains the following public routines:

        sim_brk_init            initialize
        sim_brk_set             set breakpoint
        sim_brk_clr             clear breakpoint
        sim_brk_clrall          clear all breakpoints
        sim_brk_show            show breakpoint
        sim_brk_showall         show all breakpoints
        sim_brk_test            test for breakpoint
        sim_brk_npc             PC has been changed
        sim_brk_getact          get next action
        sim_brk_clract          clear pending actions

   Initialize breakpoint system.
*/

t_stat sim_brk_init (void)
{














sim_brk_lnt = SIM_BRK_INILNT;
sim_brk_tab = (BRKTAB *) calloc (sim_brk_lnt, sizeof (BRKTAB));
if (sim_brk_tab == NULL)
    return SCPE_MEM;

sim_brk_ent = sim_brk_ins = 0;
sim_brk_clract ();
sim_brk_npc (0);
return SCPE_OK;
}

/* Search for a breakpoint in the sorted breakpoint table */







|







>
>



|



















>
>
>
>
>
>
>
>
>
>
>
>
>
>

|


>







9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
return cnt;
}

/* Breakpoint package.  This module replaces the VM-implemented one
   instruction breakpoint capability.

   Breakpoints are stored in table sim_brk_tab, which is ordered by address for
   efficient binary searching.  A breakpoint consists of a six entry structure:

        addr                    address of the breakpoint
        type                    types of breakpoints set on the address
                                a bit mask representing letters A-Z
        cnt                     number of iterations before breakp is taken
        action                  pointer command string to be executed
                                when break is taken
        next                    list of other breakpoints with the same addr specifier
        time_fired              array of when this breakpoint was fired for each class

   sim_brk_summ is a summary of the types of breakpoints that are currently set (it
   is the bitwise OR of all the type fields).  A simulator need only check for
   a breakpoint of type X if bit SWMASK('X') is set in sim_brk_summ.

   The package contains the following public routines:

        sim_brk_init            initialize
        sim_brk_set             set breakpoint
        sim_brk_clr             clear breakpoint
        sim_brk_clrall          clear all breakpoints
        sim_brk_show            show breakpoint
        sim_brk_showall         show all breakpoints
        sim_brk_test            test for breakpoint
        sim_brk_npc             PC has been changed
        sim_brk_getact          get next action
        sim_brk_clract          clear pending actions

   Initialize breakpoint system.
*/

t_stat sim_brk_init (void)
{
int32 i;

for (i=0; i<sim_brk_lnt; i++) {
    BRKTAB *bp = sim_brk_tab[i];

    while (bp) {
        BRKTAB *bpt = bp->next;

        free (bp->act);
        free (bp);
        bp = bpt;
        }
    }
memset (sim_brk_tab, 0, sim_brk_lnt*sizeof (BRKTAB*));
sim_brk_lnt = SIM_BRK_INILNT;
sim_brk_tab = (BRKTAB **) realloc (sim_brk_tab, sim_brk_lnt*sizeof (BRKTAB*));
if (sim_brk_tab == NULL)
    return SCPE_MEM;
memset (sim_brk_tab, 0, sim_brk_lnt*sizeof (BRKTAB*));
sim_brk_ent = sim_brk_ins = 0;
sim_brk_clract ();
sim_brk_npc (0);
return SCPE_OK;
}

/* Search for a breakpoint in the sorted breakpoint table */
8686
8687
8688
8689
8690
8691
8692
8693
8694

8695

8696
8697
8698
8699
8700
8701
8702
8703
8704













8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725

8726

8727
8728
8729
8730

8731



8732
8733
8734
8735

8736
8737
8738
8739
8740
8741
8742
8743
8744
8745

8746
8747

8748


8749
8750
8751
8752
8753






8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778

8779
8780
8781
8782
8783
8784

8785
8786
8787




8788
8789
8790







8791



8792

8793

8794



8795
8796
8797
8798
8799
8800
8801
8802
8803
8804


8805
8806
8807


8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
    sim_brk_ins = 0;                                    /* insrt at head */
    return NULL;                                        /* sch fails */
    }
lo = 0;                                                 /* initial bounds */
hi = sim_brk_ent - 1;
do {
    p = (lo + hi) >> 1;                                 /* probe */
    bp = sim_brk_tab + p;                               /* table addr */
    if (loc == bp->addr)                                /* match? */

        return bp;

    else if (loc < bp->addr)                            /* go down? p is upper */
        hi = p - 1;
    else lo = p + 1;                                    /* go up? p is lower */
    } while (lo <= hi);
if (loc < bp->addr)                                     /* insrt before or */
    sim_brk_ins = p;
else sim_brk_ins = p + 1;                               /* after last sch */
return NULL;
}














/* Insert a breakpoint */

BRKTAB *sim_brk_new (t_addr loc)
{
int32 i, t;
BRKTAB *bp, *newp;

if (sim_brk_ins < 0)
    return NULL;
if (sim_brk_ent >= sim_brk_lnt) {                       /* out of space? */
    t = sim_brk_lnt + SIM_BRK_INILNT;                   /* new size */
    newp = (BRKTAB *) calloc (t, sizeof (BRKTAB));      /* new table */
    if (newp == NULL)                                   /* can't extend */
        return NULL;
    for (i = 0; i < sim_brk_lnt; i++)                   /* copy table */
        *(newp + i) = *(sim_brk_tab + i);
    free (sim_brk_tab);                                 /* free old table */
    sim_brk_tab = newp;                                 /* new base, lnt */
    sim_brk_lnt = t;
    }

if (sim_brk_ins != sim_brk_ent) {                       /* move needed? */

    for (bp = sim_brk_tab + sim_brk_ent;
         bp > sim_brk_tab + sim_brk_ins; bp--)
        *bp = *(bp - 1);
    }

bp = sim_brk_tab + sim_brk_ins;



bp->addr = loc;
bp->typ = 0;
bp->cnt = 0;
bp->act = NULL;

sim_brk_ent = sim_brk_ent + 1;
return bp;
}

/* Set a breakpoint of type sw */

t_stat sim_brk_set (t_addr loc, int32 sw, int32 ncnt, char *act)
{
BRKTAB *bp;


if (sw == 0) sw = sim_brk_dflt;
if ((sim_brk_types & sw) == 0)

    return SCPE_NOFNC;


if ((sw & BRK_TYP_DYN_ALL) && act)                      /* can't specify an action with a dynamic breakpoint */
    return SCPE_ARG;
bp = sim_brk_fnd (loc);                                 /* present? */
if (!bp)                                                /* no, allocate */
    bp = sim_brk_new (loc);






if (!bp)                                                /* still no? mem err */
    return SCPE_MEM;
bp->typ |= sw;                                          /* set type */
bp->cnt = ncnt;                                         /* set count */
if ((!(sw & BRK_TYP_DYN_ALL)) &&                        /* Not Dynamic and */
    (bp->act != NULL) && (act != NULL)) {               /* replace old action? */
    free (bp->act);                                     /* deallocate */
    bp->act = NULL;                                     /* now no action */
    }
if ((act != NULL) && (*act != 0)) {                     /* new action? */
    char *newp = (char *) calloc (CBUFSIZE+1, sizeof (char)); /* alloc buf */
    if (newp == NULL)                                   /* mem err? */
        return SCPE_MEM;
    strncpy (newp, act, CBUFSIZE);                      /* copy action */
    bp->act = newp;                                     /* set pointer */
    }
sim_brk_summ = sim_brk_summ | sw;
return SCPE_OK;
}

/* Clear a breakpoint */

t_stat sim_brk_clr (t_addr loc, int32 sw)
{
BRKTAB *bp = sim_brk_fnd (loc);


if (!bp)                                                /* not there? ok */
    return SCPE_OK;
if (sw == 0)
    sw = SIM_BRK_ALLTYP;
bp->typ = bp->typ & ~sw;

if (bp->typ)                                            /* clear all types? */
    return SCPE_OK;
if (bp->act != NULL)                                    /* deallocate action */




    free (bp->act);
for ( ; bp < (sim_brk_tab + sim_brk_ent - 1); bp++)     /* erase entry */
    *bp = *(bp + 1);







sim_brk_ent = sim_brk_ent - 1;                          /* decrement count */



sim_brk_summ = 0;                                       /* recalc summary */

for (bp = sim_brk_tab; bp < (sim_brk_tab + sim_brk_ent); bp++)

    sim_brk_summ = sim_brk_summ | bp->typ;



return SCPE_OK;
}

/* Clear all breakpoints */

t_stat sim_brk_clrall (int32 sw)
{
BRKTAB *bp;

if (sw == 0) sw = SIM_BRK_ALLTYP;


for (bp = sim_brk_tab; bp < (sim_brk_tab + sim_brk_ent); ) {
    if (bp->typ & sw)
        sim_brk_clr (bp->addr, sw);


    else bp++;
    }
return SCPE_OK;
}

/* Show a breakpoint */

t_stat sim_brk_show (FILE *st, t_addr loc, int32 sw)
{
BRKTAB *bp = sim_brk_fnd (loc);
DEVICE *dptr;
int32 i, any;

if ((sw == 0) || (sw == SWMASK ('C')))
    sw = SIM_BRK_ALLTYP | ((sw == SWMASK ('C')) ? SWMASK ('C') : 0);
if (!bp || (!(bp->typ & sw)))
    return SCPE_OK;







|
|
>

>









>
>
>
>
>
>
>
>
>
>
>
>
>



|


|





|


|
|




>
|
>
|
|
|

>
|
>
>
>

|


>
|





|



>
|
|
>
|
>
>


|

|
>
>
>
>
>
>


<













|







|
>





|
>
|
<
|
>
>
>
>
|
<
|
>
>
>
>
>
>
>
|
>
>
>

>
|
>
|
>
>
>







|

|
>
>
|
<
|
>
>
|








|







9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450

9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481

9482
9483
9484
9485
9486
9487

9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520

9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
    sim_brk_ins = 0;                                    /* insrt at head */
    return NULL;                                        /* sch fails */
    }
lo = 0;                                                 /* initial bounds */
hi = sim_brk_ent - 1;
do {
    p = (lo + hi) >> 1;                                 /* probe */
    bp = sim_brk_tab[p];                                /* table addr */
    if (loc == bp->addr) {                              /* match? */
        sim_brk_ins = p;
        return bp;
        }
    else if (loc < bp->addr)                            /* go down? p is upper */
        hi = p - 1;
    else lo = p + 1;                                    /* go up? p is lower */
    } while (lo <= hi);
if (loc < bp->addr)                                     /* insrt before or */
    sim_brk_ins = p;
else sim_brk_ins = p + 1;                               /* after last sch */
return NULL;
}

BRKTAB *sim_brk_fnd_ex (t_addr loc, uint32 btyp, t_bool any_typ, uint32 spc)
{
BRKTAB *bp = sim_brk_fnd (loc);

while (bp) {
    if (any_typ ? ((bp->typ & btyp) && (bp->time_fired[spc] != sim_gtime())) :
                  (bp->typ == btyp))
        return bp;
    bp = bp->next;
    }
return bp;
}

/* Insert a breakpoint */

BRKTAB *sim_brk_new (t_addr loc, uint32 btyp)
{
int32 i, t;
BRKTAB *bp, **newp;

if (sim_brk_ins < 0)
    return NULL;
if (sim_brk_ent >= sim_brk_lnt) {                       /* out of space? */
    t = sim_brk_lnt + SIM_BRK_INILNT;                   /* new size */
    newp = (BRKTAB **) calloc (t, sizeof (BRKTAB*));    /* new table */
    if (newp == NULL)                                   /* can't extend */
        return NULL;
    memcpy (newp, sim_brk_tab, sim_brk_lnt * sizeof (*sim_brk_tab));/* copy table */
    memset (newp + sim_brk_lnt, 0, SIM_BRK_INILNT * sizeof (*newp));/* zero new entries */
    free (sim_brk_tab);                                 /* free old table */
    sim_brk_tab = newp;                                 /* new base, lnt */
    sim_brk_lnt = t;
    }
if ((sim_brk_ins == sim_brk_ent) ||
    ((sim_brk_ins != sim_brk_ent) &&
     (sim_brk_tab[sim_brk_ins]->addr != loc))) {        /* need to open a hole? */
    for (i = sim_brk_ent; i > sim_brk_ins; --i)
        sim_brk_tab[i] = sim_brk_tab[i - 1];
    sim_brk_tab[sim_brk_ins] = NULL;
    }
bp = (BRKTAB *)calloc (1, sizeof (*bp));
bp->next = sim_brk_tab[sim_brk_ins];
sim_brk_tab[sim_brk_ins] = bp;
if (bp->next == NULL)
    sim_brk_ent += 1;
bp->addr = loc;
bp->typ = btyp;
bp->cnt = 0;
bp->act = NULL;
for (i = 0; i < SIM_BKPT_N_SPC; i++)
    bp->time_fired[i] = -1.0;
return bp;
}

/* Set a breakpoint of type sw */

t_stat sim_brk_set (t_addr loc, int32 sw, int32 ncnt, CONST char *act)
{
BRKTAB *bp;

if ((sw == 0) || (sw == BRK_TYP_DYN_STEPOVER))
    sw |= sim_brk_dflt;
if (~sim_brk_types & sw) {
    char gbuf[CBUFSIZE];

    return sim_messagef (SCPE_NOFNC, "Unknown breakpoint type; %s\n", put_switches(gbuf, sizeof(gbuf), sw & ~sim_brk_types));
    }
if ((sw & BRK_TYP_DYN_ALL) && act)                      /* can't specify an action with a dynamic breakpoint */
    return SCPE_ARG;
bp = sim_brk_fnd (loc);                                 /* loc present? */
if (!bp)                                                /* no, allocate */
    bp = sim_brk_new (loc, sw);
else {
    while (bp && (bp->typ != sw))
        bp = bp->next;
    if (!bp)
        bp = sim_brk_new (loc, sw);
    }
if (!bp)                                                /* still no? mem err */
    return SCPE_MEM;

bp->cnt = ncnt;                                         /* set count */
if ((!(sw & BRK_TYP_DYN_ALL)) &&                        /* Not Dynamic and */
    (bp->act != NULL) && (act != NULL)) {               /* replace old action? */
    free (bp->act);                                     /* deallocate */
    bp->act = NULL;                                     /* now no action */
    }
if ((act != NULL) && (*act != 0)) {                     /* new action? */
    char *newp = (char *) calloc (CBUFSIZE+1, sizeof (char)); /* alloc buf */
    if (newp == NULL)                                   /* mem err? */
        return SCPE_MEM;
    strncpy (newp, act, CBUFSIZE);                      /* copy action */
    bp->act = newp;                                     /* set pointer */
    }
sim_brk_summ = sim_brk_summ | (sw & ~BRK_TYP_TEMP);
return SCPE_OK;
}

/* Clear a breakpoint */

t_stat sim_brk_clr (t_addr loc, int32 sw)
{
BRKTAB *bpl, *bp = sim_brk_fnd (loc);
int32 i;

if (!bp)                                                /* not there? ok */
    return SCPE_OK;
if (sw == 0)
    sw = SIM_BRK_ALLTYP;

while (bp) {
    if (bp->typ == (bp->typ & sw)) {

        free (bp->act);                                 /* deallocate action */
        if (bp == sim_brk_tab[sim_brk_ins])
            bpl = sim_brk_tab[sim_brk_ins] = bp->next;
        else
            bpl->next = bp->next;
        free (bp);

        bp = bpl;
        }
    else {
        bpl = bp;
        bp = bp->next;
        }
    }
if (sim_brk_tab[sim_brk_ins] == NULL) {                 /* erased entry */
    sim_brk_ent = sim_brk_ent - 1;                      /* decrement count */
    for (i = sim_brk_ins; i < sim_brk_ent; i++)         /* shuffle remaining entries */
        sim_brk_tab[i] = sim_brk_tab[i+1];
    }
sim_brk_summ = 0;                                       /* recalc summary */
for (i = 0; i < sim_brk_ent; i++) {
    bp = sim_brk_tab[i];
    while (bp) {
        sim_brk_summ |= (bp->typ & ~BRK_TYP_TEMP);
        bp = bp->next;
        }
    }
return SCPE_OK;
}

/* Clear all breakpoints */

t_stat sim_brk_clrall (int32 sw)
{
int32 i;

if (sw == 0)
    sw = SIM_BRK_ALLTYP;
for (i = 0; i < sim_brk_ent;) {
    t_addr loc = sim_brk_tab[i]->addr;

    sim_brk_clr (loc, sw);
    if ((i < sim_brk_ent) &&
        (loc == sim_brk_tab[i]->addr))
        ++i;
    }
return SCPE_OK;
}

/* Show a breakpoint */

t_stat sim_brk_show (FILE *st, t_addr loc, int32 sw)
{
BRKTAB *bp = sim_brk_fnd_ex (loc, sw & (~SWMASK ('C')), FALSE, 0);
DEVICE *dptr;
int32 i, any;

if ((sw == 0) || (sw == SWMASK ('C')))
    sw = SIM_BRK_ALLTYP | ((sw == SWMASK ('C')) ? SWMASK ('C') : 0);
if (!bp || (!(bp->typ & sw)))
    return SCPE_OK;
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865

8866
8867
8868
8869


















8870















8871
8872













8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888


8889
8890
8891
8892
8893

8894

8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
if (sw & SWMASK ('C')) {
    fprintf (st, " ");
    if (sim_vm_fprint_addr)
        sim_vm_fprint_addr (st, dptr, loc);
    else fprint_val (st, loc, dptr->aradix, dptr->awidth, PV_LEFT);
    }
if (bp->cnt > 0)
    fprintf (st, " [%d]", bp->cnt);
if (bp->act != NULL)
    fprintf (st, "; %s", bp->act);
fprintf (st, "\n");
return SCPE_OK;
}

/* Show all breakpoints */

t_stat sim_brk_showall (FILE *st, int32 sw)
{

BRKTAB *bp;

if ((sw == 0) || (sw == SWMASK ('C')))
    sw = SIM_BRK_ALLTYP | ((sw == SWMASK ('C')) ? SWMASK ('C') : 0);


















for (bp = sim_brk_tab; bp < (sim_brk_tab + sim_brk_ent); bp++) {















    if (bp->typ & sw)
        sim_brk_show (st, bp->addr, sw);













    }
return SCPE_OK;
}

/* Test for breakpoint */

uint32 sim_brk_test (t_addr loc, uint32 btyp)
{
BRKTAB *bp;
uint32 spc = (btyp >> SIM_BKPT_V_SPC) & (SIM_BKPT_N_SPC - 1);

if (sim_brk_summ & BRK_TYP_DYN_ALL)
    btyp |= BRK_TYP_DYN_ALL;

if ((bp = sim_brk_fnd (loc)) && (btyp & bp->typ)) {     /* in table, and type match? */
    if ((sim_brk_pend[spc] && (loc == sim_brk_ploc[spc])) || /* previous location? */


        (--bp->cnt > 0))                                /* count > 0? */
        return 0;
    bp->cnt = 0;                                        /* reset count */
    sim_brk_ploc[spc] = loc;                            /* save location */
    sim_brk_pend[spc] = TRUE;                           /* don't do twice */

    sim_brk_setact (bp->act);                           /* set up actions */

    return (btyp & bp->typ);
    }
sim_brk_pend[spc] = FALSE;
return 0;
}

/* Get next pending action, if any */

char *sim_brk_getact (char *buf, int32 size)
{
char *ep;
size_t lnt;

if (sim_brk_act[sim_do_depth] == NULL)                  /* any action? */
    return NULL;
while (sim_isspace (*sim_brk_act[sim_do_depth]))            /* skip spaces */
    sim_brk_act[sim_do_depth]++;
if (*sim_brk_act[sim_do_depth] == 0) {                  /* now empty? */
    return sim_brk_clract ();
    }
if ((ep = strchr (sim_brk_act[sim_do_depth], ';'))) {   /* cmd delimiter? */
    lnt = ep - sim_brk_act[sim_do_depth];               /* cmd length */
    memcpy (buf, sim_brk_act[sim_do_depth], lnt + 1);   /* copy with ; */







|










>
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>














|
|
>
>
|


|
|
>
|
>
|

<





|






|







9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663

9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
if (sw & SWMASK ('C')) {
    fprintf (st, " ");
    if (sim_vm_fprint_addr)
        sim_vm_fprint_addr (st, dptr, loc);
    else fprint_val (st, loc, dptr->aradix, dptr->awidth, PV_LEFT);
    }
if (bp->cnt > 0)
    fprintf (st, "[%d]", bp->cnt);
if (bp->act != NULL)
    fprintf (st, "; %s", bp->act);
fprintf (st, "\n");
return SCPE_OK;
}

/* Show all breakpoints */

t_stat sim_brk_showall (FILE *st, int32 sw)
{
int32 bit, mask, types;
BRKTAB **bpt;

if ((sw == 0) || (sw == SWMASK ('C')))
    sw = SIM_BRK_ALLTYP | ((sw == SWMASK ('C')) ? SWMASK ('C') : 0);
for (types=bit=0; bit <= ('Z'-'A'); bit++)
    if (sim_brk_types & (1 << bit))
        ++types;
if ((!(sw & SWMASK ('C'))) && sim_brk_types && (types > 1)) {
    fprintf (st, "Supported Breakpoint Types:");
    for (bit=0; bit <= ('Z'-'A'); bit++)
        if (sim_brk_types & (1 << bit))
            fprintf (st, " -%c", 'A' + bit);
    fprintf (st, "\n");
    }
if (((sw & sim_brk_types) != sim_brk_types) && (types > 1)) {
    mask = (sw & sim_brk_types);
    fprintf (st, "Displaying Breakpoint Types:");
    for (bit=0; bit <= ('Z'-'A'); bit++)
        if (mask & (1 << bit))
            fprintf (st, " -%c", 'A' + bit);
    fprintf (st, "\n");
    }
for (bpt = sim_brk_tab; bpt < (sim_brk_tab + sim_brk_ent); bpt++) {
    BRKTAB *prev = NULL;
    BRKTAB *cur = *bpt;
    BRKTAB *next;
    /* First reverse the list */
    while (cur) {
        next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
        }
    /* save reversed list in the head pointer so lookups work */
    *bpt = prev;
    /* Walk the reversed list and print it in the order it was defined in */
    cur = prev;
    while (cur) {
        if (cur->typ & sw)
            sim_brk_show (st, cur->addr, cur->typ | ((sw & SWMASK ('C')) ? SWMASK ('C') : 0));
        cur = cur->next;
        }
    /* reversing the list again */
    cur = prev;
    prev = NULL;
    while (cur) {
        next = cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
        }
    /* restore original list */
    *bpt = prev;
    }
return SCPE_OK;
}

/* Test for breakpoint */

uint32 sim_brk_test (t_addr loc, uint32 btyp)
{
BRKTAB *bp;
uint32 spc = (btyp >> SIM_BKPT_V_SPC) & (SIM_BKPT_N_SPC - 1);

if (sim_brk_summ & BRK_TYP_DYN_ALL)
    btyp |= BRK_TYP_DYN_ALL;

if ((bp = sim_brk_fnd_ex (loc, btyp, TRUE, spc))) {     /* in table, and type match? */
    if (bp->time_fired[spc] == sim_time)                /* already taken?  */
        return 0;
    bp->time_fired[spc] = sim_time;                     /* remember match time */
    if (--bp->cnt > 0)                                  /* count > 0? */
        return 0;
    bp->cnt = 0;                                        /* reset count */
    sim_brk_setact (bp->act);                           /* set up actions */
    sim_brk_match_type = btyp & bp->typ;                               /* set return value */
    if (bp->typ & BRK_TYP_TEMP)
        sim_brk_clr (loc, bp->typ);                     /* delete one-shot breakpoint */
    sim_brk_match_addr = loc;
    return sim_brk_match_type;
    }

return 0;
}

/* Get next pending action, if any */

CONST char *sim_brk_getact (char *buf, int32 size)
{
char *ep;
size_t lnt;

if (sim_brk_act[sim_do_depth] == NULL)                  /* any action? */
    return NULL;
while (sim_isspace (*sim_brk_act[sim_do_depth]))        /* skip spaces */
    sim_brk_act[sim_do_depth]++;
if (*sim_brk_act[sim_do_depth] == 0) {                  /* now empty? */
    return sim_brk_clract ();
    }
if ((ep = strchr (sim_brk_act[sim_do_depth], ';'))) {   /* cmd delimiter? */
    lnt = ep - sim_brk_act[sim_do_depth];               /* cmd length */
    memcpy (buf, sim_brk_act[sim_do_depth], lnt + 1);   /* copy with ; */
8946
8947
8948
8949
8950
8951
8952
8953

8954
8955
8956

8957
8958
8959
8960
8961

8962
8963
8964
8965
8966
8967


8968



8969















8970

8971











8972
8973
8974
8975
8976
8977
8978
8979
    sim_brk_clract ();
}

/* New PC */

void sim_brk_npc (uint32 cnt)
{
uint32 i;


if ((cnt == 0) || (cnt > SIM_BKPT_N_SPC))
    cnt = SIM_BKPT_N_SPC;

for (i = 0; i < cnt; i++) {
    sim_brk_pend[i] = FALSE;
    sim_brk_ploc[i] = 0;
    }
return;

}

/* Clear breakpoint space */

void sim_brk_clrspc (uint32 spc)
{


if (spc < SIM_BKPT_N_SPC) {



    sim_brk_pend[spc] = FALSE;















    sim_brk_ploc[spc] = 0;

    }











return;
}

/* Expect package.  This code provides a mechanism to stop and control simulator
   execution based on traffic coming out of simulated ports and as well as a means
   to inject data into those ports.  It can conceptually viewed as a string
   breakpoint package.








|
>



>
|
|
|
|
<
>




|

>
>

>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
|







9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728

9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
    sim_brk_clract ();
}

/* New PC */

void sim_brk_npc (uint32 cnt)
{
uint32 spc;
BRKTAB **bpt, *bp;

if ((cnt == 0) || (cnt > SIM_BKPT_N_SPC))
    cnt = SIM_BKPT_N_SPC;
for (bpt = sim_brk_tab; bpt < (sim_brk_tab + sim_brk_ent); bpt++) {
    for (bp = *bpt; bp; bp = bp->next) {
        for (spc = 0; spc < cnt; spc++)
            bp->time_fired[spc] = -1.0;
        }

    }
}

/* Clear breakpoint space */

void sim_brk_clrspc (uint32 spc, uint32 btyp)
{
BRKTAB **bpt, *bp;

if (spc < SIM_BKPT_N_SPC) {
    for (bpt = sim_brk_tab; bpt < (sim_brk_tab + sim_brk_ent); bpt++) {
        for (bp = *bpt; bp; bp = bp->next) {
            if (bp->typ & btyp)
                bp->time_fired[spc] = -1.0;
            }
        }
    }
}

const char *sim_brk_message(void)
{
static char msg[256];
char addr[65];
char buf[32];

msg[0] = '\0';
if (sim_vm_sprint_addr)
    sim_vm_sprint_addr (addr, sim_dflt_dev, (t_value)sim_brk_match_addr);
else sprint_val (addr, (t_value)sim_brk_match_addr, sim_dflt_dev->aradix, sim_dflt_dev->awidth, PV_LEFT);
if (sim_brk_type_desc) {
    BRKTYPTAB *brk = sim_brk_type_desc;

    while (2 == strlen (put_switches (buf, sizeof(buf), brk->btyp))) {
        if (brk->btyp == sim_brk_match_type) {
            sprintf (msg, "%s: %s", brk->desc, addr);
            break;
            }
        brk++;
        }
    }
if (!msg[0])
    sprintf (msg, "%s Breakpoint at: %s\n", put_switches (buf, sizeof(buf), sim_brk_match_type), addr);

return msg;
}

/* Expect package.  This code provides a mechanism to stop and control simulator
   execution based on traffic coming out of simulated ports and as well as a means
   to inject data into those ports.  It can conceptually viewed as a string
   breakpoint package.

9013
9014
9015
9016
9017
9018
9019
9020
9021
9022

9023

9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042

9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
{
memset (exp, 0, sizeof(*exp));
return SCPE_OK;
}

/* Set expect */

t_stat sim_set_expect (EXPECT *exp, char *cptr)
{
char gbuf[CBUFSIZE], *tptr;

const char *c1ptr;

uint32 after = exp->after;
int32 cnt = 0;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (*cptr == '[') {
    cnt = (int32) strtotv (cptr + 1, &c1ptr, 10);
    if ((cptr == c1ptr) || (*c1ptr != ']'))
        return sim_messagef (SCPE_ARG, "Invalid Repeat count specification\n");
    cptr = (char *)(c1ptr + 1);
    while (sim_isspace(*cptr))
        ++cptr;
    }
tptr = get_glyph (cptr, gbuf, ',');
if ((!strncmp(gbuf, "HALTAFTER=", 10)) && (gbuf[10])) {
    after = (uint32)get_uint (&gbuf[10], 10, 100000000, &r);
    if (r != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Halt After Value\n");

    cptr = tptr;
    }
if ((*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);

return sim_exp_set (exp, gbuf, cnt, (after ? after : exp->after), sim_switches, cptr);
}

/* Clear expect */

t_stat sim_set_noexpect (EXPECT *exp, char *cptr)
{
char gbuf[CBUFSIZE];

if (!cptr || !*cptr)
    return sim_exp_clrall (exp);                    /* clear all rules */
if ((*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);
if (*cptr != '\0')
    return SCPE_2MARG;                              /* No more arguments */
return sim_exp_clr (exp, gbuf);                     /* clear one rule */
}

/* Search for an expect rule in an expect context */

EXPTAB *sim_exp_fnd (EXPECT *exp, const char *match)
{
int32 i;

if (!exp->rules)
    return NULL;
for (i=0; i<exp->size; i++)
    if (!strcmp (exp->rules[i].match_pattern, match))
        return &exp->rules[i];
return NULL;
}

/* Clear (delete) an expect rule */








|

|
>
|
>










|








>






|




|















|





|







9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
{
memset (exp, 0, sizeof(*exp));
return SCPE_OK;
}

/* Set expect */

t_stat sim_set_expect (EXPECT *exp, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *tptr;
CONST char *c1ptr;
t_bool after_set = FALSE;
uint32 after = exp->after;
int32 cnt = 0;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (*cptr == '[') {
    cnt = (int32) strtotv (cptr + 1, &c1ptr, 10);
    if ((cptr == c1ptr) || (*c1ptr != ']'))
        return sim_messagef (SCPE_ARG, "Invalid Repeat count specification\n");
    cptr = c1ptr + 1;
    while (sim_isspace(*cptr))
        ++cptr;
    }
tptr = get_glyph (cptr, gbuf, ',');
if ((!strncmp(gbuf, "HALTAFTER=", 10)) && (gbuf[10])) {
    after = (uint32)get_uint (&gbuf[10], 10, 100000000, &r);
    if (r != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Halt After Value\n");
    after_set = TRUE;
    cptr = tptr;
    }
if ((*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);

return sim_exp_set (exp, gbuf, cnt, (after_set ? after : exp->after), sim_switches, cptr);
}

/* Clear expect */

t_stat sim_set_noexpect (EXPECT *exp, const char *cptr)
{
char gbuf[CBUFSIZE];

if (!cptr || !*cptr)
    return sim_exp_clrall (exp);                    /* clear all rules */
if ((*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);
if (*cptr != '\0')
    return SCPE_2MARG;                              /* No more arguments */
return sim_exp_clr (exp, gbuf);                     /* clear one rule */
}

/* Search for an expect rule in an expect context */

CONST EXPTAB *sim_exp_fnd (CONST EXPECT *exp, const char *match, int32 start_rule)
{
int32 i;

if (!exp->rules)
    return NULL;
for (i=start_rule; i<exp->size; i++)
    if (!strcmp (exp->rules[i].match_pattern, match))
        return &exp->rules[i];
return NULL;
}

/* Clear (delete) an expect rule */

9102
9103
9104
9105
9106
9107
9108



9109



9110
9111
9112
9113
9114
9115
9116
    exp->rules = NULL;
    }
return SCPE_OK;
}

t_stat sim_exp_clr (EXPECT *exp, const char *match)
{



return sim_exp_clr_tab (exp, sim_exp_fnd (exp, match));



}

/* Clear all expect rules */

t_stat sim_exp_clrall (EXPECT *exp)
{
int32 i;







>
>
>
|
>
>
>







9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
    exp->rules = NULL;
    }
return SCPE_OK;
}

t_stat sim_exp_clr (EXPECT *exp, const char *match)
{
EXPTAB *ep = (EXPTAB *)sim_exp_fnd (exp, match, 0);

while (ep) {
    sim_exp_clr_tab (exp, ep);
    ep = (EXPTAB *)sim_exp_fnd (exp, match, ep - exp->rules);
    }
return SCPE_OK;
}

/* Clear all expect rules */

t_stat sim_exp_clrall (EXPECT *exp)
{
int32 i;
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
exp->buf_size = 0;
exp->buf_ins = 0;
return SCPE_OK;
}

/* Set/Add an expect rule */

t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, char *act)
{
EXPTAB *ep;
uint8 *match_buf;
uint32 match_size;
int i;

/* Validate the match string */







|







9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
exp->buf_size = 0;
exp->buf_ins = 0;
return SCPE_OK;
}

/* Set/Add an expect rule */

t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, const char *act)
{
EXPTAB *ep;
uint8 *match_buf;
uint32 match_size;
int i;

/* Validate the match string */
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187


9188
9189
9190
9191
9192
9193
9194
9195

9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
    }
#endif
else {
    if (switches & EXP_TYP_REGEX_I) {
        free (match_buf);
        return sim_messagef (SCPE_ARG, "Case independed matching is only valid for RegEx expect rules\n");
        }
    sim_data_trace(exp->dptr, exp->dptr->units, (uint8 *)match, "", strlen(match)+1, "Expect Match String", exp->dbit);
    if (SCPE_OK != sim_decode_quoted_string (match, match_buf, &match_size)) {
        free (match_buf);
        return sim_messagef (SCPE_ARG, "Invalid quoted string\n");
        }
    }
free (match_buf);
ep = sim_exp_fnd (exp, match);                          /* present? */
if (ep)                                                 /* no, allocate */
    sim_exp_clr_tab (exp, ep);                          /* clear it */


if (after && exp->size)
    return sim_messagef (SCPE_ARG, "Multiple concurrent EXPECT rules aren't valid when a HALTAFTER parameter is non-zero\n");
exp->rules = (EXPTAB *) realloc (exp->rules, sizeof (*exp->rules)*(exp->size + 1));
ep = &exp->rules[exp->size];
exp->size += 1;
exp->after = after;                                     /* set halt after value */
memset (ep, 0, sizeof(*ep));
ep->match_pattern = (char *)malloc (strlen (match) + 1);

strcpy (ep->match_pattern, match);
ep->cnt = cnt;                                          /* set proceed count */
ep->switches = switches;                                /* set switches */
match_buf = (uint8 *)calloc (strlen (match) + 1, 1);
if (!match_buf) {
    sim_exp_clr_tab (exp, ep);                          /* clear it */
    return SCPE_MEM;
    }
if (switches & EXP_TYP_REGEX) {
#if defined(USE_REGEX)
    memcpy (match_buf, match+1, strlen(match)-2);      /* extract string without surrounding quotes */
    match_buf[strlen(match)-2] = '\0';
    regcomp (&ep->regex, (char *)match_buf, REG_EXTENDED);
#endif
    free (match_buf);
    match_buf = NULL;
    }
else {
    sim_data_trace(exp->dptr, exp->dptr->units, (uint8 *)match, "", strlen(match)+1, "Expect Match String", exp->dbit);
    sim_decode_quoted_string (match, match_buf, &match_size);
    ep->match = match_buf;
    ep->size = match_size;
    }
ep->match_pattern = (char *)malloc (strlen (match) + 1);
strcpy (ep->match_pattern, match);
if (ep->act) {                                          /* replace old action? */







|






|
|
|
>
>








>
|



|













|







9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
    }
#endif
else {
    if (switches & EXP_TYP_REGEX_I) {
        free (match_buf);
        return sim_messagef (SCPE_ARG, "Case independed matching is only valid for RegEx expect rules\n");
        }
    sim_data_trace(exp->dptr, exp->dptr->units, (const uint8 *)match, "", strlen(match)+1, "Expect Match String", exp->dbit);
    if (SCPE_OK != sim_decode_quoted_string (match, match_buf, &match_size)) {
        free (match_buf);
        return sim_messagef (SCPE_ARG, "Invalid quoted string\n");
        }
    }
free (match_buf);
for (i=0; i<exp->size; i++) {                           /* Make sure this rule won't be occluded */
    if ((0 == strcmp (match, exp->rules[i].match_pattern)) &&
        (exp->rules[i].switches & EXP_TYP_PERSIST))
        return sim_messagef (SCPE_ARG, "Persistent Expect rule with identical match string already exists\n");
    }
if (after && exp->size)
    return sim_messagef (SCPE_ARG, "Multiple concurrent EXPECT rules aren't valid when a HALTAFTER parameter is non-zero\n");
exp->rules = (EXPTAB *) realloc (exp->rules, sizeof (*exp->rules)*(exp->size + 1));
ep = &exp->rules[exp->size];
exp->size += 1;
exp->after = after;                                     /* set halt after value */
memset (ep, 0, sizeof(*ep));
ep->match_pattern = (char *)malloc (strlen (match) + 1);
if (ep->match_pattern)
    strcpy (ep->match_pattern, match);
ep->cnt = cnt;                                          /* set proceed count */
ep->switches = switches;                                /* set switches */
match_buf = (uint8 *)calloc (strlen (match) + 1, 1);
if ((match_buf == NULL) || (ep->match_pattern == NULL)) {
    sim_exp_clr_tab (exp, ep);                          /* clear it */
    return SCPE_MEM;
    }
if (switches & EXP_TYP_REGEX) {
#if defined(USE_REGEX)
    memcpy (match_buf, match+1, strlen(match)-2);      /* extract string without surrounding quotes */
    match_buf[strlen(match)-2] = '\0';
    regcomp (&ep->regex, (char *)match_buf, REG_EXTENDED);
#endif
    free (match_buf);
    match_buf = NULL;
    }
else {
    sim_data_trace(exp->dptr, exp->dptr->units, (const uint8 *)match, "", strlen(match)+1, "Expect Match String", exp->dbit);
    sim_decode_quoted_string (match, match_buf, &match_size);
    ep->match = match_buf;
    ep->size = match_size;
    }
ep->match_pattern = (char *)malloc (strlen (match) + 1);
strcpy (ep->match_pattern, match);
if (ep->act) {                                          /* replace old action? */
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
        }
    }
return SCPE_OK;
}

/* Show an expect rule */

t_stat sim_exp_show_tab (FILE *st, EXPECT *exp, EXPTAB *ep)
{
if (!ep)
    return SCPE_OK;
fprintf (st, "EXPECT");
if (ep->switches & EXP_TYP_PERSIST)
    fprintf (st, " -p");
if (ep->switches & EXP_TYP_CLEARALL)







|







10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
        }
    }
return SCPE_OK;
}

/* Show an expect rule */

t_stat sim_exp_show_tab (FILE *st, const EXPECT *exp, const EXPTAB *ep)
{
if (!ep)
    return SCPE_OK;
fprintf (st, "EXPECT");
if (ep->switches & EXP_TYP_PERSIST)
    fprintf (st, " -p");
if (ep->switches & EXP_TYP_CLEARALL)
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283

9284
9285
9286

9287


9288



9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
    fprintf (st, " [%d]", ep->cnt);
if (ep->act)
    fprintf (st, " %s", ep->act);
fprintf (st, "\n");
return SCPE_OK;
}

t_stat sim_exp_show (FILE *st, EXPECT *exp, const char *match)
{
EXPTAB *ep = sim_exp_fnd (exp, match);

if (exp->buf_size) {
    char *bstr = sim_encode_quoted_string (exp->buf, exp->buf_ins);

    fprintf (st, "Match Buffer Size: %d\n", exp->buf_size);
    fprintf (st, "Buffer Insert Offset: %d\n", exp->buf_ins);
    fprintf (st, "Buffer Contents: %s\n", bstr);
    free (bstr);
    }
if (exp->after)
    fprintf (st, "Halt After: %d instructions\n", exp->after);
if (exp->dptr && exp->dbit)
    fprintf (st, "Debugging via: SET %s DEBUG%s%s\n", sim_dname(exp->dptr), exp->dptr->debflags ? "=" : "", exp->dptr->debflags ? get_dbg_verb (exp->dbit, exp->dptr) : "");

if (!*match)
    return sim_exp_showall (st, exp);
if (!ep)

    return SCPE_ARG;


return sim_exp_show_tab (st, exp, ep);



}

/* Show all expect rules */

t_stat sim_exp_showall (FILE *st, EXPECT *exp)
{
int32 i;

for (i=0; i < exp->size; i++)
    sim_exp_show_tab (st, exp, &exp->rules[i]);
return SCPE_OK;
}







|

|













>


|
>

>
>
|
>
>
>




|







10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
    fprintf (st, " [%d]", ep->cnt);
if (ep->act)
    fprintf (st, " %s", ep->act);
fprintf (st, "\n");
return SCPE_OK;
}

t_stat sim_exp_show (FILE *st, CONST EXPECT *exp, const char *match)
{
CONST EXPTAB *ep = (CONST EXPTAB *)sim_exp_fnd (exp, match, 0);

if (exp->buf_size) {
    char *bstr = sim_encode_quoted_string (exp->buf, exp->buf_ins);

    fprintf (st, "Match Buffer Size: %d\n", exp->buf_size);
    fprintf (st, "Buffer Insert Offset: %d\n", exp->buf_ins);
    fprintf (st, "Buffer Contents: %s\n", bstr);
    free (bstr);
    }
if (exp->after)
    fprintf (st, "Halt After: %d instructions\n", exp->after);
if (exp->dptr && exp->dbit)
    fprintf (st, "Debugging via: SET %s DEBUG%s%s\n", sim_dname(exp->dptr), exp->dptr->debflags ? "=" : "", exp->dptr->debflags ? get_dbg_verb (exp->dbit, exp->dptr) : "");
fprintf (st, "Match Rules:\n");
if (!*match)
    return sim_exp_showall (st, exp);
if (!ep) {
    fprintf (st, "No Rules match '%s'\n", match);
    return SCPE_ARG;
    }
do {
    sim_exp_show_tab (st, exp, ep);
    ep = (CONST EXPTAB *)sim_exp_fnd (exp, match, 1 + (ep - exp->rules));
    } while (ep);
return SCPE_OK;
}

/* Show all expect rules */

t_stat sim_exp_showall (FILE *st, const EXPECT *exp)
{
int32 i;

for (i=0; i < exp->size; i++)
    sim_exp_show_tab (st, exp, &exp->rules[i]);
return SCPE_OK;
}
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
snd->insoff = 0;
snd->extoff = 0;
return SCPE_OK;
}

/* Display console Queued input data status */

t_stat sim_show_send_input (FILE *st, SEND *snd)
{
if (snd->extoff < snd->insoff) {
    fprintf (st, "%d bytes of pending input Data:\n    ", snd->insoff-snd->extoff);
    fprint_buffer_string (st, snd->buffer+snd->extoff, snd->insoff-snd->extoff);
    fprintf (st, "\n");
    }
else







|







10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
snd->insoff = 0;
snd->extoff = 0;
return SCPE_OK;
}

/* Display console Queued input data status */

t_stat sim_show_send_input (FILE *st, const SEND *snd)
{
if (snd->extoff < snd->insoff) {
    fprintf (st, "%d bytes of pending input Data:\n    ", snd->insoff-snd->extoff);
    fprint_buffer_string (st, snd->buffer+snd->extoff, snd->insoff-snd->extoff);
    fprintf (st, "\n");
    }
else
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
    return "No Error";
if ((stat >= SCPE_BASE) && (stat <= SCPE_MAX_ERR))
    return scp_errors[stat-SCPE_BASE].message;
sprintf(msgbuf, "Error %d", stat);
return msgbuf;
}

t_stat sim_string_to_stat (char *cptr, t_stat *stat)
{
char gbuf[CBUFSIZE];
int32 cond;

*stat = SCPE_ARG;
cptr = get_glyph (cptr, gbuf, 0);
if (0 == memcmp("SCPE_", gbuf, 5))







|







10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
    return "No Error";
if ((stat >= SCPE_BASE) && (stat <= SCPE_MAX_ERR))
    return scp_errors[stat-SCPE_BASE].message;
sprintf(msgbuf, "Error %d", stat);
return msgbuf;
}

t_stat sim_string_to_stat (const char *cptr, t_stat *stat)
{
char gbuf[CBUFSIZE];
int32 cond;

*stat = SCPE_ARG;
cptr = get_glyph (cptr, gbuf, 0);
if (0 == memcmp("SCPE_", gbuf, 5))
9602
9603
9604
9605
9606
9607
9608

9609
9610
9611
9612
9613


9614
9615
9616
9617
9618


9619
9620
9621
9622
9623
9624
9625
9626
9627
9628

/* Finds debug phrase matching bitmask from from device DEBTAB table */

static const char *get_dbg_verb (uint32 dbits, DEVICE* dptr)
{
static const char *debtab_none    = "DEBTAB_ISNULL";
static const char *debtab_nomatch = "DEBTAB_NOMATCH";

int32 offset = 0;

if (dptr->debflags == 0)
    return debtab_none;



/* Find matching words for bitmask */

while (dptr->debflags[offset].name && (offset < 32)) {
    if (dptr->debflags[offset].mask & dbits)
        return dptr->debflags[offset].name;


    offset++;
    }
return debtab_nomatch;
}

/* Prints standard debug prefix unless previous call unterminated */

static const char *sim_debug_prefix (uint32 dbits, DEVICE* dptr)
{
const char* debug_type = get_dbg_verb (dbits, dptr);







>





>
>



|

>
>


|







10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452

/* Finds debug phrase matching bitmask from from device DEBTAB table */

static const char *get_dbg_verb (uint32 dbits, DEVICE* dptr)
{
static const char *debtab_none    = "DEBTAB_ISNULL";
static const char *debtab_nomatch = "DEBTAB_NOMATCH";
const char *some_match = NULL;
int32 offset = 0;

if (dptr->debflags == 0)
    return debtab_none;

dbits &= dptr->dctrl;                           /* Look for just the bits tha matched */

/* Find matching words for bitmask */

while (dptr->debflags[offset].name && (offset < 32)) {
    if (dptr->debflags[offset].mask == dbits)   /* All Bits Match */
        return dptr->debflags[offset].name;
    if (dptr->debflags[offset].mask & dbits)
        some_match = dptr->debflags[offset].name;
    offset++;
    }
return some_match ? some_match : debtab_nomatch;
}

/* Prints standard debug prefix unless previous call unterminated */

static const char *sim_debug_prefix (uint32 dbits, DEVICE* dptr)
{
const char* debug_type = get_dbg_verb (dbits, dptr);
9870
9871
9872
9873
9874
9875
9876
9877


9878

9879

9880
9881
9882
9883
9884
9885
9886
   set and the bitmask matches the current device debug options.
   Extra returns are added for un*x systems, since the output
   device is set into 'raw' mode when the cpu is booted,
   and the extra returns don't hurt any other systems.
   Callers should be calling sim_debug() which is a macro
   defined in scp.h which evaluates the action condition before
   incurring call overhead. */



void _sim_debug (uint32 dbits, DEVICE* dptr, const char* fmt, ...)

{

if (sim_deb && dptr && (dptr->dctrl & dbits)) {

    char stackbuf[STACKBUFSIZE];
    int32 bufsize = sizeof(stackbuf);
    char *buf = stackbuf;
    va_list arglist;
    int32 i, j, len;







|
>
>
|
>

>







10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
   set and the bitmask matches the current device debug options.
   Extra returns are added for un*x systems, since the output
   device is set into 'raw' mode when the cpu is booted,
   and the extra returns don't hurt any other systems.
   Callers should be calling sim_debug() which is a macro
   defined in scp.h which evaluates the action condition before
   incurring call overhead. */
#if defined(__cplusplus)
void _sim_debug (uint32 dbits, void* vdptr, const char* fmt, ...)
#else
void _sim_debug (uint32 dbits, DEVICE* vdptr, const char* fmt, ...)
#endif
{
DEVICE *dptr = (DEVICE *)vdptr;
if (sim_deb && dptr && (dptr->dctrl & dbits)) {

    char stackbuf[STACKBUFSIZE];
    int32 bufsize = sizeof(stackbuf);
    char *buf = stackbuf;
    va_list arglist;
    int32 i, j, len;
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957



































9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968






9969
9970
9971
9972
9973
9974
9975
9976


9977


















9978


9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
return;
}

void sim_data_trace(DEVICE *dptr, UNIT *uptr, const uint8 *data, const char *position, size_t len, const char *txt, uint32 reason)
{

if (sim_deb && (dptr->dctrl & reason)) {
    sim_debug (reason, dptr, "%s %s %slen: %08X\n", sim_uname(uptr), txt, position, len);
    if (data && len) {
        size_t i, same, group, sidx, oidx;
        char outbuf[80], strbuf[18];
        static char hex[] = "0123456789ABCDEF";




































        for (i=same=0; i<len; i += 16) {
            if ((i > 0) && (0 == memcmp (&data[i], &data[i-16], 16))) {
                ++same;
                continue;
                }
            if (same > 0) {
                sim_debug (reason, dptr, "%04X thru %04X same as above\n", i-(16*same), i-1);
                same = 0;
                }
            group = (((len - i) > 16) ? 16 : (len - i));






            for (sidx=oidx=0; sidx<group; ++sidx) {
                outbuf[oidx++] = ' ';
                outbuf[oidx++] = hex[(data[i+sidx]>>4)&0xf];
                outbuf[oidx++] = hex[data[i+sidx]&0xf];
                if (sim_isprint (data[i+sidx]))
                    strbuf[sidx] = data[i+sidx];
                else
                    strbuf[sidx] = '.';


                }


















            outbuf[oidx] = '\0';


            strbuf[sidx] = '\0';
            sim_debug (reason, dptr, "%04X%-48s %s\n", i, outbuf, strbuf);
            }
        if (same > 0) {
            sim_debug (reason, dptr, "%04X thru %04X same as above\n", i-(16*same), len-1);
            }
        }
    }
}

int Fprintf (FILE *f, const char* fmt, ...)
{
int ret = 0;
va_list args;

va_start (args, fmt);
if (sim_oline)
    tmxr_linemsgvf (sim_oline, fmt, args);
else
    ret = vfprintf (f, fmt, args);
va_end (args);
return ret;
}


/* Hierarchical help presentation
 *
 * Device help can be presented hierarchically by calling
 *
 * t_stat scp_help (FILE *st, struct sim_device *dptr,
 *                  struct sim_unit *uptr, int flag, const char *help, char *cptr)
 *
 * or one of its three cousins from the device HELP routine.
 *
 * *help is the pointer to the structured help text to be displayed.
 *
 * The format and usage, and some helper macros can be found in scp_help.h
 * If you don't use the macros, it is not necessary to #include "scp_help.h".







|

|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











>
>
>
>
>
>





|

|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
|
|


|



















<




|
|







10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893

10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
return;
}

void sim_data_trace(DEVICE *dptr, UNIT *uptr, const uint8 *data, const char *position, size_t len, const char *txt, uint32 reason)
{

if (sim_deb && (dptr->dctrl & reason)) {
    sim_debug (reason, dptr, "%s %s %slen: %08X\n", sim_uname(uptr), txt, position, (unsigned int)len);
    if (data && len) {
        unsigned int i, same, group, sidx, oidx, ridx, eidx, soff;
        char outbuf[80], strbuf[28], rad50buf[36], ebcdicbuf[32];
        static char hex[] = "0123456789ABCDEF";
        static char rad50[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ$._0123456789";
        static unsigned char ebcdic2ascii[] = {
            0000,0001,0002,0003,0234,0011,0206,0177,
            0227,0215,0216,0013,0014,0015,0016,0017,
            0020,0021,0022,0023,0235,0205,0010,0207,
            0030,0031,0222,0217,0034,0035,0036,0037,
            0200,0201,0202,0203,0204,0012,0027,0033,
            0210,0211,0212,0213,0214,0005,0006,0007,
            0220,0221,0026,0223,0224,0225,0226,0004,
            0230,0231,0232,0233,0024,0025,0236,0032,
            0040,0240,0241,0242,0243,0244,0245,0246,
            0247,0250,0133,0056,0074,0050,0053,0041,
            0046,0251,0252,0253,0254,0255,0256,0257,
            0260,0261,0135,0044,0052,0051,0073,0136,
            0055,0057,0262,0263,0264,0265,0266,0267,
            0270,0271,0174,0054,0045,0137,0076,0077,
            0272,0273,0274,0275,0276,0277,0300,0301,
            0302,0140,0072,0043,0100,0047,0075,0042,
            0303,0141,0142,0143,0144,0145,0146,0147,
            0150,0151,0304,0305,0306,0307,0310,0311,
            0312,0152,0153,0154,0155,0156,0157,0160,
            0161,0162,0313,0314,0315,0316,0317,0320,
            0321,0176,0163,0164,0165,0166,0167,0170,
            0171,0172,0322,0323,0324,0325,0326,0327,
            0330,0331,0332,0333,0334,0335,0336,0337,
            0340,0341,0342,0343,0344,0345,0346,0347,
            0173,0101,0102,0103,0104,0105,0106,0107,
            0110,0111,0350,0351,0352,0353,0354,0355,
            0175,0112,0113,0114,0115,0116,0117,0120,
            0121,0122,0356,0357,0360,0361,0362,0363,
            0134,0237,0123,0124,0125,0126,0127,0130,
            0131,0132,0364,0365,0366,0367,0370,0371,
            0060,0061,0062,0063,0064,0065,0066,0067,
            0070,0071,0372,0373,0374,0375,0376,0377,
            };

        for (i=same=0; i<len; i += 16) {
            if ((i > 0) && (0 == memcmp (&data[i], &data[i-16], 16))) {
                ++same;
                continue;
                }
            if (same > 0) {
                sim_debug (reason, dptr, "%04X thru %04X same as above\n", i-(16*same), i-1);
                same = 0;
                }
            group = (((len - i) > 16) ? 16 : (len - i));
            strcpy (ebcdicbuf, (sim_deb_switches & SWMASK ('E')) ? " EBCDIC:" : "");
            eidx = strlen(ebcdicbuf);
            strcpy (rad50buf, (sim_deb_switches & SWMASK ('D')) ? " RAD50:" : "");
            ridx = strlen(rad50buf);
            strcpy (strbuf, (sim_deb_switches & (SWMASK ('E') | SWMASK ('D'))) ? "ASCII:" : "");
            soff = strlen(strbuf);
            for (sidx=oidx=0; sidx<group; ++sidx) {
                outbuf[oidx++] = ' ';
                outbuf[oidx++] = hex[(data[i+sidx]>>4)&0xf];
                outbuf[oidx++] = hex[data[i+sidx]&0xf];
                if (sim_isprint (data[i+sidx]))
                    strbuf[soff+sidx] = data[i+sidx];
                else
                    strbuf[soff+sidx] = '.';
                if (ridx && ((sidx&1) == 0)) {
                    uint16 word = data[i+sidx] + (((uint16)data[i+sidx+1]) << 8);

                    if (word >= 64000) {
                        rad50buf[ridx++] = '|'; /* Invalid RAD-50 character */
                        rad50buf[ridx++] = '|'; /* Invalid RAD-50 character */
                        rad50buf[ridx++] = '|'; /* Invalid RAD-50 character */
                        }
                    else {
                        rad50buf[ridx++] = rad50[word/1600];
                        rad50buf[ridx++] = rad50[(word/40)%40];
                        rad50buf[ridx++] = rad50[word%40];
                        }
                    }
                if (eidx) {
                    if (sim_isprint (ebcdic2ascii[data[i+sidx]]))
                        ebcdicbuf[eidx++] = ebcdic2ascii[data[i+sidx]];
                    else
                        ebcdicbuf[eidx++] = '.';
                    }
                }
            outbuf[oidx] = '\0';
            strbuf[soff+sidx] = '\0';
            ebcdicbuf[eidx] = '\0';
            rad50buf[ridx] = '\0';
            sim_debug (reason, dptr, "%04X%-48s %s%s%s\n", i, outbuf, strbuf, ebcdicbuf, rad50buf);
            }
        if (same > 0) {
            sim_debug (reason, dptr, "%04X thru %04X same as above\n", i-(16*same), (unsigned int)(len-1));
            }
        }
    }
}

int Fprintf (FILE *f, const char* fmt, ...)
{
int ret = 0;
va_list args;

va_start (args, fmt);
if (sim_oline)
    tmxr_linemsgvf (sim_oline, fmt, args);
else
    ret = vfprintf (f, fmt, args);
va_end (args);
return ret;
}


/* Hierarchical help presentation
 *
 * Device help can be presented hierarchically by calling
 *
 * t_stat scp_help (FILE *st, DEVICE *dptr,
 *                  UNIT *uptr, int flag, const char *help, char *cptr)
 *
 * or one of its three cousins from the device HELP routine.
 *
 * *help is the pointer to the structured help text to be displayed.
 *
 * The format and usage, and some helper macros can be found in scp_help.h
 * If you don't use the macros, it is not necessary to #include "scp_help.h".
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
free (topic->children);
return;
}

/* Build a help tree from a string.
 * Handles substitutions, formatting.
 */
static TOPIC *buildHelp (TOPIC *topic, struct sim_device *dptr,
                         struct sim_unit *uptr, const char *htext, va_list ap)
{
char *end;
size_t n, ilvl;
#define VSMAX 100
char *vstrings[VSMAX];
size_t vsnum = 0;
char *astrings[VSMAX+1];
size_t asnum = 0;
char *const *hblock;
const char *ep;
t_bool excluded = FALSE;

/* variable arguments consumed table.
 * The scheme used allows arguments to be accessed in random
 * order, but for portability, all arguments must be char *.
 * If you try to violate this, there ARE machines that WILL break.
 */

memset (vstrings, 0, VSMAX * sizeof (char *));
memset (astrings, 0, VSMAX * sizeof (char *));
astrings[asnum++] = (char *) htext;

for (hblock = astrings; (htext = *hblock) != NULL; hblock++) {
    help_where.block = hblock - astrings;
    help_where.line = 0;
    while (*htext) {
        const char *start;







|
|






|











|
|







10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
free (topic->children);
return;
}

/* Build a help tree from a string.
 * Handles substitutions, formatting.
 */
static TOPIC *buildHelp (TOPIC *topic, DEVICE *dptr,
                         UNIT *uptr, const char *htext, va_list ap)
{
char *end;
size_t n, ilvl;
#define VSMAX 100
char *vstrings[VSMAX];
size_t vsnum = 0;
char * astrings[VSMAX+1];
size_t asnum = 0;
char *const *hblock;
const char *ep;
t_bool excluded = FALSE;

/* variable arguments consumed table.
 * The scheme used allows arguments to be accessed in random
 * order, but for portability, all arguments must be char *.
 * If you try to violate this, there ARE machines that WILL break.
 */

memset (vstrings, 0, sizeof (vstrings));
memset (astrings, 0, sizeof (astrings));
astrings[asnum++] = (char *) htext;

for (hblock = astrings; (htext = *hblock) != NULL; hblock++) {
    help_where.block = hblock - astrings;
    help_where.line = 0;
    while (*htext) {
        const char *start;
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
        strcat (newp, " ");
    }
strcat (newp, pstring);
free (prefix);
return newp;
}

static void displayMagicTopic (FILE *st, struct sim_device *dptr, TOPIC *topic)
{
char tbuf[CBUFSIZE];
size_t i, skiplines;
#ifdef _WIN32
FILE *tmp;
char *tmpnam;








|







11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
        strcat (newp, " ");
    }
strcat (newp, pstring);
free (prefix);
return newp;
}

static void displayMagicTopic (FILE *st, DEVICE *dptr, TOPIC *topic)
{
char tbuf[CBUFSIZE];
size_t i, skiplines;
#ifdef _WIN32
FILE *tmp;
char *tmpnam;

10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
free (tmpnam);
#endif
return;
}
/* Flatten and display help for those who say they prefer it.
 */

static t_stat displayFlatHelp (FILE *st, struct sim_device *dptr,
                               struct sim_unit *uptr, int32 flag,
                               TOPIC *topic, va_list ap )
{
size_t i;

if (topic->flags & HLP_MAGIC_TOPIC) {
    fprintf (st, "\n%s ", topic->label);
    displayMagicTopic (st, dptr, topic);







|
|







11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
free (tmpnam);
#endif
return;
}
/* Flatten and display help for those who say they prefer it.
 */

static t_stat displayFlatHelp (FILE *st, DEVICE *dptr,
                               UNIT *uptr, int32 flag,
                               TOPIC *topic, va_list ap )
{
size_t i;

if (topic->flags & HLP_MAGIC_TOPIC) {
    fprintf (st, "\n%s ", topic->label);
    displayMagicTopic (st, dptr, topic);
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
return match;
}

/* Main help routine
 * Takes a va_list
 */

t_stat scp_vhelp (FILE *st, struct sim_device *dptr,
                  struct sim_unit *uptr, int32 flag,
                  const char *help, const char *cptr, va_list ap)
{

TOPIC top;
TOPIC *topic = &top;
int failed;
size_t match;







|
|







11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
return match;
}

/* Main help routine
 * Takes a va_list
 */

t_stat scp_vhelp (FILE *st, DEVICE *dptr,
                  UNIT *uptr, int32 flag,
                  const char *help, const char *cptr, va_list ap)
{

TOPIC top;
TOPIC *topic = &top;
int failed;
size_t match;
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769

return SCPE_OK;
}

/* variable argument list shell - most commonly used
 */

t_stat scp_help (FILE *st, struct sim_device *dptr,
                 struct sim_unit *uptr, int32 flag,
                 const char *help, const char *cptr, ...)
{
t_stat r;
va_list ap;

va_start (ap, cptr);
r = scp_vhelp (st, dptr, uptr, flag, help, cptr, ap);
va_end (ap);

return r;
}

#if 01
/* Read help from a file
 *
 * Not recommended due to OS-dependent issues finding the file, + maintenance.
 * Don't hardcode any path - just name.hlp - so there's a chance the file can
 * be found.
 */

t_stat scp_vhelpFromFile (FILE *st, struct sim_device *dptr,
                         struct sim_unit *uptr, int32 flag,
                          const char *helpfile,
                          const char *cptr, va_list ap)
{
FILE *fp;
char *help, *p;
t_offset size, n;
int c;







|
|




















|
|







11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659

return SCPE_OK;
}

/* variable argument list shell - most commonly used
 */

t_stat scp_help (FILE *st, DEVICE *dptr,
                 UNIT *uptr, int32 flag,
                 const char *help, const char *cptr, ...)
{
t_stat r;
va_list ap;

va_start (ap, cptr);
r = scp_vhelp (st, dptr, uptr, flag, help, cptr, ap);
va_end (ap);

return r;
}

#if 01
/* Read help from a file
 *
 * Not recommended due to OS-dependent issues finding the file, + maintenance.
 * Don't hardcode any path - just name.hlp - so there's a chance the file can
 * be found.
 */

t_stat scp_vhelpFromFile (FILE *st, DEVICE *dptr,
                          UNIT *uptr, int32 flag,
                          const char *helpfile,
                          const char *cptr, va_list ap)
{
FILE *fp;
char *help, *p;
t_offset size, n;
int c;
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
         * work (one reason files are probably not a good idea),
         * but we might as well try.  Some OSs won't include a
         * path.  Having failed in the CWD, try to find the location
         * of the executable.  Failing that, try the 'help' subdirectory
         * of the executable.  Failing that, we're out of luck.
         */
        strncpy (fbuf, sim_argv[0], sizeof (fbuf));
        if ((p = match_ext (fbuf, "EXE")))
            *p = '\0';
        if ((p = strrchr (fbuf, '\\'))) {
            p[1] = '\0';
            d = "%s\\";
            }
        else {
            if ((p = strrchr (fbuf, '/'))) {







|







11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
         * work (one reason files are probably not a good idea),
         * but we might as well try.  Some OSs won't include a
         * path.  Having failed in the CWD, try to find the location
         * of the executable.  Failing that, try the 'help' subdirectory
         * of the executable.  Failing that, we're out of luck.
         */
        strncpy (fbuf, sim_argv[0], sizeof (fbuf));
        if ((p = (char *)match_ext (fbuf, "EXE")))
            *p = '\0';
        if ((p = strrchr (fbuf, '\\'))) {
            p[1] = '\0';
            d = "%s\\";
            }
        else {
            if ((p = strrchr (fbuf, '/'))) {
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871

r = scp_vhelp (st, dptr, uptr, flag, help, cptr, ap);
free (help);

return r;
}

t_stat scp_helpFromFile (FILE *st, struct sim_device *dptr,
                         struct sim_unit *uptr, int32 flag,
                         const char *helpfile, const char *cptr, ...)
{
t_stat r;
va_list ap;

va_start (ap, cptr);
r = scp_vhelpFromFile (st, dptr, uptr, flag, helpfile, cptr, ap);
va_end (ap);

return r;
}
#endif







|
|












11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761

r = scp_vhelp (st, dptr, uptr, flag, help, cptr, ap);
free (help);

return r;
}

t_stat scp_helpFromFile (FILE *st, DEVICE *dptr,
                         UNIT *uptr, int32 flag,
                         const char *helpfile, const char *cptr, ...)
{
t_stat r;
va_list ap;

va_start (ap, cptr);
r = scp_vhelpFromFile (st, dptr, uptr, flag, helpfile, cptr, ap);
va_end (ap);

return r;
}
#endif
Changes to src/scp.h.
32
33
34
35
36
37
38




39
40
41
42
43
44
45
   09-Sep-04    RMS     Added reset_all_p
   14-Feb-04    RMS     Added debug prototypes (from Dave Hittner)
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_SCP_H_
#define SIM_SCP_H_     0





/* run_cmd parameters */

#define RU_RUN          0                               /* run */
#define RU_GO           1                               /* go */
#define RU_STEP         2                               /* step */
#define RU_NEXT         3                               /* step or step/over */







>
>
>
>







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
   09-Sep-04    RMS     Added reset_all_p
   14-Feb-04    RMS     Added debug prototypes (from Dave Hittner)
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_SCP_H_
#define SIM_SCP_H_     0

#ifdef  __cplusplus
extern "C" {
#endif

/* run_cmd parameters */

#define RU_RUN          0                               /* run */
#define RU_GO           1                               /* go */
#define RU_STEP         2                               /* step */
#define RU_NEXT         3                               /* step or step/over */
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102








103
104
105
106
107
108
109
110
111
112


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

136

137
138
139

140
141
142
143
144
145
146
147


148

149



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

200
201








202
203
204
205

206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233


234
235

236
237
238
239
240
241
242
243
244

245
246




247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

269
270
271
272
273
274


275


#define CMD_OPT_SW      001                             /* switches */
#define CMD_OPT_OF      002                             /* output file */
#define CMD_OPT_SCH     004                             /* search */
#define CMD_OPT_DFT     010                             /* defaults */

/* Command processors */

t_stat reset_cmd (int32 flag, char *ptr);
t_stat exdep_cmd (int32 flag, char *ptr);
t_stat eval_cmd (int32 flag, char *ptr);
t_stat load_cmd (int32 flag, char *ptr);
t_stat run_cmd (int32 flag, char *ptr);
void run_cmd_message (const char *unechod_cmdline, t_stat r);
t_stat attach_cmd (int32 flag, char *ptr);
t_stat detach_cmd (int32 flag, char *ptr);
t_stat assign_cmd (int32 flag, char *ptr);
t_stat deassign_cmd (int32 flag, char *ptr);
t_stat save_cmd (int32 flag, char *ptr);
t_stat restore_cmd (int32 flag, char *ptr);
t_stat exit_cmd (int32 flag, char *ptr);
t_stat set_cmd (int32 flag, char *ptr);
t_stat show_cmd (int32 flag, char *ptr);
t_stat set_default_cmd (int32 flg, char *cptr);
t_stat pwd_cmd (int32 flg, char *cptr);
t_stat dir_cmd (int32 flg, char *cptr);

t_stat brk_cmd (int32 flag, char *ptr);
t_stat do_cmd (int32 flag, char *ptr);
t_stat goto_cmd (int32 flag, char *ptr);
t_stat return_cmd (int32 flag, char *ptr);
t_stat shift_cmd (int32 flag, char *ptr);
t_stat call_cmd (int32 flag, char *ptr);
t_stat on_cmd (int32 flag, char *ptr);
t_stat noop_cmd (int32 flag, char *ptr);
t_stat assert_cmd (int32 flag, char *ptr);
t_stat send_cmd (int32 flag, char *ptr);
t_stat expect_cmd (int32 flag, char *ptr);
t_stat help_cmd (int32 flag, char *ptr);
t_stat screenshot_cmd (int32 flag, char *ptr);
t_stat spawn_cmd (int32 flag, char *ptr);
t_stat echo_cmd (int32 flag, char *ptr);









/* Utility routines */

t_stat sim_process_event (void);
t_stat sim_activate (UNIT *uptr, int32 interval);
t_stat _sim_activate (UNIT *uptr, int32 interval);
t_stat sim_activate_abs (UNIT *uptr, int32 interval);
t_stat sim_activate_notbefore (UNIT *uptr, int32 rtime);
t_stat sim_activate_after (UNIT *uptr, int32 usecs_walltime);
t_stat _sim_activate_after (UNIT *uptr, int32 usecs_walltime);


t_stat sim_cancel (UNIT *uptr);
t_bool sim_is_active (UNIT *uptr);
int32 sim_activate_time (UNIT *uptr);
t_stat sim_run_boot_prep (void);
double sim_gtime (void);
uint32 sim_grtime (void);
int32 sim_qcount (void);
t_stat attach_unit (UNIT *uptr, char *cptr);
t_stat detach_unit (UNIT *uptr);
t_stat assign_device (DEVICE *dptr, char *cptr);
t_stat deassign_device (DEVICE *dptr);
t_stat reset_all (uint32 start_device);
t_stat reset_all_p (uint32 start_device);
const char *sim_dname (DEVICE *dptr);
const char *sim_uname (UNIT *dptr);
t_stat get_yn (const char *ques, t_stat deflt);
int sim_isspace (char c);
int sim_islower (char c);
int sim_isalpha (char c);
int sim_isprint (char c);
int sim_isdigit (char c);
int sim_isgraph (char c);
int sim_isalnum (char c);

char *get_sim_opt (int32 opt, char *cptr, t_stat *st);

char *get_glyph (const char *iptr, char *optr, char mchar);
char *get_glyph_nc (const char *iptr, char *optr, char mchar);
char *get_glyph_quoted (const char *iptr, char *optr, char mchar);

t_value get_uint (const char *cptr, uint32 radix, t_value max, t_stat *status);
const char *get_range (DEVICE *dptr, const char *cptr, t_addr *lo, t_addr *hi,
    uint32 rdx, t_addr max, char term);
t_stat sim_decode_quoted_string (const char *iptr, uint8 *optr, uint32 *osize);
char *sim_encode_quoted_string (const uint8 *iptr, uint32 size);
void fprint_buffer_string (FILE *st, const uint8 *buf, uint32 size);
t_value strtotv (const char *cptr, const char **endptr, uint32 radix);
int Fprintf (FILE *f, const char* fmt, ...);


t_stat fprint_val (FILE *stream, t_value val, uint32 rdx, uint32 wid, uint32 fmt);

t_stat sim_print_val (t_value val, uint32 radix, uint32 width, uint32 format);



char *read_line (char *cptr, int32 size, FILE *stream);
void fprint_reg_help (FILE *st, DEVICE *dptr);
void fprint_set_help (FILE *st, DEVICE *dptr);
void fprint_show_help (FILE *st, DEVICE *dptr);
CTAB *find_cmd (const char *gbuf);
DEVICE *find_dev (const char *ptr);
DEVICE *find_unit (const char *ptr, UNIT **uptr);
DEVICE *find_dev_from_unit (UNIT *uptr);
t_stat sim_register_internal_device (DEVICE *dptr);
void sim_sub_args (char *in_str, size_t in_str_size, char *do_arg[]);
REG *find_reg (const char *ptr, const char **optr, DEVICE *dptr);
CTAB *find_ctab (CTAB *tab, const char *gbuf);
C1TAB *find_c1tab (C1TAB *tab, const char *gbuf);
SHTAB *find_shtab (SHTAB *tab, const char *gbuf);
t_stat get_aval (t_addr addr, DEVICE *dptr, UNIT *uptr);
BRKTAB *sim_brk_fnd (t_addr loc);
uint32 sim_brk_test (t_addr bloc, uint32 btyp);
void sim_brk_clrspc (uint32 spc);
char *sim_brk_clract (void);
void sim_brk_setact (const char *action);

t_stat sim_send_input (SEND *snd, uint8 *data, size_t size, uint32 after, uint32 delay);
t_stat sim_show_send_input (FILE *st, SEND *snd);
t_bool sim_send_poll_data (SEND *snd, t_stat *stat);
t_stat sim_send_clear (SEND *snd);
t_stat sim_set_expect (EXPECT *exp, char *cptr);
t_stat sim_set_noexpect (EXPECT *exp, char *cptr);
t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, char *act);
t_stat sim_exp_clr (EXPECT *exp, const char *match);
t_stat sim_exp_clrall (EXPECT *exp);
t_stat sim_exp_show (FILE *st, EXPECT *exp, const char *match);
t_stat sim_exp_showall (FILE *st, EXPECT *exp);
t_stat sim_exp_check (EXPECT *exp, uint8 data);
char *match_ext (char *fnam, const char *ext);
t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
const char *sim_error_text (t_stat stat);
t_stat sim_string_to_stat (char *cptr, t_stat *cond);
t_stat sim_cancel_step (void);
void sim_printf (const char* fmt, ...);
void sim_perror (const char* msg);
t_stat sim_messagef (t_stat stat, const char* fmt, ...);
void sim_data_trace(DEVICE *dptr, UNIT *uptr, const uint8 *data, const char *position, size_t len, const char *txt, uint32 reason);
void sim_debug_bits_hdr (uint32 dbits, DEVICE* dptr, const char *header, 
    BITFIELD* bitdefs, uint32 before, uint32 after, int terminate);
void sim_debug_bits (uint32 dbits, DEVICE* dptr, BITFIELD* bitdefs,
    uint32 before, uint32 after, int terminate);
#if defined (__DECC) && defined (__VMS) && (defined (__VAX) || (__DECC_VER < 60590001))
#define CANT_USE_MACRO_VA_ARGS 1
#endif

#ifdef CANT_USE_MACRO_VA_ARGS
#define _sim_debug sim_debug








void sim_debug (uint32 dbits, DEVICE* dptr, const char* fmt, ...);
#else
void _sim_debug (uint32 dbits, DEVICE* dptr, const char* fmt, ...);
#define sim_debug(dbits, dptr, ...) if (sim_deb && dptr && ((dptr)->dctrl & dbits)) _sim_debug (dbits, dptr, __VA_ARGS__); else (void)0

#endif
void fprint_stopped_gen (FILE *st, t_stat v, REG *pc, DEVICE *dptr);
#define SCP_HELP_FLAT   (1u << 31)       /* Force flat help when prompting is not possible */
#define SCP_HELP_ONECMD (1u << 30)       /* Display one topic, do not prompt */
#define SCP_HELP_ATTACH (1u << 29)       /* Top level topic is ATTACH help */
t_stat scp_help (FILE *st, struct sim_device *dptr,
                 struct sim_unit *uptr, int32 flag, const char *help, const char *cptr, ...);
t_stat scp_vhelp (FILE *st, struct sim_device *dptr,
                  struct sim_unit *uptr, int32 flag, const char *help, const char *cptr, va_list ap);
t_stat scp_helpFromFile (FILE *st, struct sim_device *dptr,
                         struct sim_unit *uptr, int32 flag, const char *help, const char *cptr, ...);
t_stat scp_vhelpFromFile (FILE *st, struct sim_device *dptr,
                          struct sim_unit *uptr, int32 flag, const char *help, const char *cptr, va_list ap);

/* Global data */

extern DEVICE *sim_dflt_dev;
extern int32 sim_interval;
extern int32 sim_switches;
extern int32 sim_quiet;
extern int32 sim_step;
extern t_stat sim_last_cmd_stat;                        /* Command Status */
extern FILE *sim_log;                                   /* log file */
extern FILEREF *sim_log_ref;                            /* log file file reference */
extern FILE *sim_deb;                                   /* debug file */
extern FILEREF *sim_deb_ref;                            /* debug file file reference */
extern int32 sim_deb_switches;                          /* debug display flags */
extern struct timespec sim_deb_basetime;                /* debug base time for relative time output */


extern UNIT *sim_clock_queue;
extern int32 sim_is_running;

extern char *sim_prompt;                                /* prompt string */
extern const char *sim_savename;                        /* Simulator Name used in Save/Restore files */
extern t_value *sim_eval;
extern volatile int32 stop_cpu;
extern uint32 sim_brk_types;                            /* breakpoint info */
extern uint32 sim_brk_dflt;
extern uint32 sim_brk_summ;
extern t_bool sim_brk_pend[SIM_BKPT_N_SPC];
extern t_addr sim_brk_ploc[SIM_BKPT_N_SPC];

extern FILE *stdnul;
extern t_bool sim_asynch_enabled;





/* VM interface */

extern char sim_name[];
extern DEVICE *sim_devices[];
extern REG *sim_PC;
extern const char *sim_stop_messages[];
extern t_stat sim_instr (void);
extern t_stat sim_load (FILE *ptr, char *cptr, char *fnam, int flag);
extern int32 sim_emax;
extern t_stat fprint_sym (FILE *ofile, t_addr addr, t_value *val,
    UNIT *uptr, int32 sw);
extern t_stat parse_sym (char *cptr, t_addr addr, UNIT *uptr, t_value *val,
    int32 sw);

/* The per-simulator init routine is a weak global that defaults to NULL
   The other per-simulator pointers can be overrriden by the init routine */

extern void (*sim_vm_init) (void);
extern char* (*sim_vm_read) (char *ptr, int32 size, FILE *stream);
extern void (*sim_vm_post) (t_bool from_scp);
extern CTAB *sim_vm_cmd;

extern void (*sim_vm_fprint_addr) (FILE *st, DEVICE *dptr, t_addr addr);
extern t_addr (*sim_vm_parse_addr) (DEVICE *dptr, char *cptr, char **tptr);
extern t_bool (*sim_vm_fprint_stopped) (FILE *st, t_stat reason);
extern t_value (*sim_vm_pc_value) (void);
extern t_bool (*sim_vm_is_subroutine_call) (t_addr **ret_addrs);



#endif









|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>








|
|
>
>



|



|

|













>
|
>
|
|
|
>

|




|
|
>
>

>

>
>
>










|






|
|

>

|


|
|
|


|
|

|
|
|
|

|

|
|
|








>


>
>
>
>
>
>
>
>
|

|
|
>





|
|
|
|
|
|
|
|















>
>


>







|
|
>


>
>
>
>








|



|





|
|


>

|




>
>

>
>
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#define CMD_OPT_SW      001                             /* switches */
#define CMD_OPT_OF      002                             /* output file */
#define CMD_OPT_SCH     004                             /* search */
#define CMD_OPT_DFT     010                             /* defaults */

/* Command processors */

t_stat reset_cmd (int32 flag, CONST char *ptr);
t_stat exdep_cmd (int32 flag, CONST char *ptr);
t_stat eval_cmd (int32 flag, CONST char *ptr);
t_stat load_cmd (int32 flag, CONST char *ptr);
t_stat run_cmd (int32 flag, CONST char *ptr);
void run_cmd_message (const char *unechod_cmdline, t_stat r);
t_stat attach_cmd (int32 flag, CONST char *ptr);
t_stat detach_cmd (int32 flag, CONST char *ptr);
t_stat assign_cmd (int32 flag, CONST char *ptr);
t_stat deassign_cmd (int32 flag, CONST char *ptr);
t_stat save_cmd (int32 flag, CONST char *ptr);
t_stat restore_cmd (int32 flag, CONST char *ptr);
t_stat exit_cmd (int32 flag, CONST char *ptr);
t_stat set_cmd (int32 flag, CONST char *ptr);
t_stat show_cmd (int32 flag, CONST char *ptr);
t_stat set_default_cmd (int32 flg, CONST char *cptr);
t_stat pwd_cmd (int32 flg, CONST char *cptr);
t_stat dir_cmd (int32 flg, CONST char *cptr);
t_stat type_cmd (int32 flg, CONST char *cptr);
t_stat brk_cmd (int32 flag, CONST char *ptr);
t_stat do_cmd (int32 flag, CONST char *ptr);
t_stat goto_cmd (int32 flag, CONST char *ptr);
t_stat return_cmd (int32 flag, CONST char *ptr);
t_stat shift_cmd (int32 flag, CONST char *ptr);
t_stat call_cmd (int32 flag, CONST char *ptr);
t_stat on_cmd (int32 flag, CONST char *ptr);
t_stat noop_cmd (int32 flag, CONST char *ptr);
t_stat assert_cmd (int32 flag, CONST char *ptr);
t_stat send_cmd (int32 flag, CONST char *ptr);
t_stat expect_cmd (int32 flag, CONST char *ptr);
t_stat help_cmd (int32 flag, CONST char *ptr);
t_stat screenshot_cmd (int32 flag, CONST char *ptr);
t_stat spawn_cmd (int32 flag, CONST char *ptr);
t_stat echo_cmd (int32 flag, CONST char *ptr);

/* Allow compiler to help validate printf style format arguments */
#if !defined __GNUC__
#define GCC_FMT_ATTR(n, m)
#endif
#if !defined(GCC_FMT_ATTR)
#define GCC_FMT_ATTR(n, m) __attribute__ ((format (__printf__, n, m)))
#endif

/* Utility routines */

t_stat sim_process_event (void);
t_stat sim_activate (UNIT *uptr, int32 interval);
t_stat _sim_activate (UNIT *uptr, int32 interval);
t_stat sim_activate_abs (UNIT *uptr, int32 interval);
t_stat sim_activate_notbefore (UNIT *uptr, int32 rtime);
t_stat sim_activate_after (UNIT *uptr, uint32 usecs_walltime);
t_stat _sim_activate_after (UNIT *uptr, uint32 usecs_walltime);
t_stat sim_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat _sim_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat sim_cancel (UNIT *uptr);
t_bool sim_is_active (UNIT *uptr);
int32 sim_activate_time (UNIT *uptr);
t_stat sim_run_boot_prep (int32 flag);
double sim_gtime (void);
uint32 sim_grtime (void);
int32 sim_qcount (void);
t_stat attach_unit (UNIT *uptr, CONST char *cptr);
t_stat detach_unit (UNIT *uptr);
t_stat assign_device (DEVICE *dptr, const char *cptr);
t_stat deassign_device (DEVICE *dptr);
t_stat reset_all (uint32 start_device);
t_stat reset_all_p (uint32 start_device);
const char *sim_dname (DEVICE *dptr);
const char *sim_uname (UNIT *dptr);
t_stat get_yn (const char *ques, t_stat deflt);
int sim_isspace (char c);
int sim_islower (char c);
int sim_isalpha (char c);
int sim_isprint (char c);
int sim_isdigit (char c);
int sim_isgraph (char c);
int sim_isalnum (char c);
int sim_strncasecmp (const char *string1, const char *string2, size_t len);
CONST char *get_sim_opt (int32 opt, CONST char *cptr, t_stat *st);
const char *put_switches (char *buf, size_t bufsize, uint32 sw);
CONST char *get_glyph (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_nc (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_quoted (const char *iptr, char *optr, char mchar);
CONST char *get_glyph_cmd (const char *iptr, char *optr);
t_value get_uint (const char *cptr, uint32 radix, t_value max, t_stat *status);
CONST char *get_range (DEVICE *dptr, CONST char *cptr, t_addr *lo, t_addr *hi,
    uint32 rdx, t_addr max, char term);
t_stat sim_decode_quoted_string (const char *iptr, uint8 *optr, uint32 *osize);
char *sim_encode_quoted_string (const uint8 *iptr, uint32 size);
void fprint_buffer_string (FILE *st, const uint8 *buf, uint32 size);
t_value strtotv (CONST char *cptr, CONST char **endptr, uint32 radix);
int Fprintf (FILE *f, const char *fmt, ...) GCC_FMT_ATTR(2, 3);
t_stat sim_set_memory_load_file (const unsigned char *data, size_t size);
int Fgetc (FILE *f);
t_stat fprint_val (FILE *stream, t_value val, uint32 rdx, uint32 wid, uint32 fmt);
t_stat sprint_val (char *buf, t_value val, uint32 rdx, uint32 wid, uint32 fmt);
t_stat sim_print_val (t_value val, uint32 radix, uint32 width, uint32 format);
const char *sim_fmt_secs (double seconds);
const char *sim_fmt_numeric (double number);
const char *sprint_capac (DEVICE *dptr, UNIT *uptr);
char *read_line (char *cptr, int32 size, FILE *stream);
void fprint_reg_help (FILE *st, DEVICE *dptr);
void fprint_set_help (FILE *st, DEVICE *dptr);
void fprint_show_help (FILE *st, DEVICE *dptr);
CTAB *find_cmd (const char *gbuf);
DEVICE *find_dev (const char *ptr);
DEVICE *find_unit (const char *ptr, UNIT **uptr);
DEVICE *find_dev_from_unit (UNIT *uptr);
t_stat sim_register_internal_device (DEVICE *dptr);
void sim_sub_args (char *in_str, size_t in_str_size, char *do_arg[]);
REG *find_reg (CONST char *ptr, CONST char **optr, DEVICE *dptr);
CTAB *find_ctab (CTAB *tab, const char *gbuf);
C1TAB *find_c1tab (C1TAB *tab, const char *gbuf);
SHTAB *find_shtab (SHTAB *tab, const char *gbuf);
t_stat get_aval (t_addr addr, DEVICE *dptr, UNIT *uptr);
BRKTAB *sim_brk_fnd (t_addr loc);
uint32 sim_brk_test (t_addr bloc, uint32 btyp);
void sim_brk_clrspc (uint32 spc, uint32 btyp);
void sim_brk_npc (uint32 cnt);
void sim_brk_setact (const char *action);
const char *sim_brk_message(void);
t_stat sim_send_input (SEND *snd, uint8 *data, size_t size, uint32 after, uint32 delay);
t_stat sim_show_send_input (FILE *st, const SEND *snd);
t_bool sim_send_poll_data (SEND *snd, t_stat *stat);
t_stat sim_send_clear (SEND *snd);
t_stat sim_set_expect (EXPECT *exp, CONST char *cptr);
t_stat sim_set_noexpect (EXPECT *exp, const char *cptr);
t_stat sim_exp_set (EXPECT *exp, const char *match, int32 cnt, uint32 after, int32 switches, const char *act);
t_stat sim_exp_clr (EXPECT *exp, const char *match);
t_stat sim_exp_clrall (EXPECT *exp);
t_stat sim_exp_show (FILE *st, CONST EXPECT *exp, const char *match);
t_stat sim_exp_showall (FILE *st, const EXPECT *exp);
t_stat sim_exp_check (EXPECT *exp, uint8 data);
CONST char *match_ext (CONST char *fnam, const char *ext);
t_stat show_version (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat set_dev_debug (DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_dev_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
const char *sim_error_text (t_stat stat);
t_stat sim_string_to_stat (const char *cptr, t_stat *cond);
t_stat sim_cancel_step (void);
void sim_printf (const char *fmt, ...) GCC_FMT_ATTR(1, 2);
void sim_perror (const char *msg);
t_stat sim_messagef (t_stat stat, const char *fmt, ...) GCC_FMT_ATTR(2, 3);
void sim_data_trace(DEVICE *dptr, UNIT *uptr, const uint8 *data, const char *position, size_t len, const char *txt, uint32 reason);
void sim_debug_bits_hdr (uint32 dbits, DEVICE* dptr, const char *header, 
    BITFIELD* bitdefs, uint32 before, uint32 after, int terminate);
void sim_debug_bits (uint32 dbits, DEVICE* dptr, BITFIELD* bitdefs,
    uint32 before, uint32 after, int terminate);
#if defined (__DECC) && defined (__VMS) && (defined (__VAX) || (__DECC_VER < 60590001))
#define CANT_USE_MACRO_VA_ARGS 1
#endif
#if defined(__cplusplus)
#ifdef CANT_USE_MACRO_VA_ARGS
#define _sim_debug sim_debug
void sim_debug (uint32 dbits, void* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug (uint32 dbits, void* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#define sim_debug(dbits, dptr, ...) do { if (sim_deb && dptr && ((dptr)->dctrl & dbits)) _sim_debug (dbits, dptr, __VA_ARGS__);} while (0)
#endif
#else
#ifdef CANT_USE_MACRO_VA_ARGS
#define _sim_debug sim_debug
void sim_debug (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#define sim_debug(dbits, dptr, ...) do { if (sim_deb && dptr && ((dptr)->dctrl & dbits)) _sim_debug (dbits, dptr, __VA_ARGS__);} while (0)
#endif
#endif
void fprint_stopped_gen (FILE *st, t_stat v, REG *pc, DEVICE *dptr);
#define SCP_HELP_FLAT   (1u << 31)       /* Force flat help when prompting is not possible */
#define SCP_HELP_ONECMD (1u << 30)       /* Display one topic, do not prompt */
#define SCP_HELP_ATTACH (1u << 29)       /* Top level topic is ATTACH help */
t_stat scp_help (FILE *st, DEVICE *dptr,
                 UNIT *uptr, int32 flag, const char *help, const char *cptr, ...);
t_stat scp_vhelp (FILE *st, DEVICE *dptr,
                  UNIT *uptr, int32 flag, const char *help, const char *cptr, va_list ap);
t_stat scp_helpFromFile (FILE *st, DEVICE *dptr,
                         UNIT *uptr, int32 flag, const char *help, const char *cptr, ...);
t_stat scp_vhelpFromFile (FILE *st, DEVICE *dptr,
                          UNIT *uptr, int32 flag, const char *help, const char *cptr, va_list ap);

/* Global data */

extern DEVICE *sim_dflt_dev;
extern int32 sim_interval;
extern int32 sim_switches;
extern int32 sim_quiet;
extern int32 sim_step;
extern t_stat sim_last_cmd_stat;                        /* Command Status */
extern FILE *sim_log;                                   /* log file */
extern FILEREF *sim_log_ref;                            /* log file file reference */
extern FILE *sim_deb;                                   /* debug file */
extern FILEREF *sim_deb_ref;                            /* debug file file reference */
extern int32 sim_deb_switches;                          /* debug display flags */
extern struct timespec sim_deb_basetime;                /* debug base time for relative time output */
extern DEVICE **sim_internal_devices;
extern uint32 sim_internal_device_count;
extern UNIT *sim_clock_queue;
extern int32 sim_is_running;
extern t_bool sim_processing_event;                     /* Called from sim_process_event */
extern char *sim_prompt;                                /* prompt string */
extern const char *sim_savename;                        /* Simulator Name used in Save/Restore files */
extern t_value *sim_eval;
extern volatile int32 stop_cpu;
extern uint32 sim_brk_types;                            /* breakpoint info */
extern uint32 sim_brk_dflt;
extern uint32 sim_brk_summ;
extern uint32 sim_brk_match_type;
extern t_addr sim_brk_match_addr;
extern BRKTYPTAB *sim_brk_type_desc;                      /* type descriptions */
extern FILE *stdnul;
extern t_bool sim_asynch_enabled;
#if defined(SIM_ASYNCH_IO)
int sim_aio_update_queue (void);
void sim_aio_activate (ACTIVATE_API caller, UNIT *uptr, int32 event_time);
#endif

/* VM interface */

extern char sim_name[];
extern DEVICE *sim_devices[];
extern REG *sim_PC;
extern const char *sim_stop_messages[];
extern t_stat sim_instr (void);
extern t_stat sim_load (FILE *ptr, CONST char *cptr, CONST char *fnam, int flag);
extern int32 sim_emax;
extern t_stat fprint_sym (FILE *ofile, t_addr addr, t_value *val,
    UNIT *uptr, int32 sw);
extern t_stat parse_sym (CONST char *cptr, t_addr addr, UNIT *uptr, t_value *val,
    int32 sw);

/* The per-simulator init routine is a weak global that defaults to NULL
   The other per-simulator pointers can be overrriden by the init routine */

WEAK extern void (*sim_vm_init) (void);
extern char *(*sim_vm_read) (char *ptr, int32 size, FILE *stream);
extern void (*sim_vm_post) (t_bool from_scp);
extern CTAB *sim_vm_cmd;
extern void (*sim_vm_sprint_addr) (char *buf, DEVICE *dptr, t_addr addr);
extern void (*sim_vm_fprint_addr) (FILE *st, DEVICE *dptr, t_addr addr);
extern t_addr (*sim_vm_parse_addr) (DEVICE *dptr, CONST char *cptr, CONST char **tptr);
extern t_bool (*sim_vm_fprint_stopped) (FILE *st, t_stat reason);
extern t_value (*sim_vm_pc_value) (void);
extern t_bool (*sim_vm_is_subroutine_call) (t_addr **ret_addrs);

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_console.c.
125
126
127
128
129
130
131

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175



176
177
178
179
180
181
182
183
*/

#include "sim_defs.h"
#include "sim_tmxr.h"
#include "sim_serial.h"
#include "sim_timer.h"
#include <ctype.h>

 
#ifdef __HAIKU__
#define nice(n) ({})
#endif

/* Forward Declaraations of Platform specific routines */

static t_stat sim_os_poll_kbd (void);
static t_bool sim_os_poll_kbd_ready (int ms_timeout);
static t_stat sim_os_putchar (int32 out);
static t_stat sim_os_ttinit (void);
static t_stat sim_os_ttrun (void);
static t_stat sim_os_ttcmd (void);
static t_stat sim_os_ttclose (void);
static t_bool sim_os_ttisatty (void);

static t_stat sim_set_rem_telnet (int32 flag, char *cptr);

static t_stat sim_set_rem_connections (int32 flag, char *cptr);
static t_stat sim_set_rem_timeout (int32 flag, char *cptr);
static t_stat sim_set_rem_master (int32 flag, char *cptr);

/* Deprecated CONSOLE HALT, CONSOLE RESPONSE and CONSOLE DELAY support */
static t_stat sim_set_halt (int32 flag, char *cptr);
static t_stat sim_set_response (int32 flag, char *cptr);
static t_stat sim_set_delay (int32 flag, char *cptr);


#define KMAP_WRU        0
#define KMAP_BRK        1
#define KMAP_DEL        2
#define KMAP_MASK       0377
#define KMAP_NZ         0400

int32 sim_int_char = 005;                               /* interrupt character */
int32 sim_brk_char = 000;                               /* break character */
int32 sim_tt_pchar = 0x00002780;
#if defined (_WIN32) || defined (__OS2__) || (defined (__MWERKS__) && defined (macintosh))
int32 sim_del_char = '\b';                              /* delete character */
#else
int32 sim_del_char = 0177;
#endif

static t_stat sim_con_poll_svc (UNIT *uptr);                /* console connection poll routine */
static t_stat sim_con_reset (DEVICE *dptr);                 /* console reset routine */



UNIT sim_con_unit = { UDATA (&sim_con_poll_svc, 0, 0)  };   /* console connection unit */
/* debugging bitmaps */
#define DBG_TRC  TMXR_DBG_TRC                           /* trace routine calls */
#define DBG_XMT  TMXR_DBG_XMT                           /* display Transmitted Data */
#define DBG_RCV  TMXR_DBG_RCV                           /* display Received Data */
#define DBG_RET  TMXR_DBG_RET                           /* display Returned Received Data */
#define DBG_ASY  TMXR_DBG_ASY                           /* asynchronous thread activity */
#define DBG_EXP  0x00000001                             /* Expect match activity */







>
|















|
>
|
|
|


|
|
|



















>
>
>
|







125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
*/

#include "sim_defs.h"
#include "sim_tmxr.h"
#include "sim_serial.h"
#include "sim_timer.h"
#include <ctype.h>
#include <math.h>

#ifdef __HAIKU__
#define nice(n) ({})
#endif

/* Forward Declaraations of Platform specific routines */

static t_stat sim_os_poll_kbd (void);
static t_bool sim_os_poll_kbd_ready (int ms_timeout);
static t_stat sim_os_putchar (int32 out);
static t_stat sim_os_ttinit (void);
static t_stat sim_os_ttrun (void);
static t_stat sim_os_ttcmd (void);
static t_stat sim_os_ttclose (void);
static t_bool sim_os_ttisatty (void);

static t_stat sim_set_rem_telnet (int32 flag, CONST char *cptr);
static t_stat sim_set_rem_bufsize (int32 flag, CONST char *cptr);
static t_stat sim_set_rem_connections (int32 flag, CONST char *cptr);
static t_stat sim_set_rem_timeout (int32 flag, CONST char *cptr);
static t_stat sim_set_rem_master (int32 flag, CONST char *cptr);

/* Deprecated CONSOLE HALT, CONSOLE RESPONSE and CONSOLE DELAY support */
static t_stat sim_set_halt (int32 flag, CONST char *cptr);
static t_stat sim_set_response (int32 flag, CONST char *cptr);
static t_stat sim_set_delay (int32 flag, CONST char *cptr);


#define KMAP_WRU        0
#define KMAP_BRK        1
#define KMAP_DEL        2
#define KMAP_MASK       0377
#define KMAP_NZ         0400

int32 sim_int_char = 005;                               /* interrupt character */
int32 sim_brk_char = 000;                               /* break character */
int32 sim_tt_pchar = 0x00002780;
#if defined (_WIN32) || defined (__OS2__) || (defined (__MWERKS__) && defined (macintosh))
int32 sim_del_char = '\b';                              /* delete character */
#else
int32 sim_del_char = 0177;
#endif

static t_stat sim_con_poll_svc (UNIT *uptr);                /* console connection poll routine */
static t_stat sim_con_reset (DEVICE *dptr);                 /* console reset routine */
static t_stat sim_con_attach (UNIT *uptr, CONST char *ptr); /* console attach routine (save,restore) */
static t_stat sim_con_detach (UNIT *uptr);                  /* console detach routine (save,restore) */

UNIT sim_con_unit = { UDATA (&sim_con_poll_svc, UNIT_ATTABLE, 0)  };/* console connection unit */
/* debugging bitmaps */
#define DBG_TRC  TMXR_DBG_TRC                           /* trace routine calls */
#define DBG_XMT  TMXR_DBG_XMT                           /* display Transmitted Data */
#define DBG_RCV  TMXR_DBG_RCV                           /* display Received Data */
#define DBG_RET  TMXR_DBG_RET                           /* display Returned Received Data */
#define DBG_ASY  TMXR_DBG_ASY                           /* asynchronous thread activity */
#define DBG_EXP  0x00000001                             /* Expect match activity */
201
202
203
204
205
206
207





208
209
210
211
212
213

214
215
216
217
218
219
220
    { ORDATAD (PCHAR, sim_tt_pchar, 32, "printable character mask") },
  { 0 },
};

static MTAB sim_con_mod[] = {
  { 0 },
};






DEVICE sim_con_telnet = {
    "CON-TEL", &sim_con_unit, sim_con_reg, sim_con_mod, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, sim_con_reset, NULL, NULL, NULL, 
    NULL, DEV_DEBUG, 0, sim_con_debug};

TMLN sim_con_ldsc = { 0 };                                          /* console line descr */
TMXR sim_con_tmxr = { 1, 0, 0, &sim_con_ldsc, NULL, &sim_con_telnet };/* console line mux */


SEND sim_con_send = {SEND_DEFAULT_DELAY, &sim_con_telnet, DBG_SND};
EXPECT sim_con_expect = {&sim_con_telnet, DBG_EXP};








>
>
>
>
>




|
|
>







206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    { ORDATAD (PCHAR, sim_tt_pchar, 32, "printable character mask") },
  { 0 },
};

static MTAB sim_con_mod[] = {
  { 0 },
};

static const char *sim_con_telnet_description (DEVICE *dptr)
{
return "Console telnet support";
}

DEVICE sim_con_telnet = {
    "CON-TEL", &sim_con_unit, sim_con_reg, sim_con_mod, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, sim_con_reset, NULL, sim_con_attach, sim_con_detach, 
    NULL, DEV_DEBUG, 0, sim_con_debug,
    NULL, NULL, NULL, NULL, NULL, sim_con_telnet_description};
TMLN sim_con_ldsc = { 0 };                                          /* console line descr */
TMXR sim_con_tmxr = { 1, 0, 0, &sim_con_ldsc, NULL, &sim_con_telnet };/* console line mux */


SEND sim_con_send = {SEND_DEFAULT_DELAY, &sim_con_telnet, DBG_SND};
EXPECT sim_con_expect = {&sim_con_telnet, DBG_EXP};

247
248
249
250
251
252
253











254
255
256
257
258
259
260
261

262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

282
283
284
285
286
287
288
289
290
291
292
293

294
295
296
297
298
299
300
}

static t_stat sim_con_reset (DEVICE *dptr)
{
return sim_con_poll_svc (&dptr->units[0]);              /* establish polling as needed */
}













/* Set/show data structures */

static CTAB set_con_tab[] = {
    { "WRU", &sim_set_kmap, KMAP_WRU | KMAP_NZ },
    { "BRK", &sim_set_kmap, KMAP_BRK },
    { "DEL", &sim_set_kmap, KMAP_DEL |KMAP_NZ },
    { "PCHAR", &sim_set_pchar, 0 },

    { "TELNET", &sim_set_telnet, 0 },
    { "NOTELNET", &sim_set_notelnet, 0 },
    { "SERIAL", &sim_set_serial, 0 },
    { "NOSERIAL", &sim_set_noserial, 0 },
    { "LOG", &sim_set_logon, 0 },
    { "NOLOG", &sim_set_logoff, 0 },
    { "DEBUG", &sim_set_debon, 0 },
    { "NODEBUG", &sim_set_deboff, 0 },
#define CMD_WANTSTR     0100000
    { "HALT", &sim_set_halt, 1 | CMD_WANTSTR },
    { "NOHALT", &sim_set_halt, 0 },
    { "DELAY", &sim_set_delay, 0 },
    { "RESPONSE", &sim_set_response, 1 | CMD_WANTSTR },
    { "NORESPONSE", &sim_set_response, 0 },
    { NULL, NULL, 0 }
    };

static CTAB set_rem_con_tab[] = {
    { "CONNECTIONS", &sim_set_rem_connections, 0 },
    { "TELNET", &sim_set_rem_telnet, 1 },

    { "NOTELNET", &sim_set_rem_telnet, 0 },
    { "TIMEOUT", &sim_set_rem_timeout, 0 },
    { "MASTER", &sim_set_rem_master, 1 },
    { "NOMASTER", &sim_set_rem_master, 0 },
    { NULL, NULL, 0 }
    };

static SHTAB show_con_tab[] = {
    { "WRU", &sim_show_kmap, KMAP_WRU },
    { "BRK", &sim_show_kmap, KMAP_BRK },
    { "DEL", &sim_show_kmap, KMAP_DEL },
    { "PCHAR", &sim_show_pchar, 0 },

    { "LOG", &sim_show_cons_log, 0 },
    { "TELNET", &sim_show_telnet, 0 },
    { "DEBUG", &sim_show_cons_debug, 0 },
    { "BUFFERED", &sim_show_cons_buff, 0 },
    { "EXPECT", &sim_show_cons_expect, 0 },
    { "HALT", &sim_show_cons_expect, 0 },
    { "INPUT", &sim_show_cons_send_input, 0 },







>
>
>
>
>
>
>
>
>
>
>








>




















>












>







258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
}

static t_stat sim_con_reset (DEVICE *dptr)
{
return sim_con_poll_svc (&dptr->units[0]);              /* establish polling as needed */
}

/* Console Attach/Detach - only used indirectly in restore */

static t_stat sim_con_attach (UNIT *uptr, CONST char *ptr)
{
return tmxr_attach (&sim_con_tmxr, &sim_con_unit, ptr);
}

static t_stat sim_con_detach (UNIT *uptr)
{
return sim_set_notelnet (0, NULL);
}

/* Set/show data structures */

static CTAB set_con_tab[] = {
    { "WRU", &sim_set_kmap, KMAP_WRU | KMAP_NZ },
    { "BRK", &sim_set_kmap, KMAP_BRK },
    { "DEL", &sim_set_kmap, KMAP_DEL |KMAP_NZ },
    { "PCHAR", &sim_set_pchar, 0 },
    { "SPEED", &sim_set_cons_speed, 0 },
    { "TELNET", &sim_set_telnet, 0 },
    { "NOTELNET", &sim_set_notelnet, 0 },
    { "SERIAL", &sim_set_serial, 0 },
    { "NOSERIAL", &sim_set_noserial, 0 },
    { "LOG", &sim_set_logon, 0 },
    { "NOLOG", &sim_set_logoff, 0 },
    { "DEBUG", &sim_set_debon, 0 },
    { "NODEBUG", &sim_set_deboff, 0 },
#define CMD_WANTSTR     0100000
    { "HALT", &sim_set_halt, 1 | CMD_WANTSTR },
    { "NOHALT", &sim_set_halt, 0 },
    { "DELAY", &sim_set_delay, 0 },
    { "RESPONSE", &sim_set_response, 1 | CMD_WANTSTR },
    { "NORESPONSE", &sim_set_response, 0 },
    { NULL, NULL, 0 }
    };

static CTAB set_rem_con_tab[] = {
    { "CONNECTIONS", &sim_set_rem_connections, 0 },
    { "TELNET", &sim_set_rem_telnet, 1 },
    { "BUFFERSIZE", &sim_set_rem_bufsize, 1 },
    { "NOTELNET", &sim_set_rem_telnet, 0 },
    { "TIMEOUT", &sim_set_rem_timeout, 0 },
    { "MASTER", &sim_set_rem_master, 1 },
    { "NOMASTER", &sim_set_rem_master, 0 },
    { NULL, NULL, 0 }
    };

static SHTAB show_con_tab[] = {
    { "WRU", &sim_show_kmap, KMAP_WRU },
    { "BRK", &sim_show_kmap, KMAP_BRK },
    { "DEL", &sim_show_kmap, KMAP_DEL },
    { "PCHAR", &sim_show_pchar, 0 },
    { "SPEED", &sim_show_cons_speed, 0 },
    { "LOG", &sim_show_cons_log, 0 },
    { "TELNET", &sim_show_telnet, 0 },
    { "DEBUG", &sim_show_cons_debug, 0 },
    { "BUFFERED", &sim_show_cons_buff, 0 },
    { "EXPECT", &sim_show_cons_expect, 0 },
    { "HALT", &sim_show_cons_expect, 0 },
    { "INPUT", &sim_show_cons_send_input, 0 },
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
   or to a Telnet connection.  If attached to a Telnet connection,
   the console is described by internal terminal multiplexor
   sim_con_tmxr and internal terminal line description sim_con_ldsc.
*/

/* SET CONSOLE command */

t_stat sim_set_console (int32 flag, char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;







|







355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
   or to a Telnet connection.  If attached to a Telnet connection,
   the console is described by internal terminal multiplexor
   sim_con_tmxr and internal terminal line description sim_con_ldsc.
*/

/* SET CONSOLE command */

t_stat sim_set_console (int32 flag, CONST char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

/* SHOW CONSOLE command */

t_stat sim_show_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
SHTAB *shptr;
int32 i;

if (*cptr == 0) {                                       /* show all */
    for (i = 0; show_con_tab[i].name; i++)







|







380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

/* SHOW CONSOLE command */

t_stat sim_show_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
SHTAB *shptr;
int32 i;

if (*cptr == 0) {                                       /* show all */
    for (i = 0; show_con_tab[i].name; i++)
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398





399
400
401
402
403
404

405
406
407
408
409
410
411
return SCPE_OK;
}

t_stat sim_rem_con_poll_svc (UNIT *uptr);               /* remote console connection poll routine */
t_stat sim_rem_con_data_svc (UNIT *uptr);               /* remote console connection data routine */
t_stat sim_rem_con_reset (DEVICE *dptr);                /* remote console reset routine */
UNIT sim_rem_con_unit[2] = {
    { UDATA (&sim_rem_con_poll_svc, 0, 0)  },           /* remote console connection polling unit */
    { UDATA (&sim_rem_con_data_svc, 0, 0)  }};          /* console data handling unit */

DEBTAB sim_rem_con_debug[] = {
  {"TRC",    DBG_TRC},
  {"XMT",    DBG_XMT},
  {"RCV",    DBG_RCV},
  {0}
};

MTAB sim_rem_con_mod[] = {
  { 0 },
};






DEVICE sim_remote_console = {
    "REM-CON", sim_rem_con_unit, NULL, sim_rem_con_mod, 
    2, 0, 0, 0, 0, 0, 
    NULL, NULL, sim_rem_con_reset, NULL, NULL, NULL, 
    NULL, DEV_DEBUG | DEV_NOSAVE, 0, sim_rem_con_debug};

#define MAX_REMOTE_SESSIONS 40          /* Arbitrary Session Limit */
static int32 *sim_rem_buf_size = NULL;
static int32 *sim_rem_buf_ptr = NULL;
static char **sim_rem_buf = NULL;
static t_bool *sim_rem_single_mode = NULL;  /* per line command mode (single command or must continue) */
static TMXR sim_rem_con_tmxr = { 0, 0, 0, NULL, NULL, &sim_remote_console };/* remote console line mux */
static uint32 sim_rem_read_timeout = 30;    /* seconds before automatic continue */







|
|











>
>
>
>
>





|
>







404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
return SCPE_OK;
}

t_stat sim_rem_con_poll_svc (UNIT *uptr);               /* remote console connection poll routine */
t_stat sim_rem_con_data_svc (UNIT *uptr);               /* remote console connection data routine */
t_stat sim_rem_con_reset (DEVICE *dptr);                /* remote console reset routine */
UNIT sim_rem_con_unit[2] = {
    { UDATA (&sim_rem_con_poll_svc, UNIT_IDLE, 0)  },   /* remote console connection polling unit */
    { UDATA (&sim_rem_con_data_svc, UNIT_IDLE|UNIT_DIS, 0)  }};  /* console data handling unit */

DEBTAB sim_rem_con_debug[] = {
  {"TRC",    DBG_TRC},
  {"XMT",    DBG_XMT},
  {"RCV",    DBG_RCV},
  {0}
};

MTAB sim_rem_con_mod[] = {
  { 0 },
};

static const char *sim_rem_con_description (DEVICE *dptr)
{
return "Remote Console Facility";
}

DEVICE sim_remote_console = {
    "REM-CON", sim_rem_con_unit, NULL, sim_rem_con_mod, 
    2, 0, 0, 0, 0, 0, 
    NULL, NULL, sim_rem_con_reset, NULL, NULL, NULL, 
    NULL, DEV_DEBUG | DEV_NOSAVE, 0, sim_rem_con_debug,
    NULL, NULL, NULL, NULL, NULL, sim_rem_con_description};
#define MAX_REMOTE_SESSIONS 40          /* Arbitrary Session Limit */
static int32 *sim_rem_buf_size = NULL;
static int32 *sim_rem_buf_ptr = NULL;
static char **sim_rem_buf = NULL;
static t_bool *sim_rem_single_mode = NULL;  /* per line command mode (single command or must continue) */
static TMXR sim_rem_con_tmxr = { 0, 0, 0, NULL, NULL, &sim_remote_console };/* remote console line mux */
static uint32 sim_rem_read_timeout = 30;    /* seconds before automatic continue */
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
static t_bool sim_rem_master_was_enabled = FALSE; /* Master was Enabled */
static t_bool sim_rem_master_was_connected = FALSE; /* Master Mode has been connected */
static t_offset sim_rem_cmd_log_start = 0;  /* Log File saved position */


/* SET REMOTE CONSOLE command */

t_stat sim_set_remote_console (int32 flag, char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;







|







451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
static t_bool sim_rem_master_was_enabled = FALSE; /* Master was Enabled */
static t_bool sim_rem_master_was_connected = FALSE; /* Master Mode has been connected */
static t_offset sim_rem_cmd_log_start = 0;  /* Log File saved position */


/* SET REMOTE CONSOLE command */

t_stat sim_set_remote_console (int32 flag, CONST char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472


473
474
475
476
477
478
479
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

/* SHOW REMOTE CONSOLE command */

t_stat sim_show_remote_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
int32 i, connections;
TMLN *lp;

if (*cptr != 0)
    return SCPE_NOPARAM;
if (sim_rem_active_number >= 0) {
    if (sim_rem_master_mode && (sim_rem_active_number == 0))
        fprintf (st, "Running from Master Mode Remote Console Connection\n");
    else
        fprintf (st, "Running from Remote Console Connection %d\n", sim_rem_active_number);
    }
if (sim_rem_con_tmxr.lines > 1)
    fprintf (st, "Remote Console Input Connections from %d sources are supported concurrently\n", sim_rem_con_tmxr.lines);
if (sim_rem_read_timeout)
    fprintf (st, "Remote Console Input automatically continues after %d seconds\n", sim_rem_read_timeout);
if (!sim_rem_con_tmxr.master)
    fprintf (st, "Remote Console Command input is disabled\n");
else
    fprintf (st, "Remote Console Command Input listening on TCP port: %s\n", sim_rem_con_unit[0].filename);


for (i=connections=0; i<sim_rem_con_tmxr.lines; i++) {
    lp = &sim_rem_con_tmxr.ldsc[i];
    if (!lp->conn)
        continue;
    ++connections;
    if (connections == 1)
        fprintf (st, "Remote Console Connections:\n");







|


















|

>
>







476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

/* SHOW REMOTE CONSOLE command */

t_stat sim_show_remote_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 i, connections;
TMLN *lp;

if (*cptr != 0)
    return SCPE_NOPARAM;
if (sim_rem_active_number >= 0) {
    if (sim_rem_master_mode && (sim_rem_active_number == 0))
        fprintf (st, "Running from Master Mode Remote Console Connection\n");
    else
        fprintf (st, "Running from Remote Console Connection %d\n", sim_rem_active_number);
    }
if (sim_rem_con_tmxr.lines > 1)
    fprintf (st, "Remote Console Input Connections from %d sources are supported concurrently\n", sim_rem_con_tmxr.lines);
if (sim_rem_read_timeout)
    fprintf (st, "Remote Console Input automatically continues after %d seconds\n", sim_rem_read_timeout);
if (!sim_rem_con_tmxr.master)
    fprintf (st, "Remote Console Command input is disabled\n");
else {
    fprintf (st, "Remote Console Command Input listening on TCP port: %s\n", sim_rem_con_unit[0].filename);
    fprintf (st, "Remote Console Per Command Output buffer size:      %d bytes\n", sim_rem_con_tmxr.buffered);
    }
for (i=connections=0; i<sim_rem_con_tmxr.lines; i++) {
    lp = &sim_rem_con_tmxr.ldsc[i];
    if (!lp->conn)
        continue;
    ++connections;
    if (connections == 1)
        fprintf (st, "Remote Console Connections:\n");
522
523
524
525
526
527
528
529





530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
    }
sim_activate_after(uptr, 1000000);                      /* check again in 1 second */
if (sim_con_ldsc.conn)
    tmxr_send_buffered_data (&sim_con_ldsc);            /* try to flush any buffered data */
return SCPE_OK;
}

static t_stat x_continue_cmd (int32 flag, char *cptr)





{
return SCPE_IERR;           /* This routine should never be called */
}

static t_stat x_step_cmd (int32 flag, char *cptr)
{
return SCPE_IERR;           /* This routine should never be called */
}

static t_stat x_run_cmd (int32 flag, char *cptr)
{
return SCPE_IERR;           /* This routine should never be called */
}

static t_stat x_help_cmd (int32 flag, char *cptr);

static CTAB allowed_remote_cmds[] = {
    { "EXAMINE",  &exdep_cmd,      EX_E },
    { "DEPOSIT",  &exdep_cmd,      EX_D },
    { "EVALUATE", &eval_cmd,          0 },
    { "ATTACH",   &attach_cmd,        0 },
    { "DETACH",   &detach_cmd,        0 },







|
>
>
>
>
>




|




<
<
<
<
<
|







555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576





577
578
579
580
581
582
583
584
    }
sim_activate_after(uptr, 1000000);                      /* check again in 1 second */
if (sim_con_ldsc.conn)
    tmxr_send_buffered_data (&sim_con_ldsc);            /* try to flush any buffered data */
return SCPE_OK;
}

static t_stat x_continue_cmd (int32 flag, CONST char *cptr)
{
return SCPE_IERR;           /* This routine should never be called */
}

static t_stat x_step_cmd (int32 flag, CONST char *cptr)
{
return SCPE_IERR;           /* This routine should never be called */
}

static t_stat x_run_cmd (int32 flag, CONST char *cptr)
{
return SCPE_IERR;           /* This routine should never be called */
}






static t_stat x_help_cmd (int32 flag, CONST char *cptr);

static CTAB allowed_remote_cmds[] = {
    { "EXAMINE",  &exdep_cmd,      EX_E },
    { "DEPOSIT",  &exdep_cmd,      EX_D },
    { "EVALUATE", &eval_cmd,          0 },
    { "ATTACH",   &attach_cmd,        0 },
    { "DETACH",   &detach_cmd,        0 },
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
    { "LS",       &dir_cmd,           0 },
    { "ECHO",     &echo_cmd,          0 },
    { "SHOW",     &show_cmd,          0 },
    { "HELP",     &x_help_cmd,        0 },
    { NULL,       NULL }
    };

static t_stat x_help_cmd (int32 flag, char *cptr)
{
CTAB *cmdp, *cmdph;

if (*cptr) {
    int32 saved_switches = sim_switches;
    t_stat r;








|







636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    { "LS",       &dir_cmd,           0 },
    { "ECHO",     &echo_cmd,          0 },
    { "SHOW",     &show_cmd,          0 },
    { "HELP",     &x_help_cmd,        0 },
    { NULL,       NULL }
    };

static t_stat x_help_cmd (int32 flag, CONST char *cptr)
{
CTAB *cmdp, *cmdph;

if (*cptr) {
    int32 saved_switches = sim_switches;
    t_stat r;

668
669
670
671
672
673
674
675

676
677
678
679
680
681
682
            } while (unwritten == lp->txbsz);
        }
    }
}

void sim_remote_process_command (void)
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *cptr, *argv[1] = {NULL};

int32 saved_switches = sim_switches;
t_stat stat;

strcpy (cbuf, sim_rem_command_buf);
while (isspace(cbuf[0]))
    memmove (cbuf, cbuf+1, strlen(cbuf+1)+1);   /* skip leading whitespace */
sim_sub_args (cbuf, sizeof(cbuf), argv);







|
>







701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
            } while (unwritten == lp->txbsz);
        }
    }
}

void sim_remote_process_command (void)
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *argv[1] = {NULL};
CONST char *cptr;
int32 saved_switches = sim_switches;
t_stat stat;

strcpy (cbuf, sim_rem_command_buf);
while (isspace(cbuf[0]))
    memmove (cbuf, cbuf+1, strlen(cbuf+1)+1);   /* skip leading whitespace */
sim_sub_args (cbuf, sizeof(cbuf), argv);
703
704
705
706
707
708
709
710

711
712
713
714
715
716
717
t_stat stat = SCPE_OK;
t_bool active_command = FALSE;
int32 steps = 0;
t_bool was_active_command = (sim_rem_cmd_active_line != -1);
t_bool got_command;
t_bool close_session = FALSE;
TMLN *lp;
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *cptr, *argv[1] = {NULL};

CTAB *cmdp = NULL;
CTAB *basecmdp = NULL;
uint32 read_start_time = 0;

tmxr_poll_rx (&sim_rem_con_tmxr);                      /* poll input */
for (i=(was_active_command ? sim_rem_cmd_active_line : 0); 
     (i < sim_rem_con_tmxr.lines) && (!active_command); 







|
>







737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
t_stat stat = SCPE_OK;
t_bool active_command = FALSE;
int32 steps = 0;
t_bool was_active_command = (sim_rem_cmd_active_line != -1);
t_bool got_command;
t_bool close_session = FALSE;
TMLN *lp;
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE], *argv[1] = {NULL};
CONST char *cptr;
CTAB *cmdp = NULL;
CTAB *basecmdp = NULL;
uint32 read_start_time = 0;

tmxr_poll_rx (&sim_rem_con_tmxr);                      /* poll input */
for (i=(was_active_command ? sim_rem_cmd_active_line : 0); 
     (i < sim_rem_con_tmxr.lines) && (!active_command); 
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
    if (i != sim_rem_con_tmxr.lines)
        sim_activate_after (&dptr->units[1], 100000);   /* continue polling for open sessions */
    return sim_rem_con_poll_svc (&dptr->units[0]);      /* establish polling as needed */
    }
return SCPE_OK;
}

static t_stat sim_set_rem_telnet (int32 flag, char *cptr)
{
t_stat r;

if (flag) {
    r = sim_parse_addr (cptr, NULL, 0, NULL, NULL, 0, NULL, NULL);
    if (r == SCPE_OK) {
        if (sim_rem_con_tmxr.master)                    /* already open? */
            sim_set_rem_telnet (0, NULL);               /* close first */
        if (sim_rem_con_tmxr.lines == 0)                /* Ir no connection limit set */
            sim_set_rem_connections (0, "1");           /* use 1 */
        sim_rem_con_tmxr.buffered = 1400;               /* Use big enough buffers */
        sim_register_internal_device (&sim_remote_console);
        r = tmxr_attach (&sim_rem_con_tmxr, &sim_rem_con_unit[0], cptr);/* open master socket */
        if (r == SCPE_OK)
            sim_activate_after(&sim_rem_con_unit[0], 1000000); /* check for connection in 1 second */
        return r;
        }
    return SCPE_NOPARAM;







|










|







1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
    if (i != sim_rem_con_tmxr.lines)
        sim_activate_after (&dptr->units[1], 100000);   /* continue polling for open sessions */
    return sim_rem_con_poll_svc (&dptr->units[0]);      /* establish polling as needed */
    }
return SCPE_OK;
}

static t_stat sim_set_rem_telnet (int32 flag, CONST char *cptr)
{
t_stat r;

if (flag) {
    r = sim_parse_addr (cptr, NULL, 0, NULL, NULL, 0, NULL, NULL);
    if (r == SCPE_OK) {
        if (sim_rem_con_tmxr.master)                    /* already open? */
            sim_set_rem_telnet (0, NULL);               /* close first */
        if (sim_rem_con_tmxr.lines == 0)                /* Ir no connection limit set */
            sim_set_rem_connections (0, "1");           /* use 1 */
        sim_rem_con_tmxr.buffered = 8192;               /* Use big enough buffers */
        sim_register_internal_device (&sim_remote_console);
        r = tmxr_attach (&sim_rem_con_tmxr, &sim_rem_con_unit[0], cptr);/* open master socket */
        if (r == SCPE_OK)
            sim_activate_after(&sim_rem_con_unit[0], 1000000); /* check for connection in 1 second */
        return r;
        }
    return SCPE_NOPARAM;
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
            sim_rem_single_mode[i] = TRUE;
            }
        }
    }
return SCPE_OK;
}

static t_stat sim_set_rem_connections (int32 flag, char *cptr)
{
int32 lines;
t_stat r;
int32 i;

if (cptr == NULL)
    return SCPE_ARG;







|







1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
            sim_rem_single_mode[i] = TRUE;
            }
        }
    }
return SCPE_OK;
}

static t_stat sim_set_rem_connections (int32 flag, CONST char *cptr)
{
int32 lines;
t_stat r;
int32 i;

if (cptr == NULL)
    return SCPE_ARG;
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198

















1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
sim_rem_read_timeouts = (uint32 *)realloc (sim_rem_read_timeouts, sizeof(*sim_rem_read_timeouts)*lines);
memset (sim_rem_read_timeouts, 0, sizeof(*sim_rem_read_timeouts)*lines);
sim_rem_command_buf = (char *)realloc (sim_rem_command_buf, 4*CBUFSIZE+1);
memset (sim_rem_command_buf, 0, 4*CBUFSIZE+1);
return SCPE_OK;
}

static t_stat sim_set_rem_timeout (int32 flag, char *cptr)
{
int32 timeout;
t_stat r;

if (cptr == NULL)
    return SCPE_ARG;
timeout = (int32) get_uint (cptr, 10, 3600, &r);
if (r != SCPE_OK)
    return r;
if (sim_rem_active_number >= 0)
    sim_rem_read_timeouts[sim_rem_active_number] = timeout;
else
    sim_rem_read_timeout = timeout;
return SCPE_OK;
}


















/* Enable or disable Remote Console master mode */

/* In master mode, commands are subsequently processed from the
   primary/initial (master mode) remote console session.  Commands
   are processed from that source until that source disables master
   mode or the simulator exits 
 */

static t_stat sim_set_rem_master (int32 flag, char *cptr)
{
t_stat stat = SCPE_OK;

if (cptr && *cptr)
    return SCPE_2MARG;

if (sim_rem_active_number > 0) {







|















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









|







1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
sim_rem_read_timeouts = (uint32 *)realloc (sim_rem_read_timeouts, sizeof(*sim_rem_read_timeouts)*lines);
memset (sim_rem_read_timeouts, 0, sizeof(*sim_rem_read_timeouts)*lines);
sim_rem_command_buf = (char *)realloc (sim_rem_command_buf, 4*CBUFSIZE+1);
memset (sim_rem_command_buf, 0, 4*CBUFSIZE+1);
return SCPE_OK;
}

static t_stat sim_set_rem_timeout (int32 flag, CONST char *cptr)
{
int32 timeout;
t_stat r;

if (cptr == NULL)
    return SCPE_ARG;
timeout = (int32) get_uint (cptr, 10, 3600, &r);
if (r != SCPE_OK)
    return r;
if (sim_rem_active_number >= 0)
    sim_rem_read_timeouts[sim_rem_active_number] = timeout;
else
    sim_rem_read_timeout = timeout;
return SCPE_OK;
}

static t_stat sim_set_rem_bufsize (int32 flag, CONST char *cptr)
{
char cmdbuf[CBUFSIZE];
int32 bufsize;
t_stat r;

if (cptr == NULL)
    return SCPE_ARG;
bufsize = (int32) get_uint (cptr, 10, 32768, &r);
if (r != SCPE_OK)
    return r;
if (bufsize < 1400)
    return sim_messagef (SCPE_ARG, "%d is too small.  Minimum size is 1400\n", bufsize);
sprintf(cmdbuf, "BUFFERED=%d", bufsize);
return tmxr_open_master (&sim_rem_con_tmxr, cmdbuf);    /* open master socket */
}

/* Enable or disable Remote Console master mode */

/* In master mode, commands are subsequently processed from the
   primary/initial (master mode) remote console session.  Commands
   are processed from that source until that source disables master
   mode or the simulator exits 
 */

static t_stat sim_set_rem_master (int32 flag, CONST char *cptr)
{
t_stat stat = SCPE_OK;

if (cptr && *cptr)
    return SCPE_2MARG;

if (sim_rem_active_number > 0) {
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
    return SCPE_INVREM;
    }

if (sim_rem_master_mode) {
    t_stat stat_nomessage;

    sim_printf ("Command input starting on Master Remote Console Session\n");
    stat = sim_run_boot_prep ();
    sim_rem_master_was_enabled = TRUE;
    while (sim_rem_master_mode) {
        sim_rem_single_mode[0] = FALSE;
        sim_cancel (&sim_rem_con_unit[1]);
        sim_activate (&sim_rem_con_unit[1], -1);
        stat = run_cmd (RU_GO, "");
        if (stat != SCPE_TTMO) {







|







1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    return SCPE_INVREM;
    }

if (sim_rem_master_mode) {
    t_stat stat_nomessage;

    sim_printf ("Command input starting on Master Remote Console Session\n");
    stat = sim_run_boot_prep (0);
    sim_rem_master_was_enabled = TRUE;
    while (sim_rem_master_mode) {
        sim_rem_single_mode[0] = FALSE;
        sim_cancel (&sim_rem_con_unit[1]);
        sim_activate (&sim_rem_con_unit[1], -1);
        stat = run_cmd (RU_GO, "");
        if (stat != SCPE_TTMO) {
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321

















1322
1323
1324


















1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
    }

return stat;
}

/* Set keyboard map */

t_stat sim_set_kmap (int32 flag, char *cptr)
{
DEVICE *dptr = sim_devices[0];
int32 val, rdx;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (dptr->dradix == 16) rdx = 16;
else rdx = 8;
val = (int32) get_uint (cptr, rdx, 0177, &r);
if ((r != SCPE_OK) ||
    ((val == 0) && (flag & KMAP_NZ)))
    return SCPE_ARG;
*(cons_kmap[flag & KMAP_MASK]) = val;
return SCPE_OK;
}

/* Show keyboard map */

t_stat sim_show_kmap (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (sim_devices[0]->dradix == 16)
    fprintf (st, "%s = %X\n", show_con_tab[flag].name, *(cons_kmap[flag & KMAP_MASK]));
else fprintf (st, "%s = %o\n", show_con_tab[flag].name, *(cons_kmap[flag & KMAP_MASK]));
return SCPE_OK;
}

/* Set printable characters */

t_stat sim_set_pchar (int32 flag, char *cptr)
{
DEVICE *dptr = sim_devices[0];
uint32 val, rdx;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (dptr->dradix == 16) rdx = 16;
else rdx = 8;
val = (uint32) get_uint (cptr, rdx, 0xFFFFFFFF, &r);
if ((r != SCPE_OK) ||
    ((val & 0x00002400) == 0))
    return SCPE_ARG;
sim_tt_pchar = val;
return SCPE_OK;
}

/* Show printable characters */

t_stat sim_show_pchar (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (sim_devices[0]->dradix == 16)
    fprintf (st, "pchar mask = %X\n", sim_tt_pchar);
else fprintf (st, "pchar mask = %o\n", sim_tt_pchar);

















return SCPE_OK;
}



















/* Set log routine */

t_stat sim_set_logon (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
time_t now;

if ((cptr == NULL) || (*cptr == 0))                     /* need arg */
    return SCPE_2FARG;







|



















|









|



















|


|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|







1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    }

return stat;
}

/* Set keyboard map */

t_stat sim_set_kmap (int32 flag, CONST char *cptr)
{
DEVICE *dptr = sim_devices[0];
int32 val, rdx;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (dptr->dradix == 16) rdx = 16;
else rdx = 8;
val = (int32) get_uint (cptr, rdx, 0177, &r);
if ((r != SCPE_OK) ||
    ((val == 0) && (flag & KMAP_NZ)))
    return SCPE_ARG;
*(cons_kmap[flag & KMAP_MASK]) = val;
return SCPE_OK;
}

/* Show keyboard map */

t_stat sim_show_kmap (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (sim_devices[0]->dradix == 16)
    fprintf (st, "%s = %X\n", show_con_tab[flag].name, *(cons_kmap[flag & KMAP_MASK]));
else fprintf (st, "%s = %o\n", show_con_tab[flag].name, *(cons_kmap[flag & KMAP_MASK]));
return SCPE_OK;
}

/* Set printable characters */

t_stat sim_set_pchar (int32 flag, CONST char *cptr)
{
DEVICE *dptr = sim_devices[0];
uint32 val, rdx;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
if (dptr->dradix == 16) rdx = 16;
else rdx = 8;
val = (uint32) get_uint (cptr, rdx, 0xFFFFFFFF, &r);
if ((r != SCPE_OK) ||
    ((val & 0x00002400) == 0))
    return SCPE_ARG;
sim_tt_pchar = val;
return SCPE_OK;
}

/* Show printable characters */

t_stat sim_show_pchar (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (sim_devices[0]->dradix == 16)
    fprintf (st, "pchar mask = %X", sim_tt_pchar);
else fprintf (st, "pchar mask = %o", sim_tt_pchar);
if (sim_tt_pchar) {
    static const char *pchars[] = {"NUL(^@)", "SOH(^A)", "STX(^B)", "ETX(^C)", "EOT(^D)", "ENQ(^E)", "ACK(^F)", "BEL(^G)", 
                                   "BS(^H)" , "HT(^I)",  "LF(^J)",  "VT(^K)",  "FF(^L)",  "CR(^M)",  "SO(^N)",  "SI(^O)",
                                   "DLE(^P)", "DC1(^Q)", "DC2(^R)", "DC3(^S)", "DC4(^T)", "NAK(^U)", "SYN(^V)", "ETB(^W)",
                                   "CAN(^X)", "EM(^Y)",  "SUB(^Z)", "ESC",     "FS",      "GS",      "RS",      "US"};
    int i;
    t_bool found = FALSE;

    fprintf (st, " {");
    for (i=31; i>=0; i--)
        if (sim_tt_pchar & (1 << i)) {
            fprintf (st, "%s%s", found ? "," : "", pchars[i]);
            found = TRUE;
            }
    fprintf (st, "}");
    }
fprintf (st, "\n");
return SCPE_OK;
}

/* Set input speed (bps) */

t_stat sim_set_cons_speed (int32 flag, CONST char *cptr)
{
return tmxr_set_line_speed (&sim_con_ldsc, cptr);
}

t_stat sim_show_cons_speed (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (sim_con_ldsc.rxbps) {
    fprintf (st, "Speed = %d", sim_con_ldsc.rxbps);
    if (sim_con_ldsc.rxbpsfactor != TMXR_RX_BPS_UNIT_SCALE)
        fprintf (st, "*%.0f", sim_con_ldsc.rxbpsfactor/TMXR_RX_BPS_UNIT_SCALE);
    fprintf (st, " bps\n");
    }
return SCPE_OK;
}

/* Set log routine */

t_stat sim_set_logon (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
time_t now;

if ((cptr == NULL) || (*cptr == 0))                     /* need arg */
    return SCPE_2FARG;
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
time(&now);
fprintf (sim_log, "Logging to file \"%s\" at %s", sim_logfile_name (sim_log, sim_log_ref), ctime(&now));
return SCPE_OK;
}

/* Set nolog routine */

t_stat sim_set_logoff (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (sim_log == NULL)                                    /* no log? */
    return SCPE_OK;
if (!sim_quiet)
    printf ("Log file closed\n");
fprintf (sim_log, "Log file closed\n");
sim_close_logfile (&sim_log_ref);                       /* close log */
sim_log = NULL;
return SCPE_OK;
}

/* Show log status */

t_stat sim_show_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_log)
    fprintf (st, "Logging enabled to \"%s\"\n", 
                 sim_logfile_name (sim_log, sim_log_ref));
else fprintf (st, "Logging disabled\n");
return SCPE_OK;
}

/* Set debug routine */

t_stat sim_set_debon (int32 flag, char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
time_t now;

sim_deb_switches = sim_switches;                        /* save debug switches */
if ((cptr == NULL) || (*cptr == 0))                     /* need arg */







|















|












|







1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
time(&now);
fprintf (sim_log, "Logging to file \"%s\" at %s", sim_logfile_name (sim_log, sim_log_ref), ctime(&now));
return SCPE_OK;
}

/* Set nolog routine */

t_stat sim_set_logoff (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (sim_log == NULL)                                    /* no log? */
    return SCPE_OK;
if (!sim_quiet)
    printf ("Log file closed\n");
fprintf (sim_log, "Log file closed\n");
sim_close_logfile (&sim_log_ref);                       /* close log */
sim_log = NULL;
return SCPE_OK;
}

/* Show log status */

t_stat sim_show_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_log)
    fprintf (st, "Logging enabled to \"%s\"\n", 
                 sim_logfile_name (sim_log, sim_log_ref));
else fprintf (st, "Logging disabled\n");
return SCPE_OK;
}

/* Set debug routine */

t_stat sim_set_debon (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
t_stat r;
time_t now;

sim_deb_switches = sim_switches;                        /* save debug switches */
if ((cptr == NULL) || (*cptr == 0))                     /* need arg */
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
sim_switches = saved_sim_switches;
sim_quiet = saved_quiet;
return SCPE_OK;
}

/* Set nodebug routine */

t_stat sim_set_deboff (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (sim_deb == NULL)                                    /* no debug? */
    return SCPE_OK;
sim_close_logfile (&sim_deb_ref);
sim_deb = NULL;
sim_deb_switches = 0;
if (!sim_quiet)
    sim_printf ("Debug output disabled\n");
return SCPE_OK;
}

/* Show debug routine */

t_stat sim_show_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
int32 i;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_deb) {
    fprintf (st, "Debug output enabled to \"%s\"\n", 







|















|







1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
sim_switches = saved_sim_switches;
sim_quiet = saved_quiet;
return SCPE_OK;
}

/* Set nodebug routine */

t_stat sim_set_deboff (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* now eol? */
    return SCPE_2MARG;
if (sim_deb == NULL)                                    /* no debug? */
    return SCPE_OK;
sim_close_logfile (&sim_deb_ref);
sim_deb = NULL;
sim_deb_switches = 0;
if (!sim_quiet)
    sim_printf ("Debug output disabled\n");
return SCPE_OK;
}

/* Show debug routine */

t_stat sim_show_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 i;

if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_deb) {
    fprintf (st, "Debug output enabled to \"%s\"\n", 
1485
1486
1487
1488
1489
1490
1491








1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
        if (!(dptr->flags & DEV_DIS) &&
            (dptr->flags & DEV_DEBUG) &&
            (dptr->dctrl)) {
            fprintf (st, "Device: %-6s ", dptr->name);
            show_dev_debug (st, dptr, NULL, 0, NULL);
            }
        }








    }
else fprintf (st, "Debug output disabled\n");
return SCPE_OK;
}

/* SET CONSOLE command */

/* Set console to Telnet port (and parameters) */

t_stat sim_set_telnet (int32 flag, char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;







>
>
>
>
>
>
>
>









|







1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
        if (!(dptr->flags & DEV_DIS) &&
            (dptr->flags & DEV_DEBUG) &&
            (dptr->dctrl)) {
            fprintf (st, "Device: %-6s ", dptr->name);
            show_dev_debug (st, dptr, NULL, 0, NULL);
            }
        }
    for (i = 0; sim_internal_device_count && (dptr = sim_internal_devices[i]); ++i) {
        if (!(dptr->flags & DEV_DIS) &&
            (dptr->flags & DEV_DEBUG) &&
            (dptr->dctrl)) {
            fprintf (st, "Device: %-6s ", dptr->name);
            show_dev_debug (st, dptr, NULL, 0, NULL);
            }
        }
    }
else fprintf (st, "Debug output disabled\n");
return SCPE_OK;
}

/* SET CONSOLE command */

/* Set console to Telnet port (and parameters) */

t_stat sim_set_telnet (int32 flag, CONST char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
        }
    }
return SCPE_OK;
}

/* Close console Telnet port */

t_stat sim_set_notelnet (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* too many arguments? */
    return SCPE_2MARG;
if (sim_con_tmxr.master == 0)                           /* ignore if already closed */
    return SCPE_OK;
return tmxr_close_master (&sim_con_tmxr);               /* close master socket */
}

/* Show console Telnet status */

t_stat sim_show_telnet (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if ((sim_con_tmxr.master == 0) && 
    (sim_con_ldsc.serport == 0))
    fprintf (st, "Connected to console window\n");
else {







|










|







1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
        }
    }
return SCPE_OK;
}

/* Close console Telnet port */

t_stat sim_set_notelnet (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* too many arguments? */
    return SCPE_2MARG;
if (sim_con_tmxr.master == 0)                           /* ignore if already closed */
    return SCPE_OK;
return tmxr_close_master (&sim_con_tmxr);               /* close master socket */
}

/* Show console Telnet status */

t_stat sim_show_telnet (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if ((sim_con_tmxr.master == 0) && 
    (sim_con_ldsc.serport == 0))
    fprintf (st, "Connected to console window\n");
else {
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
    tmxr_fstats (st, &sim_con_ldsc, -1);
    }
return SCPE_OK;
}

/* Set console to Buffering  */

t_stat sim_set_cons_buff (int32 flg, char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "BUFFERED%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to NoBuffering */

t_stat sim_set_cons_unbuff (int32 flg, char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "UNBUFFERED%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to Logging */

t_stat sim_set_cons_log (int32 flg, char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "LOG%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to NoLogging */

t_stat sim_set_cons_nolog (int32 flg, char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "NOLOG%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

t_stat sim_show_cons_log (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_con_tmxr.ldsc->txlog)
    fprintf (st, "Log File being written to %s\n", sim_con_tmxr.ldsc->txlogname);
else
    fprintf (st, "No Logging\n");
return SCPE_OK;
}

t_stat sim_show_cons_buff (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (!sim_con_tmxr.ldsc->txbfd)
    fprintf (st, "Unbuffered\n");
else
    fprintf (st, "Buffer Size = %d\n", sim_con_tmxr.ldsc->txbsz);
return SCPE_OK;
}

/* Set console Debug Mode */

t_stat sim_set_cons_debug (int32 flg, char *cptr)
{
return set_dev_debug (&sim_con_telnet, &sim_con_unit, flg, cptr);
}

t_stat sim_show_cons_debug (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
return show_dev_debug (st, &sim_con_telnet, &sim_con_unit, flag, cptr);
}

/* Set console to Serial port (and parameters) */

t_stat sim_set_serial (int32 flag, char *cptr)
{
char *cvptr, gbuf[CBUFSIZE], ubuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;







|









|









|









|







|










|












|




|








|







1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
    tmxr_fstats (st, &sim_con_ldsc, -1);
    }
return SCPE_OK;
}

/* Set console to Buffering  */

t_stat sim_set_cons_buff (int32 flg, CONST char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "BUFFERED%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to NoBuffering */

t_stat sim_set_cons_unbuff (int32 flg, CONST char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "UNBUFFERED%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to Logging */

t_stat sim_set_cons_log (int32 flg, CONST char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "LOG%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

/* Set console to NoLogging */

t_stat sim_set_cons_nolog (int32 flg, CONST char *cptr)
{
char cmdbuf[CBUFSIZE];

sprintf(cmdbuf, "NOLOG%c%s", cptr ? '=' : '\0', cptr ? cptr : "");
return tmxr_open_master (&sim_con_tmxr, cmdbuf);      /* open master socket */
}

t_stat sim_show_cons_log (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_con_tmxr.ldsc->txlog)
    fprintf (st, "Log File being written to %s\n", sim_con_tmxr.ldsc->txlogname);
else
    fprintf (st, "No Logging\n");
return SCPE_OK;
}

t_stat sim_show_cons_buff (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (!sim_con_tmxr.ldsc->txbfd)
    fprintf (st, "Unbuffered\n");
else
    fprintf (st, "Buffer Size = %d\n", sim_con_tmxr.ldsc->txbsz);
return SCPE_OK;
}

/* Set console Debug Mode */

t_stat sim_set_cons_debug (int32 flg, CONST char *cptr)
{
return set_dev_debug (&sim_con_telnet, &sim_con_unit, flg, cptr);
}

t_stat sim_show_cons_debug (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
return show_dev_debug (st, &sim_con_telnet, &sim_con_unit, flag, cptr);
}

/* Set console to Serial port (and parameters) */

t_stat sim_set_serial (int32 flag, CONST char *cptr)
{
char *cvptr, gbuf[CBUFSIZE], ubuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713

1714
1715
1716
1717
1718
1719
1720
        }
    }
return SCPE_OK;
}

/* Close console Serial port */

t_stat sim_set_noserial (int32 flag, char *cptr)
{
if (cptr && (*cptr != 0))                               /* too many arguments? */
    return SCPE_2MARG;
if (sim_con_ldsc.serport == 0)                  /* ignore if already closed */
    return SCPE_OK;
return tmxr_close_master (&sim_con_tmxr);               /* close master socket */
}

/* Show the console expect rules and state */

t_stat sim_show_cons_expect (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, char *cptr)
{
return sim_exp_show (st, &sim_con_expect, cptr);
}

/* Log File Open/Close/Show Support */

/* Open log file */

t_stat sim_open_logfile (char *filename, t_bool binary, FILE **pf, FILEREF **pref)
{
char *tptr, gbuf[CBUFSIZE];


if ((filename == NULL) || (*filename == 0))             /* too few arguments? */
    return SCPE_2FARG;
tptr = get_glyph (filename, gbuf, 0);
if (*tptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
sim_close_logfile (pref);







|



|






|








|

|
>







1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
        }
    }
return SCPE_OK;
}

/* Close console Serial port */

t_stat sim_set_noserial (int32 flag, CONST char *cptr)
{
if (cptr && (*cptr != 0))                               /* too many arguments? */
    return SCPE_2MARG;
if (sim_con_ldsc.serport == 0)                          /* ignore if already closed */
    return SCPE_OK;
return tmxr_close_master (&sim_con_tmxr);               /* close master socket */
}

/* Show the console expect rules and state */

t_stat sim_show_cons_expect (FILE *st, DEVICE *dunused, UNIT *uunused, int32 flag, CONST char *cptr)
{
return sim_exp_show (st, &sim_con_expect, cptr);
}

/* Log File Open/Close/Show Support */

/* Open log file */

t_stat sim_open_logfile (const char *filename, t_bool binary, FILE **pf, FILEREF **pref)
{
char gbuf[CBUFSIZE];
const char *tptr;

if ((filename == NULL) || (*filename == 0))             /* too few arguments? */
    return SCPE_2FARG;
tptr = get_glyph (filename, gbuf, 0);
if (*tptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
sim_close_logfile (pref);
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908



1909
1910
1911
1912
1913
1914
1915



1916

1917
1918
1919
1920
1921
1922
1923
EXPECT *sim_cons_get_expect (void)
{
return &sim_con_expect;
}

/* Display console Queued input data status */

t_stat sim_show_cons_send_input (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
return sim_show_send_input (st, &sim_con_send);
}

/* Poll for character */

t_stat sim_poll_kbd (void)
{
t_stat c;

if (sim_send_poll_data (&sim_con_send, &c))                 /* injected input characters available? */
    return c;
if (!sim_rem_master_mode) {



    c = sim_os_poll_kbd ();                                 /* get character */
    if (c == SCPE_STOP) {                                   /* ^E */
        stop_cpu = 1;                                       /* Force a stop (which is picked up by sim_process_event */
        return SCPE_OK;
        }
    if ((sim_con_tmxr.master == 0) &&                       /* not Telnet? */
        (sim_con_ldsc.serport == 0))                        /* and not serial? */



        return c;                                           /* in-window */

    if (!sim_con_ldsc.conn) {                               /* no telnet or serial connection? */
        if (!sim_con_ldsc.txbfd)                            /* unbuffered? */
            return SCPE_LOST;                               /* connection lost */
        if (tmxr_poll_conn (&sim_con_tmxr) >= 0)            /* poll connect */
            sim_con_ldsc.rcve = 1;                          /* rcv enabled */
        else                                                /* fall through to poll reception */
            return SCPE_OK;                                 /* unconnected and buffered - nothing to receive */







|













>
>
>






|
>
>
>

>







1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
EXPECT *sim_cons_get_expect (void)
{
return &sim_con_expect;
}

/* Display console Queued input data status */

t_stat sim_show_cons_send_input (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
return sim_show_send_input (st, &sim_con_send);
}

/* Poll for character */

t_stat sim_poll_kbd (void)
{
t_stat c;

if (sim_send_poll_data (&sim_con_send, &c))                 /* injected input characters available? */
    return c;
if (!sim_rem_master_mode) {
    if ((sim_con_ldsc.rxbps) &&                             /* rate limiting && */
        (sim_gtime () < sim_con_ldsc.rxnexttime))           /* too soon? */
        return SCPE_OK;                                     /* not yet */
    c = sim_os_poll_kbd ();                                 /* get character */
    if (c == SCPE_STOP) {                                   /* ^E */
        stop_cpu = 1;                                       /* Force a stop (which is picked up by sim_process_event */
        return SCPE_OK;
        }
    if ((sim_con_tmxr.master == 0) &&                       /* not Telnet? */
        (sim_con_ldsc.serport == 0)) {                      /* and not serial? */
        if (c && sim_con_ldsc.rxbps)                        /* got something && rate limiting? */
            sim_con_ldsc.rxnexttime =                       /* compute next input time */
                floor (sim_gtime () + ((sim_con_ldsc.rxdelta * sim_timer_inst_per_sec ())/sim_con_ldsc.rxbpsfactor));
        return c;                                           /* in-window */
        }
    if (!sim_con_ldsc.conn) {                               /* no telnet or serial connection? */
        if (!sim_con_ldsc.txbfd)                            /* unbuffered? */
            return SCPE_LOST;                               /* connection lost */
        if (tmxr_poll_conn (&sim_con_tmxr) >= 0)            /* poll connect */
            sim_con_ldsc.rcve = 1;                          /* rcv enabled */
        else                                                /* fall through to poll reception */
            return SCPE_OK;                                 /* unconnected and buffered - nothing to receive */
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
/* Input character processing */

int32 sim_tt_inpcvt (int32 c, uint32 mode)
{
uint32 md = mode & TTUF_M_MODE;

if (md != TTUF_MODE_8B) {
    uint32 par_bit = 0;
    uint32 par_mode = (mode >> TTUF_W_MODE) & TTUF_M_PAR;
    static int32 nibble_even_parity = 0x699600;   /* bit array indicating the even parity for each index (offset by 8) */

    c = c & 0177;
    if (md == TTUF_MODE_UC) {
        if (islower (c))
            c = toupper (c);







<







2081
2082
2083
2084
2085
2086
2087

2088
2089
2090
2091
2092
2093
2094
/* Input character processing */

int32 sim_tt_inpcvt (int32 c, uint32 mode)
{
uint32 md = mode & TTUF_M_MODE;

if (md != TTUF_MODE_8B) {

    uint32 par_mode = (mode >> TTUF_W_MODE) & TTUF_M_PAR;
    static int32 nibble_even_parity = 0x699600;   /* bit array indicating the even parity for each index (offset by 8) */

    c = c & 0177;
    if (md == TTUF_MODE_UC) {
        if (islower (c))
            c = toupper (c);
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048

/* Tab stop array handling

   *desc points to a uint8 array of length val

   Columns with tabs set are non-zero; columns without tabs are 0 */

t_stat sim_tt_settabs (UNIT *uptr, int32 val, char *cptr, void *desc)
{
uint8 *temptabs, *tabs = (uint8 *) desc;
int32 i, d;
t_stat r;
char gbuf[CBUFSIZE];

if ((cptr == NULL) || (tabs == NULL) || (val <= 1))







|







2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150

/* Tab stop array handling

   *desc points to a uint8 array of length val

   Columns with tabs set are non-zero; columns without tabs are 0 */

t_stat sim_tt_settabs (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
uint8 *temptabs, *tabs = (uint8 *) desc;
int32 i, d;
t_stat r;
char gbuf[CBUFSIZE];

if ((cptr == NULL) || (tabs == NULL) || (val <= 1))
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
    } while (*cptr != 0);
for (i = 0; i < val; i++)
    tabs[i] = temptabs[i];
free (temptabs);
return SCPE_OK;
}

t_stat sim_tt_showtabs (FILE *st, UNIT *uptr, int32 val, void *desc)
{
uint8 *tabs = (uint8 *) desc;
int32 i, any;

if ((st == NULL) || (val == 0) || (desc == NULL))
    return SCPE_IERR;
for (i = any = 0; i < val; i++) {
    if (tabs[i] != 0) {
        fprintf (st, (any? ";%d": "%d"), i + 1);







|

|







2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
    } while (*cptr != 0);
for (i = 0; i < val; i++)
    tabs[i] = temptabs[i];
free (temptabs);
return SCPE_OK;
}

t_stat sim_tt_showtabs (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const uint8 *tabs = (const uint8 *) desc;
int32 i, any;

if ((st == NULL) || (val == 0) || (desc == NULL))
    return SCPE_IERR;
for (i = any = 0; i < val; i++) {
    if (tabs[i] != 0) {
        fprintf (st, (any? ";%d": "%d"), i + 1);
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
pthread_t           sim_console_poll_thread;       /* Keyboard Polling Thread Id */
t_bool              sim_console_poll_running = FALSE;
pthread_cond_t      sim_console_startup_cond;

static void *
_console_poll(void *arg)
{
int sched_policy;
struct sched_param sched_priority;
int wait_count = 0;
DEVICE *d;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (DBG_ASY, &sim_con_telnet, "_console_poll() - starting\n");

pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_console_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_enabled) {








<
<






<
|
<







2198
2199
2200
2201
2202
2203
2204


2205
2206
2207
2208
2209
2210

2211

2212
2213
2214
2215
2216
2217
2218
pthread_t           sim_console_poll_thread;       /* Keyboard Polling Thread Id */
t_bool              sim_console_poll_running = FALSE;
pthread_cond_t      sim_console_startup_cond;

static void *
_console_poll(void *arg)
{


int wait_count = 0;
DEVICE *d;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug (DBG_ASY, &sim_con_telnet, "_console_poll() - starting\n");

pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_console_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_enabled) {

2169
2170
2171
2172
2173
2174
2175

2176
2177
2178
2179
2180
2181
2182


#endif /* defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX) */


t_stat sim_ttinit (void)
{

sim_register_internal_device (&sim_con_telnet);
tmxr_startup ();
return sim_os_ttinit ();
}

t_stat sim_ttrun (void)
{







>







2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281


#endif /* defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX) */


t_stat sim_ttinit (void)
{
sim_con_tmxr.ldsc->mp = &sim_con_tmxr;
sim_register_internal_device (&sim_con_telnet);
tmxr_startup ();
return sim_os_ttinit ();
}

t_stat sim_ttrun (void)
{
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
    (!GetConsoleMode(std_input, &saved_mode) ||         /* Set mode to RAW */
     !SetConsoleMode(std_input, RAW_MODE)))
    return SCPE_TTYERR;
if (sim_log) {
    fflush (sim_log);
    _setmode (_fileno (sim_log), _O_BINARY);
    }
SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
if (sim_log) {
    fflush (sim_log);
    _setmode (_fileno (sim_log), _O_TEXT);
    }
SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_NORMAL);
if ((std_input) &&                                      /* If Not Background process? */
    (std_input != INVALID_HANDLE_VALUE) &&
    (!SetConsoleMode(std_input, saved_mode)))           /* Restore Normal mode */
    return SCPE_TTYERR;
return SCPE_OK;
}








|









|







2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
    (!GetConsoleMode(std_input, &saved_mode) ||         /* Set mode to RAW */
     !SetConsoleMode(std_input, RAW_MODE)))
    return SCPE_TTYERR;
if (sim_log) {
    fflush (sim_log);
    _setmode (_fileno (sim_log), _O_BINARY);
    }
sim_os_set_thread_priority (PRIORITY_BELOW_NORMAL);
return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
if (sim_log) {
    fflush (sim_log);
    _setmode (_fileno (sim_log), _O_TEXT);
    }
sim_os_set_thread_priority (PRIORITY_NORMAL);
if ((std_input) &&                                      /* If Not Background process? */
    (std_input != INVALID_HANDLE_VALUE) &&
    (!SetConsoleMode(std_input, saved_mode)))           /* Restore Normal mode */
    return SCPE_TTYERR;
return SCPE_OK;
}

2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
fcntl (0, F_SETFL, runfl);                              /* non-block mode */
if (ioctl (0, TIOCSETP, &runtty) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSETC, &runtchars) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSLTC, &runltchars) < 0)
    return SCPE_TTIERR;
nice (10);                                              /* lower priority */
return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
nice (-10);                                             /* restore priority */
fcntl (0, F_SETFL, cmdfl);                              /* block mode */
if (ioctl (0, TIOCSETP, &cmdtty) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSETC, &cmdtchars) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSLTC, &cmdltchars) < 0)
    return SCPE_TTIERR;







|





|







2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
fcntl (0, F_SETFL, runfl);                              /* non-block mode */
if (ioctl (0, TIOCSETP, &runtty) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSETC, &runtchars) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSLTC, &runltchars) < 0)
    return SCPE_TTIERR;
sim_os_set_thread_priority (PRIORITY_BELOW_NORMAL)l     /* lower priority */
return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
sim_os_set_thread_priority (PRIORITY_NORMAL);           /* restore priority */
fcntl (0, F_SETFL, cmdfl);                              /* block mode */
if (ioctl (0, TIOCSETP, &cmdtty) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSETC, &cmdtchars) < 0)
    return SCPE_TTIERR;
if (ioctl (0, TIOCSLTC, &cmdltchars) < 0)
    return SCPE_TTIERR;
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979

#else

#include <termios.h>
#include <unistd.h>

struct termios cmdtty, runtty;
static int prior_norm = 1;

static t_stat sim_os_ttinit (void)
{
if (!isatty (fileno (stdin)))                           /* skip if !tty */
    return SCPE_OK;
if (tcgetattr (0, &cmdtty) < 0)                         /* get old flags */
    return SCPE_TTIERR;







<







3064
3065
3066
3067
3068
3069
3070

3071
3072
3073
3074
3075
3076
3077

#else

#include <termios.h>
#include <unistd.h>

struct termios cmdtty, runtty;


static t_stat sim_os_ttinit (void)
{
if (!isatty (fileno (stdin)))                           /* skip if !tty */
    return SCPE_OK;
if (tcgetattr (0, &cmdtty) < 0)                         /* get old flags */
    return SCPE_TTIERR;
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
#if defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)
runtty.c_cc[VINTR] = 0;                                 /* OS X doesn't deliver SIGINT to main thread when enabled */
#else
runtty.c_cc[VINTR] = sim_int_char;                      /* in case changed */
#endif
if (tcsetattr (0, TCSAFLUSH, &runtty) < 0)
    return SCPE_TTIERR;
if (prior_norm) {                                       /* at normal pri? */
    errno =     0;
    (void)nice (10);                                    /* try to lower pri */
    prior_norm = errno;                                 /* if no error, done */
    }
return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
if (!isatty (fileno (stdin)))                           /* skip if !tty */
    return SCPE_OK;
if (!prior_norm) {                                      /* priority down? */
    errno =     0;
    (void)nice (-10);                                   /* try to raise pri */
    prior_norm = (errno == 0);                          /* if no error, done */
    }
if (tcsetattr (0, TCSAFLUSH, &cmdtty) < 0)
    return SCPE_TTIERR;
return SCPE_OK;
}

static t_stat sim_os_ttclose (void)
{







<
<
|
<
<







<
<
|
<
<







3122
3123
3124
3125
3126
3127
3128


3129


3130
3131
3132
3133
3134
3135
3136


3137


3138
3139
3140
3141
3142
3143
3144
#if defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)
runtty.c_cc[VINTR] = 0;                                 /* OS X doesn't deliver SIGINT to main thread when enabled */
#else
runtty.c_cc[VINTR] = sim_int_char;                      /* in case changed */
#endif
if (tcsetattr (0, TCSAFLUSH, &runtty) < 0)
    return SCPE_TTIERR;


sim_os_set_thread_priority (PRIORITY_BELOW_NORMAL);     /* try to lower pri */


return SCPE_OK;
}

static t_stat sim_os_ttcmd (void)
{
if (!isatty (fileno (stdin)))                           /* skip if !tty */
    return SCPE_OK;


sim_os_set_thread_priority (PRIORITY_NORMAL);           /* try to raise pri */


if (tcsetattr (0, TCSAFLUSH, &cmdtty) < 0)
    return SCPE_TTIERR;
return SCPE_OK;
}

static t_stat sim_os_ttclose (void)
{
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
            }
        }
return;
}

/* Set console halt */

static t_stat sim_set_halt (int32 flag, char *cptr)
{
if (flag == 0)                                              /* no halt? */
    sim_exp_clrall (&sim_con_expect);                       /* disable halt checks */
else {
    char *mbuf;
    char *mbuf2;








|







3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
            }
        }
return;
}

/* Set console halt */

static t_stat sim_set_halt (int32 flag, CONST char *cptr)
{
if (flag == 0)                                              /* no halt? */
    sim_exp_clrall (&sim_con_expect);                       /* disable halt checks */
else {
    char *mbuf;
    char *mbuf2;

3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174

return SCPE_OK;
}


/* Set console response */

static t_stat sim_set_response (int32 flag, char *cptr)
{
if (flag == 0)                                          /* no response? */
    sim_send_clear (&sim_con_send);
else {
    uint8 *rbuf;

    if (cptr == NULL || *cptr == 0)







|







3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264

return SCPE_OK;
}


/* Set console response */

static t_stat sim_set_response (int32 flag, CONST char *cptr)
{
if (flag == 0)                                          /* no response? */
    sim_send_clear (&sim_con_send);
else {
    uint8 *rbuf;

    if (cptr == NULL || *cptr == 0)
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
    }

return SCPE_OK;
}

/* Set console delay */

static t_stat sim_set_delay (int32 flag, char *cptr)
{
int32 val;
t_stat r;

if (cptr == NULL || *cptr == 0)                         /* no argument string? */
    return SCPE_2FARG;                                  /* need an argument */








|







3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
    }

return SCPE_OK;
}

/* Set console delay */

static t_stat sim_set_delay (int32 flag, CONST char *cptr)
{
int32 val;
t_stat r;

if (cptr == NULL || *cptr == 0)                         /* no argument string? */
    return SCPE_2FARG;                                  /* need an argument */

Changes to src/sim_console.h.
30
31
32
33
34
35
36




37
38
39
40
41
42
43
   05-Nov-04    RMS     Moved SET/SHOW DEBUG under CONSOLE hierarchy
   28-May-04    RMS     Added SET/SHOW CONSOLE
   02-Jan-04    RMS     Removed timer routines, added Telnet console routines
*/

#ifndef SIM_CONSOLE_H_
#define SIM_CONSOLE_H_ 0





#define TTUF_V_MODE     (UNIT_V_UF + 0)
#define TTUF_W_MODE     2
#define  TTUF_MODE_7B   0
#define  TTUF_MODE_8B   1
#define  TTUF_MODE_UC   2
#define  TTUF_MODE_7P   3







>
>
>
>







30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
   05-Nov-04    RMS     Moved SET/SHOW DEBUG under CONSOLE hierarchy
   28-May-04    RMS     Added SET/SHOW CONSOLE
   02-Jan-04    RMS     Removed timer routines, added Telnet console routines
*/

#ifndef SIM_CONSOLE_H_
#define SIM_CONSOLE_H_ 0

#ifdef  __cplusplus
extern "C" {
#endif

#define TTUF_V_MODE     (UNIT_V_UF + 0)
#define TTUF_W_MODE     2
#define  TTUF_MODE_7B   0
#define  TTUF_MODE_8B   1
#define  TTUF_MODE_UC   2
#define  TTUF_MODE_7P   3
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

91
92
93
94
95
96
97

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129


130


#define  TT_PAR_MARK    (TTUF_PAR_MARK  << TTUF_V_PAR)
#define  TT_PAR_EVEN    (TTUF_PAR_EVEN  << TTUF_V_PAR)
#define  TT_PAR_ODD     (TTUF_PAR_ODD   << TTUF_V_PAR)
/* TT_GET_MODE returns both the TT_MODE and TT_PAR fields 
   since they together are passed into sim_tt_inpcvt() */
#define TT_GET_MODE(x)  (((x) >> TTUF_V_MODE) & (TTUF_M_MODE | (TTUF_M_PAR << TTUF_W_MODE)))

t_stat sim_set_console (int32 flag, char *cptr);
t_stat sim_set_remote_console (int32 flag, char *cptr);
void sim_remote_process_command (void);
t_stat sim_set_kmap (int32 flag, char *cptr);
t_stat sim_set_telnet (int32 flag, char *cptr);
t_stat sim_set_notelnet (int32 flag, char *cptr);
t_stat sim_set_serial (int32 flag, char *cptr);
t_stat sim_set_noserial (int32 flag, char *cptr);
t_stat sim_set_logon (int32 flag, char *cptr);
t_stat sim_set_logoff (int32 flag, char *cptr);
t_stat sim_set_debon (int32 flag, char *cptr);
t_stat sim_set_cons_debug (int32 flg, char *cptr);
t_stat sim_set_cons_buff (int32 flg, char *cptr);
t_stat sim_set_cons_unbuff (int32 flg, char *cptr);
t_stat sim_set_cons_log (int32 flg, char *cptr);
t_stat sim_set_cons_nolog (int32 flg, char *cptr);
t_stat sim_set_deboff (int32 flag, char *cptr);
t_stat sim_set_cons_expect (int32 flg, char *cptr);
t_stat sim_set_cons_noexpect (int32 flg, char *cptr);
t_stat sim_debug_flush (void);
t_stat sim_set_pchar (int32 flag, char *cptr);

t_stat sim_show_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_remote_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_kmap (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_telnet (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_pchar (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);

t_stat sim_show_cons_buff (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_cons_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_cons_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_show_cons_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_check_console (int32 sec);
t_stat sim_open_logfile (char *filename, t_bool binary, FILE **pf, FILEREF **pref);
t_stat sim_close_logfile (FILEREF **pref);
const char *sim_logfile_name (FILE *st, FILEREF *ref);
SEND *sim_cons_get_send (void);
EXPECT *sim_cons_get_expect (void);
t_stat sim_show_cons_send_input (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_stat sim_set_noconsole_port (void);
t_stat sim_poll_kbd (void);
t_stat sim_putchar (int32 c);
t_stat sim_putchar_s (int32 c);
t_stat sim_ttinit (void);
t_stat sim_ttrun (void);
t_stat sim_ttcmd (void);
t_stat sim_ttclose (void);
t_bool sim_ttisatty (void);
int32 sim_tt_inpcvt (int32 c, uint32 mode);
int32 sim_tt_outcvt (int32 c, uint32 mode);
t_stat sim_tt_settabs (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_tt_showtabs (FILE *st, UNIT *uptr, int32 val, void *desc);

extern int32 sim_rem_cmd_active_line;                       /* command in progress on line # */

extern int32 sim_int_char;                                  /* interrupt character */
extern int32 sim_brk_char;                                  /* break character */
extern int32 sim_tt_pchar;                                  /* printable character mask */
extern int32 sim_del_char;                                  /* delete character */



#endif









|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
>
|
|
|
|
|
|
|
>
|
|
|
|

|




|











|
|








>
>

>
>
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#define  TT_PAR_MARK    (TTUF_PAR_MARK  << TTUF_V_PAR)
#define  TT_PAR_EVEN    (TTUF_PAR_EVEN  << TTUF_V_PAR)
#define  TT_PAR_ODD     (TTUF_PAR_ODD   << TTUF_V_PAR)
/* TT_GET_MODE returns both the TT_MODE and TT_PAR fields 
   since they together are passed into sim_tt_inpcvt() */
#define TT_GET_MODE(x)  (((x) >> TTUF_V_MODE) & (TTUF_M_MODE | (TTUF_M_PAR << TTUF_W_MODE)))

t_stat sim_set_console (int32 flag, CONST char *cptr);
t_stat sim_set_remote_console (int32 flag, CONST char *cptr);
void sim_remote_process_command (void);
t_stat sim_set_kmap (int32 flag, CONST char *cptr);
t_stat sim_set_telnet (int32 flag, CONST char *cptr);
t_stat sim_set_notelnet (int32 flag, CONST char *cptr);
t_stat sim_set_serial (int32 flag, CONST char *cptr);
t_stat sim_set_noserial (int32 flag, CONST char *cptr);
t_stat sim_set_logon (int32 flag, CONST char *cptr);
t_stat sim_set_logoff (int32 flag, CONST char *cptr);
t_stat sim_set_debon (int32 flag, CONST char *cptr);
t_stat sim_set_cons_debug (int32 flg, CONST char *cptr);
t_stat sim_set_cons_buff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_unbuff (int32 flg, CONST char *cptr);
t_stat sim_set_cons_log (int32 flg, CONST char *cptr);
t_stat sim_set_cons_nolog (int32 flg, CONST char *cptr);
t_stat sim_set_deboff (int32 flag, CONST char *cptr);
t_stat sim_set_cons_expect (int32 flg, CONST char *cptr);
t_stat sim_set_cons_noexpect (int32 flg, CONST char *cptr);
t_stat sim_debug_flush (void);
t_stat sim_set_pchar (int32 flag, CONST char *cptr);
t_stat sim_set_cons_speed (int32 flag, CONST char *cptr);
t_stat sim_show_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_remote_console (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_kmap (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_telnet (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_pchar (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_cons_speed (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_cons_buff (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_cons_log (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_cons_debug (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_show_cons_expect (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_check_console (int32 sec);
t_stat sim_open_logfile (const char *filename, t_bool binary, FILE **pf, FILEREF **pref);
t_stat sim_close_logfile (FILEREF **pref);
const char *sim_logfile_name (FILE *st, FILEREF *ref);
SEND *sim_cons_get_send (void);
EXPECT *sim_cons_get_expect (void);
t_stat sim_show_cons_send_input (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat sim_set_noconsole_port (void);
t_stat sim_poll_kbd (void);
t_stat sim_putchar (int32 c);
t_stat sim_putchar_s (int32 c);
t_stat sim_ttinit (void);
t_stat sim_ttrun (void);
t_stat sim_ttcmd (void);
t_stat sim_ttclose (void);
t_bool sim_ttisatty (void);
int32 sim_tt_inpcvt (int32 c, uint32 mode);
int32 sim_tt_outcvt (int32 c, uint32 mode);
t_stat sim_tt_settabs (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tt_showtabs (FILE *st, UNIT *uptr, int32 val, CONST void *desc);

extern int32 sim_rem_cmd_active_line;                       /* command in progress on line # */

extern int32 sim_int_char;                                  /* interrupt character */
extern int32 sim_brk_char;                                  /* break character */
extern int32 sim_tt_pchar;                                  /* printable character mask */
extern int32 sim_del_char;                                  /* delete character */

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_defs.h.
104
105
106
107
108
109
110



111
112
113
114
115
116
117

#ifndef SIM_DEFS_H_
#define SIM_DEFS_H_    0

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>



#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#ifdef _WIN32
#include <winsock2.h>







>
>
>







104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

#ifndef SIM_DEFS_H_
#define SIM_DEFS_H_    0

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#if defined(_MSC_VER) && (_MSC_VER < 1900)
#define snprintf _snprintf      /* poor man's snprintf which will work most of the time but has different return value */
#endif
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#ifdef _WIN32
#include <winsock2.h>
127
128
129
130
131
132
133




134
135
136
137
138
139
140
#if defined(HAVE_PCREPOSIX_H)
#include <pcreposix.h>
#define USE_REGEX 1
#elif defined(HAVE_REGEX_H)
#include <regex.h>
#define USE_REGEX 1
#endif





/* avoid macro names collisions */
#ifdef MAX
#undef MAX
#endif
#ifdef MIN
#undef MIN







>
>
>
>







130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#if defined(HAVE_PCREPOSIX_H)
#include <pcreposix.h>
#define USE_REGEX 1
#elif defined(HAVE_REGEX_H)
#include <regex.h>
#define USE_REGEX 1
#endif

#ifdef  __cplusplus
extern "C" {
#endif

/* avoid macro names collisions */
#ifdef MAX
#undef MAX
#endif
#ifdef MIN
#undef MIN
150
151
152
153
154
155
156












157
158
159
160
161
162
163
#endif


#ifndef TRUE
#define TRUE            1
#define FALSE           0
#endif













/* Length specific integer declarations */

#if defined (VMS)
#include <ints.h>
#else
typedef signed char     int8;







>
>
>
>
>
>
>
>
>
>
>
>







157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#endif


#ifndef TRUE
#define TRUE            1
#define FALSE           0
#endif

/* SCP API shim.

   The SCP API for version 4.0 introduces a number of "pointer-to-const"
   parameter qualifiers that were not present in the 3.x versions.  To maintain
   compatibility with the earlier versions, the new qualifiers are expressed as
   "CONST" rather than "const".  This allows macro removal of the qualifiers
   when compiling for SIMH 3.x.
*/
#ifndef CONST
#define CONST const
#endif

/* Length specific integer declarations */

#if defined (VMS)
#include <ints.h>
#else
typedef signed char     int8;
249
250
251
252
253
254
255














256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

280
281
282
283
284
285
286
#if defined(_MSC_VER)
#define SIM_INLINE _inline
#elif defined(__GNUC__)
#define SIM_INLINE inline
#else
#define SIM_INLINE 
#endif















/* System independent definitions */

#define FLIP_SIZE       (1 << 16)                       /* flip buf size */
#if !defined (PATH_MAX)                                 /* usually in limits */
#define PATH_MAX        512
#endif
#if (PATH_MAX >= 128)
#define CBUFSIZE        (128 + PATH_MAX)                /* string buf size */
#else
#define CBUFSIZE        256
#endif

/* Breakpoint spaces definitions */

#define SIM_BKPT_N_SPC  16                              /* max number spaces */
#define SIM_BKPT_V_SPC  28                              /* location in arg */

/* Extended switch definitions (bits >= 26) */

#define SIM_SW_HIDE     (1u << 26)                      /* enable hiding */
#define SIM_SW_REST     (1u << 27)                      /* attach/restore */
#define SIM_SW_REG      (1u << 28)                      /* register value */
#define SIM_SW_STOP     (1u << 29)                      /* stop message */


/* Simulator status codes

   0                    ok
   1 - (SCPE_BASE - 1)  simulator specific
   SCPE_BASE - n        general
*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>















|
|







>







268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#if defined(_MSC_VER)
#define SIM_INLINE _inline
#elif defined(__GNUC__)
#define SIM_INLINE inline
#else
#define SIM_INLINE 
#endif

/* Storage class modifier for weak link definition for sim_vm_init() */

#if defined(__cplusplus)
#if defined(__GNUC__)
#define WEAK __attribute__((weak))
#elif defined(_MSC_VER)
#define WEAK __declspec(selectany) 
#else
#define WEAK extern 
#endif
#else
#define WEAK 
#endif

/* System independent definitions */

#define FLIP_SIZE       (1 << 16)                       /* flip buf size */
#if !defined (PATH_MAX)                                 /* usually in limits */
#define PATH_MAX        512
#endif
#if (PATH_MAX >= 128)
#define CBUFSIZE        (128 + PATH_MAX)                /* string buf size */
#else
#define CBUFSIZE        256
#endif

/* Breakpoint spaces definitions */

#define SIM_BKPT_N_SPC  (1 << (32 - SIM_BKPT_V_SPC))    /* max number spaces */
#define SIM_BKPT_V_SPC  (BRK_TYP_MAX + 1)               /* location in arg */

/* Extended switch definitions (bits >= 26) */

#define SIM_SW_HIDE     (1u << 26)                      /* enable hiding */
#define SIM_SW_REST     (1u << 27)                      /* attach/restore */
#define SIM_SW_REG      (1u << 28)                      /* register value */
#define SIM_SW_STOP     (1u << 29)                      /* stop message */
#define SIM_SW_SHUT     (1u << 30)                      /* shutdown */

/* Simulator status codes

   0                    ok
   1 - (SCPE_BASE - 1)  simulator specific
   SCPE_BASE - n        general
*/
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376





















377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422

/* Convert switch letter to bit mask */

#define SWMASK(x) (1u << (((int) (x)) - ((int) 'A')))

/* String match - at least one character required */

#define MATCH_CMD(ptr,cmd) ((NULL == (ptr)) || (!*(ptr)) || strncmp ((ptr), (cmd), strlen (ptr)))

/* End of Linked List/Queue value                           */
/* Chosen for 2 reasons:                                    */
/*     1 - to not be NULL, this allowing the NULL value to  */
/*         indicate inclusion on a list                     */
/* and                                                      */
/*     2 - to not be a valid/possible pointer (alignment)   */
#define QUEUE_LIST_END ((UNIT *)1)






















/* Device data structure */

struct sim_device {
    const char          *name;                          /* name */
    struct sim_unit     *units;                         /* units */
    struct sim_reg      *registers;                     /* registers */
    struct sim_mtab     *modifiers;                     /* modifiers */
    uint32              numunits;                       /* #units */
    uint32              aradix;                         /* address radix */
    uint32              awidth;                         /* address width */
    uint32              aincr;                          /* addr increment */
    uint32              dradix;                         /* data radix */
    uint32              dwidth;                         /* data width */
    t_stat              (*examine)(t_value *v, t_addr a, struct sim_unit *up,
                            int32 sw);                  /* examine routine */
    t_stat              (*deposit)(t_value v, t_addr a, struct sim_unit *up,
                            int32 sw);                  /* deposit routine */
    t_stat              (*reset)(struct sim_device *dp);/* reset routine */
    t_stat              (*boot)(int32 u, struct sim_device *dp);
                                                        /* boot routine */
    t_stat              (*attach)(struct sim_unit *up, char *cp);
                                                        /* attach routine */
    t_stat              (*detach)(struct sim_unit *up); /* detach routine */
    void                *ctxt;                          /* context */
    uint32              flags;                          /* flags */
    uint32              dctrl;                          /* debug control */
    struct sim_debtab   *debflags;                      /* debug flags */
    t_stat              (*msize)(struct sim_unit *up, int32 v, char *cp, void *dp);
                                                        /* mem size routine */
    char                *lname;                         /* logical name */
    t_stat              (*help)(FILE *st, struct sim_device *dptr,
                            struct sim_unit *uptr, int32 flag, const char *cptr); 
                                                        /* help */
    t_stat              (*attach_help)(FILE *st, struct sim_device *dptr,
                            struct sim_unit *uptr, int32 flag, const char *cptr);
                                                        /* attach help */
    void *help_ctx;                                     /* Context available to help routines */
    const char          *(*description)(struct sim_device *dptr);
                                                        /* Device Description */
    };

/* Device flags */

#define DEV_V_DIS       0                               /* dev disabled */
#define DEV_V_DISABLE   1                               /* dev disable-able */
#define DEV_V_DYNM      2                               /* mem size dynamic */







|









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|

|
|
|






|

|

|
|

|

|



|
|


|
|

|
|


|
|







394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477

/* Convert switch letter to bit mask */

#define SWMASK(x) (1u << (((int) (x)) - ((int) 'A')))

/* String match - at least one character required */

#define MATCH_CMD(ptr,cmd) ((NULL == (ptr)) || (!*(ptr)) || sim_strncasecmp ((ptr), (cmd), strlen (ptr)))

/* End of Linked List/Queue value                           */
/* Chosen for 2 reasons:                                    */
/*     1 - to not be NULL, this allowing the NULL value to  */
/*         indicate inclusion on a list                     */
/* and                                                      */
/*     2 - to not be a valid/possible pointer (alignment)   */
#define QUEUE_LIST_END ((UNIT *)1)

/* Typedefs for principal structures */

typedef struct DEVICE DEVICE;
typedef struct UNIT UNIT;
typedef struct REG REG;
typedef struct CTAB CTAB;
typedef struct C1TAB C1TAB;
typedef struct SHTAB SHTAB;
typedef struct MTAB MTAB;
typedef struct SCHTAB SCHTAB;
typedef struct BRKTAB BRKTAB;
typedef struct BRKTYPTAB BRKTYPTAB;
typedef struct EXPTAB EXPTAB;
typedef struct EXPECT EXPECT;
typedef struct SEND SEND;
typedef struct DEBTAB DEBTAB;
typedef struct FILEREF FILEREF;
typedef struct BITFIELD BITFIELD;

typedef t_stat (*ACTIVATE_API)(UNIT *unit, int32 interval);

/* Device data structure */

struct DEVICE {
    const char          *name;                          /* name */
    UNIT                *units;                         /* units */
    REG                 *registers;                     /* registers */
    MTAB                *modifiers;                     /* modifiers */
    uint32              numunits;                       /* #units */
    uint32              aradix;                         /* address radix */
    uint32              awidth;                         /* address width */
    uint32              aincr;                          /* addr increment */
    uint32              dradix;                         /* data radix */
    uint32              dwidth;                         /* data width */
    t_stat              (*examine)(t_value *v, t_addr a, UNIT *up,
                            int32 sw);                  /* examine routine */
    t_stat              (*deposit)(t_value v, t_addr a, UNIT *up,
                            int32 sw);                  /* deposit routine */
    t_stat              (*reset)(DEVICE *dp);           /* reset routine */
    t_stat              (*boot)(int32 u, DEVICE *dp);
                                                        /* boot routine */
    t_stat              (*attach)(UNIT *up, CONST char *cp);
                                                        /* attach routine */
    t_stat              (*detach)(UNIT *up);            /* detach routine */
    void                *ctxt;                          /* context */
    uint32              flags;                          /* flags */
    uint32              dctrl;                          /* debug control */
    DEBTAB              *debflags;                      /* debug flags */
    t_stat              (*msize)(UNIT *up, int32 v, CONST char *cp, void *dp);
                                                        /* mem size routine */
    char                *lname;                         /* logical name */
    t_stat              (*help)(FILE *st, DEVICE *dptr,
                            UNIT *uptr, int32 flag, const char *cptr); 
                                                        /* help */
    t_stat              (*attach_help)(FILE *st, DEVICE *dptr,
                            UNIT *uptr, int32 flag, const char *cptr);
                                                        /* attach help */
    void *help_ctx;                                     /* Context available to help routines */
    const char          *(*description)(DEVICE *dptr);  /* Device Description */
    BRKTYPTAB           *brk_types;                     /* Breakpoint types */
    };

/* Device flags */

#define DEV_V_DIS       0                               /* dev disabled */
#define DEV_V_DISABLE   1                               /* dev disable-able */
#define DEV_V_DYNM      2                               /* mem size dynamic */
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487


488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
   Parts of the unit structure are device specific, that is, they are
   not referenced by the simulator control package and can be freely
   used by device simulators.  Fields starting with 'buf', and flags
   starting with 'UF', are device specific.  The definitions given here
   are for a typical sequential device.
*/

struct sim_unit {
    struct sim_unit     *next;                          /* next active */
    t_stat              (*action)(struct sim_unit *up); /* action routine */
    char                *filename;                      /* open file name */
    FILE                *fileref;                       /* file reference */
    void                *filebuf;                       /* memory buffer */
    uint32              hwmark;                         /* high water mark */
    int32               time;                           /* time out */
    uint32              flags;                          /* flags */
    uint32              dynflags;                       /* dynamic flags */
    t_addr              capac;                          /* capacity */
    t_addr              pos;                            /* file position */
    void                (*io_flush)(struct sim_unit *up);/* io flush routine */
    uint32              iostarttime;                    /* I/O start time */
    int32               buf;                            /* buffer */
    int32               wait;                           /* wait */
    int32               u3;                             /* device specific */
    int32               u4;                             /* device specific */
    int32               u5;                             /* device specific */
    int32               u6;                             /* device specific */
    void                *up7;                           /* device specific */
    void                *up8;                           /* device specific */


#ifdef SIM_ASYNCH_IO
    void                (*a_check_completion)(struct sim_unit *);
    t_bool              (*a_is_active)(struct sim_unit *);
    void                (*a_cancel)(struct sim_unit *);
    struct sim_unit     *a_next;                        /* next asynch active */
    int32               a_event_time;
    t_stat              (*a_activate_call)(struct sim_unit *, int32);
    /* Asynchronous Polling control */
    /* These fields should only be referenced when holding the sim_tmxr_poll_lock */
    t_bool              a_polling_now;                  /* polling active flag */
    int32               a_poll_waiter_count;            /* count of polling threads */
                                                        /* waiting for this unit */
    /* Asynchronous Timer control */
    double              a_due_time;                     /* due time for timer event */
    double              a_skew;                         /* accumulated skew being corrected */
    double              a_last_fired_time;              /* time last event fired */
    int32               a_usec_delay;                   /* time delay for timer event */
#endif
    };

/* Unit flags */

#define UNIT_V_UF_31    12              /* dev spec, V3.1 */







|
|
|









|









>
>

|
|
<
|

|







<
|







514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

548
549
550
551
552
553
554
555
556
557

558
559
560
561
562
563
564
565
   Parts of the unit structure are device specific, that is, they are
   not referenced by the simulator control package and can be freely
   used by device simulators.  Fields starting with 'buf', and flags
   starting with 'UF', are device specific.  The definitions given here
   are for a typical sequential device.
*/

struct UNIT {
    UNIT                *next;                          /* next active */
    t_stat              (*action)(UNIT *up);            /* action routine */
    char                *filename;                      /* open file name */
    FILE                *fileref;                       /* file reference */
    void                *filebuf;                       /* memory buffer */
    uint32              hwmark;                         /* high water mark */
    int32               time;                           /* time out */
    uint32              flags;                          /* flags */
    uint32              dynflags;                       /* dynamic flags */
    t_addr              capac;                          /* capacity */
    t_addr              pos;                            /* file position */
    void                (*io_flush)(UNIT *up);          /* io flush routine */
    uint32              iostarttime;                    /* I/O start time */
    int32               buf;                            /* buffer */
    int32               wait;                           /* wait */
    int32               u3;                             /* device specific */
    int32               u4;                             /* device specific */
    int32               u5;                             /* device specific */
    int32               u6;                             /* device specific */
    void                *up7;                           /* device specific */
    void                *up8;                           /* device specific */
    void                *tmxr;                          /* TMXR linkage */
    void                (*cancel)(UNIT *);
#ifdef SIM_ASYNCH_IO
    void                (*a_check_completion)(UNIT *);
    t_bool              (*a_is_active)(UNIT *);

    UNIT                *a_next;                        /* next asynch active */
    int32               a_event_time;
    ACTIVATE_API        a_activate_call;
    /* Asynchronous Polling control */
    /* These fields should only be referenced when holding the sim_tmxr_poll_lock */
    t_bool              a_polling_now;                  /* polling active flag */
    int32               a_poll_waiter_count;            /* count of polling threads */
                                                        /* waiting for this unit */
    /* Asynchronous Timer control */
    double              a_due_time;                     /* due time for timer event */

    double              a_due_gtime;                    /* due time (in instructions) for timer event */
    int32               a_usec_delay;                   /* time delay for timer event */
#endif
    };

/* Unit flags */

#define UNIT_V_UF_31    12              /* dev spec, V3.1 */
535
536
537
538
539
540
541


542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565

566
567
568
569
570
571
572
573
574
575
576
577
578

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/* Unit dynamic flags (dynflags) */

/* These flags are only set dynamically */

#define UNIT_ATTMULT    0000001         /* Allow multiple attach commands */
#define UNIT_TM_POLL    0000002         /* TMXR Polling unit */
#define UNIT_NO_FIO     0000004         /* fileref is NOT a FILE * */


#define UNIT_V_DF_TAPE  3               /* Bit offset for Tape Density reservation */
#define UNIT_S_DF_TAPE  3               /* Bits Reserved for Tape Density */

struct sim_bitfield {
    const char      *name;                              /* field name */
    uint32          offset;                             /* starting bit */
    uint32          width;                              /* width */
    const char      **valuenames;                       /* map of values to strings */
    const char      *format;                            /* value format string */
    };

/* Register data structure */

struct sim_reg {
    const char          *name;                          /* name */
    void                *loc;                           /* location */
    uint32              radix;                          /* radix */
    uint32              width;                          /* width */
    uint32              offset;                         /* starting bit */
    uint32              depth;                          /* save depth */
    const char          *desc;                          /* description */
    struct sim_bitfield *fields;                        /* bit fields */
    uint32              flags;                          /* flags */
    uint32              qptr;                           /* circ q ptr */

    };

/* Register flags */

#define REG_FMT         00003                           /* see PV_x */
#define REG_RO          00004                           /* read only */
#define REG_HIDDEN      00010                           /* hidden */
#define REG_NZ          00020                           /* must be non-zero */
#define REG_UNIT        00040                           /* in unit struct */
#define REG_CIRC        00100                           /* circular array */
#define REG_VMIO        00200                           /* use VM data print/parse */
#define REG_VMAD        00400                           /* use VM addr print/parse */
#define REG_FIT         01000                           /* fit access to size */

#define REG_HRO         (REG_RO | REG_HIDDEN)           /* hidden, read only */

#define REG_V_UF        16                              /* device specific */
#define REG_UFMASK      (~((1u << REG_V_UF) - 1))       /* user flags mask */
#define REG_VMFLAGS     (REG_VMIO | REG_UFMASK)         /* call VM routine if any of these are set */

/* Command tables, base and alternate formats */

struct sim_ctab {
    const char          *name;                          /* name */
    t_stat              (*action)(int32 flag, char *cptr);
                                                        /* action routine */
    int32               arg;                            /* argument */
    const char          *help;                          /* help string/structured locator */
    const char          *help_base;                     /* structured help base*/
    void                (*message)(const char *unechoed_cmdline, t_stat stat);
                                                        /* message printing routine */
    };

struct sim_c1tab {
    const char          *name;                          /* name */
    t_stat              (*action)(struct sim_device *dptr, struct sim_unit *uptr,
                            int32 flag, char *cptr);    /* action routine */
    int32               arg;                            /* argument */
    const char          *help;                          /* help string */
    };

struct sim_shtab {
    const char          *name;                          /* name */
    t_stat              (*action)(FILE *st, struct sim_device *dptr,
                            struct sim_unit *uptr, int32 flag, char *cptr);
    int32               arg;                            /* argument */
    const char          *help;                          /* help string */
    };

/* Modifier table - only extended entries have disp, reg, or flags */

struct sim_mtab {
    uint32              mask;                           /* mask */
    uint32              match;                          /* match */
    const char          *pstring;                       /* print string */
    const char          *mstring;                       /* match string */
    t_stat              (*valid)(struct sim_unit *up, int32 v, char *cp, void *dp);
                                                        /* validation routine */
    t_stat              (*disp)(FILE *st, struct sim_unit *up, int32 v, void *dp);
                                                        /* display routine */
    void                *desc;                          /* value descriptor */
                                                        /* REG * if MTAB_VAL */
                                                        /* int * if not */
    const char          *help;                          /* help string */
    };








>
>
|


|









|
|






|


>









|
|
|
|
>








|

|








|

|
|




|

|
|






|




|

|







590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/* Unit dynamic flags (dynflags) */

/* These flags are only set dynamically */

#define UNIT_ATTMULT    0000001         /* Allow multiple attach commands */
#define UNIT_TM_POLL    0000002         /* TMXR Polling unit */
#define UNIT_NO_FIO     0000004         /* fileref is NOT a FILE * */
#define UNIT_DISK_CHK   0000010         /* disk data debug checking (sim_disk) */
#define UNIT_TMR_UNIT   0000020         /* Unit registered as a calibrated timer */
#define UNIT_V_DF_TAPE  5               /* Bit offset for Tape Density reservation */
#define UNIT_S_DF_TAPE  3               /* Bits Reserved for Tape Density */

struct BITFIELD {
    const char      *name;                              /* field name */
    uint32          offset;                             /* starting bit */
    uint32          width;                              /* width */
    const char      **valuenames;                       /* map of values to strings */
    const char      *format;                            /* value format string */
    };

/* Register data structure */

struct REG {
    CONST char          *name;                          /* name */
    void                *loc;                           /* location */
    uint32              radix;                          /* radix */
    uint32              width;                          /* width */
    uint32              offset;                         /* starting bit */
    uint32              depth;                          /* save depth */
    const char          *desc;                          /* description */
    BITFIELD            *fields;                        /* bit fields */
    uint32              flags;                          /* flags */
    uint32              qptr;                           /* circ q ptr */
    size_t              str_size;                       /* structure size */
    };

/* Register flags */

#define REG_FMT         00003                           /* see PV_x */
#define REG_RO          00004                           /* read only */
#define REG_HIDDEN      00010                           /* hidden */
#define REG_NZ          00020                           /* must be non-zero */
#define REG_UNIT        00040                           /* in unit struct */
#define REG_STRUCT      00100                           /* in structure array */
#define REG_CIRC        00200                           /* circular array */
#define REG_VMIO        00400                           /* use VM data print/parse */
#define REG_VMAD        01000                           /* use VM addr print/parse */
#define REG_FIT         02000                           /* fit access to size */
#define REG_HRO         (REG_RO | REG_HIDDEN)           /* hidden, read only */

#define REG_V_UF        16                              /* device specific */
#define REG_UFMASK      (~((1u << REG_V_UF) - 1))       /* user flags mask */
#define REG_VMFLAGS     (REG_VMIO | REG_UFMASK)         /* call VM routine if any of these are set */

/* Command tables, base and alternate formats */

struct CTAB {
    const char          *name;                          /* name */
    t_stat              (*action)(int32 flag, CONST char *cptr);
                                                        /* action routine */
    int32               arg;                            /* argument */
    const char          *help;                          /* help string/structured locator */
    const char          *help_base;                     /* structured help base*/
    void                (*message)(const char *unechoed_cmdline, t_stat stat);
                                                        /* message printing routine */
    };

struct C1TAB {
    const char          *name;                          /* name */
    t_stat              (*action)(DEVICE *dptr, UNIT *uptr,
                            int32 flag, CONST char *cptr);/* action routine */
    int32               arg;                            /* argument */
    const char          *help;                          /* help string */
    };

struct SHTAB {
    const char          *name;                          /* name */
    t_stat              (*action)(FILE *st, DEVICE *dptr,
                            UNIT *uptr, int32 flag, CONST char *cptr);
    int32               arg;                            /* argument */
    const char          *help;                          /* help string */
    };

/* Modifier table - only extended entries have disp, reg, or flags */

struct MTAB {
    uint32              mask;                           /* mask */
    uint32              match;                          /* match */
    const char          *pstring;                       /* print string */
    const char          *mstring;                       /* match string */
    t_stat              (*valid)(UNIT *up, int32 v, CONST char *cp, void *dp);
                                                        /* validation routine */
    t_stat              (*disp)(FILE *st, UNIT *up, int32 v, CONST void *dp);
                                                        /* display routine */
    void                *desc;                          /* value descriptor */
                                                        /* REG * if MTAB_VAL */
                                                        /* int * if not */
    const char          *help;                          /* help string */
    };

640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659

660
661
662


663
664


665








666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739

740





741
742
743
744





745
746
747
748
749
750


751
752
753
754
755
756
757
758
759
760
761
762
763

764
765
766
767
768
769
770
771
772

773
774
775
776
777
778
779
780
781
782
783
784


785
786
787

788
789
790
791
792
793
794
795

796
797
798
799
800
801
802
803

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856


857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897

898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
#define MTAB_NC         (0040 | MTAB_XTD)               /* no UC conversion */
#define MTAB_QUOTE      (0100 | MTAB_XTD)               /* quoted string */
#define MTAB_SHP        (0200 | MTAB_XTD)               /* show takes parameter */
#define MODMASK(mptr,flag) (((mptr)->mask & (uint32)(flag)) == (uint32)(flag))/* flag mask test */

/* Search table */

struct sim_schtab {
    int32               logic;                          /* logical operator */
    int32               boolop;                         /* boolean operator */
    uint32              count;                          /* value count in mask and comp arrays */
    t_value             *mask;                          /* mask for logical */
    t_value             *comp;                          /* comparison for boolean */
    };

/* Breakpoint table */

struct sim_brktab {
    t_addr              addr;                           /* address */
    uint32              typ;                            /* mask of types */

#define BRK_TYP_DYN_STEPOVER    (SWMASK ('Z'+1))
#define BRK_TYP_DYN_USR         (SWMASK ('Z'+2))
#define BRK_TYP_DYN_ALL         (BRK_TYP_DYN_USR|BRK_TYP_DYN_STEPOVER) /* Mask of All Dynamic types */


    int32               cnt;                            /* proceed count */
    char                *act;                           /* action string */


    };









/* Expect rule */

struct sim_exptab {
    uint8               *match;                         /* match string */
    uint32              size;                           /* match string size */
    char                *match_pattern;                 /* match pattern for format */
    int32               cnt;                            /* proceed count */
    int32               switches;                       /* flags */
#define EXP_TYP_PERSIST         (SWMASK ('P'))      /* rule persists after match, default is once a rule matches, it is removed */
#define EXP_TYP_CLEARALL        (SWMASK ('C'))      /* clear all rules after matching this rule, default is to once a rule matches, it is removed */
#define EXP_TYP_REGEX           (SWMASK ('R'))      /* rule pattern is a regular expression */
#define EXP_TYP_REGEX_I         (SWMASK ('I'))      /* regular expression pattern matching should be case independent */
#define EXP_TYP_TIME            (SWMASK ('T'))      /* halt delay is in microseconds instead of instructions */
#if defined(USE_REGEX)
    regex_t             regex;                          /* compiled regular expression */
#endif
    char                *act;                           /* action string */
    };

/* Expect Context */

struct sim_expect {
    struct sim_device   *dptr;                          /* Device (for Debug) */
    uint32              dbit;                           /* Debugging Bit */
    struct sim_exptab   *rules;                         /* match rules */
    int32               size;                           /* count of match rules */
    uint32              after;                          /* delay before halting */
    uint8               *buf;                           /* buffer of output data which has produced */
    uint32              buf_ins;                        /* buffer insertion point for the next output data */
    uint32              buf_size;                       /* buffer size */
    };

/* Send Context */

struct sim_send {
    uint32              delay;                          /* instruction delay between sent data */
#define SEND_DEFAULT_DELAY  1000                        /* default delay instruction count */
    struct sim_device   *dptr;                          /* Device (for Debug) */
    uint32              dbit;                           /* Debugging Bit */
    uint32              after;                          /* instruction delay before sending any data */
    double              next_time;                      /* execution time when next data can be sent */
    uint8               *buffer;                        /* buffer */
    size_t              bufsize;                        /* buffer size */
    int32               insoff;                         /* insert offset */
    int32               extoff;                         /* extra offset */
    };

/* Debug table */

struct sim_debtab {
    const char          *name;                          /* control name */
    uint32              mask;                           /* control bit */
    const char          *desc;                          /* description */
    };

/* Deprecated Debug macros.  Use sim_debug() */

#define DEBUG_PRS(d)    (sim_deb && d.dctrl)
#define DEBUG_PRD(d)    (sim_deb && d->dctrl)
#define DEBUG_PRI(d,m)  (sim_deb && (d.dctrl & (m)))
#define DEBUG_PRJ(d,m)  (sim_deb && ((d)->dctrl & (m)))

#define SIM_DBG_EVENT       0x10000
#define SIM_DBG_ACTIVATE    0x20000
#define SIM_DBG_AIO_QUEUE   0x40000

/* File Reference */
struct sim_fileref {
    char                name[CBUFSIZE];                 /* file name */
    FILE                *file;                          /* file handle */
    int32               refcount;                       /* reference count */
    };


/* The following macros define structure contents */






#define UDATA(act,fl,cap) NULL,act,NULL,NULL,NULL,0,0,(fl),0,(cap),0,NULL,0,0

#if defined (__STDC__) || defined (_WIN32)





/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) #nm, &(loc), 8, (wd), 0, 1, NULL, NULL
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) #nm, &(loc), 10, (wd), 0, 1, NULL, NULL
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) #nm, &(loc), 16, (wd), 0, 1, NULL, NULL


/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) #nm, &(loc), 2, 1, (pos), 1, NULL, NULL
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) #nm, &(loc), (rdx), (wd), (pos), 1, NULL, NULL
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) #nm, (loc), (rdx), (wd), 0, (dep), NULL, NULL
/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    #nm, &(loc), (rdx), (wd), (off), (dep), NULL, NULL, ((fl) | REG_UNIT)
/* Same as above, but with additional description initializer */
#define ORDATAD(nm,loc,wd,desc) #nm, &(loc), 8, (wd), 0, 1, (desc), NULL
#define DRDATAD(nm,loc,wd,desc) #nm, &(loc), 10, (wd), 0, 1, (desc), NULL
#define HRDATAD(nm,loc,wd,desc) #nm, &(loc), 16, (wd), 0, 1, (desc), NULL

#define FLDATAD(nm,loc,pos,desc) #nm, &(loc), 2, 1, (pos), 1, (desc), NULL
#define GRDATAD(nm,loc,rdx,wd,pos,desc) #nm, &(loc), (rdx), (wd), (pos), 1, (desc), NULL
#define BRDATAD(nm,loc,rdx,wd,dep,desc) #nm, (loc), (rdx), (wd), 0, (dep), (desc), NULL
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    #nm, &(loc), (rdx), (wd), (off), (dep), (desc), NULL, ((fl) | REG_UNIT)
/* Same as above, but with additional description initializer, and bitfields */
#define ORDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 8, (wd), 0, 1, (desc), (flds)
#define DRDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 10, (wd), 0, 1, (desc), (flds)
#define HRDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 16, (wd), 0, 1, (desc), (flds)

#define FLDATADF(nm,loc,pos,desc,flds) #nm, &(loc), 2, 1, (pos), 1, (desc), (flds)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) #nm, &(loc), (rdx), (wd), (pos), 1, (desc), (flds)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) #nm, (loc), (rdx), (wd), 0, (dep), (desc), (flds)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    #nm, &(loc), (rdx), (wd), (off), (dep), (desc), (flds), ((fl) | REG_UNIT)
#define BIT(nm)              {#nm, 0xffffffff, 1}             /* Single Bit definition */
#define BITNC                {"",  0xffffffff, 1}             /* Don't care Bit definition */
#define BITF(nm,sz)          {#nm, 0xffffffff, sz}            /* Bit Field definition */
#define BITNCF(sz)           {"",  0xffffffff, sz}            /* Don't care Bit Field definition */
#define BITFFMT(nm,sz,fmt)   {#nm, 0xffffffff, sz, NULL, #fmt}/* Bit Field definition with Output format */
#define BITFNAM(nm,sz,names) {#nm, 0xffffffff, sz, names}     /* Bit Field definition with value->name map */
#else


#define ORDATA(nm,loc,wd) "nm", &(loc), 8, (wd), 0, 1, NULL, NULL
#define DRDATA(nm,loc,wd) "nm", &(loc), 10, (wd), 0, 1, NULL, NULL
#define HRDATA(nm,loc,wd) "nm", &(loc), 16, (wd), 0, 1, NULL, NULL

#define FLDATA(nm,loc,pos) "nm", &(loc), 2, 1, (pos), 1, NULL, NULL
#define GRDATA(nm,loc,rdx,wd,pos) "nm", &(loc), (rdx), (wd), (pos), 1, NULL, NULL
#define BRDATA(nm,loc,rdx,wd,dep) "nm", (loc), (rdx), (wd), 0, (dep), NULL, NULL
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    "nm", &(loc), (rdx), (wd), (off), (dep), NULL, NULL, ((fl) | REG_UNIT)
#define ORDATAD(nm,loc,wd,desc) "nm", &(loc), 8, (wd), 0, 1, (desc), NULL
#define DRDATAD(nm,loc,wd,desc) "nm", &(loc), 10, (wd), 0, 1, (desc), NULL
#define HRDATAD(nm,loc,wd,desc) "nm", &(loc), 16, (wd), 0, 1, (desc), NULL

#define FLDATAD(nm,loc,pos,desc) "nm", &(loc), 2, 1, (pos), 1, (desc), NULL
#define GRDATAD(nm,loc,rdx,wd,pos,desc) "nm", &(loc), (rdx), (wd), (pos), 1, (desc), NULL
#define BRDATAD(nm,loc,rdx,wd,dep,desc) "nm", (loc), (rdx), (wd), 0, (dep), (desc), NULL
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    "nm", &(loc), (rdx), (wd), (off), (dep), (desc), NULL, ((fl) | REG_UNIT)
#define ORDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 8, (wd), 0, 1, (desc), (flds)
#define DRDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 10, (wd), 0, 1, (desc), (flds)
#define HRDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 16, (wd), 0, 1, (desc), (flds)

#define FLDATADF(nm,loc,pos,desc,flds) "nm", &(loc), 2, 1, (pos), 1, (desc), (flds)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) "nm", &(loc), (rdx), (wd), (pos), 1, (desc), (flds)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) "nm", (loc), (rdx), (wd), 0, (dep), (desc), (flds)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    "nm", &(loc), (rdx), (wd), (off), (dep), (desc), (flds), ((fl) | REG_UNIT)
#define BIT(nm)              {"nm", 0xffffffff, 1}              /* Single Bit definition */
#define BITNC                {"",   0xffffffff, 1}              /* Don't care Bit definition */
#define BITF(nm,sz)          {"nm", 0xffffffff, sz}             /* Bit Field definition */
#define BITNCF(sz)           {"",   0xffffffff, sz}             /* Don't care Bit Field definition */
#define BITFFMT(nm,sz,fmt)   {"nm", 0xffffffff, sz, NULL, "fmt"}/* Bit Field definition with Output format */
#define BITFNAM(nm,sz,names) {"nm", 0xffffffff, sz, names}      /* Bit Field definition with value->name map */
#endif
#define ENDBITS {NULL}  /* end of bitfield list */

/* Typedefs for principal structures */

typedef struct sim_device DEVICE;
typedef struct sim_unit UNIT;
typedef struct sim_reg REG;
typedef struct sim_ctab CTAB;
typedef struct sim_c1tab C1TAB;
typedef struct sim_shtab SHTAB;
typedef struct sim_mtab MTAB;
typedef struct sim_schtab SCHTAB;
typedef struct sim_brktab BRKTAB;
typedef struct sim_exptab EXPTAB;
typedef struct sim_expect EXPECT;
typedef struct sim_send SEND;
typedef struct sim_debtab DEBTAB;
typedef struct sim_fileref FILEREF;
typedef struct sim_bitfield BITFIELD;

/* Function prototypes */

#include "scp.h"
#include "sim_console.h"
#include "sim_timer.h"
#include "sim_fio.h"

/* Macro to ALWAYS execute the specified expression and fail if it evaluates to false. */
/* This replaces any references to "assert()" which should never be invoked */
/* with an expression which causes side effects (i.e. must be executed for */
/* the program to work correctly) */
#define ASSURE(_Expression) if (!(_Expression)) {const char *_exp = #_Expression; const char *_file = __FILE__;                                 \
                                                 fprintf(stderr, "%s failed at %s line %d\n", _exp, _file, __LINE__);               \
                                                 if (sim_log) fprintf(sim_log, "%s failed at %s line %d\n", _exp, _file, __LINE__); \
                                                 if (sim_deb) fprintf(sim_deb, "%s failed at %s line %d\n", _exp, _file, __LINE__); \
                                                 abort();} else (void)0

/* Asynch/Threaded I/O support */

#if defined (SIM_ASYNCH_IO)
#include <pthread.h>



extern pthread_mutex_t sim_asynch_lock;
extern pthread_cond_t sim_asynch_wake;
extern pthread_mutex_t sim_timer_lock;
extern pthread_cond_t sim_timer_wake;
extern t_bool sim_timer_event_canceled;
extern int32 sim_tmxr_poll_count;
extern pthread_cond_t sim_tmxr_poll_cond;
extern pthread_mutex_t sim_tmxr_poll_lock;
extern pthread_t sim_asynch_main_threadid;
extern UNIT * volatile sim_asynch_queue;
extern UNIT * volatile sim_wallclock_queue;
extern UNIT * volatile sim_wallclock_entry;
extern volatile t_bool sim_idle_wait;
extern int32 sim_asynch_check;
extern int32 sim_asynch_latency;
extern int32 sim_asynch_inst_latency;

/* Thread local storage */
#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__hpux) && !defined(__OpenBSD__) && !defined(_AIX)
#define AIO_TLS __thread
#elif defined(_MSC_VER)
#define AIO_TLS __declspec(thread)
#else
/* Other compiler environment, then don't worry about thread local storage. */
/* It is primarily used only used in debugging messages */
#define AIO_TLS
#endif
#define AIO_QUEUE_CHECK(que, lock)                                  \
    if (1) {                                                        \
            UNIT *_cptr;                                            \
            if (lock)                                               \
                pthread_mutex_lock (lock);                          \
            for (_cptr = que;                                       \
                (_cptr != QUEUE_LIST_END);                          \
                _cptr = _cptr->next)                                \
                if (!_cptr->next) {                                 \
                    if (sim_deb) {                                  \
                        sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Queue Corruption detected\n");\
                        fclose(sim_deb);                            \
                        }                                           \

                    abort();                                        \
                    }                                               \
            if (lock)                                               \
                pthread_mutex_unlock (lock);                        \
        } else (void)0
#define AIO_MAIN_THREAD (pthread_equal ( pthread_self(), sim_asynch_main_threadid ))
#define AIO_LOCK                                                  \
    pthread_mutex_lock(&sim_asynch_lock)
#define AIO_UNLOCK                                                \
    pthread_mutex_unlock(&sim_asynch_lock)
#define AIO_IS_ACTIVE(uptr) (((uptr)->a_is_active ? (uptr)->a_is_active (uptr) : FALSE) || ((uptr)->a_next))
#if !defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_CLOCKS)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->a_cancel)                                         \
        (uptr)->a_cancel (uptr);                                  \
    else                                                          \
        (void)0
#endif /* !defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_CLOCKS) */
#if !defined(SIM_ASYNCH_MUX) && defined(SIM_ASYNCH_CLOCKS)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->a_cancel)                                         \
        (uptr)->a_cancel (uptr);                                  \
    else {                                                        \
        AIO_UPDATE_QUEUE;                                         \
        if ((uptr)->a_next) {                                     \
            UNIT *cptr;                                           \
            pthread_mutex_lock (&sim_timer_lock);                 \
            if ((uptr) == sim_wallclock_queue) {                  \
                sim_wallclock_queue = (uptr)->a_next;             \
                (uptr)->a_next = NULL;                            \
                sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Timer Event for %s\n", sim_uname(uptr));\
                sim_timer_event_canceled = TRUE;                  \
                pthread_cond_signal (&sim_timer_wake);            \
                }                                                 \
            else                                                  \
                for (cptr = sim_wallclock_queue;                  \
                    (cptr != QUEUE_LIST_END);                     \
                    cptr = cptr->a_next)                          \
                    if (cptr->a_next == (uptr)) {                 \
                        cptr->a_next = (uptr)->a_next;            \
                        (uptr)->a_next = NULL;                    \
                        sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Timer Event for %s\n", sim_uname(uptr));\
                        break;                                    \
                        }                                         \
            if ((uptr)->a_next == NULL)                           \
                (uptr)->a_due_time = (uptr)->a_usec_delay = 0;    \
            else {                                                \
                int tmr;                                          \
                for (tmr=0; tmr<SIM_NTIMERS; tmr++) {             \
                    if ((uptr) == sim_clock_cosched_queue[tmr]) { \
                        sim_clock_cosched_queue[tmr] = (uptr)->a_next; \
                        (uptr)->a_next = NULL;                    \
                        }                                         \
                    else                                          \
                        for (cptr = sim_clock_cosched_queue[tmr]; \
                            (cptr != QUEUE_LIST_END);             \
                            cptr = cptr->a_next)                  \
                            if (cptr->a_next == (uptr)) {         \
                                cptr->a_next = (uptr)->a_next;    \
                                (uptr)->a_next = NULL;            \
                                break;                            \
                                }                                 \
                    if ((uptr)->a_next == NULL) {                 \
                        sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Clock Coscheduling Event for %s\n", sim_uname(uptr));\
                        }                                         \
                    }                                             \
                }                                                 \
            while (sim_timer_event_canceled) {                    \
                pthread_mutex_unlock (&sim_timer_lock);           \
                sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Waiting for Timer Event cancelation for %s\n", sim_uname(uptr));\
                sim_os_ms_sleep (0);                              \
                pthread_mutex_lock (&sim_timer_lock);             \
                }                                                 \
            pthread_mutex_unlock (&sim_timer_lock);               \
            }                                                     \
        }
#endif
#if defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_CLOCKS)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->a_cancel)                                         \
        (uptr)->a_cancel (uptr);                                  \
    else {                                                        \
        if (((uptr)->dynflags & UNIT_TM_POLL) &&                  \
            !((uptr)->next) && !((uptr)->a_next)) {               \
            (uptr)->a_polling_now = FALSE;                        \
            sim_tmxr_poll_count -= (uptr)->a_poll_waiter_count;   \
            (uptr)->a_poll_waiter_count = 0;                      \
            }                                                     \
        }
#endif /* defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_CLOCKS) */
#if defined(SIM_ASYNCH_MUX) && defined(SIM_ASYNCH_CLOCKS)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->a_cancel)                                         \
        (uptr)->a_cancel (uptr);                                  \
    else {                                                        \
        AIO_UPDATE_QUEUE;                                         \
        if (((uptr)->dynflags & UNIT_TM_POLL) &&                  \
            !((uptr)->next) && !((uptr)->a_next)) {               \
            (uptr)->a_polling_now = FALSE;                        \
            sim_tmxr_poll_count -= (uptr)->a_poll_waiter_count;   \
            (uptr)->a_poll_waiter_count = 0;                      \
            }                                                     \
        if ((uptr)->a_next) {                                     \
            UNIT *cptr;                                           \
            pthread_mutex_lock (&sim_timer_lock);                 \
            if ((uptr) == sim_wallclock_queue) {                  \
                sim_wallclock_queue = (uptr)->a_next;             \
                (uptr)->a_next = NULL;                            \
                sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Timer Event for %s\n", sim_uname(uptr));\
                sim_timer_event_canceled = TRUE;                  \
                pthread_cond_signal (&sim_timer_wake);            \
                }                                                 \
            else                                                  \
                for (cptr = sim_wallclock_queue;                  \
                    (cptr != QUEUE_LIST_END);                     \
                    cptr = cptr->a_next)                          \
                    if (cptr->a_next == (uptr)) {                 \
                        cptr->a_next = (uptr)->a_next;            \
                        (uptr)->a_next = NULL;                    \
                        sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Timer Event for %s\n", sim_uname(uptr));\
                        break;                                    \
                        }                                         \
            if ((uptr)->a_next == NULL)                           \
                (uptr)->a_due_time = (uptr)->a_usec_delay = 0;    \
            else {                                                \
                if ((uptr) == sim_clock_cosched_queue) {          \
                    sim_clock_cosched_queue = (uptr)->a_next;     \
                    (uptr)->a_next = NULL;                        \
                    }                                             \
                else                                              \
                    for (cptr = sim_clock_cosched_queue;          \
                        (cptr != QUEUE_LIST_END);                 \
                        cptr = cptr->a_next)                      \
                        if (cptr->a_next == (uptr)) {             \
                            cptr->a_next = (uptr)->a_next;        \
                            (uptr)->a_next = NULL;                \
                            break;                                \
                            }                                     \
                if ((uptr)->a_next == NULL) {                     \
                    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Canceling Clock Coscheduling Event for %s\n", sim_uname(uptr));\
                    }                                             \
                }                                                 \
            while (sim_timer_event_canceled) {                    \
                pthread_mutex_unlock (&sim_timer_lock);           \
                sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Waiting for Timer Event cancelation for %s\n", sim_uname(uptr));\
                sim_os_ms_sleep (0);                              \
                pthread_mutex_lock (&sim_timer_lock);             \
                }                                                 \
            pthread_mutex_unlock (&sim_timer_lock);               \
            }                                                     \
        }
#endif
#if defined(SIM_ASYNCH_CLOCKS)
#define AIO_RETURN_TIME(uptr)                                     \
    if (1) {                                                      \
        pthread_mutex_lock (&sim_timer_lock);                     \
        for (cptr = sim_wallclock_queue;                          \
             cptr != QUEUE_LIST_END;                              \
             cptr = cptr->a_next)                                 \
            if ((uptr) == cptr) {                                 \
                double inst_per_sec = sim_timer_inst_per_sec ();  \
                int32 result;                                     \
                                                                  \
                result = (int32)(((uptr)->a_due_time - sim_timenow_double())*inst_per_sec);\
                if (result < 0)                                   \
                    result = 0;                                   \
                pthread_mutex_unlock (&sim_timer_lock);           \
                return result + 1;                                \
                }                                                 \
        pthread_mutex_unlock (&sim_timer_lock);                   \
        if ((uptr)->a_next) /* On asynch queue? */                \
            return (uptr)->a_event_time + 1;                      \
        }                                                         \
    else                                                          \
        (void)0
#else
#define AIO_RETURN_TIME(uptr) (void)0
#endif
#define AIO_EVENT_BEGIN(uptr)                                     \
    do {                                                          \
        int __was_poll = uptr->dynflags & UNIT_TM_POLL
#define AIO_EVENT_COMPLETE(uptr, reason)                          \
        if (__was_poll) {                                         \
            pthread_mutex_lock (&sim_tmxr_poll_lock);             \
            uptr->a_polling_now = FALSE;                          \







|









|


>



>
>


>
>

>
>
>
>
>
>
>
>



|


















|
|

|









|


|











|

















|





>
|
>
>
>
>
>



|
>
>
>
>
>






>
>






<
<
<




>



<
<




>



<
<






|
>
>



>



<
<



>



<
<



>



<
<









|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<












<
|
|
<
|





>
>











<
<















|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|






<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

|
|








|
|

|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841



842
843
844
845
846
847
848
849


850
851
852
853
854
855
856
857


858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873


874
875
876
877
878
879
880


881
882
883
884
885
886
887


888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912

913
914
915
916
917
918
919
920
921
922
923
924

925
926

927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945


946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985


































































986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002

























































1003


























1004
1005
1006
1007
1008
1009
1010
#define MTAB_NC         (0040 | MTAB_XTD)               /* no UC conversion */
#define MTAB_QUOTE      (0100 | MTAB_XTD)               /* quoted string */
#define MTAB_SHP        (0200 | MTAB_XTD)               /* show takes parameter */
#define MODMASK(mptr,flag) (((mptr)->mask & (uint32)(flag)) == (uint32)(flag))/* flag mask test */

/* Search table */

struct SCHTAB {
    int32               logic;                          /* logical operator */
    int32               boolop;                         /* boolean operator */
    uint32              count;                          /* value count in mask and comp arrays */
    t_value             *mask;                          /* mask for logical */
    t_value             *comp;                          /* comparison for boolean */
    };

/* Breakpoint table */

struct BRKTAB {
    t_addr              addr;                           /* address */
    uint32              typ;                            /* mask of types */
#define BRK_TYP_USR_TYPES       ((1 << ('Z'-'A'+1)) - 1)/* all types A-Z */
#define BRK_TYP_DYN_STEPOVER    (SWMASK ('Z'+1))
#define BRK_TYP_DYN_USR         (SWMASK ('Z'+2))
#define BRK_TYP_DYN_ALL         (BRK_TYP_DYN_USR|BRK_TYP_DYN_STEPOVER) /* Mask of All Dynamic types */
#define BRK_TYP_TEMP            (SWMASK ('Z'+3))        /* Temporary (one-shot) */
#define BRK_TYP_MAX             (('Z'-'A')+3)           /* Maximum breakpoint type */
    int32               cnt;                            /* proceed count */
    char                *act;                           /* action string */
    double              time_fired[SIM_BKPT_N_SPC];     /* instruction count when match occurred */
    BRKTAB *next;                                       /* list with same address value */
    };

/* Breakpoint table */

struct BRKTYPTAB {
    uint32      btyp;                                   /* type mask */
    const char *desc;                                   /* description */
    };
#define BRKTYPE(typ,descrip) {SWMASK(typ), descrip}

/* Expect rule */

struct EXPTAB {
    uint8               *match;                         /* match string */
    uint32              size;                           /* match string size */
    char                *match_pattern;                 /* match pattern for format */
    int32               cnt;                            /* proceed count */
    int32               switches;                       /* flags */
#define EXP_TYP_PERSIST         (SWMASK ('P'))      /* rule persists after match, default is once a rule matches, it is removed */
#define EXP_TYP_CLEARALL        (SWMASK ('C'))      /* clear all rules after matching this rule, default is to once a rule matches, it is removed */
#define EXP_TYP_REGEX           (SWMASK ('R'))      /* rule pattern is a regular expression */
#define EXP_TYP_REGEX_I         (SWMASK ('I'))      /* regular expression pattern matching should be case independent */
#define EXP_TYP_TIME            (SWMASK ('T'))      /* halt delay is in microseconds instead of instructions */
#if defined(USE_REGEX)
    regex_t             regex;                          /* compiled regular expression */
#endif
    char                *act;                           /* action string */
    };

/* Expect Context */

struct EXPECT {
    DEVICE              *dptr;                          /* Device (for Debug) */
    uint32              dbit;                           /* Debugging Bit */
    EXPTAB              *rules;                         /* match rules */
    int32               size;                           /* count of match rules */
    uint32              after;                          /* delay before halting */
    uint8               *buf;                           /* buffer of output data which has produced */
    uint32              buf_ins;                        /* buffer insertion point for the next output data */
    uint32              buf_size;                       /* buffer size */
    };

/* Send Context */

struct SEND {
    uint32              delay;                          /* instruction delay between sent data */
#define SEND_DEFAULT_DELAY  1000                        /* default delay instruction count */
    DEVICE              *dptr;                          /* Device (for Debug) */
    uint32              dbit;                           /* Debugging Bit */
    uint32              after;                          /* instruction delay before sending any data */
    double              next_time;                      /* execution time when next data can be sent */
    uint8               *buffer;                        /* buffer */
    size_t              bufsize;                        /* buffer size */
    int32               insoff;                         /* insert offset */
    int32               extoff;                         /* extra offset */
    };

/* Debug table */

struct DEBTAB {
    const char          *name;                          /* control name */
    uint32              mask;                           /* control bit */
    const char          *desc;                          /* description */
    };

/* Deprecated Debug macros.  Use sim_debug() */

#define DEBUG_PRS(d)    (sim_deb && d.dctrl)
#define DEBUG_PRD(d)    (sim_deb && d->dctrl)
#define DEBUG_PRI(d,m)  (sim_deb && (d.dctrl & (m)))
#define DEBUG_PRJ(d,m)  (sim_deb && ((d)->dctrl & (m)))

#define SIM_DBG_EVENT       0x10000
#define SIM_DBG_ACTIVATE    0x20000
#define SIM_DBG_AIO_QUEUE   0x40000

/* File Reference */
struct FILEREF {
    char                name[CBUFSIZE];                 /* file name */
    FILE                *file;                          /* file handle */
    int32               refcount;                       /* reference count */
    };

/* 
   The following macros exist to help populate structure contents

   They are dependent on the declaration order of the fields 
   of the structures they exist to populate.

 */

#define UDATA(act,fl,cap) NULL,act,NULL,NULL,NULL,0,0,(fl),0,(cap),0,NULL,0,0

#if defined (__STDC__) || defined (_WIN32) /* Variants which depend on how macro arguments are convered to strings */
/* Generic Register declaration for all fields.  
   If the register structure is extended, this macro will be retained and a 
   new macro will be provided that populates the new register structure */
#define REGDATA(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    #nm, &(loc), (rdx), (wd), (off), (dep), (desc), (flds), (fl), (qptr), (siz)
/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) #nm, &(loc), 8, (wd), 0, 1, NULL, NULL
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) #nm, &(loc), 10, (wd), 0, 1, NULL, NULL
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) #nm, &(loc), 16, (wd), 0, 1, NULL, NULL
/* Right Justified Binary Register Data */
#define BINRDATA(nm,loc,wd) #nm, &(loc), 2, (wd), 0, 1, NULL, NULL
/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) #nm, &(loc), 2, 1, (pos), 1, NULL, NULL
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) #nm, &(loc), (rdx), (wd), (pos), 1, NULL, NULL
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) #nm, (loc), (rdx), (wd), 0, (dep), NULL, NULL



/* Same as above, but with additional description initializer */
#define ORDATAD(nm,loc,wd,desc) #nm, &(loc), 8, (wd), 0, 1, (desc), NULL
#define DRDATAD(nm,loc,wd,desc) #nm, &(loc), 10, (wd), 0, 1, (desc), NULL
#define HRDATAD(nm,loc,wd,desc) #nm, &(loc), 16, (wd), 0, 1, (desc), NULL
#define BINRDATAD(nm,loc,wd,desc) #nm, &(loc), 2, (wd), 0, 1, (desc), NULL
#define FLDATAD(nm,loc,pos,desc) #nm, &(loc), 2, 1, (pos), 1, (desc), NULL
#define GRDATAD(nm,loc,rdx,wd,pos,desc) #nm, &(loc), (rdx), (wd), (pos), 1, (desc), NULL
#define BRDATAD(nm,loc,rdx,wd,dep,desc) #nm, (loc), (rdx), (wd), 0, (dep), (desc), NULL


/* Same as above, but with additional description initializer, and bitfields */
#define ORDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 8, (wd), 0, 1, (desc), (flds)
#define DRDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 10, (wd), 0, 1, (desc), (flds)
#define HRDATADF(nm,loc,wd,desc,flds) #nm, &(loc), 16, (wd), 0, 1, (desc), (flds)
#define BINRDATADF(nm,loc,wd) #nm, &(loc), 2, (wd), 0, 1, NULL, NULL
#define FLDATADF(nm,loc,pos,desc,flds) #nm, &(loc), 2, 1, (pos), 1, (desc), (flds)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) #nm, &(loc), (rdx), (wd), (pos), 1, (desc), (flds)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) #nm, (loc), (rdx), (wd), 0, (dep), (desc), (flds)


#define BIT(nm)              {#nm, 0xffffffff, 1}             /* Single Bit definition */
#define BITNC                {"",  0xffffffff, 1}             /* Don't care Bit definition */
#define BITF(nm,sz)          {#nm, 0xffffffff, sz}            /* Bit Field definition */
#define BITNCF(sz)           {"",  0xffffffff, sz}            /* Don't care Bit Field definition */
#define BITFFMT(nm,sz,fmt)   {#nm, 0xffffffff, sz, NULL, #fmt}/* Bit Field definition with Output format */
#define BITFNAM(nm,sz,names) {#nm, 0xffffffff, sz, names}     /* Bit Field definition with value->name map */
#else /* For non-STD-C compiler which can't stringify macro arguments with # */
#define REGDATA(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    "nm", &(loc), (rdx), (wd), (off), (dep), (desc), (flds), (fl), (qptr), (siz)
#define ORDATA(nm,loc,wd) "nm", &(loc), 8, (wd), 0, 1, NULL, NULL
#define DRDATA(nm,loc,wd) "nm", &(loc), 10, (wd), 0, 1, NULL, NULL
#define HRDATA(nm,loc,wd) "nm", &(loc), 16, (wd), 0, 1, NULL, NULL
#define BINRDATA(nm,loc,wd) "nm", &(loc), 2, (wd), 0, 1, NULL, NULL
#define FLDATA(nm,loc,pos) "nm", &(loc), 2, 1, (pos), 1, NULL, NULL
#define GRDATA(nm,loc,rdx,wd,pos) "nm", &(loc), (rdx), (wd), (pos), 1, NULL, NULL
#define BRDATA(nm,loc,rdx,wd,dep) "nm", (loc), (rdx), (wd), 0, (dep), NULL, NULL


#define ORDATAD(nm,loc,wd,desc) "nm", &(loc), 8, (wd), 0, 1, (desc), NULL
#define DRDATAD(nm,loc,wd,desc) "nm", &(loc), 10, (wd), 0, 1, (desc), NULL
#define HRDATAD(nm,loc,wd,desc) "nm", &(loc), 16, (wd), 0, 1, (desc), NULL
#define BINRDATAD(nm,loc,wd,desc) "nm", &(loc), 2, (wd), 0, 1, (desc), NULL
#define FLDATAD(nm,loc,pos,desc) "nm", &(loc), 2, 1, (pos), 1, (desc), NULL
#define GRDATAD(nm,loc,rdx,wd,pos,desc) "nm", &(loc), (rdx), (wd), (pos), 1, (desc), NULL
#define BRDATAD(nm,loc,rdx,wd,dep,desc) "nm", (loc), (rdx), (wd), 0, (dep), (desc), NULL


#define ORDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 8, (wd), 0, 1, (desc), (flds)
#define DRDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 10, (wd), 0, 1, (desc), (flds)
#define HRDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 16, (wd), 0, 1, (desc), (flds)
#define BINRDATADF(nm,loc,wd,desc,flds) "nm", &(loc), 2, (wd), 0, 1, (desc), (flds)
#define FLDATADF(nm,loc,pos,desc,flds) "nm", &(loc), 2, 1, (pos), 1, (desc), (flds)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) "nm", &(loc), (rdx), (wd), (pos), 1, (desc), (flds)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) "nm", (loc), (rdx), (wd), 0, (dep), (desc), (flds)


#define BIT(nm)              {"nm", 0xffffffff, 1}              /* Single Bit definition */
#define BITNC                {"",   0xffffffff, 1}              /* Don't care Bit definition */
#define BITF(nm,sz)          {"nm", 0xffffffff, sz}             /* Bit Field definition */
#define BITNCF(sz)           {"",   0xffffffff, sz}             /* Don't care Bit Field definition */
#define BITFFMT(nm,sz,fmt)   {"nm", 0xffffffff, sz, NULL, "fmt"}/* Bit Field definition with Output format */
#define BITFNAM(nm,sz,names) {"nm", 0xffffffff, sz, names}      /* Bit Field definition with value->name map */
#endif
#define ENDBITS {NULL}  /* end of bitfield list */

/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),NULL,NULL,((fl) | REG_UNIT),0,0)
/* Arrayed register whose data is part of an arbitrary structure */
#define STRDATA(nm,loc,rdx,wd,off,dep,siz,fl) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),NULL,NULL,((fl) | REG_STRUCT),0,(siz))
/* Same as above, but with additional description initializer */
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),(desc),NULL,((fl) | REG_UNIT),0,0)
#define STRDATAD(nm,loc,rdx,wd,off,dep,siz,fl,desc) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),(desc),NULL,((fl) | REG_STRUCT),0,(siz))
/* Same as above, but with additional description initializer, and bitfields */
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),(desc),(flds),((fl) | REG_UNIT),0,0)
#define STRDATADF(nm,loc,rdx,wd,off,dep,siz,fl,desc,flds) \
    REGDATA(nm,(loc),(rdx),(wd),(off),(dep),(desc),(flds),((fl) | REG_STRUCT),0,(siz))


/* Function prototypes */

#include "scp.h"
#include "sim_console.h"
#include "sim_timer.h"
#include "sim_fio.h"

/* Macro to ALWAYS execute the specified expression and fail if it evaluates to false. */
/* This replaces any references to "assert()" which should never be invoked */
/* with an expression which causes side effects (i.e. must be executed for */
/* the program to work correctly) */

#define ASSURE(_Expression) while (!(_Expression)) {fprintf(stderr, "%s failed at %s line %d\n", #_Expression, __FILE__, __LINE__);  \
                                                    sim_printf("%s failed at %s line %d\n", #_Expression, __FILE__, __LINE__);       \

                                                    abort();}

/* Asynch/Threaded I/O support */

#if defined (SIM_ASYNCH_IO)
#include <pthread.h>

#define SIM_ASYNCH_CLOCKS 1

extern pthread_mutex_t sim_asynch_lock;
extern pthread_cond_t sim_asynch_wake;
extern pthread_mutex_t sim_timer_lock;
extern pthread_cond_t sim_timer_wake;
extern t_bool sim_timer_event_canceled;
extern int32 sim_tmxr_poll_count;
extern pthread_cond_t sim_tmxr_poll_cond;
extern pthread_mutex_t sim_tmxr_poll_lock;
extern pthread_t sim_asynch_main_threadid;
extern UNIT * volatile sim_asynch_queue;


extern volatile t_bool sim_idle_wait;
extern int32 sim_asynch_check;
extern int32 sim_asynch_latency;
extern int32 sim_asynch_inst_latency;

/* Thread local storage */
#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__hpux) && !defined(__OpenBSD__) && !defined(_AIX)
#define AIO_TLS __thread
#elif defined(_MSC_VER)
#define AIO_TLS __declspec(thread)
#else
/* Other compiler environment, then don't worry about thread local storage. */
/* It is primarily used only used in debugging messages */
#define AIO_TLS
#endif
#define AIO_QUEUE_CHECK(que, lock)                              \
    do {                                                        \
        UNIT *_cptr;                                            \
        if (lock)                                               \
            pthread_mutex_lock (lock);                          \
        for (_cptr = que;                                       \
            (_cptr != QUEUE_LIST_END);                          \
            _cptr = _cptr->next)                                \
            if (!_cptr->next) {                                 \
                if (sim_deb) {                                  \
                    sim_debug (SIM_DBG_EVENT, sim_dflt_dev, "Queue Corruption detected\n");\
                    fclose(sim_deb);                            \
                    }                                           \
                sim_printf("Queue Corruption detected\n");      \
                abort();                                        \
                }                                               \
        if (lock)                                               \
            pthread_mutex_unlock (lock);                        \
        } while (0)
#define AIO_MAIN_THREAD (pthread_equal ( pthread_self(), sim_asynch_main_threadid ))
#define AIO_LOCK                                                  \
    pthread_mutex_lock(&sim_asynch_lock)
#define AIO_UNLOCK                                                \
    pthread_mutex_unlock(&sim_asynch_lock)
#define AIO_IS_ACTIVE(uptr) (((uptr)->a_is_active ? (uptr)->a_is_active (uptr) : FALSE) || ((uptr)->a_next))


































































#if defined(SIM_ASYNCH_MUX)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->cancel)                                           \
        (uptr)->cancel (uptr);                                    \
    else {                                                        \
        if (((uptr)->dynflags & UNIT_TM_POLL) &&                  \
            !((uptr)->next) && !((uptr)->a_next)) {               \
            (uptr)->a_polling_now = FALSE;                        \
            sim_tmxr_poll_count -= (uptr)->a_poll_waiter_count;   \
            (uptr)->a_poll_waiter_count = 0;                      \
            }                                                     \
        }
#endif /* defined(SIM_ASYNCH_MUX) */
#if !defined(AIO_CANCEL)
#define AIO_CANCEL(uptr)                                          \
    if ((uptr)->cancel)                                           \
        (uptr)->cancel (uptr)

























































#endif /* !defined(AIO_CANCEL) */


























#define AIO_EVENT_BEGIN(uptr)                                     \
    do {                                                          \
        int __was_poll = uptr->dynflags & UNIT_TM_POLL
#define AIO_EVENT_COMPLETE(uptr, reason)                          \
        if (__was_poll) {                                         \
            pthread_mutex_lock (&sim_tmxr_poll_lock);             \
            uptr->a_polling_now = FALSE;                          \
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
#endif
#ifdef USE_AIO_INTRINSICS
/* This approach uses intrinsics to manage access to the link list head     */
/* sim_asynch_queue.  This implementation is a completely lock free design  */
/* which avoids the potential ABA issues.                                   */
#define AIO_QUEUE_MODE "Lock free asynchronous event queue access"
#define AIO_INIT                                                  \
    if (1) {                                                      \
      int tmr;                                                    \
      sim_asynch_main_threadid = pthread_self();                  \
      /* Empty list/list end uses the point value (void *)1.      \
         This allows NULL in an entry's a_next pointer to         \
         indicate that the entry is not currently in any list */  \
      sim_asynch_queue = QUEUE_LIST_END;                          \
      sim_wallclock_queue = QUEUE_LIST_END;                       \
      sim_wallclock_entry = NULL;                                 \
      for (tmr=0; tmr<SIM_NTIMERS; tmr++)                         \
          sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;          \
      }                                                           \
    else                                                          \
      (void)0
#define AIO_CLEANUP                                               \
    if (1) {                                                      \
      pthread_mutex_destroy(&sim_asynch_lock);                    \
      pthread_cond_destroy(&sim_asynch_wake);                     \
      pthread_mutex_destroy(&sim_timer_lock);                     \
      pthread_cond_destroy(&sim_timer_wake);                      \
      pthread_mutex_destroy(&sim_tmxr_poll_lock);                 \
      pthread_cond_destroy(&sim_tmxr_poll_cond);                  \
      }                                                           \
    else                                                          \
      (void)0
#ifdef _WIN32
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)
#define InterlockedCompareExchangePointer(Destination, Exchange, Comparand) __sync_val_compare_and_swap(Destination, Comparand, Exchange)
#elif defined(__DECC_VER)
#define InterlockedCompareExchangePointer(Destination, Exchange, Comparand) (void *)((int32)_InterlockedCompareExchange64(Destination, Exchange, Comparand))
#else
#error "Implementation of function InterlockedCompareExchangePointer() is needed to build with USE_AIO_INTRINSICS"
#endif
#define AIO_QUEUE_VAL (UNIT *)(InterlockedCompareExchangePointer(&sim_asynch_queue, sim_asynch_queue, NULL))
#define AIO_QUEUE_SET(val, queue) (UNIT *)(InterlockedCompareExchangePointer(&sim_asynch_queue, val, queue))
#define AIO_UPDATE_QUEUE                                                         \
    if (AIO_QUEUE_VAL != QUEUE_LIST_END) { /* List !Empty */                     \
      UNIT *q, *uptr;                                                            \
      int32 a_event_time;                                                        \
      do                                                                         \
        q = AIO_QUEUE_VAL;                                                       \
        while (q != AIO_QUEUE_SET(QUEUE_LIST_END, q));                           \
      while (q != QUEUE_LIST_END) {   /* List !Empty */                          \
        sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Migrating Asynch event for %s after %d instructions\n", sim_uname(q), q->a_event_time);\
        uptr = q;                                                                \
        q = q->a_next;                                                           \
        uptr->a_next = NULL;        /* hygiene */                                \
        if (uptr->a_activate_call != &sim_activate_notbefore) {                  \
          a_event_time = uptr->a_event_time-((sim_asynch_inst_latency+1)/2);     \
          if (a_event_time < 0)                                                  \
            a_event_time = 0;                                                    \
          }                                                                      \
        else                                                                     \
          a_event_time = uptr->a_event_time;                                     \
        uptr->a_activate_call (uptr, a_event_time);                              \
        if (uptr->a_check_completion) {                                          \
          sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Calling Completion Check for asynch event on %s\n", sim_uname(uptr));\
          uptr->a_check_completion (uptr);                                       \
          }                                                                      \
      }                                                                          \
    } else (void)0
#define AIO_ACTIVATE(caller, uptr, event_time)                                   \
    if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) {           \
      UNIT *ouptr = (uptr);                                                      \
      sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch event for %s after %d instructions\n", sim_uname(ouptr), event_time);\
      if (ouptr->a_next) {                                                       \
        ouptr->a_activate_call = sim_activate_abs;                               \
      } else {                                                                   \
        UNIT *q, *qe;                                                            \
        ouptr->a_event_time = event_time;                                        \
        ouptr->a_activate_call = caller;                                         \
        ouptr->a_next = QUEUE_LIST_END;                 /* Mark as on list */    \
        do {                                                                     \
          do                                                                     \
            q = AIO_QUEUE_VAL;                                                   \
            while (q != AIO_QUEUE_SET(QUEUE_LIST_END, q));/* Grab current list */\
          for (qe = ouptr; qe->a_next != QUEUE_LIST_END; qe = qe->a_next);       \
          qe->a_next = q;                               /* append current list */\
          do                                                                     \
            q = AIO_QUEUE_VAL;                                                   \
            while (q != AIO_QUEUE_SET(ouptr, q));                                \
          ouptr = q;                                                             \
          } while (ouptr != QUEUE_LIST_END);                                     \
      }                                                                          \
      sim_asynch_check = 0;                             /* try to force check */ \
      if (sim_idle_wait) {                                                       \
        sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(ouptr), event_time);\
        pthread_cond_signal (&sim_asynch_wake);                                  \
        }                                                                        \
      return SCPE_OK;                                                            \
    } else (void)0
#define AIO_ACTIVATE_LIST(caller, list, event_time)                              \
    if (list) {                                                                  \
      UNIT *ouptr, *q, *qe;                                                      \
      sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch events for %s after %d instructions\n", sim_uname(list), event_time);\
      for (qe=(list); qe->a_next != QUEUE_LIST_END;) {                           \
          qe->a_event_time = event_time;                                         \
          qe->a_activate_call = caller;                                          \
          qe = qe->a_next;                                                       \
          }                                                                      \
      qe->a_event_time = event_time;                                             \
      qe->a_activate_call = caller;                                              \
      ouptr = (list);                                                            \
      do {                                                                       \
        do                                                                       \
          q = AIO_QUEUE_VAL;                                                     \
          while (q != AIO_QUEUE_SET(QUEUE_LIST_END, q));/* Grab current list */  \
        for (qe = ouptr; qe->a_next != QUEUE_LIST_END; qe = qe->a_next);         \
        qe->a_next = q;                               /* append current list */  \
        do                                                                       \
          q = AIO_QUEUE_VAL;                                                     \
          while (q != AIO_QUEUE_SET(ouptr, q));                                  \
        ouptr = q;                                                               \
        } while (ouptr != QUEUE_LIST_END);                                       \
      sim_asynch_check = 0;                             /* try to force check */ \
      if (sim_idle_wait) {                                                       \
        sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(ouptr), event_time);\
        pthread_cond_signal (&sim_asynch_wake);                                  \
        }                                                                        \
      } else (void)0
#else /* !USE_AIO_INTRINSICS */
/* This approach uses a pthread mutex to manage access to the link list     */
/* head sim_asynch_queue.  It will always work, but may be slower than the  */
/* lock free approach when using USE_AIO_INTRINSICS                         */
#define AIO_QUEUE_MODE "Lock based asynchronous event queue access"
#define AIO_INIT                                                  \
    if (1) {                                                      \
      int tmr;                                                    \
      pthread_mutexattr_t attr;                                   \
                                                                  \
      pthread_mutexattr_init (&attr);                             \
      pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);  \
      pthread_mutex_init (&sim_asynch_lock, &attr);               \
      pthread_mutexattr_destroy (&attr);                          \
      sim_asynch_main_threadid = pthread_self();                  \
      /* Empty list/list end uses the point value (void *)1.      \
         This allows NULL in an entry's a_next pointer to         \
         indicate that the entry is not currently in any list */  \
      sim_asynch_queue = QUEUE_LIST_END;                          \
      sim_wallclock_queue = QUEUE_LIST_END;                       \
      sim_wallclock_entry = NULL;                                 \
      for (tmr=0; tmr<SIM_NTIMERS; tmr++)                         \
          sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;          \
      }                                                           \
    else                                                          \
      (void)0
#define AIO_CLEANUP                                               \
    if (1) {                                                      \
      pthread_mutex_destroy(&sim_asynch_lock);                    \
      pthread_cond_destroy(&sim_asynch_wake);                     \
      pthread_mutex_destroy(&sim_timer_lock);                     \
      pthread_cond_destroy(&sim_timer_wake);                      \
      pthread_mutex_destroy(&sim_tmxr_poll_lock);                 \
      pthread_cond_destroy(&sim_tmxr_poll_cond);                  \
      }                                                           \
    else                                                          \
      (void)0
#define AIO_UPDATE_QUEUE                                                         \
    if (1) {                                                                     \
      UNIT *uptr;                                                                \
      AIO_LOCK;                                                                  \
      while (sim_asynch_queue != QUEUE_LIST_END) { /* List !Empty */             \
        int32 a_event_time;                                                      \
        uptr = sim_asynch_queue;                                                 \
        sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Migrating Asynch event for %s after %d instructions\n", sim_uname(uptr), uptr->a_event_time);\
        sim_asynch_queue = uptr->a_next;                                         \







|






<
<


<
<
|

|






<
<
|








|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






|












<
<


<
<
|

|






<
<
|

|







1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048


1049
1050


1051
1052
1053
1054
1055
1056
1057
1058
1059


1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071

























1072
1073











1074














1075
1076





























1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095


1096
1097


1098
1099
1100
1101
1102
1103
1104
1105
1106


1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
#endif
#ifdef USE_AIO_INTRINSICS
/* This approach uses intrinsics to manage access to the link list head     */
/* sim_asynch_queue.  This implementation is a completely lock free design  */
/* which avoids the potential ABA issues.                                   */
#define AIO_QUEUE_MODE "Lock free asynchronous event queue access"
#define AIO_INIT                                                  \
    do {                                                          \
      int tmr;                                                    \
      sim_asynch_main_threadid = pthread_self();                  \
      /* Empty list/list end uses the point value (void *)1.      \
         This allows NULL in an entry's a_next pointer to         \
         indicate that the entry is not currently in any list */  \
      sim_asynch_queue = QUEUE_LIST_END;                          \


      for (tmr=0; tmr<SIM_NTIMERS; tmr++)                         \
          sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;          \


      } while (0)
#define AIO_CLEANUP                                               \
    do {                                                          \
      pthread_mutex_destroy(&sim_asynch_lock);                    \
      pthread_cond_destroy(&sim_asynch_wake);                     \
      pthread_mutex_destroy(&sim_timer_lock);                     \
      pthread_cond_destroy(&sim_timer_wake);                      \
      pthread_mutex_destroy(&sim_tmxr_poll_lock);                 \
      pthread_cond_destroy(&sim_tmxr_poll_cond);                  \


      } while (0)
#ifdef _WIN32
#elif defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)
#define InterlockedCompareExchangePointer(Destination, Exchange, Comparand) __sync_val_compare_and_swap(Destination, Comparand, Exchange)
#elif defined(__DECC_VER)
#define InterlockedCompareExchangePointer(Destination, Exchange, Comparand) (void *)((int32)_InterlockedCompareExchange64(Destination, Exchange, Comparand))
#else
#error "Implementation of function InterlockedCompareExchangePointer() is needed to build with USE_AIO_INTRINSICS"
#endif
#define AIO_QUEUE_VAL (UNIT *)(InterlockedCompareExchangePointer((void * volatile *)&sim_asynch_queue, (void *)sim_asynch_queue, NULL))
#define AIO_QUEUE_SET(val, queue) (UNIT *)(InterlockedCompareExchangePointer((void * volatile *)&sim_asynch_queue, (void *)val, queue))
#define AIO_UPDATE_QUEUE sim_aio_update_queue ()

























#define AIO_ACTIVATE(caller, uptr, event_time)                                   \
    if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) {           \











      sim_aio_activate ((ACTIVATE_API)caller, uptr, event_time);                 \














      return SCPE_OK;                                                            \
    } else (void)0





























#else /* !USE_AIO_INTRINSICS */
/* This approach uses a pthread mutex to manage access to the link list     */
/* head sim_asynch_queue.  It will always work, but may be slower than the  */
/* lock free approach when using USE_AIO_INTRINSICS                         */
#define AIO_QUEUE_MODE "Lock based asynchronous event queue access"
#define AIO_INIT                                                  \
    do {                                                          \
      int tmr;                                                    \
      pthread_mutexattr_t attr;                                   \
                                                                  \
      pthread_mutexattr_init (&attr);                             \
      pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);  \
      pthread_mutex_init (&sim_asynch_lock, &attr);               \
      pthread_mutexattr_destroy (&attr);                          \
      sim_asynch_main_threadid = pthread_self();                  \
      /* Empty list/list end uses the point value (void *)1.      \
         This allows NULL in an entry's a_next pointer to         \
         indicate that the entry is not currently in any list */  \
      sim_asynch_queue = QUEUE_LIST_END;                          \


      for (tmr=0; tmr<SIM_NTIMERS; tmr++)                         \
          sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;          \


      } while (0)
#define AIO_CLEANUP                                               \
    do {                                                          \
      pthread_mutex_destroy(&sim_asynch_lock);                    \
      pthread_cond_destroy(&sim_asynch_wake);                     \
      pthread_mutex_destroy(&sim_timer_lock);                     \
      pthread_cond_destroy(&sim_timer_wake);                      \
      pthread_mutex_destroy(&sim_tmxr_poll_lock);                 \
      pthread_cond_destroy(&sim_tmxr_poll_cond);                  \


      } while (0)
#define AIO_UPDATE_QUEUE                                                         \
    do {                                                                         \
      UNIT *uptr;                                                                \
      AIO_LOCK;                                                                  \
      while (sim_asynch_queue != QUEUE_LIST_END) { /* List !Empty */             \
        int32 a_event_time;                                                      \
        uptr = sim_asynch_queue;                                                 \
        sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Migrating Asynch event for %s after %d instructions\n", sim_uname(uptr), uptr->a_event_time);\
        sim_asynch_queue = uptr->a_next;                                         \
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367


1368
1369
1370
1371


1372


        AIO_UNLOCK;                                                              \
        uptr->a_activate_call (uptr, a_event_time);                              \
        if (uptr->a_check_completion) {                                          \
          sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Calling Completion Check for asynch event on %s\n", sim_uname(uptr));\
          uptr->a_check_completion (uptr);                                       \
          }                                                                      \
        AIO_LOCK;                                                                \
      }                                                                          \
      AIO_UNLOCK;                                                                \
    } else (void)0
#define AIO_ACTIVATE(caller, uptr, event_time)                         \
    if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) { \
      sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch event for %s after %d instructions\n", sim_uname(uptr), event_time);\
      AIO_LOCK;                                                        \
      if (uptr->a_next) {                       /* already queued? */  \
        uptr->a_activate_call = sim_activate_abs;                      \
      } else {                                                         \
        uptr->a_next = sim_asynch_queue;                               \
        uptr->a_event_time = event_time;                               \
        uptr->a_activate_call = caller;                                \
        sim_asynch_queue = uptr;                                       \
      }                                                                \
      if (sim_idle_wait) {                                             \
        sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(uptr), event_time);\
        pthread_cond_signal (&sim_asynch_wake);                        \
        }                                                              \
      AIO_UNLOCK;                                                      \
      sim_asynch_check = 0;                                            \
      return SCPE_OK;                                                  \
    } else (void)0
#define AIO_ACTIVATE_LIST(caller, list, event_time)                              \
    if (list) {                                                                  \
      UNIT *qe;                                                                  \
      sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch events for %s after %d instructions\n", sim_uname(list), event_time);\
      for (qe=list; qe->a_next != QUEUE_LIST_END;) {                             \
          qe->a_event_time = event_time;                                         \
          qe->a_activate_call = caller;                                          \
          qe = qe->a_next;                                                       \
          }                                                                      \
      qe->a_event_time = event_time;                                             \
      qe->a_activate_call = caller;                                              \
      AIO_LOCK;                                                                  \
      qe->a_next = sim_asynch_queue;                                             \
      sim_asynch_queue = list;                                                   \
      sim_asynch_check = 0;                             /* try to force check */ \
      if (sim_idle_wait) {                                                       \
        sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(list), event_time);\
        pthread_cond_signal (&sim_asynch_wake);                                  \
        }                                                                        \
      AIO_UNLOCK;                                                                \
      } else (void)0
#endif /* USE_AIO_INTRINSICS */
#define AIO_VALIDATE if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) abort()
#define AIO_CHECK_EVENT                                                \
    if (0 > --sim_asynch_check) {                                      \
      AIO_UPDATE_QUEUE;                                                \
      sim_asynch_check = sim_asynch_inst_latency;                      \
    } else (void)0
#define AIO_SET_INTERRUPT_LATENCY(instpersec)                                                   \
    if (1) {                                                                                    \
      sim_asynch_inst_latency = (int32)((((double)(instpersec))*sim_asynch_latency)/1000000000);\
      if (sim_asynch_inst_latency == 0)                                                         \
        sim_asynch_inst_latency = 1;                                                            \
    } else (void)0
#else /* !SIM_ASYNCH_IO */
#define AIO_QUEUE_MODE "Asynchronous I/O is not available"
#define AIO_UPDATE_QUEUE
#define AIO_ACTIVATE(caller, uptr, event_time)
#define AIO_VALIDATE
#define AIO_CHECK_EVENT
#define AIO_INIT
#define AIO_MAIN_THREAD TRUE
#define AIO_LOCK
#define AIO_UNLOCK
#define AIO_CLEANUP
#define AIO_RETURN_TIME(uptr)
#define AIO_EVENT_BEGIN(uptr)
#define AIO_EVENT_COMPLETE(uptr, reason)
#define AIO_IS_ACTIVE(uptr) FALSE
#define AIO_CANCEL(uptr)


#define AIO_SET_INTERRUPT_LATENCY(instpersec)
#define AIO_TLS
#endif /* SIM_ASYNCH_IO */



#endif









|

|









|










<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|




|

|



|











<



|
>
>




>
>

>
>
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154





















1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178

1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
        AIO_UNLOCK;                                                              \
        uptr->a_activate_call (uptr, a_event_time);                              \
        if (uptr->a_check_completion) {                                          \
          sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Calling Completion Check for asynch event on %s\n", sim_uname(uptr));\
          uptr->a_check_completion (uptr);                                       \
          }                                                                      \
        AIO_LOCK;                                                                \
        }                                                                        \
      AIO_UNLOCK;                                                                \
      } while (0)
#define AIO_ACTIVATE(caller, uptr, event_time)                         \
    if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) { \
      sim_debug (SIM_DBG_AIO_QUEUE, sim_dflt_dev, "Queueing Asynch event for %s after %d instructions\n", sim_uname(uptr), event_time);\
      AIO_LOCK;                                                        \
      if (uptr->a_next) {                       /* already queued? */  \
        uptr->a_activate_call = sim_activate_abs;                      \
      } else {                                                         \
        uptr->a_next = sim_asynch_queue;                               \
        uptr->a_event_time = event_time;                               \
        uptr->a_activate_call = (ACTIVATE_API)&caller;                 \
        sim_asynch_queue = uptr;                                       \
      }                                                                \
      if (sim_idle_wait) {                                             \
        sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(uptr), event_time);\
        pthread_cond_signal (&sim_asynch_wake);                        \
        }                                                              \
      AIO_UNLOCK;                                                      \
      sim_asynch_check = 0;                                            \
      return SCPE_OK;                                                  \
    } else (void)0





















#endif /* USE_AIO_INTRINSICS */
#define AIO_VALIDATE if (!pthread_equal ( pthread_self(), sim_asynch_main_threadid )) {sim_printf("Improper thread context for operation\n"); abort();}
#define AIO_CHECK_EVENT                                                \
    if (0 > --sim_asynch_check) {                                      \
      AIO_UPDATE_QUEUE;                                                \
      sim_asynch_check = sim_asynch_inst_latency;                      \
      } else (void)0
#define AIO_SET_INTERRUPT_LATENCY(instpersec)                                                   \
    do {                                                                                        \
      sim_asynch_inst_latency = (int32)((((double)(instpersec))*sim_asynch_latency)/1000000000);\
      if (sim_asynch_inst_latency == 0)                                                         \
        sim_asynch_inst_latency = 1;                                                            \
      } while (0)
#else /* !SIM_ASYNCH_IO */
#define AIO_QUEUE_MODE "Asynchronous I/O is not available"
#define AIO_UPDATE_QUEUE
#define AIO_ACTIVATE(caller, uptr, event_time)
#define AIO_VALIDATE
#define AIO_CHECK_EVENT
#define AIO_INIT
#define AIO_MAIN_THREAD TRUE
#define AIO_LOCK
#define AIO_UNLOCK
#define AIO_CLEANUP

#define AIO_EVENT_BEGIN(uptr)
#define AIO_EVENT_COMPLETE(uptr, reason)
#define AIO_IS_ACTIVE(uptr) FALSE
#define AIO_CANCEL(uptr)                                        \
    if ((uptr)->cancel)                                         \
        (uptr)->cancel (uptr)
#define AIO_SET_INTERRUPT_LATENCY(instpersec)
#define AIO_TLS
#endif /* SIM_ASYNCH_IO */

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_disk.c.
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#define DOP_WSEC  2             /* sim_disk_wrsect_a */
#define DOP_IAVL  3             /* sim_disk_isavailable_a */

static void *
_disk_io(void *arg)
{
UNIT* volatile uptr = (UNIT*)arg;
int sched_policy;
struct sched_param sched_priority;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

/* Boost Priority for this I/O thread vs the CPU instruction execution
   thread which in general won't be readily yielding the processor when
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (ctx->dbit, ctx->dptr, "_disk_io(unit=%d) starting\n", (int)(uptr-ctx->dptr->units));

pthread_mutex_lock (&ctx->io_lock);
pthread_cond_signal (&ctx->startup_cond);   /* Signal we're ready to go */
while (ctx->asynch_io) {
    pthread_cond_wait (&ctx->io_cond, &ctx->io_lock);







<
<





<
|
<







158
159
160
161
162
163
164


165
166
167
168
169

170

171
172
173
174
175
176
177
#define DOP_WSEC  2             /* sim_disk_wrsect_a */
#define DOP_IAVL  3             /* sim_disk_isavailable_a */

static void *
_disk_io(void *arg)
{
UNIT* volatile uptr = (UNIT*)arg;


struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

/* Boost Priority for this I/O thread vs the CPU instruction execution
   thread which in general won't be readily yielding the processor when
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug (ctx->dbit, ctx->dptr, "_disk_io(unit=%d) starting\n", (int)(uptr-ctx->dptr->units));

pthread_mutex_lock (&ctx->io_lock);
pthread_cond_signal (&ctx->startup_cond);   /* Signal we're ready to go */
while (ctx->asynch_io) {
    pthread_cond_wait (&ctx->io_cond, &ctx->io_lock);
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
}

static t_bool _disk_is_active (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_disk_is_active(unit=%d, dop=%d)\n", uptr-ctx->dptr->units, ctx->io_dop);
    return (ctx->io_dop != DOP_DONE);
    }
return FALSE;
}

static void _disk_cancel (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_disk_cancel(unit=%d, dop=%d)\n", uptr-ctx->dptr->units, ctx->io_dop);
    if (ctx->asynch_io) {
        pthread_mutex_lock (&ctx->io_lock);
        while (ctx->io_dop != DOP_DONE)
            pthread_cond_wait (&ctx->io_done, &ctx->io_lock);
        pthread_mutex_unlock (&ctx->io_lock);
        }
    }







|










|







229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
}

static t_bool _disk_is_active (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_disk_is_active(unit=%d, dop=%d)\n", (int)(uptr-ctx->dptr->units), ctx->io_dop);
    return (ctx->io_dop != DOP_DONE);
    }
return FALSE;
}

static void _disk_cancel (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_disk_cancel(unit=%d, dop=%d)\n", (int)(uptr-ctx->dptr->units), ctx->io_dop);
    if (ctx->asynch_io) {
        pthread_mutex_lock (&ctx->io_lock);
        while (ctx->io_dop != DOP_DONE)
            pthread_cond_wait (&ctx->io_done, &ctx->io_lock);
        pthread_mutex_unlock (&ctx->io_lock);
        }
    }
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    { "RAW",  0, DKUF_F_RAW, sim_os_disk_implemented_raw},
    { "VHD",  0, DKUF_F_VHD, sim_vhd_disk_implemented},
    { NULL,   0, 0}
    };

/* Set disk format */

t_stat sim_disk_set_fmt (UNIT *uptr, int32 val, char *cptr, void *desc)
{
uint32 f;

if (uptr == NULL)
    return SCPE_IERR;
if (cptr == NULL)
    return SCPE_ARG;







|







301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    { "RAW",  0, DKUF_F_RAW, sim_os_disk_implemented_raw},
    { "VHD",  0, DKUF_F_VHD, sim_vhd_disk_implemented},
    { NULL,   0, 0}
    };

/* Set disk format */

t_stat sim_disk_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
uint32 f;

if (uptr == NULL)
    return SCPE_IERR;
if (cptr == NULL)
    return SCPE_ARG;
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        }
    }
return SCPE_ARG;
}

/* Show disk format */

t_stat sim_disk_show_fmt (FILE *st, UNIT *uptr, int32 val, void *desc)
{
int32 f = DK_GET_FMT (uptr);
size_t i;

for (i = 0; i < DKUF_N_FMT; i++)
    if (fmts[i].fmtval == f) {
        fprintf (st, "%s format", fmts[i].name);
        return SCPE_OK;
        }
fprintf (st, "invalid format");
return SCPE_OK;
}

/* Set disk capacity */

t_stat sim_disk_set_capac (UNIT *uptr, int32 val, char *cptr, void *desc)
{
t_offset cap;
t_stat r;
DEVICE *dptr = find_dev_from_unit (uptr);

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_ARG;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
cap = (t_offset) get_uint (cptr, 10, sim_taddr_64? 2000000: 2000, &r);
if (r != SCPE_OK)
    return SCPE_ARG;
uptr->capac = (t_addr)((cap * ((t_offset) 1000000))/((dptr->flags & DEV_SECTORS) ? 512 : 1));
return SCPE_OK;
}

/* Show disk capacity */

t_stat sim_disk_show_capac (FILE *st, UNIT *uptr, int32 val, void *desc)
{
const char *cap_units = "B";
DEVICE *dptr = find_dev_from_unit (uptr);
t_offset capac = ((t_offset)uptr->capac)*((dptr->flags & DEV_SECTORS) ? 512 : 1);

if ((dptr->dwidth / dptr->aincr) == 16)
    cap_units = "W";







|















|


















|







323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
        }
    }
return SCPE_ARG;
}

/* Show disk format */

t_stat sim_disk_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
int32 f = DK_GET_FMT (uptr);
size_t i;

for (i = 0; i < DKUF_N_FMT; i++)
    if (fmts[i].fmtval == f) {
        fprintf (st, "%s format", fmts[i].name);
        return SCPE_OK;
        }
fprintf (st, "invalid format");
return SCPE_OK;
}

/* Set disk capacity */

t_stat sim_disk_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
t_offset cap;
t_stat r;
DEVICE *dptr = find_dev_from_unit (uptr);

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_ARG;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
cap = (t_offset) get_uint (cptr, 10, sim_taddr_64? 2000000: 2000, &r);
if (r != SCPE_OK)
    return SCPE_ARG;
uptr->capac = (t_addr)((cap * ((t_offset) 1000000))/((dptr->flags & DEV_SECTORS) ? 512 : 1));
return SCPE_OK;
}

/* Show disk capacity */

t_stat sim_disk_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const char *cap_units = "B";
DEVICE *dptr = find_dev_from_unit (uptr);
t_offset capac = ((t_offset)uptr->capac)*((dptr->flags & DEV_SECTORS) ? 512 : 1);

if ((dptr->dwidth / dptr->aincr) == 16)
    cap_units = "W";
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
    pthread_attr_destroy(&attr);
    pthread_cond_wait (&ctx->startup_cond, &ctx->io_lock); /* Wait for thread to stabilize */
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_cond_destroy (&ctx->startup_cond);
    }
uptr->a_check_completion = _disk_completion_dispatch;
uptr->a_is_active = _disk_is_active;
uptr->a_cancel = _disk_cancel;
return SCPE_OK;
#endif
}

/* Disable asynchronous operation */

t_stat sim_disk_clr_async (UNIT *uptr)







|







463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    pthread_attr_destroy(&attr);
    pthread_cond_wait (&ctx->startup_cond, &ctx->io_lock); /* Wait for thread to stabilize */
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_cond_destroy (&ctx->startup_cond);
    }
uptr->a_check_completion = _disk_completion_dispatch;
uptr->a_is_active = _disk_is_active;
uptr->cancel = _disk_cancel;
return SCPE_OK;
#endif
}

/* Disable asynchronous operation */

t_stat sim_disk_clr_async (UNIT *uptr)
650
651
652
653
654
655
656





























657
658
659
660
661
662
663
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
uint32 f = DK_GET_FMT (uptr);
t_stat r;
uint8 *tbuf = NULL;

sim_debug (ctx->dbit, ctx->dptr, "sim_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);






























if (f == DKUF_F_STD)
    return _sim_disk_wrsect (uptr, lba, buf, sectswritten, sects);
if ((0 == (ctx->sector_size & (ctx->storage_sector_size - 1))) ||   /* Sector Aligned & whole sector transfers */
    ((0 == ((lba*ctx->sector_size) & (ctx->storage_sector_size - 1))) &&
     (0 == ((sects*ctx->sector_size) & (ctx->storage_sector_size - 1))))) {

    if (sim_end || (ctx->xfer_element_size == sizeof (char)))







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
uint32 f = DK_GET_FMT (uptr);
t_stat r;
uint8 *tbuf = NULL;

sim_debug (ctx->dbit, ctx->dptr, "sim_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);

if (uptr->dynflags & UNIT_DISK_CHK) {
    DEVICE *dptr = find_dev_from_unit (uptr);
    uint32 capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (word: 2, byte: 1) */
    t_lba total_sectors = (t_lba)((uptr->capac*capac_factor)/(ctx->sector_size/((dptr->flags & DEV_SECTORS) ? 512 : 1)));
    t_lba sect;

    for (sect = 0; sect < sects; sect++) {
        t_lba offset;
        t_bool sect_error = FALSE;

        for (offset = 0; offset < ctx->sector_size; offset += sizeof(uint32)) {
            if (*((uint32 *)&buf[sect*ctx->sector_size + offset]) != (uint32)(lba + sect)) {
                sect_error = TRUE;
                break;
                }
            }
        if (sect_error) {
            uint32 save_dctrl = dptr->dctrl;
            FILE *save_sim_deb = sim_deb;

            sim_printf ("\n%s%d: Write Address Verification Error on lbn %d(0x%X) of %d(0x%X).\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)(lba+sect), (int)(lba+sect), (int)total_sectors, (int)total_sectors);
            dptr->dctrl = 0xFFFFFFFF;
            sim_deb = save_sim_deb ? save_sim_deb : stdout;
            sim_disk_data_trace (uptr, buf+sect*ctx->sector_size, lba+sect, ctx->sector_size,    "Found", TRUE, 1);
            dptr->dctrl = save_dctrl;
            sim_deb = save_sim_deb;
            }
        }
    }
if (f == DKUF_F_STD)
    return _sim_disk_wrsect (uptr, lba, buf, sectswritten, sects);
if ((0 == (ctx->sector_size & (ctx->storage_sector_size - 1))) ||   /* Sector Aligned & whole sector transfers */
    ((0 == ((lba*ctx->sector_size) & (ctx->storage_sector_size - 1))) &&
     (0 == ((sects*ctx->sector_size) & (ctx->storage_sector_size - 1))))) {

    if (sim_end || (ctx->xfer_element_size == sizeof (char)))
808
809
810
811
812
813
814


815






























































































































































































































816
817
818
819
820

821
822
823
824
825
826
827
828
829
830
831
832
833
834
free (uptr->filename);
uptr->filename = NULL;
free (uptr->disk_ctx);
uptr->disk_ctx = NULL;
return stat;
}


































































































































































































































t_stat sim_disk_attach (UNIT *uptr, char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontautosize,
                        uint32 dbit, const char *dtype, uint32 pdp11tracksize, int completion_delay)
{
struct disk_context *ctx;
DEVICE *dptr;

FILE *(*open_function)(const char *filename, const char *mode) = sim_fopen;
FILE *(*create_function)(const char *filename, t_offset desiredsize) = NULL;
t_offset (*size_function)(FILE *file);
t_stat (*storage_function)(FILE *file, uint32 *sector_size, uint32 *removable) = NULL;
t_bool created = FALSE, copied = FALSE;
t_bool auto_format = FALSE;
t_offset capac;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;
if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;







>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|




>






|







833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
free (uptr->filename);
uptr->filename = NULL;
free (uptr->disk_ctx);
uptr->disk_ctx = NULL;
return stat;
}

#pragma pack(push,1)
typedef struct _ODS2_HomeBlock
    {
    uint32 hm2_l_homelbn;
    uint32 hm2_l_alhomelbn;
    uint32 hm2_l_altidxlbn;
    uint8  hm2_b_strucver;
    uint8  hm2_b_struclev;
    uint16 hm2_w_cluster;
    uint16 hm2_w_homevbn;
    uint16 hm2_w_alhomevbn;
    uint16 hm2_w_altidxvbn;
    uint16 hm2_w_ibmapvbn;
    uint32 hm2_l_ibmaplbn;
    uint32 hm2_l_maxfiles;
    uint16 hm2_w_ibmapsize;
    uint16 hm2_w_resfiles;
    uint16 hm2_w_devtype;
    uint16 hm2_w_rvn;
    uint16 hm2_w_setcount;
    uint16 hm2_w_volchar;
    uint32 hm2_l_volowner;
    uint32 hm2_l_reserved;
    uint16 hm2_w_protect;
    uint16 hm2_w_fileprot;
    uint16 hm2_w_reserved;
    uint16 hm2_w_checksum1;
    uint32 hm2_q_credate[2];
    uint8  hm2_b_window;
    uint8  hm2_b_lru_lim;
    uint16 hm2_w_extend;
    uint32 hm2_q_retainmin[2];
    uint32 hm2_q_retainmax[2];
    uint32 hm2_q_revdate[2];
    uint8  hm2_r_min_class[20];
    uint8  hm2_r_max_class[20];
    uint8  hm2_r_reserved[320];
    uint32 hm2_l_serialnum;
    uint8  hm2_t_strucname[12];
    uint8  hm2_t_volname[12];
    uint8  hm2_t_ownername[12];
    uint8  hm2_t_format[12];
    uint16 hm2_w_reserved2;
    uint16 hm2_w_checksum2;
    } ODS2_HomeBlock;

typedef struct _ODS2_FileHeader
    {
    uint8  fh2_b_idoffset;
    uint8  fh2_b_mpoffset;
    uint8  fh2_b_acoffset;
    uint8  fh2_b_rsoffset;
    uint16 fh2_w_seg_num;
    uint16 fh2_w_structlev;
    uint16 fh2_w_fid[3];
    uint16 fh2_w_ext_fid[3];
    uint16 fh2_w_recattr[16];
    uint32 fh2_l_filechar;
    uint16 fh2_w_remaining[228];
    } ODS2_FileHeader;

typedef union _ODS2_Retreval
    {
        struct 
            {
            unsigned fm2___fill   : 14;       /* type specific data               */
            unsigned fm2_v_format : 2;        /* format type code                 */
            } fm2_r_word0_bits;
        struct
            {
            unsigned fm2_v_exact    : 1;      /* exact placement specified        */
            unsigned fm2_v_oncyl    : 1;      /* on cylinder allocation desired   */
            unsigned fm2___fill     : 10;
            unsigned fm2_v_lbn      : 1;      /* use LBN of next map pointer      */
            unsigned fm2_v_rvn      : 1;      /* place on specified RVN           */
            unsigned fm2_v_format0  : 2;
            } fm2_r_map_bits0;
        struct
            {
            unsigned fm2_b_count1   : 8;      /* low byte described below         */
            unsigned fm2_v_highlbn1 : 6;      /* high order LBN                   */
            unsigned fm2_v_format1  : 2;
            unsigned fm2_w_lowlbn1  : 16;     /* low order LBN                    */
            } fm2_r_map_bits1;
        struct
            {
            struct
                {
                unsigned fm2_v_count2   : 14; /* count field                      */
                unsigned fm2_v_format2  : 2;
                unsigned fm2_l_lowlbn2  : 16; /* low order LBN                    */
                } fm2_r_map2_long0;
            uint16 fm2_l_highlbn2;            /* high order LBN                   */
            } fm2_r_map_bits2;
        struct
            {
            struct
                {
                unsigned fm2_v_highcount3 : 14; /* low order count field          */
                unsigned fm2_v_format3  : 2;
                unsigned fm2_w_lowcount3 : 16;  /* high order count field         */
                } fm2_r_map3_long0;
            uint32 fm2_l_lbn3;
            } fm2_r_map_bits3;
    } ODS2_Retreval;

typedef struct _ODS2_StorageControlBlock
    {
    uint8  scb_b_strucver;   /* 1 */
    uint8  scb_b_struclev;   /* 2 */
    uint16 scb_w_cluster;
    uint32 scb_l_volsize;
    uint32 scb_l_blksize;
    uint32 scb_l_sectors;
    uint32 scb_l_tracks;
    uint32 scb_l_cylinder;
    uint32 scb_l_status;
    uint32 scb_l_status2;
    uint16 scb_w_writecnt;
    uint8  scb_t_volockname[12];
    uint32 scb_q_mounttime[2];
    uint16 scb_w_backrev;
    uint32 scb_q_genernum[2];
    uint8  scb_b_reserved[446];
    uint16 scb_w_checksum;
    } ODS2_SCB;
#pragma pack(pop)

static uint16
ODS2Checksum (void *Buffer, uint16 WordCount)
    {
    int i;
    uint16 Sum = 0;
    uint16 CheckSum = 0;
    uint16 *Buf = (uint16 *)Buffer;

    for (i=0; i<WordCount; i++)
        CheckSum += Buf[i];
    return CheckSum;
    }


static t_offset get_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
t_offset temp_capac = 512 * (t_offset)0xFFFFFFFFu;  /* Make sure we can access the largest sector */
uint32 capac_factor;
ODS2_HomeBlock Home;
ODS2_FileHeader Header;
ODS2_Retreval *Retr;
ODS2_SCB Scb;
uint16 CheckSum1, CheckSum2;
uint32 ScbLbn;
t_offset ret_val = (t_offset)-1;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return ret_val;
capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (word: 2, byte: 1) */
saved_capac = uptr->capac;
uptr->capac = (t_addr)(temp_capac/(capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
if (sim_disk_rdsect (uptr, 1, (uint8 *)&Home, NULL, 1))
    goto Return_Cleanup;
CheckSum1 = ODS2Checksum (&Home, (uint16)((((char *)&Home.hm2_w_checksum1)-((char *)&Home.hm2_l_homelbn))/2));
CheckSum2 = ODS2Checksum (&Home, (uint16)((((char *)&Home.hm2_w_checksum2)-((char *)&Home.hm2_l_homelbn))/2));
if ((Home.hm2_l_homelbn == 0) || 
    (Home.hm2_l_alhomelbn == 0) || 
    (Home.hm2_l_altidxlbn == 0) || 
    ((Home.hm2_b_struclev != 2) && (Home.hm2_b_struclev != 5)) || 
    (Home.hm2_b_strucver == 0) || 
    (Home.hm2_w_cluster == 0) || 
    (Home.hm2_w_homevbn == 0) || 
    (Home.hm2_w_alhomevbn == 0) || 
    (Home.hm2_w_ibmapvbn == 0) || 
    (Home.hm2_l_ibmaplbn == 0) || 
    (Home.hm2_w_resfiles >= Home.hm2_l_maxfiles) || 
    (Home.hm2_w_ibmapsize == 0) || 
    (Home.hm2_w_resfiles < 5) || 
    (Home.hm2_w_checksum1 != CheckSum1) ||
    (Home.hm2_w_checksum2 != CheckSum2))
    goto Return_Cleanup;
if (sim_disk_rdsect (uptr, Home.hm2_l_ibmaplbn+Home.hm2_w_ibmapsize+1, (uint8 *)&Header, NULL, 1))
    goto Return_Cleanup;
CheckSum1 = ODS2Checksum (&Header, 255);
if (CheckSum1 != *(((uint16 *)&Header)+255)) /* Verify Checksum on BITMAP.SYS file header */
    goto Return_Cleanup;
Retr = (ODS2_Retreval *)(((uint16*)(&Header))+Header.fh2_b_mpoffset);
/* The BitMap File has a single extent, which may be preceeded by a placement descriptor */
if (Retr->fm2_r_word0_bits.fm2_v_format == 0)
    Retr = (ODS2_Retreval *)(((uint16 *)Retr)+1); /* skip placement descriptor */
switch (Retr->fm2_r_word0_bits.fm2_v_format)
    {
    case 1:
        ScbLbn = (Retr->fm2_r_map_bits1.fm2_v_highlbn1<<16)+Retr->fm2_r_map_bits1.fm2_w_lowlbn1;
        break;
    case 2:
        ScbLbn = (Retr->fm2_r_map_bits2.fm2_l_highlbn2<<16)+Retr->fm2_r_map_bits2.fm2_r_map2_long0.fm2_l_lowlbn2;
        break;
    case 3:
        ScbLbn = Retr->fm2_r_map_bits3.fm2_l_lbn3;
        break;
    }
Retr = (ODS2_Retreval *)(((uint16 *)Retr)+Retr->fm2_r_word0_bits.fm2_v_format+1);
if (sim_disk_rdsect (uptr, ScbLbn, (uint8 *)&Scb, NULL, 1))
    goto Return_Cleanup;
CheckSum1 = ODS2Checksum (&Scb, 255);
if (CheckSum1 != *(((uint16 *)&Scb)+255)) /* Verify Checksum on Storage Control Block */
    goto Return_Cleanup;
if ((Scb.scb_w_cluster != Home.hm2_w_cluster) || 
    (Scb.scb_b_strucver != Home.hm2_b_strucver) ||
    (Scb.scb_b_struclev != Home.hm2_b_struclev))
    goto Return_Cleanup;
if (!sim_quiet) {
    sim_printf ("%s%d: '%s' Contains ODS%d File system:\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename, Home.hm2_b_struclev);
    sim_printf ("%s%d: Volume Name: %12.12s ", sim_dname (dptr), (int)(uptr-dptr->units), Home.hm2_t_volname);
    sim_printf ("Format: %12.12s ", Home.hm2_t_format);
    sim_printf ("SectorsInVolume: %d\n", Scb.scb_l_volsize);
    }
ret_val = ((t_offset)Scb.scb_l_volsize) * 512;

Return_Cleanup:
uptr->capac = saved_capac;
return ret_val;
}

t_stat sim_disk_attach (UNIT *uptr, const char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontautosize,
                        uint32 dbit, const char *dtype, uint32 pdp11tracksize, int completion_delay)
{
struct disk_context *ctx;
DEVICE *dptr;
char tbuf[4*CBUFSIZE];
FILE *(*open_function)(const char *filename, const char *mode) = sim_fopen;
FILE *(*create_function)(const char *filename, t_offset desiredsize) = NULL;
t_offset (*size_function)(FILE *file);
t_stat (*storage_function)(FILE *file, uint32 *sector_size, uint32 *removable) = NULL;
t_bool created = FALSE, copied = FALSE;
t_bool auto_format = FALSE;
t_offset capac, filesystem_capac;

if (uptr->flags & UNIT_DIS)                             /* disabled? */
    return SCPE_UDIS;
if (!(uptr->flags & UNIT_ATTABLE))                      /* not attachable? */
    return SCPE_NOATT;
if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
977
978
979
980
981
982
983


984
985
986
987
988
989
990
991
992

993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013


1014
1015
1016
1017
1018
1019
1020
            }
        free (copy_buf);
        sim_vhd_disk_close (vhd);
        sim_disk_detach (uptr);
        if (r == SCPE_OK) {
            created = TRUE;
            copied = TRUE;


            strcpy (cptr, gbuf);
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);
            sim_switches = saved_sim_switches;
            }
        else
            return r;
        /* fall through and open/return the newly created & copied vhd */
        }
    }

else if (sim_switches & SWMASK ('M')) {                 /* merge difference disk? */
    char gbuf[CBUFSIZE], *Parent = NULL;
    FILE *vhd;

    sim_switches = sim_switches & ~(SWMASK ('M'));
    get_glyph_nc (cptr, gbuf, 0);                       /* get spec */
    vhd = sim_vhd_disk_merge (gbuf, &Parent);
    if (vhd) {
        t_stat r;

        sim_vhd_disk_close (vhd);
        r = sim_disk_attach (uptr, Parent, sector_size, xfer_element_size, dontautosize, dbit, dtype, pdp11tracksize, completion_delay);
        free (Parent);
        return r;
        }
    return SCPE_ARG;
    }

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* SIMH format */
        if (NULL == (uptr->fileref = sim_vhd_disk_open (cptr, "rb"))) {


            open_function = sim_fopen;
            size_function = sim_fsize_ex;
            break;
            }
        sim_disk_set_fmt (uptr, 0, "VHD", NULL);        /* set file format to VHD */
        sim_vhd_disk_close (uptr->fileref);             /* close vhd file*/
        auto_format = TRUE;







>
>
|








>
|
|
|

|
|
|
|
|

|
|
|
|
|
|
|




>
>







1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
            }
        free (copy_buf);
        sim_vhd_disk_close (vhd);
        sim_disk_detach (uptr);
        if (r == SCPE_OK) {
            created = TRUE;
            copied = TRUE;
            tbuf[sizeof(tbuf)-1] = '\0';
            strncpy (tbuf, gbuf, sizeof(tbuf)-1);
            cptr = tbuf;
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);
            sim_switches = saved_sim_switches;
            }
        else
            return r;
        /* fall through and open/return the newly created & copied vhd */
        }
    }
else
    if (sim_switches & SWMASK ('M')) {                 /* merge difference disk? */
        char gbuf[CBUFSIZE], *Parent = NULL;
        FILE *vhd;

        sim_switches = sim_switches & ~(SWMASK ('M'));
        get_glyph_nc (cptr, gbuf, 0);                  /* get spec */
        vhd = sim_vhd_disk_merge (gbuf, &Parent);
        if (vhd) {
            t_stat r;

            sim_vhd_disk_close (vhd);
            r = sim_disk_attach (uptr, Parent, sector_size, xfer_element_size, dontautosize, dbit, dtype, pdp11tracksize, completion_delay);
            free (Parent);
            return r;
            }
        return SCPE_ARG;
        }

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* SIMH format */
        if (NULL == (uptr->fileref = sim_vhd_disk_open (cptr, "rb"))) {
            if (errno == EBADF)                        /* VHD but broken */
                return SCPE_OPENERR;
            open_function = sim_fopen;
            size_function = sim_fsize_ex;
            break;
            }
        sim_disk_set_fmt (uptr, 0, "VHD", NULL);        /* set file format to VHD */
        sim_vhd_disk_close (uptr->fileref);             /* close vhd file*/
        auto_format = TRUE;
1042
1043
1044
1045
1046
1047
1048
1049

1050

1051
1052
1053
1054
1055
1056
1057
ctx->capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (word: 2, byte: 1) */
ctx->xfer_element_size = (uint32)xfer_element_size;     /* save xfer_element_size */
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
sim_debug (ctx->dbit, ctx->dptr, "sim_disk_attach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);
ctx->auto_format = auto_format;                         /* save that we auto selected format */
ctx->storage_sector_size = (uint32)sector_size;         /* Default */
if (sim_switches & SWMASK ('R')) {                      /* read only? */

    if ((uptr->flags & UNIT_ROABLE) == 0)               /* allowed? */

        return _err_return (uptr, SCPE_NORO);           /* no, error */
    uptr->fileref = open_function (cptr, "rb");         /* open rd only */
    if (uptr->fileref == NULL)                          /* open fail? */
        return _err_return (uptr, SCPE_OPENERR);        /* yes, error */
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    if (!sim_quiet) {
        sim_printf ("%s%d: unit is read only\n", sim_dname (dptr), (int)(uptr-dptr->units));







|
>
|
>







1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
ctx->capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (word: 2, byte: 1) */
ctx->xfer_element_size = (uint32)xfer_element_size;     /* save xfer_element_size */
ctx->dptr = dptr;                                       /* save DEVICE pointer */
ctx->dbit = dbit;                                       /* save debug bit */
sim_debug (ctx->dbit, ctx->dptr, "sim_disk_attach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);
ctx->auto_format = auto_format;                         /* save that we auto selected format */
ctx->storage_sector_size = (uint32)sector_size;         /* Default */
if ((sim_switches & SWMASK ('R')) ||                    /* read only? */
    ((uptr->flags & UNIT_RO) != 0)) {
    if (((uptr->flags & UNIT_ROABLE) == 0) &&           /* allowed? */
        ((uptr->flags & UNIT_RO) == 0))
        return _err_return (uptr, SCPE_NORO);           /* no, error */
    uptr->fileref = open_function (cptr, "rb");         /* open rd only */
    if (uptr->fileref == NULL)                          /* open fail? */
        return _err_return (uptr, SCPE_OPENERR);        /* yes, error */
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    if (!sim_quiet) {
        sim_printf ("%s%d: unit is read only\n", sim_dname (dptr), (int)(uptr-dptr->units));
1125
1126
1127
1128
1129
1130
1131



































1132
1133
1134
1135




















































1136
1137
1138













1139
1140

1141
1142
1143
1144
1145
1146


1147
1148
1149



1150

1151

1152
1153
1154
1155
1156
1157
1158
        r = sim_disk_wrsect (uptr, (t_lba)(0), secbuf, NULL, 1); /* Write First Sector */
    free (secbuf);
    if (r != SCPE_OK) {
        sim_disk_detach (uptr);                         /* report error now */
        remove (cptr);                                  /* remove the create file */
        return SCPE_OPENERR;
        }



































    if (pdp11tracksize)
        sim_disk_pdp11_bad_block (uptr, pdp11tracksize);
    }





















































capac = size_function (uptr->fileref);
if (capac && (capac != (t_offset)-1)) {
    if (dontautosize) {













        if ((capac < (((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1))) && (DKUF_F_STD != DK_GET_FMT (uptr))) {
            if (!sim_quiet) {

                sim_printf ("%s%d: non expandable disk %s is smaller than simulated device (", sim_dname (dptr), (int)(uptr-dptr->units), cptr);
                sim_print_val ((t_addr)(capac/ctx->capac_factor), 10, T_ADDR_W, PV_LEFT);
                sim_printf ("%s < ", (ctx->capac_factor == 2) ? "W" : "");
                sim_print_val (uptr->capac*((dptr->flags & DEV_SECTORS) ? 512 : 1), 10, T_ADDR_W, PV_LEFT);
                sim_printf ("%s)\n", (ctx->capac_factor == 2) ? "W" : "");
                }


            }
        }
    else



        if ((capac > (((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1))) || (DKUF_F_STD != DK_GET_FMT (uptr)))

            uptr->capac = (t_addr)(capac/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));

    }

#if defined (SIM_ASYNCH_IO)
sim_disk_set_async (uptr, completion_delay);
#endif
uptr->io_flush = _sim_disk_io_flush;








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>


>
|
<
<
|
|

>
>


|
>
>
>
|
>

>







1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499


1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
        r = sim_disk_wrsect (uptr, (t_lba)(0), secbuf, NULL, 1); /* Write First Sector */
    free (secbuf);
    if (r != SCPE_OK) {
        sim_disk_detach (uptr);                         /* report error now */
        remove (cptr);                                  /* remove the create file */
        return SCPE_OPENERR;
        }
    if (sim_switches & SWMASK ('I')) {                  /* Initialize To Sector Address */
        uint8 *init_buf = (uint8*) malloc (1024*1024);
        t_lba lba, sect;
        uint32 capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (word: 2, byte: 1) */
        t_seccnt sectors_per_buffer = (t_seccnt)((1024*1024)/sector_size);
        t_lba total_sectors = (t_lba)((uptr->capac*capac_factor)/(sector_size/((dptr->flags & DEV_SECTORS) ? 512 : 1)));
        t_seccnt sects = sectors_per_buffer;

        if (!init_buf) {
            sim_disk_detach (uptr);                         /* report error now */
            remove (cptr);
            return SCPE_MEM;
            }
        for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects) {
            sects = sectors_per_buffer;
            if (lba + sects > total_sectors)
                sects = total_sectors - lba;
            for (sect = 0; sect < sects; sect++) {
                t_lba offset;
                for (offset = 0; offset < sector_size; offset += sizeof(uint32))
                    *((uint32 *)&init_buf[sect*sector_size + offset]) = (uint32)(lba + sect);
                }
            r = sim_disk_wrsect (uptr, lba, init_buf, NULL, sects);
            if (r != SCPE_OK) {
                free (init_buf);
                sim_disk_detach (uptr);                         /* report error now */
                remove (cptr);                                  /* remove the create file */
                return SCPE_OPENERR;
                }
            if (!sim_quiet)
                sim_printf ("%s%d: Initialized To Sector Address %dMB.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000), (int)((((float)lba)*100)/total_sectors));
            }
        if (!sim_quiet)
            sim_printf ("%s%d: Initialized To Sector Address %dMB.  100%% complete.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000));
        }
    if (pdp11tracksize)
        sim_disk_pdp11_bad_block (uptr, pdp11tracksize);
    }

if (sim_switches & SWMASK ('K')) {
    t_stat r = SCPE_OK;
    t_lba lba, sect;
    uint32 capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (word: 2, byte: 1) */
    t_seccnt sectors_per_buffer = (t_seccnt)((1024*1024)/sector_size);
    t_lba total_sectors = (t_lba)((uptr->capac*capac_factor)/(sector_size/((dptr->flags & DEV_SECTORS) ? 512 : 1)));
    t_seccnt sects = sectors_per_buffer;
    uint8 *verify_buf = (uint8*) malloc (1024*1024);

    if (!verify_buf) {
        sim_disk_detach (uptr);                         /* report error now */
        return SCPE_MEM;
        }
    for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects) {
        sects = sectors_per_buffer;
        if (lba + sects > total_sectors)
            sects = total_sectors - lba;
        r = sim_disk_rdsect (uptr, lba, verify_buf, NULL, sects);
        if (r == SCPE_OK) {
            for (sect = 0; sect < sects; sect++) {
                t_lba offset;
                t_bool sect_error = FALSE;

                for (offset = 0; offset < sector_size; offset += sizeof(uint32)) {
                    if (*((uint32 *)&verify_buf[sect*sector_size + offset]) != (uint32)(lba + sect)) {
                        sect_error = TRUE;
                        break;
                        }
                    }
                if (sect_error) {
                    uint32 save_dctrl = dptr->dctrl;
                    FILE *save_sim_deb = sim_deb;

                    sim_printf ("\n%s%d: Verification Error on lbn %d(0x%X) of %d(0x%X).\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)(lba+sect), (int)(lba+sect), (int)total_sectors, (int)total_sectors);
                    dptr->dctrl = 0xFFFFFFFF;
                    sim_deb = stdout;
                    sim_disk_data_trace (uptr, verify_buf+sect*sector_size, lba+sect, sector_size,    "Found", TRUE, 1);
                    dptr->dctrl = save_dctrl;
                    sim_deb = save_sim_deb;
                    }
                }
            }
        if (!sim_quiet)
            sim_printf ("%s%d: Verified containing Sector Address %dMB.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000), (int)((((float)lba)*100)/total_sectors));
        }
    if (!sim_quiet)
        sim_printf ("%s%d: Verified containing Sector Address %dMB.  100%% complete.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000));
    free (verify_buf);
    uptr->dynflags |= UNIT_DISK_CHK;
    }

filesystem_capac = get_filesystem_size (uptr);
capac = size_function (uptr->fileref);
if (capac && (capac != (t_offset)-1)) {
    if (dontautosize) {
        t_addr saved_capac = uptr->capac;

        if ((filesystem_capac != (t_offset)-1) &&
            (filesystem_capac > (((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)))) {
            if (!sim_quiet) {
                uptr->capac = (t_addr)(filesystem_capac/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
                sim_printf ("%s%d: The file system on the disk %s is larger than simulated device (%s > ", sim_dname (dptr), (int)(uptr-dptr->units), cptr, sprint_capac (dptr, uptr));
                uptr->capac = saved_capac;
                sim_printf ("%s)\n", sprint_capac (dptr, uptr));
                }
            sim_disk_detach (uptr);
            return SCPE_OPENERR;
            }
        if ((capac < (((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1))) && (DKUF_F_STD != DK_GET_FMT (uptr))) {
            if (!sim_quiet) {
                uptr->capac = (t_addr)(capac/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
                sim_printf ("%s%d: non expandable disk %s is smaller than simulated device (%s < ", sim_dname (dptr), (int)(uptr-dptr->units), cptr, sprint_capac (dptr, uptr));


                uptr->capac = saved_capac;
                sim_printf ("%s)\n", sprint_capac (dptr, uptr));
                }
            sim_disk_detach (uptr);
            return SCPE_OPENERR;
            }
        }
    else {
        if ((filesystem_capac != (t_offset)-1) &&
            (filesystem_capac > capac))
            capac = filesystem_capac;
        if ((capac > (((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1))) || 
            (DKUF_F_STD != DK_GET_FMT (uptr)))
            uptr->capac = (t_addr)(capac/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
        }
    }

#if defined (SIM_ASYNCH_IO)
sim_disk_set_async (uptr, completion_delay);
#endif
uptr->io_flush = _sim_disk_io_flush;

1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211

if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */

sim_disk_clr_async (uptr);

uptr->flags &= ~(UNIT_ATT | UNIT_RO);
uptr->dynflags &= ~UNIT_NO_FIO;
free (uptr->filename);
uptr->filename = NULL;
uptr->fileref = NULL;
free (uptr->disk_ctx);
uptr->disk_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)







|







1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574

if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */

sim_disk_clr_async (uptr);

uptr->flags &= ~(UNIT_ATT | UNIT_RO);
uptr->dynflags &= ~(UNIT_NO_FIO | UNIT_DISK_CHK);
free (uptr->filename);
uptr->filename = NULL;
uptr->fileref = NULL;
free (uptr->disk_ctx);
uptr->disk_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)
1255
1256
1257
1258
1259
1260
1261





1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272



1273
1274
1275
1276
1277
1278
1279
fprintf (st, "\n%s attach command switches\n", dptr->name);
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified an attempt to create the indicated\n");
fprintf (st, "                disk container will be attempted).\n");
fprintf (st, "    -F          Open the indicated disk container in a specific format (default\n");
fprintf (st, "                is to autodetect VHD defaulting to simh if the indicated\n");
fprintf (st, "                container is not a VHD).\n");





fprintf (st, "    -C          Create a VHD and copy its contents from another disk (simh, VHD,\n");
fprintf (st, "                or RAW format). Add a -V switch to verify a copy operation.\n");
fprintf (st, "    -V          Perform a verification pass to confirm successful data copy\n");
fprintf (st, "                operation.\n");
fprintf (st, "    -X          When creating a VHD, create a fixed sized VHD (vs a Dynamically\n");
fprintf (st, "                expanding one).\n");
fprintf (st, "    -D          Create a Differencing VHD (relative to an already existing VHD\n");
fprintf (st, "                disk)\n");
fprintf (st, "    -M          Merge a Differencing VHD into its parent VHD disk\n");
fprintf (st, "    -O          Override consistency checks when attaching differencing disks\n");
fprintf (st, "                which have unexpected parent disk GUID or timestamps\n\n");



fprintf (st, "Examples:\n");
fprintf (st, "  sim> show rq\n");
fprintf (st, "    RQ, address=20001468-2000146B*, no vector, 4 units\n");
fprintf (st, "    RQ0, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ1, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ2, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ3, 409KB, not attached, write enabled, RX50, autosize, SIMH format\n");







>
>
>
>
>











>
>
>







1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
fprintf (st, "\n%s attach command switches\n", dptr->name);
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified an attempt to create the indicated\n");
fprintf (st, "                disk container will be attempted).\n");
fprintf (st, "    -F          Open the indicated disk container in a specific format (default\n");
fprintf (st, "                is to autodetect VHD defaulting to simh if the indicated\n");
fprintf (st, "                container is not a VHD).\n");
fprintf (st, "    -I          Initialize newly created disk so that each sector contains its\n");
fprintf (st, "                sector address\n");
fprintf (st, "    -K          Verify that the disk contents contain the sector address in each\n");
fprintf (st, "                sector.  Whole disk checked at attach time and each sector is\n");
fprintf (st, "                checked when written.\n");
fprintf (st, "    -C          Create a VHD and copy its contents from another disk (simh, VHD,\n");
fprintf (st, "                or RAW format). Add a -V switch to verify a copy operation.\n");
fprintf (st, "    -V          Perform a verification pass to confirm successful data copy\n");
fprintf (st, "                operation.\n");
fprintf (st, "    -X          When creating a VHD, create a fixed sized VHD (vs a Dynamically\n");
fprintf (st, "                expanding one).\n");
fprintf (st, "    -D          Create a Differencing VHD (relative to an already existing VHD\n");
fprintf (st, "                disk)\n");
fprintf (st, "    -M          Merge a Differencing VHD into its parent VHD disk\n");
fprintf (st, "    -O          Override consistency checks when attaching differencing disks\n");
fprintf (st, "                which have unexpected parent disk GUID or timestamps\n\n");
fprintf (st, "    -U          Fix inconsistencies which are overridden by the -O switch\n");
fprintf (st, "    -Y          Answer Yes to prompt to overwrite last track (on disk create)\n");
fprintf (st, "    -N          Answer No to prompt to overwrite last track (on disk create)\n");
fprintf (st, "Examples:\n");
fprintf (st, "  sim> show rq\n");
fprintf (st, "    RQ, address=20001468-2000146B*, no vector, 4 units\n");
fprintf (st, "    RQ0, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ1, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ2, 159MB, not attached, write enabled, RD54, autosize, SIMH format\n");
fprintf (st, "    RQ3, 409KB, not attached, write enabled, RX50, autosize, SIMH format\n");
1382
1383
1384
1385
1386
1387
1388
1389
1390


1391
1392
1393
1394
1395
1396
1397
1398
    }
return SCPE_OK;
}


/* Factory bad block table creation routine

   This routine writes a DEC standard 044 compliant bad block table on the
   last track of the specified unit.  The bad block table consists of 10


   repetitions of the same table, formatted as follows:

        words 0-1       pack id number
        words 2-3       cylinder/sector/surface specifications
         :
        words n-n+1     end of table (-1,-1)

   Inputs:







|
|
>
>
|







1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
    }
return SCPE_OK;
}


/* Factory bad block table creation routine

   This routine writes a DEC standard 144 compliant bad block table on the
   last track of the specified unit as described in: 
      EL-00144_B_DEC_STD_144_Disk_Standard_for_Recording_and_Handling_Bad_Sectors_Nov76.pdf
   The bad block table consists of 10 repetitions of the same table, 
   formatted as follows:

        words 0-1       pack id number
        words 2-3       cylinder/sector/surface specifications
         :
        words n-n+1     end of table (-1,-1)

   Inputs:
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
    return SCPE_RO;
if (ctx->capac_factor != 2)                  /* Must be Word oriented Capacity */
    return SCPE_IERR;
if (!get_yn ("Overwrite last track? [N]", FALSE))
    return SCPE_OK;
if ((buf = (uint16 *) malloc (wds * sizeof (uint16))) == NULL)
    return SCPE_MEM;
if ((namebuf = (char *) malloc (1 + strlen (uptr->filename))) == NULL) {
    free (buf);
    return SCPE_MEM;
    }
strcpy (namebuf, uptr->filename);
if ((c = strrchr (namebuf, '/')))
    memcpy (namebuf, c+1, strlen(c+1)+1);
if ((c = strrchr (namebuf, '\\')))
    memcpy (namebuf, c+1, strlen(c+1)+1);
if ((c = strrchr (namebuf, ']')))
    memcpy (namebuf, c+1, strlen(c+1)+1);
packid = eth_crc32(0, namebuf, strlen (namebuf));
buf[0] = (uint16)packid;
buf[1] = (uint16)(packid >> 16) & 0x7FFF;   /* Make sure MSB is clear */
buf[2] = buf[3] = 0;
for (i = 4; i < wds; i++)
    buf[i] = 0177777u;
da = (uptr->capac*((dptr->flags & DEV_SECTORS) ? 512 : 1)) - (sec * wds);







<
<
<
<
|

|

|

|







1796
1797
1798
1799
1800
1801
1802




1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
    return SCPE_RO;
if (ctx->capac_factor != 2)                  /* Must be Word oriented Capacity */
    return SCPE_IERR;
if (!get_yn ("Overwrite last track? [N]", FALSE))
    return SCPE_OK;
if ((buf = (uint16 *) malloc (wds * sizeof (uint16))) == NULL)
    return SCPE_MEM;




namebuf = uptr->filename;
if ((c = strrchr (namebuf, '/')))
    namebuf = c+1;
if ((c = strrchr (namebuf, '\\')))
    namebuf = c+1;
if ((c = strrchr (namebuf, ']')))
    namebuf = c+1;
packid = eth_crc32(0, namebuf, strlen (namebuf));
buf[0] = (uint16)packid;
buf[1] = (uint16)(packid >> 16) & 0x7FFF;   /* Make sure MSB is clear */
buf[2] = buf[3] = 0;
for (i = 4; i < wds; i++)
    buf[i] = 0177777u;
da = (uptr->capac*((dptr->flags & DEV_SECTORS) ? 512 : 1)) - (sec * wds);
1544
1545
1546
1547
1548
1549
1550









1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
}
#if defined(__GNUC__)
#include <ddk/ntddstor.h>
#include <ddk/ntdddisk.h>
#else
#include <winioctl.h>
#endif









struct _device_type {
    int32 Type;
    char *desc;
    } DeviceTypes[] = {
        {FILE_DEVICE_8042_PORT,             "8042_PORT"},
        {FILE_DEVICE_ACPI,                  "ACPI"},
        {FILE_DEVICE_BATTERY,               "BATTERY"},
        {FILE_DEVICE_BEEP,                  "BEEP"},
#ifdef FILE_DEVICE_BLUETOOTH
        {FILE_DEVICE_BLUETOOTH,             "BLUETOOTH"},







>
>
>
>
>
>
>
>
>


|







1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
}
#if defined(__GNUC__)
#include <ddk/ntddstor.h>
#include <ddk/ntdddisk.h>
#else
#include <winioctl.h>
#endif

#if defined(__cplusplus)
extern "C" {
#endif
WINBASEAPI BOOL WINAPI GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize);
#if defined(__cplusplus)
    }
#endif

struct _device_type {
    int32 Type;
    const char *desc;
    } DeviceTypes[] = {
        {FILE_DEVICE_8042_PORT,             "8042_PORT"},
        {FILE_DEVICE_ACPI,                  "ACPI"},
        {FILE_DEVICE_BATTERY,               "BATTERY"},
        {FILE_DEVICE_BEEP,                  "BEEP"},
#ifdef FILE_DEVICE_BLUETOOTH
        {FILE_DEVICE_BLUETOOTH,             "BLUETOOTH"},
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
if (strchr (openmode, 'w') || strchr (openmode, '+'))
    DesiredAccess |= GENERIC_WRITE;
/* SCP Command Line parsing replaces \\ with \ presuming this is an 
   escape sequence.  This only affecdts RAW device names and UNC paths.
   We handle the RAW device name case here by prepending paths beginning 
   with \.\ with an extra \. */
if (!memcmp ("\\.\\", rawdevicename, 3)) {
    char *tmpname = malloc (2 + strlen (rawdevicename));

    if (tmpname == NULL)
        return NULL;
    *tmpname = '\\';
    strcpy (tmpname + 1, rawdevicename);
    Handle = CreateFileA (tmpname, DesiredAccess, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS|FILE_FLAG_WRITE_THROUGH, NULL);
    free (tmpname);







|







2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
if (strchr (openmode, 'w') || strchr (openmode, '+'))
    DesiredAccess |= GENERIC_WRITE;
/* SCP Command Line parsing replaces \\ with \ presuming this is an 
   escape sequence.  This only affecdts RAW device names and UNC paths.
   We handle the RAW device name case here by prepending paths beginning 
   with \.\ with an extra \. */
if (!memcmp ("\\.\\", rawdevicename, 3)) {
    char *tmpname = (char *)malloc (2 + strlen (rawdevicename));

    if (tmpname == NULL)
        return NULL;
    *tmpname = '\\';
    strcpy (tmpname + 1, rawdevicename);
    Handle = CreateFileA (tmpname, DesiredAccess, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS|FILE_FLAG_WRITE_THROUGH, NULL);
    free (tmpname);
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
FlushFileBuffers ((HANDLE)f);
}

static t_offset sim_os_disk_size_raw (FILE *Disk)
{
DWORD IoctlReturnSize;
LARGE_INTEGER Size;
WINBASEAPI BOOL WINAPI GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize);

if (GetFileSizeEx((HANDLE)Disk, &Size))
    return (t_offset)(Size.QuadPart);
#ifdef IOCTL_STORAGE_READ_CAPACITY
if (1) {
    STORAGE_READ_CAPACITY S;








<







2069
2070
2071
2072
2073
2074
2075

2076
2077
2078
2079
2080
2081
2082
FlushFileBuffers ((HANDLE)f);
}

static t_offset sim_os_disk_size_raw (FILE *Disk)
{
DWORD IoctlReturnSize;
LARGE_INTEGER Size;


if (GetFileSizeEx((HANDLE)Disk, &Size))
    return (t_offset)(Size.QuadPart);
#ifdef IOCTL_STORAGE_READ_CAPACITY
if (1) {
    STORAGE_READ_CAPACITY S;

2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765







2766
2767


2768







2769
2770
2771

2772
2773
2774
2775
2776
2777
2778
                        const char *c;

                        if ((c = strrchr (szVHDPath, '\\')))
                             memcpy (CheckPath, szVHDPath, c-szVHDPath+1);
                             strncpy (CheckPath+strlen(CheckPath), ParentName, sizeof (CheckPath)-(strlen (CheckPath)+1));
                        }
                VhdPathToHostPath (CheckPath, CheckPath, sizeof (CheckPath));
                if ((0 == GetVHDFooter(CheckPath,
                                       &sParentFooter,
                                       NULL,
                                       NULL,
                                       &ParentModificationTime,
                                       NULL,
                                       0)) &&
                    (0 == memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID))) &&
                    ((sDynamic->ParentTimeStamp == ParentModificationTime) ||
                     ((NtoHl(sDynamic->ParentTimeStamp)-NtoHl(ParentModificationTime)) == 3600) ||
                     (sim_switches & SWMASK ('O')))) {
                    strncpy (szParentVHDPath, CheckPath, ParentVHDPathSize);







                    break;
                    }


                }







            if (!*szParentVHDPath) {
                Return = EINVAL;                        /* File Corrupt */
                sim_printf ("Error Invalid Parent VHD for Differencing VHD\n");

                }
            }
        }
    }
Return_Cleanup:
if (File)
    fclose(File);







|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>


>
>
|
>
>
>
>
>
>
>

|
|
>







3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
                        const char *c;

                        if ((c = strrchr (szVHDPath, '\\')))
                             memcpy (CheckPath, szVHDPath, c-szVHDPath+1);
                             strncpy (CheckPath+strlen(CheckPath), ParentName, sizeof (CheckPath)-(strlen (CheckPath)+1));
                        }
                VhdPathToHostPath (CheckPath, CheckPath, sizeof (CheckPath));
                if (0 == GetVHDFooter(CheckPath,
                                      &sParentFooter,
                                      NULL,
                                      NULL,
                                      &ParentModificationTime,
                                      NULL,
                                      0)) {
                    if ((0 == memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID))) &&
                        ((sDynamic->ParentTimeStamp == ParentModificationTime) ||
                         ((NtoHl(sDynamic->ParentTimeStamp)-NtoHl(ParentModificationTime)) == 3600) ||
                         (sim_switches & SWMASK ('O'))))
                         strncpy (szParentVHDPath, CheckPath, ParentVHDPathSize);
                    else {
                        if (0 != memcmp (sDynamic->ParentUniqueID, sParentFooter.UniqueID, sizeof (sParentFooter.UniqueID)))
                            sim_printf ("Error Invalid Parent VHD '%s' for Differencing VHD: %s\n", CheckPath, szVHDPath);
                        else
                            sim_printf ("Error Parent VHD '%s' has been modified since Differencing VHD: %s was created\n", CheckPath, szVHDPath);
                        Return = EINVAL;                /* File Corrupt/Invalid */
                        }
                    break;
                    }
                else {
                    struct stat statb;

                    if (0 == stat (CheckPath, &statb)) {
                        sim_printf ("Parent VHD '%s' corrupt for Differencing VHD: %s\n", CheckPath, szVHDPath);
                        Return = EBADF;                /* File Corrupt/Invalid */
                        break;
                        }
                    }
                }
            if (!*szParentVHDPath) {
                if (Return != EINVAL)                   /* File Not Corrupt? */
                    sim_printf ("Missing Parent VHD for Differencing VHD: %s\n", szVHDPath);
                Return = EBADF;
                }
            }
        }
    }
Return_Cleanup:
if (File)
    fclose(File);
2855
2856
2857
2858
2859
2860
2861

2862
2863
2864
2865
2866
2867
2868

return (char *)(&hVHD->Footer.DriveType[0]);
}

static FILE *sim_vhd_disk_open (const char *szVHDPath, const char *DesiredAccess)
    {
    VHDHANDLE hVHD = (VHDHANDLE) calloc (1, sizeof(*hVHD));

    int Status;

    if (!hVHD)
        return (FILE *)hVHD;
    Status = GetVHDFooter (szVHDPath,
                           &hVHD->Footer,
                           &hVHD->Dynamic,







>







3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263

return (char *)(&hVHD->Footer.DriveType[0]);
}

static FILE *sim_vhd_disk_open (const char *szVHDPath, const char *DesiredAccess)
    {
    VHDHANDLE hVHD = (VHDHANDLE) calloc (1, sizeof(*hVHD));
    int NeedUpdate = FALSE;
    int Status;

    if (!hVHD)
        return (FILE *)hVHD;
    Status = GetVHDFooter (szVHDPath,
                           &hVHD->Footer,
                           &hVHD->Dynamic,
2887
2888
2889
2890
2891
2892
2893

2894











2895
2896

2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912












2913
2914
2915
2916
2917
2918
2919
                               &ParentDynamic,
                               NULL,
                               &ParentModifiedTimeStamp,
                               NULL,
                               0);
        if (Status)
            goto Cleanup_Return;

        if (ParentModifiedTimeStamp != hVHD->Dynamic.ParentTimeStamp) {











            Status = EBADF;
            goto Cleanup_Return;

            }
        }
    if (hVHD->Footer.SavedState) {
        Status = EAGAIN;                                /* Busy */
        goto Cleanup_Return;
        }
    hVHD->File = sim_fopen (szVHDPath, DesiredAccess);
    if (!hVHD->File) {
        Status = errno;
        goto Cleanup_Return;
        }
Cleanup_Return:
    if (Status) {
        sim_vhd_disk_close ((FILE *)hVHD);
        hVHD = NULL;
        }












    errno = Status;
    return (FILE *)hVHD;
    }

static t_stat
WriteVirtualDiskSectors(VHDHANDLE hVHD,
                        uint8 *buf,







>
|
>
>
>
>
>
>
>
>
>
>
>
|
|
>
















>
>
>
>
>
>
>
>
>
>
>
>







3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
                               &ParentDynamic,
                               NULL,
                               &ParentModifiedTimeStamp,
                               NULL,
                               0);
        if (Status)
            goto Cleanup_Return;
        if ((0 != memcmp (hVHD->Dynamic.ParentUniqueID, ParentFooter.UniqueID, sizeof (ParentFooter.UniqueID))) || 
            (ParentModifiedTimeStamp != hVHD->Dynamic.ParentTimeStamp)) {
            if (sim_switches & SWMASK ('O')) {                      /* OVERRIDE consistency checks? */
                if ((sim_switches & SWMASK ('U')) &&                /* FIX (UPDATE) consistency checks AND */
                    (strchr (DesiredAccess, '+'))) {                /* open for write/update? */
                    memcpy (hVHD->Dynamic.ParentUniqueID, ParentFooter.UniqueID, sizeof (ParentFooter.UniqueID));
                    hVHD->Dynamic.ParentTimeStamp = ParentModifiedTimeStamp;
                    hVHD->Dynamic.Checksum = 0;
                    hVHD->Dynamic.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Dynamic, sizeof(hVHD->Dynamic)));
                    NeedUpdate = TRUE;
                    }
                }
            else {
                Status = EBADF;
                goto Cleanup_Return;
                }
            }
        }
    if (hVHD->Footer.SavedState) {
        Status = EAGAIN;                                /* Busy */
        goto Cleanup_Return;
        }
    hVHD->File = sim_fopen (szVHDPath, DesiredAccess);
    if (!hVHD->File) {
        Status = errno;
        goto Cleanup_Return;
        }
Cleanup_Return:
    if (Status) {
        sim_vhd_disk_close ((FILE *)hVHD);
        hVHD = NULL;
        }
    else {
        if (NeedUpdate) {                               /* Update Differencing Disk Header? */
            if (WriteFilePosition(hVHD->File,
                                  &hVHD->Dynamic,
                                  sizeof (hVHD->Dynamic),
                                  NULL,
                                  NtoHll (hVHD->Footer.DataOffset))) {
                sim_vhd_disk_close ((FILE *)hVHD);
                hVHD = NULL;
                }
            }
        }
    errno = Status;
    return (FILE *)hVHD;
    }

static t_stat
WriteVirtualDiskSectors(VHDHANDLE hVHD,
                        uint8 *buf,
Changes to src/sim_disk.h.
25
26
27
28
29
30
31




32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
   authorization from Robert M Supnik and Mark Pizzolato.

   25-Jan-11    MP      Initial Implemementation
*/

#ifndef SIM_DISK_H_
#define SIM_DISK_H_    0





/* SIMH/Disk format */

typedef uint32          t_seccnt;                       /* disk sector count */
typedef uint32          t_lba;                          /* disk logical block address */

/* Unit flags */

#define DKUF_V_WLK      (UNIT_V_UF + 12)                /* write locked */
#define DKUF_V_FMT      (UNIT_V_UF + 13)                /* disk file format */
#define DKUF_W_FMT      3                               /* 3b of formats */
#define DKUF_N_FMT      (1u << DKUF_W_FMT)              /* number of formats */
#define DKUF_M_FMT      ((1u << DKUF_W_FMT) - 1)
#define DKUF_F_STD       0                              /* SIMH format */
#define DKUF_F_RAW       1                              /* Raw Physical Disk Access */
#define DKUF_F_VHD       2                              /* VHD format */
#define DKUF_V_UF       (DKUF_V_FMT + DKUF_W_FMT)
#define DKUF_WLK        (1u << DKUF_V_WLK)







>
>
>
>








|
|
|







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
   authorization from Robert M Supnik and Mark Pizzolato.

   25-Jan-11    MP      Initial Implemementation
*/

#ifndef SIM_DISK_H_
#define SIM_DISK_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

/* SIMH/Disk format */

typedef uint32          t_seccnt;                       /* disk sector count */
typedef uint32          t_lba;                          /* disk logical block address */

/* Unit flags */

#define DKUF_V_WLK      (UNIT_V_UF + 0)                 /* write locked */
#define DKUF_V_FMT      (UNIT_V_UF + 1)                 /* disk file format */
#define DKUF_W_FMT      2                               /* 2b of formats */
#define DKUF_N_FMT      (1u << DKUF_W_FMT)              /* number of formats */
#define DKUF_M_FMT      ((1u << DKUF_W_FMT) - 1)
#define DKUF_F_STD       0                              /* SIMH format */
#define DKUF_F_RAW       1                              /* Raw Physical Disk Access */
#define DKUF_F_VHD       2                              /* VHD format */
#define DKUF_V_UF       (DKUF_V_FMT + DKUF_W_FMT)
#define DKUF_WLK        (1u << DKUF_V_WLK)
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92


93



#define DKSE_OK         0                               /* no error */

typedef void (*DISK_PCALLBACK)(UNIT *unit, t_stat status);

/* Prototypes */

t_stat sim_disk_attach (UNIT *uptr, char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontautosize, 
                        uint32 debugbit, const char *drivetype, uint32 pdp11_tracksize, int completion_delay);
t_stat sim_disk_detach (UNIT *uptr);
t_stat sim_disk_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);
t_stat sim_disk_rdsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects, DISK_PCALLBACK callback);
t_stat sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);
t_stat sim_disk_wrsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects, DISK_PCALLBACK callback);
t_stat sim_disk_unload (UNIT *uptr);
t_stat sim_disk_set_fmt (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_disk_show_fmt (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat sim_disk_set_capac (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_disk_show_capac (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat sim_disk_set_asynch (UNIT *uptr, int latency);
t_stat sim_disk_clr_asynch (UNIT *uptr);
t_stat sim_disk_reset (UNIT *uptr);
t_stat sim_disk_perror (UNIT *uptr, const char *msg);
t_stat sim_disk_clearerr (UNIT *uptr);
t_bool sim_disk_isavailable (UNIT *uptr);
t_bool sim_disk_isavailable_a (UNIT *uptr, DISK_PCALLBACK callback);
t_bool sim_disk_wrp (UNIT *uptr);
t_offset sim_disk_size (UNIT *uptr);
t_bool sim_disk_vhd_support (void);
t_bool sim_disk_raw_support (void);
void sim_disk_data_trace (UNIT *uptr, const uint8 *data, size_t lba, size_t len, const char* txt, int detail, uint32 reason);



#endif









|








|
|
|
|













>
>

>
>
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

#define DKSE_OK         0                               /* no error */

typedef void (*DISK_PCALLBACK)(UNIT *unit, t_stat status);

/* Prototypes */

t_stat sim_disk_attach (UNIT *uptr, const char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontautosize, 
                        uint32 debugbit, const char *drivetype, uint32 pdp11_tracksize, int completion_delay);
t_stat sim_disk_detach (UNIT *uptr);
t_stat sim_disk_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);
t_stat sim_disk_rdsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects, DISK_PCALLBACK callback);
t_stat sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);
t_stat sim_disk_wrsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects, DISK_PCALLBACK callback);
t_stat sim_disk_unload (UNIT *uptr);
t_stat sim_disk_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_disk_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_disk_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_disk_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_disk_set_asynch (UNIT *uptr, int latency);
t_stat sim_disk_clr_asynch (UNIT *uptr);
t_stat sim_disk_reset (UNIT *uptr);
t_stat sim_disk_perror (UNIT *uptr, const char *msg);
t_stat sim_disk_clearerr (UNIT *uptr);
t_bool sim_disk_isavailable (UNIT *uptr);
t_bool sim_disk_isavailable_a (UNIT *uptr, DISK_PCALLBACK callback);
t_bool sim_disk_wrp (UNIT *uptr);
t_offset sim_disk_size (UNIT *uptr);
t_bool sim_disk_vhd_support (void);
t_bool sim_disk_raw_support (void);
void sim_disk_data_trace (UNIT *uptr, const uint8 *data, size_t lba, size_t len, const char* txt, int detail, uint32 reason);

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_ether.c.
146
147
148
149
150
151
152



153
154
155
156
157
158
159
                      capabilities to share a single LAN interface.  It also
                      can allow a simulator to have useful networking 
                      functionality when running without root access.  This 
                      allows device names of the form vde:/tmp/switch to be 
                      specified at open time.  This functionality is only 
                      available on *nix platforms since the vde api isn't 
                      available on Windows.




  NEED_PCAP_SENDPACKET
                    - Specifies that you are using an older version of libpcap
                      which doesn't provide a pcap_sendpacket API.

  NOTE: Changing these defines is done in either sim_ether.h OR on the global 
        compiler command line which builds all of the modules included in a







>
>
>







146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                      capabilities to share a single LAN interface.  It also
                      can allow a simulator to have useful networking 
                      functionality when running without root access.  This 
                      allows device names of the form vde:/tmp/switch to be 
                      specified at open time.  This functionality is only 
                      available on *nix platforms since the vde api isn't 
                      available on Windows.
  HAVE_SLIRP_NETWORK- Specifies that support for SLiRP networking should be 
                      included.  This can be leveraged to provide User Mode 
                      IP NAT connectivity for simulators.

  NEED_PCAP_SENDPACKET
                    - Specifies that you are using an older version of libpcap
                      which doesn't provide a pcap_sendpacket API.

  NOTE: Changing these defines is done in either sim_ether.h OR on the global 
        compiler command line which builds all of the modules included in a
362
363
364
365
366
367
368








369
370
371
372
373
374
375





376



377
378
379











380
































381
382
383
384

385
386


387
388

389

390
391
392

393
394
395
396
397
398

399


















400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
  ------------------------------------------------------------------------------
*/

#include <ctype.h>
#include "sim_ether.h"
#include "sim_sock.h"
#include "sim_timer.h"









/*============================================================================*/
/*                  OS-independant ethernet routines                          */
/*============================================================================*/

t_stat eth_mac_scan (ETH_MAC* mac, char* strmac)
{





  unsigned int a0, a1, a2, a3, a4, a5;



  const ETH_MAC zeros = {0,0,0,0,0,0};
  const ETH_MAC ones  = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  ETH_MAC newmac;












































  if ((6 != sscanf(strmac, "%x:%x:%x:%x:%x:%x", &a0, &a1, &a2, &a3, &a4, &a5)) &&
      (6 != sscanf(strmac, "%x.%x.%x.%x.%x.%x", &a0, &a1, &a2, &a3, &a4, &a5)) &&
      (6 != sscanf(strmac, "%x-%x-%x-%x-%x-%x", &a0, &a1, &a2, &a3, &a4, &a5)))
    return SCPE_ARG;

  if ((a0 > 0xFF) || (a1 > 0xFF) || (a2 > 0xFF) || (a3 > 0xFF) || (a4 > 0xFF) || (a5 > 0xFF))
    return SCPE_ARG;


  newmac[0] = (unsigned char)a0;
  newmac[1] = (unsigned char)a1;

  newmac[2] = (unsigned char)a2;

  newmac[3] = (unsigned char)a3;
  newmac[4] = (unsigned char)a4;
  newmac[5] = (unsigned char)a5;


  /* final check - mac cannot be broadcast or multicast address */
  if (!memcmp(newmac, zeros, sizeof(ETH_MAC)) ||  /* broadcast */
      !memcmp(newmac, ones,  sizeof(ETH_MAC)) ||  /* broadcast */
      (newmac[0] & 0x01)                          /* multicast */
     )

    return SCPE_ARG;



















  /* new mac is OK, copy into passed mac */
  memcpy (*mac, newmac, sizeof(ETH_MAC));
  return SCPE_OK;
}

void eth_mac_fmt(ETH_MAC* mac, char* buff)
{
  uint8* m = (uint8*) mac;
  sprintf(buff, "%02X:%02X:%02X:%02X:%02X:%02X", m[0], m[1], m[2], m[3], m[4], m[5]);
  return;
}

static const uint32 crcTable[256] = {
  0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
  0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,







>
>
>
>
>
>
>
>





|

>
>
>
>
>
|
>
>
>
|
|

>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
>
|
|
>
>
|
|
>
|
>
|
|
|
>






>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|




|

|







365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
  ------------------------------------------------------------------------------
*/

#include <ctype.h>
#include "sim_ether.h"
#include "sim_sock.h"
#include "sim_timer.h"
#if defined(_WIN32)
#include <direct.h>
#else
#include <unistd.h>
#endif

/* Internal routines - forward declarations */
static int _eth_get_system_id (char *buf, size_t buf_size);

/*============================================================================*/
/*                  OS-independant ethernet routines                          */
/*============================================================================*/

t_stat eth_mac_scan (ETH_MAC* mac, const char* strmac)
{
return eth_mac_scan_ex (mac, strmac, NULL);
}

t_stat eth_mac_scan_ex (ETH_MAC* mac, const char* strmac, UNIT *uptr)
{
  unsigned int a[6], g[6];
  FILE *f;
  char filebuf[64] = "";
  uint32 i;
  static const ETH_MAC zeros = {0,0,0,0,0,0};
  static const ETH_MAC ones  = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  ETH_MAC newmac;
  struct {
      uint32 bits;
      char system_id[37];
      char cwd[PATH_MAX];
      char file[PATH_MAX];
      ETH_MAC base_mac;
      char uname[64];
      char sim[128];
      } state;
  CONST char *cptr, *tptr;
  uint32 data;

  /* Allow generated MAC address */
  /* XX:XX:XX:XX:XX:XX{/bits{>file}} */
  /* bits (if specified) must be from 16 thru 48 */

  memset (&state, 0, sizeof(state));
  _eth_get_system_id (state.system_id, sizeof(state.system_id));
  strncpy (state.sim, sim_name, sizeof(state.sim));
  getcwd (state.cwd, sizeof(state.cwd));
  if (uptr)
    strncpy (state.uname, sim_uname (uptr), sizeof(state.uname));
  cptr = strchr (strmac, '>');
  if (cptr) {
    strncpy (state.file, cptr + 1, sizeof(state.file));
    if ((f = fopen (state.file, "r"))) {
      filebuf[sizeof(filebuf)-1] = '\0';
      fgets (filebuf, sizeof(filebuf)-1, f);
      strmac = filebuf;
      fclose (f);
      strcpy (state.file, "");  /* avoid saving */
      }
    }
  cptr = strchr (strmac, '/');
  if (cptr) {
    state.bits = (uint32)strtotv (cptr + 1, &tptr, 10);
    if ((state.bits < 16) || (state.bits > 48))
      return sim_messagef (SCPE_ARG, "Invalid MAC address bits specifier '%d'. Valid values are from 16 thru 48\n", state.bits);
    }
  else
    state.bits = 48;
  data = eth_crc32 (0, (void *)&state, sizeof(state));
  for (i=g[0]=g[1]=0; i<4; i++)
    g[i+2] = (data >> (i << 3)) & 0xFF;
  if ((6 != sscanf(strmac, "%x:%x:%x:%x:%x:%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5])) &&
      (6 != sscanf(strmac, "%x.%x.%x.%x.%x.%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5])) &&
      (6 != sscanf(strmac, "%x-%x-%x-%x-%x-%x", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5])))
    return sim_messagef (SCPE_ARG, "Invalid MAC address format: '%s'\n", strmac);
  for (i=0; i<6; i++)
    if (a[i] > 0xFF)
      return sim_messagef (SCPE_ARG, "Invalid MAC address byte value: %02X\n", a[i]);
    else {
      uint32 mask, shift;
    
      state.base_mac[i] = a[i];
      if (((i + 1) << 3) < state.bits)
          shift = 0;
      else
          shift = ((i + 1) << 3) - state.bits;
      mask = 0xFF << shift;
      newmac[i] = (unsigned char)((a[i] & mask) | (g[i] & ~mask));
      }

  /* final check - mac cannot be broadcast or multicast address */
  if (!memcmp(newmac, zeros, sizeof(ETH_MAC)) ||  /* broadcast */
      !memcmp(newmac, ones,  sizeof(ETH_MAC)) ||  /* broadcast */
      (newmac[0] & 0x01)                          /* multicast */
     )
    return sim_messagef (SCPE_ARG, "Can't use Broadcast or MultiCast address as interface MAC address\n");

  /* new mac is OK */
  /* optionally save */
  if (state.file[0]) {              /* Save File specified? */
    f = fopen (state.file, "w");
    if (f == NULL)
      return sim_messagef (SCPE_ARG, "Can't open MAC address configuration file '%s'.\n", state.file);
    eth_mac_fmt (&newmac, filebuf);
    fprintf (f, "%s/48\n", filebuf);
    fprintf (f, "system-id: %s\n", state.system_id);
    fprintf (f, "directory: %s\n", state.cwd);
    fprintf (f, "simulator: %s\n", state.sim);
    fprintf (f, "device:    %s\n", state.uname);
    fprintf (f, "file:      %s\n", state.file);
    eth_mac_fmt (&state.base_mac, filebuf);
    fprintf (f, "base-mac:  %s\n", filebuf);
    fprintf (f, "specified: %d bits\n", state.bits);
    fprintf (f, "generated: %d bits\n", 48-state.bits);
    fclose (f);
    }
  /* copy into passed mac */
  memcpy (*mac, newmac, sizeof(ETH_MAC));
  return SCPE_OK;
}

void eth_mac_fmt(ETH_MAC* const mac, char* buff)
{
  const uint8* m = (const uint8*) mac;
  sprintf(buff, "%02X:%02X:%02X:%02X:%02X:%02X", m[0], m[1], m[2], m[3], m[4], m[5]);
  return;
}

static const uint32 crcTable[256] = {
  0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
  0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
}

void eth_packet_trace_ex(ETH_DEV* dev, const uint8 *msg, int len, const char* txt, int detail, uint32 reason)
{
  if (dev->dptr->dctrl & reason) {
    char src[20];
    char dst[20];
    unsigned short* proto = (unsigned short*) &msg[12];
    uint32 crc = eth_crc32(0, msg, len);
    eth_mac_fmt((ETH_MAC*)&msg[0], dst);
    eth_mac_fmt((ETH_MAC*)&msg[6], src);
    sim_debug(reason, dev->dptr, "%s  dst: %s  src: %s  proto: 0x%04X  len: %d  crc: %X\n",
          txt, dst, src, ntohs(*proto), len, crc);
    if (detail) {
      int i, same, group, sidx, oidx;
      char outbuf[80], strbuf[18];
      static char hex[] = "0123456789ABCDEF";

      for (i=same=0; i<len; i += 16) {
        if ((i > 0) && (0 == memcmp(&msg[i], &msg[i-16], 16))) {
          ++same;
          continue;
        }
        if (same > 0) {







|

|
|





|







599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
}

void eth_packet_trace_ex(ETH_DEV* dev, const uint8 *msg, int len, const char* txt, int detail, uint32 reason)
{
  if (dev->dptr->dctrl & reason) {
    char src[20];
    char dst[20];
    const unsigned short* proto = (const unsigned short*) &msg[12];
    uint32 crc = eth_crc32(0, msg, len);
    eth_mac_fmt((ETH_MAC*)msg, dst);
    eth_mac_fmt((ETH_MAC*)(msg+6), src);
    sim_debug(reason, dev->dptr, "%s  dst: %s  src: %s  proto: 0x%04X  len: %d  crc: %X\n",
          txt, dst, src, ntohs(*proto), len, crc);
    if (detail) {
      int i, same, group, sidx, oidx;
      char outbuf[80], strbuf[18];
      static const char hex[] = "0123456789ABCDEF";

      for (i=same=0; i<len; i += 16) {
        if ((i > 0) && (0 == memcmp(&msg[i], &msg[i-16], 16))) {
          ++same;
          continue;
        }
        if (same > 0) {
563
564
565
566
567
568
569
570
571
572
573
574
575
576





577

578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


672
673

674
675
676
677
678
679
680
}

void eth_packet_trace_detail(ETH_DEV* dev, const uint8 *msg, int len, const char* txt)
{
  eth_packet_trace_ex(dev, msg, len, txt, 1     , dev->dbit);
}

char* eth_getname(int number, char* name)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);

  if ((number < 0) || (count <= number))
      return NULL;





  strcpy(name, list[number].name);

  return name;
}

char* eth_getname_bydesc(char* desc, char* name)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  int i;
  size_t j=strlen(desc);

  for (i=0; i<count; i++) {
    int found = 1;
    size_t k = strlen(list[i].desc);

    if (j != k) continue;
    for (k=0; k<j; k++)
      if (tolower(list[i].desc[k]) != tolower(desc[k]))
        found = 0;
    if (found == 0) continue;

    /* found a case-insensitive description match */
    strcpy(name, list[i].name);

    return name;
  }
  /* not found */
  return NULL;
}

/* strncasecmp() is not available on all platforms */
int eth_strncasecmp(char* string1, char* string2, size_t len)
{
  size_t i;
  unsigned char s1, s2;

  for (i=0; i<len; i++) {
    s1 = string1[i];
    s2 = string2[i];
    if (islower (s1)) s1 = (unsigned char)toupper (s1);
    if (islower (s2)) s2 = (unsigned char)toupper (s2);

    if (s1 < s2)
      return -1;
    if (s1 > s2)
      return 1;
    if (s1 == 0) return 0;
  }
  return 0;
}

char* eth_getname_byname(char* name, char* temp)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  size_t n;
  int i, found;

  found = 0;
  n = strlen(name);
  for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (eth_strncasecmp(name, list[i].name, n) == 0)) {
      found = 1;
      strcpy(temp, list[i].name); /* only case might be different */

    }
  }
  return (found ? temp : NULL);
}

char* eth_getdesc_byname(char* name, char* temp)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  size_t n;
  int i, found;

  found = 0;
  n = strlen(name);
  for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (eth_strncasecmp(name, list[i].name, n) == 0)) {
      found = 1;
      strcpy(temp, list[i].desc);
    }
  }
  return (found ? temp : NULL);
}

void eth_zero(ETH_DEV* dev)
{
  /* set all members to NULL OR 0 */
  memset(dev, 0, sizeof(ETH_DEV));
  dev->reflections = -1;                          /* not established yet */
}



static ETH_DEV **eth_open_devices = NULL;
static int eth_open_device_count = 0;


#if defined (USE_NETWORK) || defined (USE_SHARED)
static void _eth_add_to_open_list (ETH_DEV* dev)
{
eth_open_devices = (ETH_DEV**)realloc(eth_open_devices, (eth_open_device_count+1)*sizeof(*eth_open_devices));
eth_open_devices[eth_open_device_count++] = dev;
}







|






>
>
>
>
>

>



|


















>






<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|










|


>
















|














>
>


>







650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699





















700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
}

void eth_packet_trace_detail(ETH_DEV* dev, const uint8 *msg, int len, const char* txt)
{
  eth_packet_trace_ex(dev, msg, len, txt, 1     , dev->dbit);
}

const char* eth_getname(int number, char* name, char *desc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);

  if ((number < 0) || (count <= number))
      return NULL;
  if (list[number].eth_api != ETH_API_PCAP) {
    sim_printf ("Eth: Pcap capable device not found.  You may need to run as root\n");
    return NULL;
    }

  strcpy(name, list[number].name);
  strcpy(desc, list[number].desc);
  return name;
}

const char* eth_getname_bydesc(const char* desc, char* name, char *ndesc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  int i;
  size_t j=strlen(desc);

  for (i=0; i<count; i++) {
    int found = 1;
    size_t k = strlen(list[i].desc);

    if (j != k) continue;
    for (k=0; k<j; k++)
      if (tolower(list[i].desc[k]) != tolower(desc[k]))
        found = 0;
    if (found == 0) continue;

    /* found a case-insensitive description match */
    strcpy(name, list[i].name);
    strcpy(ndesc, list[i].desc);
    return name;
  }
  /* not found */
  return NULL;
}






















char* eth_getname_byname(const char* name, char* temp, char *desc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  size_t n;
  int i, found;

  found = 0;
  n = strlen(name);
  for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_strncasecmp(name, list[i].name, n) == 0)) {
      found = 1;
      strcpy(temp, list[i].name); /* only case might be different */
      strcpy(desc, list[i].desc);
    }
  }
  return (found ? temp : NULL);
}

char* eth_getdesc_byname(char* name, char* temp)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int count = eth_devices(ETH_MAX_DEVICE, list);
  size_t n;
  int i, found;

  found = 0;
  n = strlen(name);
  for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_strncasecmp(name, list[i].name, n) == 0)) {
      found = 1;
      strcpy(temp, list[i].desc);
    }
  }
  return (found ? temp : NULL);
}

void eth_zero(ETH_DEV* dev)
{
  /* set all members to NULL OR 0 */
  memset(dev, 0, sizeof(ETH_DEV));
  dev->reflections = -1;                          /* not established yet */
}

static char*   (*p_pcap_lib_version) (void);

static ETH_DEV **eth_open_devices = NULL;
static int eth_open_device_count = 0;
static t_bool eth_show_active = FALSE;

#if defined (USE_NETWORK) || defined (USE_SHARED)
static void _eth_add_to_open_list (ETH_DEV* dev)
{
eth_open_devices = (ETH_DEV**)realloc(eth_open_devices, (eth_open_device_count+1)*sizeof(*eth_open_devices));
eth_open_devices[eth_open_device_count++] = dev;
}
689
690
691
692
693
694
695
696
697
698
699
700


701
702
703
704
705
706
707
708
709
710
711
712
713
714



715
716
717
718
719
720
721
722
723
724
725
726
727
728

729
730
731
732
733
734
735
736
737
738
739
740
741
            eth_open_devices[j-1] = eth_open_devices[j];
        --eth_open_device_count;
        break;
        }
}
#endif

t_stat eth_show (FILE* st, UNIT* uptr, int32 val, void* desc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int number = eth_devices(ETH_MAX_DEVICE, list);



  fprintf(st, "ETH devices:\n");
  if (number == -1)
    fprintf(st, "  network support not available in simulator\n");
  else
    if (number == 0)
      fprintf(st, "  no network devices are available\n");
    else {
      size_t min, len;
      int i;
      for (i=0, min=0; i<number; i++)
        if ((len = strlen(list[i].name)) > min) min = len;
      for (i=0; i<number; i++)
        fprintf(st," eth%d\t%-*s (%s)\n", i, (int)min, list[i].name, list[i].desc);
    }



  if (eth_open_device_count) {
    int i;
    char desc[ETH_DEV_DESC_MAX], *d;

    fprintf(st,"Open ETH Devices:\n");
    for (i=0; i<eth_open_device_count; i++) {
      d = eth_getdesc_byname(eth_open_devices[i]->name, desc);
      if (d)
        fprintf(st, " %-7s%s (%s)\n", eth_open_devices[i]->dptr->name, eth_open_devices[i]->dptr->units[0].filename, d);
      else
        fprintf(st, " %-7s%s\n", eth_open_devices[i]->dptr->name, eth_open_devices[i]->dptr->units[0].filename);
      eth_show_dev (st, eth_open_devices[i]);
      }
    }

  return SCPE_OK;
}

t_stat eth_show_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc)
{
return eth_show (st, uptr, val, desc);
}

t_stat ethq_init(ETH_QUE* que, int max)
{
  /* create dynamic queue if it does not exist */
  if (!que->item) {
    que->item = (struct eth_item *) calloc(max, sizeof(struct eth_item));







|


|

>
>














>
>
>














>



|

|







766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
            eth_open_devices[j-1] = eth_open_devices[j];
        --eth_open_device_count;
        break;
        }
}
#endif

t_stat eth_show (FILE* st, UNIT* uptr, int32 val, CONST void* desc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int number;

  eth_show_active = TRUE;
  number = eth_devices(ETH_MAX_DEVICE, list);
  fprintf(st, "ETH devices:\n");
  if (number == -1)
    fprintf(st, "  network support not available in simulator\n");
  else
    if (number == 0)
      fprintf(st, "  no network devices are available\n");
    else {
      size_t min, len;
      int i;
      for (i=0, min=0; i<number; i++)
        if ((len = strlen(list[i].name)) > min) min = len;
      for (i=0; i<number; i++)
        fprintf(st," eth%d\t%-*s (%s)\n", i, (int)min, list[i].name, list[i].desc);
    }
  if (p_pcap_lib_version) {
    fprintf(st, "%s\n", p_pcap_lib_version());
    }
  if (eth_open_device_count) {
    int i;
    char desc[ETH_DEV_DESC_MAX], *d;

    fprintf(st,"Open ETH Devices:\n");
    for (i=0; i<eth_open_device_count; i++) {
      d = eth_getdesc_byname(eth_open_devices[i]->name, desc);
      if (d)
        fprintf(st, " %-7s%s (%s)\n", eth_open_devices[i]->dptr->name, eth_open_devices[i]->dptr->units[0].filename, d);
      else
        fprintf(st, " %-7s%s\n", eth_open_devices[i]->dptr->name, eth_open_devices[i]->dptr->units[0].filename);
      eth_show_dev (st, eth_open_devices[i]);
      }
    }
  eth_show_active = FALSE;
  return SCPE_OK;
}

t_stat eth_show_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char *desc)
{
return eth_show (st, uptr, val, NULL);
}

t_stat ethq_init(ETH_QUE* que, int max)
{
  /* create dynamic queue if it does not exist */
  if (!que->item) {
    que->item = (struct eth_item *) calloc(max, sizeof(struct eth_item));
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/*============================================================================*/
/*                        Non-implemented versions                            */
/*============================================================================*/

#if !defined (USE_NETWORK) && !defined (USE_SHARED)
const char *eth_capabilities(void)
    {return "no Ethernet";}
t_stat eth_open(ETH_DEV* dev, char* name, DEVICE* dptr, uint32 dbit)
  {return SCPE_NOFNC;}
t_stat eth_close (ETH_DEV* dev)
  {return SCPE_NOFNC;}
t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
  {
  fprintf (st, "%s attach help\n\n", dptr->name);
  fprintf (st, "This simulator was not built with ethernet device support\n");







|







926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
/*============================================================================*/
/*                        Non-implemented versions                            */
/*============================================================================*/

#if !defined (USE_NETWORK) && !defined (USE_SHARED)
const char *eth_capabilities(void)
    {return "no Ethernet";}
t_stat eth_open(ETH_DEV* dev, const char* name, DEVICE* dptr, uint32 dbit)
  {return SCPE_NOFNC;}
t_stat eth_close (ETH_DEV* dev)
  {return SCPE_NOFNC;}
t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
  {
  fprintf (st, "%s attach help\n\n", dptr->name);
  fprintf (st, "This simulator was not built with ethernet device support\n");
876
877
878
879
880
881
882


883
884
885
886
887
888
889
890
891
892
893
894
895



896
897
898
899
900
901
902
t_stat eth_filter_hash (ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                   ETH_BOOL all_multicast, ETH_BOOL promiscuous, ETH_MULTIHASH* const hash)
  {return SCPE_NOFNC;}
int eth_devices (int max, ETH_LIST* dev)
  {return -1;}
void eth_show_dev (FILE* st, ETH_DEV* dev)
  {}


#else    /* endif unimplemented */

const char *eth_capabilities(void)
 {
 return "Ethernet Packet transport"
#if defined (HAVE_PCAP_NETWORK)
     ":PCAP"
#endif
#if defined (HAVE_TAP_NETWORK)
     ":TAP"
#endif
#if defined (HAVE_VDE_NETWORK)
     ":VDE"



#endif
     ":UDP";
 }

#if (defined (xBSD) || defined (__APPLE__)) && (defined (HAVE_TAP_NETWORK) || defined (HAVE_PCAP_NETWORK))
#include <sys/ioctl.h>
#include <net/bpf.h>







>
>




|








>
>
>







959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
t_stat eth_filter_hash (ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                   ETH_BOOL all_multicast, ETH_BOOL promiscuous, ETH_MULTIHASH* const hash)
  {return SCPE_NOFNC;}
int eth_devices (int max, ETH_LIST* dev)
  {return -1;}
void eth_show_dev (FILE* st, ETH_DEV* dev)
  {}
static int _eth_get_system_id (char *buf, size_t buf_size)
  {memset (buf, 0, buf_size); return 0;}
#else    /* endif unimplemented */

const char *eth_capabilities(void)
 {
 return "Ethernet Packet transports"
#if defined (HAVE_PCAP_NETWORK)
     ":PCAP"
#endif
#if defined (HAVE_TAP_NETWORK)
     ":TAP"
#endif
#if defined (HAVE_VDE_NETWORK)
     ":VDE"
#endif
#if defined (HAVE_SLIRP_NETWORK)
     ":NAT"
#endif
     ":UDP";
 }

#if (defined (xBSD) || defined (__APPLE__)) && (defined (HAVE_TAP_NETWORK) || defined (HAVE_PCAP_NETWORK))
#include <sys/ioctl.h>
#include <net/bpf.h>
931
932
933
934
935
936
937



938



939
940




941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
#include <net/if.h>
#else /* We don't know how to do this on the current platform */
#undef HAVE_TAP_NETWORK
#endif
#endif /* HAVE_TAP_NETWORK */

#ifdef HAVE_VDE_NETWORK



#include <libvdeplug.h>



#endif /* HAVE_VDE_NETWORK */





/* Allows windows to look up user-defined adapter names */
#if defined(_WIN32)
#include <winreg.h>
#endif

#ifdef HAVE_DLOPEN
#include <dlfcn.h>
#endif

#if defined(USE_SHARED) && (defined(_WIN32) || defined(HAVE_DLOPEN))
/* Dynamic DLL loading technique and modified source comes from
   Etherial/WireShark capture_pcap.c */

/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0;                      /* handle to DLL */
#else
static void *hLib = 0;                      /* handle to Library */
#endif
static int lib_loaded = 0;                      /* 0=not loaded, 1=loaded, 2=library load failed, 3=Func load failed */
static const char* lib_name =
#if defined(_WIN32) || defined(__CYGWIN__)
                          "wpcap.dll";
#elif defined(__APPLE__)
                          "/usr/lib/libpcap.A.dylib";
#else
#define __STR_QUOTE(tok) #tok







>
>
>

>
>
>


>
>
>
>















|



|







1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
#include <net/if.h>
#else /* We don't know how to do this on the current platform */
#undef HAVE_TAP_NETWORK
#endif
#endif /* HAVE_TAP_NETWORK */

#ifdef HAVE_VDE_NETWORK
#ifdef  __cplusplus
extern "C" {
#endif
#include <libvdeplug.h>
#ifdef  __cplusplus
}
#endif
#endif /* HAVE_VDE_NETWORK */

#ifdef HAVE_SLIRP_NETWORK
#include "sim_slirp.h"
#endif /* HAVE_SLIRP_NETWORK */

/* Allows windows to look up user-defined adapter names */
#if defined(_WIN32)
#include <winreg.h>
#endif

#ifdef HAVE_DLOPEN
#include <dlfcn.h>
#endif

#if defined(USE_SHARED) && (defined(_WIN32) || defined(HAVE_DLOPEN))
/* Dynamic DLL loading technique and modified source comes from
   Etherial/WireShark capture_pcap.c */

/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = NULL;               /* handle to DLL */
#else
static void *hLib = 0;                      /* handle to Library */
#endif
static int lib_loaded = 0;                  /* 0=not loaded, 1=loaded, 2=library load failed, 3=Func load failed */
static const char* lib_name =
#if defined(_WIN32) || defined(__CYGWIN__)
                          "wpcap.dll";
#elif defined(__APPLE__)
                          "/usr/lib/libpcap.A.dylib";
#else
#define __STR_QUOTE(tok) #tok
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016








1017
1018
1019
1020
1021
1022
1023












1024





1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
static int     (*p_pcap_get_selectable_fd) (pcap_t *);
#endif
static int     (*p_pcap_fileno) (pcap_t *);
#endif
static int     (*p_pcap_sendpacket) (pcap_t* handle, const u_char* msg, int len);
static int     (*p_pcap_setfilter) (pcap_t *, struct bpf_program *);
static int     (*p_pcap_setnonblock)(pcap_t* a, int nonblock, char *errbuf);
static char*   (*p_pcap_lib_version) (void);

/* load function pointer from DLL */
typedef int (*_func)();

static void load_function(const char* function, _func* func_ptr) {
#ifdef _WIN32
    *func_ptr = (_func)((size_t)GetProcAddress(hLib, function));
#else
    *func_ptr = (_func)((size_t)dlsym(hLib, function));
#endif
    if (*func_ptr == 0) {
    sim_printf ("Eth: Failed to find function '%s' in %s\r\n", function, lib_name);
    lib_loaded = 3;
  }
}









/* load wpcap.dll as required */
int load_pcap(void) {
  switch(lib_loaded) {
    case 0:                  /* not loaded */
            /* attempt to load DLL */
#ifdef _WIN32












      hLib = LoadLibraryA(lib_name);





#else
      hLib = dlopen(lib_name, RTLD_NOW);
#endif
      if (hLib == 0) {
        /* failed to load DLL */
        sim_printf ("Eth: Failed to load %s\r\n", lib_name);
#ifdef _WIN32
        sim_printf ("Eth: You must install WinPcap 4.x to use networking\r\n");
#else
        sim_printf ("Eth: You must install libpcap to use networking\r\n");
#endif
        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */







<















>
>
>
>
>
>
>
>







>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>







|







1092
1093
1094
1095
1096
1097
1098

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
static int     (*p_pcap_get_selectable_fd) (pcap_t *);
#endif
static int     (*p_pcap_fileno) (pcap_t *);
#endif
static int     (*p_pcap_sendpacket) (pcap_t* handle, const u_char* msg, int len);
static int     (*p_pcap_setfilter) (pcap_t *, struct bpf_program *);
static int     (*p_pcap_setnonblock)(pcap_t* a, int nonblock, char *errbuf);


/* load function pointer from DLL */
typedef int (*_func)();

static void load_function(const char* function, _func* func_ptr) {
#ifdef _WIN32
    *func_ptr = (_func)((size_t)GetProcAddress(hLib, function));
#else
    *func_ptr = (_func)((size_t)dlsym(hLib, function));
#endif
    if (*func_ptr == 0) {
    sim_printf ("Eth: Failed to find function '%s' in %s\r\n", function, lib_name);
    lib_loaded = 3;
  }
}

static void try_load_function(const char* function, _func* func_ptr) {
#ifdef _WIN32
    *func_ptr = (_func)((size_t)GetProcAddress(hLib, function));
#else
    *func_ptr = (_func)((size_t)dlsym(hLib, function));
#endif
}

/* load wpcap.dll as required */
int load_pcap(void) {
  switch(lib_loaded) {
    case 0:                  /* not loaded */
            /* attempt to load DLL */
#ifdef _WIN32
      if (1) {
        BOOL(WINAPI *p_SetDllDirectory)(LPCTSTR);
        UINT(WINAPI *p_GetSystemDirectory)(LPTSTR lpBuffer, UINT uSize);

        p_SetDllDirectory = (BOOL(WINAPI *)(LPCTSTR)) GetProcAddress(GetModuleHandle("kernel32.dll"), "SetDllDirectoryA");
        p_GetSystemDirectory = (UINT(WINAPI *)(LPTSTR, UINT)) GetProcAddress(GetModuleHandle("kernel32.dll"), "GetSystemDirectoryA");
        if (p_SetDllDirectory && p_GetSystemDirectory) {
          char npcap_path[512] = "";

          if (p_GetSystemDirectory (npcap_path, sizeof(npcap_path) - 7))
            strcat (npcap_path, "\\Npcap");
          if (p_SetDllDirectory(npcap_path))
            hLib = LoadLibraryA(lib_name);
          p_SetDllDirectory (NULL);
          }
        if (hLib == NULL)
          hLib = LoadLibraryA(lib_name);
        }
#else
      hLib = dlopen(lib_name, RTLD_NOW);
#endif
      if (hLib == 0) {
        /* failed to load DLL */
        sim_printf ("Eth: Failed to load %s\r\n", lib_name);
#ifdef _WIN32
        sim_printf ("Eth: You must install Npcap or WinPcap 4.x to use networking\r\n");
#else
        sim_printf ("Eth: You must install libpcap to use networking\r\n");
#endif
        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
      load_function("pcap_fileno",       (_func *) &p_pcap_fileno);
#endif
      load_function("pcap_sendpacket",   (_func *) &p_pcap_sendpacket);
      load_function("pcap_setfilter",    (_func *) &p_pcap_setfilter);
      load_function("pcap_setnonblock",  (_func *) &p_pcap_setnonblock);
      load_function("pcap_lib_version",  (_func *) &p_pcap_lib_version);

      if (lib_loaded == 1) {
        /* log successful load */
        sim_printf("%s\n", p_pcap_lib_version());
      }
      break;
    default:                /* loaded or failed */
      break;
  }







|







1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
      load_function("pcap_fileno",       (_func *) &p_pcap_fileno);
#endif
      load_function("pcap_sendpacket",   (_func *) &p_pcap_sendpacket);
      load_function("pcap_setfilter",    (_func *) &p_pcap_setfilter);
      load_function("pcap_setnonblock",  (_func *) &p_pcap_setnonblock);
      load_function("pcap_lib_version",  (_func *) &p_pcap_lib_version);

      if ((lib_loaded == 1) && (!eth_show_active)) {
        /* log successful load */
        sim_printf("%s\n", p_pcap_lib_version());
      }
      break;
    default:                /* loaded or failed */
      break;
  }
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
    uint8 Data[1];              ///< variable-lenght field that contains the information passed to or received 
                                ///< from the adapter.
}; 
typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA;
typedef void **LPADAPTER;
#define OID_802_3_CURRENT_ADDRESS               0x01010102 /* Extracted from ntddmdis.h */

static int pcap_mac_if_win32(char *AdapterName, unsigned char MACAddress[6])
{
  LPADAPTER         lpAdapter;
  PPACKET_OID_DATA  OidData;
  int               Status;
  int               ReturnValue;
#ifdef _WIN32
  HMODULE           hDll;         /* handle to DLL */
#else
  static void       *hDll = NULL; /* handle to Library */
  typedef int BOOLEAN;
#endif
  LPADAPTER (*p_PacketOpenAdapter)(char *AdapterName);
  void (*p_PacketCloseAdapter)(LPADAPTER lpAdapter);
  int (*p_PacketRequest)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData);

#ifdef _WIN32
  hDll = LoadLibraryA("packet.dll");
  p_PacketOpenAdapter = (LPADAPTER (*)(char *AdapterName))GetProcAddress(hDll, "PacketOpenAdapter");
  p_PacketCloseAdapter = (void (*)(LPADAPTER lpAdapter))GetProcAddress(hDll, "PacketCloseAdapter");
  p_PacketRequest = (int (*)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData))GetProcAddress(hDll, "PacketRequest");
#else
  hDll = dlopen("packet.dll", RTLD_NOW);
  p_PacketOpenAdapter = (LPADAPTER (*)(char *AdapterName))dlsym(hDll, "PacketOpenAdapter");
  p_PacketCloseAdapter = (void (*)(LPADAPTER lpAdapter))dlsym(hDll, "PacketCloseAdapter");
  p_PacketRequest = (int (*)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData))dlsym(hDll, "PacketRequest");
#endif
  
  /* Open the selected adapter */

  lpAdapter =   p_PacketOpenAdapter(AdapterName);







|











|





|




|







1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
    uint8 Data[1];              ///< variable-lenght field that contains the information passed to or received 
                                ///< from the adapter.
}; 
typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA;
typedef void **LPADAPTER;
#define OID_802_3_CURRENT_ADDRESS               0x01010102 /* Extracted from ntddmdis.h */

static int pcap_mac_if_win32(const char *AdapterName, unsigned char MACAddress[6])
{
  LPADAPTER         lpAdapter;
  PPACKET_OID_DATA  OidData;
  int               Status;
  int               ReturnValue;
#ifdef _WIN32
  HMODULE           hDll;         /* handle to DLL */
#else
  static void       *hDll = NULL; /* handle to Library */
  typedef int BOOLEAN;
#endif
  LPADAPTER (*p_PacketOpenAdapter)(const char *AdapterName);
  void (*p_PacketCloseAdapter)(LPADAPTER lpAdapter);
  int (*p_PacketRequest)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData);

#ifdef _WIN32
  hDll = LoadLibraryA("packet.dll");
  p_PacketOpenAdapter = (LPADAPTER (*)(const char *AdapterName))GetProcAddress(hDll, "PacketOpenAdapter");
  p_PacketCloseAdapter = (void (*)(LPADAPTER lpAdapter))GetProcAddress(hDll, "PacketCloseAdapter");
  p_PacketRequest = (int (*)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData))GetProcAddress(hDll, "PacketRequest");
#else
  hDll = dlopen("packet.dll", RTLD_NOW);
  p_PacketOpenAdapter = (LPADAPTER (*)(const char *AdapterName))dlsym(hDll, "PacketOpenAdapter");
  p_PacketCloseAdapter = (void (*)(LPADAPTER lpAdapter))dlsym(hDll, "PacketCloseAdapter");
  p_PacketRequest = (int (*)(LPADAPTER  AdapterObject,BOOLEAN Set,PPACKET_OID_DATA  OidData))dlsym(hDll, "PacketRequest");
#endif
  
  /* Open the selected adapter */

  lpAdapter =   p_PacketOpenAdapter(AdapterName);
1330
1331
1332
1333
1334
1335
1336

1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
#ifdef _WIN32
  FreeLibrary(hDll);
#else
  dlclose(hDll);
#endif
  return ReturnValue;
}

#endif  /* defined(_WIN32) || defined(__CYGWIN__) */

#if defined (__VMS) && !defined(__VAX)
#include <descrip.h>
#include <iodef.h>
#include <ssdef.h>
#include <starlet.h>
#include <stdio.h>
#include <stsdef.h>
#include <nmadef.h>

static int pcap_mac_if_vms(char *AdapterName, unsigned char MACAddress[6])
{
  char VMS_Device[16];
  $DESCRIPTOR(Device, VMS_Device);
  unsigned short iosb[4];
  unsigned short *w;
  unsigned char *pha = NULL;
  unsigned char *hwa = NULL;







>











|







1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
#ifdef _WIN32
  FreeLibrary(hDll);
#else
  dlclose(hDll);
#endif
  return ReturnValue;
}

#endif  /* defined(_WIN32) || defined(__CYGWIN__) */

#if defined (__VMS) && !defined(__VAX)
#include <descrip.h>
#include <iodef.h>
#include <ssdef.h>
#include <starlet.h>
#include <stdio.h>
#include <stsdef.h>
#include <nmadef.h>

static int pcap_mac_if_vms(const char *AdapterName, unsigned char MACAddress[6])
{
  char VMS_Device[16];
  $DESCRIPTOR(Device, VMS_Device);
  unsigned short iosb[4];
  unsigned short *w;
  unsigned char *pha = NULL;
  unsigned char *hwa = NULL;
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
      memcpy(MACAddress, hwa, 6);
    else
      return -1;
  return 0;
}
#endif /* defined (__VMS) && !defined(__VAX) */

static void eth_get_nic_hw_addr(ETH_DEV* dev, char *devname)
{
  memset(&dev->host_nic_phy_hw_addr, 0, sizeof(dev->host_nic_phy_hw_addr));
  dev->have_host_nic_phy_addr = 0;
  if (dev->eth_api != ETH_API_PCAP)
    return;
#if defined(_WIN32) || defined(__CYGWIN__)
  if (!pcap_mac_if_win32(devname, dev->host_nic_phy_hw_addr))







|







1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
      memcpy(MACAddress, hwa, 6);
    else
      return -1;
  return 0;
}
#endif /* defined (__VMS) && !defined(__VAX) */

static void eth_get_nic_hw_addr(ETH_DEV* dev, const char *devname)
{
  memset(&dev->host_nic_phy_hw_addr, 0, sizeof(dev->host_nic_phy_hw_addr));
  dev->have_host_nic_phy_addr = 0;
  if (dev->eth_api != ETH_API_PCAP)
    return;
#if defined(_WIN32) || defined(__CYGWIN__)
  if (!pcap_mac_if_win32(devname, dev->host_nic_phy_hw_addr))
1480
1481
1482
1483
1484
1485
1486

































































1487
1488
1489
1490
1491
1492
1493
1494
1495
1496











1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526

1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549








1550
1551
1552
1553
1554
1555
1556
1557
1558
1559

1560
1561
1562

1563
1564
1565
1566
1567
1568
1569
        fclose(f);
        remove("NIC.hwaddr");
        }
      }
    }
#endif
}


































































/* Forward declarations */
static void
_eth_callback(u_char* info, const struct pcap_pkthdr* header, const u_char* data);

static t_stat
_eth_write(ETH_DEV* dev, ETH_PACK* packet, ETH_PCALLBACK routine);

static void
_eth_error(ETH_DEV* dev, const char* where);












#if defined (USE_READER_THREAD)
#include <pthread.h>

static void *
_eth_reader(void *arg)
{
ETH_DEV* volatile dev = (ETH_DEV*)arg;
int status = 0;
int sched_policy;
struct sched_param sched_priority;
int sel_ret = 0;
int do_select = 0;
SOCKET select_fd = 0;
#if defined (_WIN32)
HANDLE hWait = (dev->eth_api == ETH_API_PCAP) ? pcap_getevent ((pcap_t*)dev->handle) : NULL;
#endif

switch (dev->eth_api) {
  case ETH_API_PCAP:
#if defined (HAVE_PCAP_NETWORK)
#if defined (MUST_DO_SELECT)
    do_select = 1;
    select_fd = pcap_get_selectable_fd((pcap_t *)dev->handle);
#endif
#endif
    break;
  case ETH_API_TAP:
  case ETH_API_VDE:
  case ETH_API_UDP:

    do_select = 1;
    select_fd = dev->fd_handle;
    break;
  }

sim_debug(dev->dbit, dev->dptr, "Reader Thread Starting\n");

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which in general won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

while (dev->handle) {
#if defined (_WIN32)
  if (dev->eth_api == ETH_API_PCAP) {
    if (WAIT_OBJECT_0 == WaitForSingleObject (hWait, 250))
      sel_ret = 1;
    }
  if (dev->eth_api == ETH_API_UDP)
#endif /* _WIN32 */
  if (1) {








    fd_set setl;
    struct timeval timeout;

    if (do_select) {
      FD_ZERO(&setl);
      FD_SET(select_fd, &setl);
      timeout.tv_sec = 0;
      timeout.tv_usec = 250*1000;
      sel_ret = select(1+select_fd, &setl, NULL, NULL, &timeout);
      }

    else
      sel_ret = 1;
    if (sel_ret < 0 && errno != EINTR) break;

    }
  if (sel_ret > 0) {
    if (!dev->handle)
      break;
    /* dispatch read request queue available packets */
    switch (dev->eth_api) {
#ifdef HAVE_PCAP_NETWORK







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










>
>
>
>
>
>
>
>
>
>
>









<
<



















>








|
|
<
|
<







|


>
>
>
>
>
>
>
>
|
|
|
<
|
|
|
|
|
|
>


|
>







1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704


1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734

1735

1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756

1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
        fclose(f);
        remove("NIC.hwaddr");
        }
      }
    }
#endif
}

#if defined(__APPLE__)
#include <uuid/uuid.h>
#include <unistd.h>
static int _eth_get_system_id (char *buf, size_t buf_size)
{
static struct timespec wait = {5, 0};   /* 5 seconds */
static uuid_t uuid;

memset (buf, 0, buf_size);
if (buf_size < 37)
  return -1;
if (gethostuuid (uuid, &wait))
  memset (uuid, 0, sizeof(uuid));
uuid_unparse_lower(uuid, buf);
return 0;
}

#elif defined(_WIN32)
static int _eth_get_system_id (char *buf, size_t buf_size)
{
  LONG status;
  DWORD reglen, regtype;
  HKEY reghnd;

  memset (buf, 0, buf_size);
#ifndef KEY_WOW64_64KEY
#define KEY_WOW64_64KEY         (0x0100)
#endif
  if ((status = RegOpenKeyExA (HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_QUERY_VALUE|KEY_WOW64_64KEY, &reghnd)) != ERROR_SUCCESS)
    return -1;
  reglen = buf_size;
  if ((status = RegQueryValueExA (reghnd, "MachineGuid", NULL, &regtype, buf, &reglen)) != ERROR_SUCCESS) {
    RegCloseKey (reghnd);
    return -1;
    }
  RegCloseKey (reghnd );
  /* make sure value is the right type, bail if not acceptable */
  if ((regtype != REG_SZ) || (reglen > buf_size))
    return -1;
  /* registry value seems OK */
  return 0;
}

#else
static int _eth_get_system_id (char *buf, size_t buf_size)
{
FILE *f;

memset (buf, 0, buf_size);
if ((f = fopen ("/etc/machine-id", "r"))) {
  fread (buf, 1, buf_size, f);
  fclose (f);
  }
else {
  if ((f = popen ("hostname", "r"))) {
    fread (buf, 1, buf_size, f);
    pclose (f);
    }
  }
while ((strlen (buf) > 0) && sim_isspace(buf[strlen (buf) - 1]))
  buf[strlen (buf) - 1] = '\0';
return 0;
}
#endif

/* Forward declarations */
static void
_eth_callback(u_char* info, const struct pcap_pkthdr* header, const u_char* data);

static t_stat
_eth_write(ETH_DEV* dev, ETH_PACK* packet, ETH_PCALLBACK routine);

static void
_eth_error(ETH_DEV* dev, const char* where);

#if defined(HAVE_SLIRP_NETWORK)
static void _slirp_callback (void *opaque, const unsigned char *buf, int len)
{
struct pcap_pkthdr header;

memset(&header, 0, sizeof(header));
header.caplen = header.len = len;
_eth_callback((u_char *)opaque, &header, buf);
}
#endif

#if defined (USE_READER_THREAD)
#include <pthread.h>

static void *
_eth_reader(void *arg)
{
ETH_DEV* volatile dev = (ETH_DEV*)arg;
int status = 0;


int sel_ret = 0;
int do_select = 0;
SOCKET select_fd = 0;
#if defined (_WIN32)
HANDLE hWait = (dev->eth_api == ETH_API_PCAP) ? pcap_getevent ((pcap_t*)dev->handle) : NULL;
#endif

switch (dev->eth_api) {
  case ETH_API_PCAP:
#if defined (HAVE_PCAP_NETWORK)
#if defined (MUST_DO_SELECT)
    do_select = 1;
    select_fd = pcap_get_selectable_fd((pcap_t *)dev->handle);
#endif
#endif
    break;
  case ETH_API_TAP:
  case ETH_API_VDE:
  case ETH_API_UDP:
  case ETH_API_NAT:
    do_select = 1;
    select_fd = dev->fd_handle;
    break;
  }

sim_debug(dev->dbit, dev->dptr, "Reader Thread Starting\n");

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor 
   when this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


while (dev->handle) {
#if defined (_WIN32)
  if (dev->eth_api == ETH_API_PCAP) {
    if (WAIT_OBJECT_0 == WaitForSingleObject (hWait, 250))
      sel_ret = 1;
    }
  if ((dev->eth_api == ETH_API_UDP) || (dev->eth_api == ETH_API_NAT))
#endif /* _WIN32 */
  if (1) {
    if (do_select) {
#ifdef HAVE_SLIRP_NETWORK
      if (dev->eth_api == ETH_API_NAT) {
        sel_ret = sim_slirp_select ((SLIRP*)dev->handle, 250);
        }
      else
#endif
        {
        fd_set setl;
        struct timeval timeout;
        

        FD_ZERO(&setl);
        FD_SET(select_fd, &setl);
        timeout.tv_sec = 0;
        timeout.tv_usec = 250*1000;
        sel_ret = select(1+select_fd, &setl, NULL, NULL, &timeout);
        }
      }
    else
      sel_ret = 1;
    if (sel_ret < 0 && errno != EINTR) 
      break;
    }
  if (sel_ret > 0) {
    if (!dev->handle)
      break;
    /* dispatch read request queue available packets */
    switch (dev->eth_api) {
#ifdef HAVE_PCAP_NETWORK
1613
1614
1615
1616
1617
1618
1619






1620
1621
1622
1623
1624
1625
1626
              status = -1;
            else
              status = 0;
            }
          }
        break;
#endif /* HAVE_VDE_NETWORK */






      case ETH_API_UDP:
        if (1) {
          struct pcap_pkthdr header;
          int len;
          u_char buf[ETH_MAX_JUMBO_FRAME];

          memset(&header, 0, sizeof(header));







>
>
>
>
>
>







1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
              status = -1;
            else
              status = 0;
            }
          }
        break;
#endif /* HAVE_VDE_NETWORK */
#ifdef HAVE_SLIRP_NETWORK
      case ETH_API_NAT:
        sim_slirp_dispatch ((SLIRP*)dev->handle);
        status = 1;
        break;
#endif /* HAVE_SLIRP_NETWORK */
      case ETH_API_UDP:
        if (1) {
          struct pcap_pkthdr header;
          int len;
          u_char buf[ETH_MAX_JUMBO_FRAME];

          memset(&header, 0, sizeof(header));
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
return NULL;
}

static void *
_eth_writer(void *arg)
{
ETH_DEV* volatile dev = (ETH_DEV*)arg;
struct write_request *request;
int sched_policy;
struct sched_param sched_priority;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which in general won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug(dev->dbit, dev->dptr, "Writer Thread Starting\n");

pthread_mutex_lock (&dev->writer_lock);
while (dev->handle) {
  pthread_cond_wait (&dev->writer_cond, &dev->writer_lock);
  while (NULL != (request = dev->write_requests)) {







|
<
<




<
|
<







1884
1885
1886
1887
1888
1889
1890
1891


1892
1893
1894
1895

1896

1897
1898
1899
1900
1901
1902
1903
return NULL;
}

static void *
_eth_writer(void *arg)
{
ETH_DEV* volatile dev = (ETH_DEV*)arg;
ETH_WRITE_REQUEST *request;



/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which in general won't be readily yielding the processor when 
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug(dev->dbit, dev->dptr, "Writer Thread Starting\n");

pthread_mutex_lock (&dev->writer_lock);
while (dev->handle) {
  pthread_cond_wait (&dev->writer_cond, &dev->writer_lock);
  while (NULL != (request = dev->write_requests)) {
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787

1788


1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
dev->throttle_time = time;
dev->throttle_burst = burst;
dev->throttle_delay = delay;
dev->throttle_mask = (1 << dev->throttle_burst) - 1;
return SCPE_OK;
}

static t_stat _eth_open_port(char *savname, int *eth_api, void **handle, SOCKET *fd_handle, char errbuf[PCAP_ERRBUF_SIZE], char *bpf_filter)
{
int bufsz = (BUFSIZ < ETH_MAX_PACKET) ? ETH_MAX_PACKET : BUFSIZ;

if (bufsz < ETH_MAX_JUMBO_FRAME)
  bufsz = ETH_MAX_JUMBO_FRAME;    /* Enable handling of jumbo frames */

*eth_api = 0;
*handle = NULL;
*fd_handle = 0;

/* attempt to connect device */
memset(errbuf, 0, PCAP_ERRBUF_SIZE);
if (0 == strncmp("tap:", savname, 4)) {
  int  tun = -1;    /* TUN/TAP Socket */
  int  on = 1;




#if defined(HAVE_TAP_NETWORK)
  if (!strcmp(savname, "tap:tapN")) {
    sim_printf ("Eth: Must specify actual tap device name (i.e. tap:tap0)\r\n");
    return SCPE_OPENERR;
    }
#endif
#if (defined(__linux) || defined(__linux__)) && defined(HAVE_TAP_NETWORK)
  if ((tun = open("/dev/net/tun", O_RDWR)) >= 0) {
    struct ifreq ifr; /* Interface Requests */

    memset(&ifr, 0, sizeof(ifr));
    /* Set up interface flags */
    strcpy(ifr.ifr_name, savname+4);
    ifr.ifr_flags = IFF_TAP|IFF_NO_PI;

    /* Send interface requests to TUN/TAP driver. */
    if (ioctl(tun, TUNSETIFF, &ifr) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);







|















>

>
>



|








|







1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
dev->throttle_time = time;
dev->throttle_burst = burst;
dev->throttle_delay = delay;
dev->throttle_mask = (1 << dev->throttle_burst) - 1;
return SCPE_OK;
}

static t_stat _eth_open_port(char *savname, int *eth_api, void **handle, SOCKET *fd_handle, char errbuf[PCAP_ERRBUF_SIZE], char *bpf_filter, void *opaque, DEVICE *dptr, uint32 dbit)
{
int bufsz = (BUFSIZ < ETH_MAX_PACKET) ? ETH_MAX_PACKET : BUFSIZ;

if (bufsz < ETH_MAX_JUMBO_FRAME)
  bufsz = ETH_MAX_JUMBO_FRAME;    /* Enable handling of jumbo frames */

*eth_api = 0;
*handle = NULL;
*fd_handle = 0;

/* attempt to connect device */
memset(errbuf, 0, PCAP_ERRBUF_SIZE);
if (0 == strncmp("tap:", savname, 4)) {
  int  tun = -1;    /* TUN/TAP Socket */
  int  on = 1;
  const char *devname = savname + 4;

  while (isspace(*devname))
      ++devname;
#if defined(HAVE_TAP_NETWORK)
  if (!strcmp(savname, "tap:tapN")) {
    sim_printf ("Eth: Must specify actual tap device name (i.e. tap:tap0)\r\n");
    return SCPE_OPENERR | SCPE_NOMESSAGE;
    }
#endif
#if (defined(__linux) || defined(__linux__)) && defined(HAVE_TAP_NETWORK)
  if ((tun = open("/dev/net/tun", O_RDWR)) >= 0) {
    struct ifreq ifr; /* Interface Requests */

    memset(&ifr, 0, sizeof(ifr));
    /* Set up interface flags */
    strcpy(ifr.ifr_name, devname);
    ifr.ifr_flags = IFF_TAP|IFF_NO_PI;

    /* Send interface requests to TUN/TAP driver. */
    if (ioctl(tun, TUNSETIFF, &ifr) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
    }
  else
    strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
#elif defined(HAVE_BSDTUNTAP) && defined(HAVE_TAP_NETWORK)
  if (1) {
    char dev_name[64] = "";

    snprintf(dev_name, sizeof(dev_name)-1, "/dev/%s", savname+4);
    dev_name[sizeof(dev_name)-1] = '\0';

    if ((tun = open(dev_name, O_RDWR)) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, savname+4);
        }
#if defined (__APPLE__)
      if (1) {
        struct ifreq ifr;
        int s;

        memset (&ifr, 0, sizeof(ifr));







|









|







2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
    }
  else
    strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
#elif defined(HAVE_BSDTUNTAP) && defined(HAVE_TAP_NETWORK)
  if (1) {
    char dev_name[64] = "";

    snprintf(dev_name, sizeof(dev_name)-1, "/dev/%s", devname);
    dev_name[sizeof(dev_name)-1] = '\0';

    if ((tun = open(dev_name, O_RDWR)) >= 0) {
      if (ioctl(tun, FIONBIO, &on)) {
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
        close(tun);
        }
      else {
        *fd_handle = tun;
        strcpy(savname, devname);
        }
#if defined (__APPLE__)
      if (1) {
        struct ifreq ifr;
        int s;

        memset (&ifr, 0, sizeof(ifr));
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871

1872
1873
1874
1875
1876
1877


1878
1879
1880
1881
1882
1883
1884
1885
1886
1887









1888








1889
1890
1891

1892
1893
1894
1895
1896
1897


1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955

1956
1957

1958
1959
1960
1961
1962
1963
1964
  strncpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE-1);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }
  }
else
  if (0 == strncmp("vde:", savname, 4)) {
#if defined(HAVE_VDE_NETWORK)
    struct vde_open_args voa;


    memset(&voa, 0, sizeof(voa));
    if (!strcmp(savname, "vde:vdedevice")) {
      sim_printf ("Eth: Must specify actual vde device name (i.e. vde:/tmp/switch)\r\n", errbuf);
      return SCPE_OPENERR;
      }


    if (!(*handle = (void*) vde_open(savname+4, "simh", &voa)))
      strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = vde_datafd((VDECONN*)(*handle));
      }
#else
    strncpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_VDE_NETWORK) */
    }









  else {








    if (0 == strncmp("udp:", savname, 4)) {
      char localport[CBUFSIZE], host[CBUFSIZE], port[CBUFSIZE];
      char hostport[2*CBUFSIZE];


      if (!strcmp(savname, "udp:sourceport:remotehost:remoteport")) {
        sim_printf ("Eth: Must specify actual udp host and ports(i.e. udp:1224:somehost.com:2234)\r\n");
        return SCPE_OPENERR;
        }



      if (SCPE_OK != sim_parse_addr_ex (savname+4, host, sizeof(host), "localhost", port, sizeof(port), localport, sizeof(localport), NULL))
        return SCPE_OPENERR;

      if (localport[0] == '\0')
        strcpy (localport, port);
      sprintf (hostport, "%s:%s", host, port);
      if ((SCPE_OK == sim_parse_addr (hostport, NULL, 0, NULL, NULL, 0, NULL, "localhost")) &&
          (0 == strcmp (localport, port))) {
        sim_printf ("Eth: Must specify different udp localhost ports\r\n");
        return SCPE_OPENERR;
        }
      *fd_handle = sim_connect_sock_ex (localport, hostport, NULL, NULL, SIM_SOCK_OPT_DATAGRAM);
      if (INVALID_SOCKET == *fd_handle)
          return SCPE_OPENERR;
      *eth_api = ETH_API_UDP;
      *handle = (void *)1;  /* Flag used to indicated open */
      }
    else {
#if defined(HAVE_PCAP_NETWORK)
      *handle = (void*) pcap_open_live(savname, bufsz, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
      if (!*handle) { /* can't open device */
        sim_printf ("Eth: pcap_open_live error - %s\r\n", errbuf);
        return SCPE_OPENERR;
        }
      *eth_api = ETH_API_PCAP;
#if !defined(HAS_PCAP_SENDPACKET) && defined (xBSD) && !defined (__APPLE__)
      /* Tell the kernel that the header is fully-formed when it gets it.
         This is required in order to fake the src address. */
      if (1) {
        int one = 1;
        ioctl(pcap_fileno(*handle), BIOCSHDRCMPLT, &one);
        }
#endif /* xBSD */
#if defined(_WIN32)
      pcap_setmintocopy ((pcap_t*)(*handle), 0);
#endif
#if !defined (USE_READER_THREAD)
#ifdef USE_SETNONBLOCK
/* set ethernet device non-blocking so pcap_dispatch() doesn't hang */
      if (pcap_setnonblock (*handle, 1, errbuf) == -1) {
        sim_printf ("Eth: Failed to set non-blocking: %s\r\n", errbuf);
        }
#endif
#if defined (__APPLE__)
      if (1) {
        /* Deliver packets immediately, needed for OS X 10.6.2 and later
         * (Snow-Leopard).
         * See this thread on libpcap and Mac Os X 10.6 Snow Leopard on
         * the tcpdump mailinglist: http://seclists.org/tcpdump/2010/q1/110
         */
        int v = 1;
        ioctl(pcap_fileno(*handle), BIOCIMMEDIATE, &v);
        }
#endif /* defined (__APPLE__) */
#endif /* !defined (USE_READER_THREAD) */
#else
      strncpy (errbuf, "Unknown or unsupported network device", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_PCAP_NETWORK) */

      }
    }

if (errbuf[0])
  return SCPE_OPENERR;

#ifdef USE_BPF
if (bpf_filter && (*eth_api == ETH_API_PCAP)) {
  struct bpf_program bpf;
  int status;







|



>



|
|

>
>
|









>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
|
|
|
>

|
|
|
|

>
>
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|

|
|
|
|
|
|


|



|
|
|
|


|
|
|
|
|
|
|
|
|



|

>
|
|
>







2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
  strncpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE-1);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }
  }
else { /* !tap: */
  if (0 == strncmp("vde:", savname, 4)) {
#if defined(HAVE_VDE_NETWORK)
    struct vde_open_args voa;
    const char *devname = savname + 4;

    memset(&voa, 0, sizeof(voa));
    if (!strcmp(savname, "vde:vdedevice")) {
      sim_printf ("Eth: Must specify actual vde device name (i.e. vde:/tmp/switch)\r\n");
      return SCPE_OPENERR | SCPE_NOMESSAGE;
      }
    while (isspace(*devname))
        ++devname;
    if (!(*handle = (void*) vde_open((char *)devname, (char *)"simh", &voa)))
      strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = vde_datafd((VDECONN*)(*handle));
      }
#else
    strncpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_VDE_NETWORK) */
    }
  else { /* !vde: */
    if (0 == strncmp("nat:", savname, 4)) {
#if defined(HAVE_SLIRP_NETWORK)
      const char *devname = savname + 4;

      while (isspace(*devname))
          ++devname;
      if (!(*handle = (void*) sim_slirp_open(devname, opaque, &_slirp_callback, dptr, dbit)))
        strncpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE-1);
      else {
        *eth_api = ETH_API_NAT;
        *fd_handle = 0;
        }
#else
      strncpy(errbuf, "No support for nat: network devices", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_SLIRP_NETWORK) */
      }
    else { /* not nat: */
      if (0 == strncmp("udp:", savname, 4)) {
        char localport[CBUFSIZE], host[CBUFSIZE], port[CBUFSIZE];
        char hostport[2*CBUFSIZE];
        const char *devname = savname + 4;

        if (!strcmp(savname, "udp:sourceport:remotehost:remoteport")) {
          sim_printf ("Eth: Must specify actual udp host and ports(i.e. udp:1224:somehost.com:2234)\r\n");
          return SCPE_OPENERR | SCPE_NOMESSAGE;
          }

        while (isspace(*devname))
            ++devname;
        if (SCPE_OK != sim_parse_addr_ex (devname, host, sizeof(host), "localhost", port, sizeof(port), localport, sizeof(localport), NULL))
          return SCPE_OPENERR;

        if (localport[0] == '\0')
          strcpy (localport, port);
        sprintf (hostport, "%s:%s", host, port);
        if ((SCPE_OK == sim_parse_addr (hostport, NULL, 0, NULL, NULL, 0, NULL, "localhost")) &&
            (0 == strcmp (localport, port))) {
          sim_printf ("Eth: Must specify different udp localhost ports\r\n");
          return SCPE_OPENERR | SCPE_NOMESSAGE;
          }
        *fd_handle = sim_connect_sock_ex (localport, hostport, NULL, NULL, SIM_SOCK_OPT_DATAGRAM);
        if (INVALID_SOCKET == *fd_handle)
            return SCPE_OPENERR;
        *eth_api = ETH_API_UDP;
        *handle = (void *)1;  /* Flag used to indicated open */
        }
      else { /* not udp:, so attempt to open the parameter as if it were an explicit device name */
#if defined(HAVE_PCAP_NETWORK)
        *handle = (void*) pcap_open_live(savname, bufsz, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
        if (!*handle) { /* can't open device */
          sim_printf ("Eth: pcap_open_live error - %s\r\n", errbuf);
          return SCPE_OPENERR | SCPE_NOMESSAGE;
          }
        *eth_api = ETH_API_PCAP;
#if !defined(HAS_PCAP_SENDPACKET) && defined (xBSD) && !defined (__APPLE__)
        /* Tell the kernel that the header is fully-formed when it gets it.
           This is required in order to fake the src address. */
        if (1) {
          int one = 1;
          ioctl(pcap_fileno(*handle), BIOCSHDRCMPLT, &one);
          }
#endif /* xBSD */
#if defined(_WIN32)
        pcap_setmintocopy ((pcap_t*)(*handle), 0);
#endif
#if !defined (USE_READER_THREAD)
#ifdef USE_SETNONBLOCK
        /* set ethernet device non-blocking so pcap_dispatch() doesn't hang */
        if (pcap_setnonblock (*handle, 1, errbuf) == -1) {
          sim_printf ("Eth: Failed to set non-blocking: %s\r\n", errbuf);
          }
#endif
#if defined (__APPLE__)
        if (1) {
          /* Deliver packets immediately, needed for OS X 10.6.2 and later
           * (Snow-Leopard).
           * See this thread on libpcap and Mac Os X 10.6 Snow Leopard on
           * the tcpdump mailinglist: http://seclists.org/tcpdump/2010/q1/110
           */
          int v = 1;
          ioctl(pcap_fileno(*handle), BIOCIMMEDIATE, &v);
          }
#endif /* defined (__APPLE__) */
#endif /* !defined (USE_READER_THREAD) */
#else
        strncpy (errbuf, "Unknown or unsupported network device", PCAP_ERRBUF_SIZE-1);
#endif /* defined(HAVE_PCAP_NETWORK) */
        } /* not udp:, so attempt to open the parameter as if it were an explicit device name */
      } /* !nat: */
    } /* !vde: */
  } /* !tap: */
if (errbuf[0])
  return SCPE_OPENERR;

#ifdef USE_BPF
if (bpf_filter && (*eth_api == ETH_API_PCAP)) {
  struct bpf_program bpf;
  int status;
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001

2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029


2030
2031
2032



2033
2034
2035
2036
2037
2038
2039
2040
2041


2042
2043
2044
2045
2046
2047
2048
2049
    pcap_freecode(&bpf);
    }
  }
#endif /* USE_BPF */
return SCPE_OK;
}

t_stat eth_open(ETH_DEV* dev, char* name, DEVICE* dptr, uint32 dbit)
{
t_stat r;
int bufsz = (BUFSIZ < ETH_MAX_PACKET) ? ETH_MAX_PACKET : BUFSIZ;
char errbuf[PCAP_ERRBUF_SIZE];
char temp[1024];
char* savname = name;

int   num;

if (bufsz < ETH_MAX_JUMBO_FRAME)
  bufsz = ETH_MAX_JUMBO_FRAME;    /* Enable handling of jumbo frames */

/* initialize device */
eth_zero(dev);

/* translate name of type "ethX" to real device name */
if ((strlen(name) == 4)
    && (tolower(name[0]) == 'e')
    && (tolower(name[1]) == 't')
    && (tolower(name[2]) == 'h')
    && isdigit(name[3])
   ) {
  num = atoi(&name[3]);
  savname = eth_getname(num, temp);
  if (savname == NULL) /* didn't translate */
    return SCPE_OPENERR;
  }
else {
  /* are they trying to use device description? */
  savname = eth_getname_bydesc(name, temp);
  if (savname == NULL) { /* didn't translate */
    /* probably is not ethX and has no description */
    savname = eth_getname_byname(name, temp);
    if (savname == NULL) /* didn't translate */
      savname = name;


    }
  }




r = _eth_open_port(savname, &dev->eth_api, &dev->handle, &dev->fd_handle, errbuf, NULL);

if (errbuf[0]) {
  sim_printf ("Eth: open error - %s\r\n", errbuf);
  return SCPE_OPENERR;
  }
if (r != SCPE_OK)
  return r;



sim_printf ("Eth: opened OS device %s\r\n", savname);

/* get the NIC's hardware MAC address */
eth_get_nic_hw_addr(dev, savname);

/* save name of device */
dev->name = (char *)malloc(strlen(savname)+1);
strcpy(dev->name, savname);







|




|
|
>
















|





|


|
|

>
>



>
>
>
|



|




>
>
|







2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
    pcap_freecode(&bpf);
    }
  }
#endif /* USE_BPF */
return SCPE_OK;
}

t_stat eth_open(ETH_DEV* dev, const char* name, DEVICE* dptr, uint32 dbit)
{
t_stat r;
int bufsz = (BUFSIZ < ETH_MAX_PACKET) ? ETH_MAX_PACKET : BUFSIZ;
char errbuf[PCAP_ERRBUF_SIZE];
char temp[1024], desc[1024] = "";
const char* savname = name;
char namebuf[4*CBUFSIZE];
int   num;

if (bufsz < ETH_MAX_JUMBO_FRAME)
  bufsz = ETH_MAX_JUMBO_FRAME;    /* Enable handling of jumbo frames */

/* initialize device */
eth_zero(dev);

/* translate name of type "ethX" to real device name */
if ((strlen(name) == 4)
    && (tolower(name[0]) == 'e')
    && (tolower(name[1]) == 't')
    && (tolower(name[2]) == 'h')
    && isdigit(name[3])
   ) {
  num = atoi(&name[3]);
  savname = eth_getname(num, temp, desc);
  if (savname == NULL) /* didn't translate */
    return SCPE_OPENERR;
  }
else {
  /* are they trying to use device description? */
  savname = eth_getname_bydesc(name, temp, desc);
  if (savname == NULL) { /* didn't translate */
    /* probably is not ethX and has no description */
    savname = eth_getname_byname(name, temp, desc);
    if (savname == NULL) {/* didn't translate */
      savname = name;
      desc[0] = '\0';   /* no description */
      }
    }
  }

namebuf[sizeof(namebuf)-1] = '\0';
strncpy (namebuf, savname, sizeof(namebuf)-1);
savname = namebuf;
r = _eth_open_port(namebuf, &dev->eth_api, &dev->handle, &dev->fd_handle, errbuf, NULL, (void *)dev, dptr, dbit);

if (errbuf[0]) {
  sim_printf ("Eth: open error - %s\r\n", errbuf);
  return SCPE_OPENERR | SCPE_NOMESSAGE;
  }
if (r != SCPE_OK)
  return r;

if (!strcmp (desc, "No description available"))
    strcpy (desc, "");
sim_printf ("Eth: opened OS device %s%s%s\r\n", savname, desc[0] ? " - " : "", desc);

/* get the NIC's hardware MAC address */
eth_get_nic_hw_addr(dev, savname);

/* save name of device */
dev->name = (char *)malloc(strlen(savname)+1);
strcpy(dev->name, savname);
2095
2096
2097
2098
2099
2100
2101





2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
    close(pcap_fd);
    break;
#endif
#ifdef HAVE_VDE_NETWORK
  case ETH_API_VDE:
    vde_close((VDECONN*)pcap);
    break;





#endif
  case ETH_API_UDP:
    sim_close_sock(pcap_fd);
    break;
#ifdef USE_SLIRP_NETWORK
  case ETH_API_NAT:
    vde_close((VDECONN*)pcap);
    break;
#endif
  }
return SCPE_OK;
}

t_stat eth_close(ETH_DEV* dev)
{
pcap_t *pcap;







>
>
>
>
>




<
<
<
<
<







2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353





2354
2355
2356
2357
2358
2359
2360
    close(pcap_fd);
    break;
#endif
#ifdef HAVE_VDE_NETWORK
  case ETH_API_VDE:
    vde_close((VDECONN*)pcap);
    break;
#endif
#ifdef HAVE_SLIRP_NETWORK
  case ETH_API_NAT:
    sim_slirp_close((SLIRP*)pcap);
    break;
#endif
  case ETH_API_UDP:
    sim_close_sock(pcap_fd);
    break;





  }
return SCPE_OK;
}

t_stat eth_close(ETH_DEV* dev)
{
pcap_t *pcap;
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
pthread_mutex_destroy (&dev->lock);
pthread_cond_signal (&dev->writer_cond);
pthread_join (dev->writer_thread, NULL);
pthread_mutex_destroy (&dev->self_lock);
pthread_mutex_destroy (&dev->writer_lock);
pthread_cond_destroy (&dev->writer_cond);
if (1) {
  struct write_request *buffer;
   while (NULL != (buffer = dev->write_buffers)) {
    dev->write_buffers = buffer->next;
    free(buffer);
    }
  while (NULL != (buffer = dev->write_requests)) {
    dev->write_requests = buffer->next;
    free(buffer);







|







2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
pthread_mutex_destroy (&dev->lock);
pthread_cond_signal (&dev->writer_cond);
pthread_join (dev->writer_thread, NULL);
pthread_mutex_destroy (&dev->self_lock);
pthread_mutex_destroy (&dev->writer_lock);
pthread_cond_destroy (&dev->writer_cond);
if (1) {
  ETH_WRITE_REQUEST *buffer;
   while (NULL != (buffer = dev->write_buffers)) {
    dev->write_buffers = buffer->next;
    free(buffer);
    }
  while (NULL != (buffer = dev->write_requests)) {
    dev->write_requests = buffer->next;
    free(buffer);
2162
2163
2164
2165
2166
2167
2168
2169

2170








2171
2172
2173



2174
2175
2176
2177
2178
2179
2180

t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
fprintf (st, "%s attach help\n\n", dptr->name);
fprintf (st, "   sim> SHOW ETHERNET\n");
fprintf (st, "   libpcap version 1.0.0\n");
fprintf (st, "   ETH devices:\n");
fprintf (st, "    eth0   en0      (No description available)\n");

fprintf (st, "   eth1   tap:tapN (Integrated Tun/Tap support)\n");








fprintf (st, "   sim> ATTACH %s eth0\n\n", dptr->name);
fprintf (st, "or equivalently:\n\n");
fprintf (st, "   sim> ATTACH %s en0\n\n", dptr->name);



return SCPE_OK;
}

static int _eth_rand_byte()
{
static int rand_initialized = 0;








|
>
|
>
>
>
>
>
>
>
>



>
>
>







2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435

t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
fprintf (st, "%s attach help\n\n", dptr->name);
fprintf (st, "   sim> SHOW ETHERNET\n");
fprintf (st, "   libpcap version 1.0.0\n");
fprintf (st, "   ETH devices:\n");
fprintf (st, "    eth0   en0                                  (No description available)\n");
#if defined(HAVE_TAP_NETWORK)
fprintf (st, "    eth1   tap:tapN                             (Integrated Tun/Tap support)\n");
#endif
#if defined(HAVE_SLIRP_NETWORK)
fprintf (st, "    eth2   vde:device                           (Integrated VDE support)\n");
#endif
#if defined(HAVE_SLIRP_NETWORK)
fprintf (st, "    eth3   nat:{optional-nat-parameters}        (Integrated NAT (SLiRP) support)\n");
#endif
fprintf (st, "    eth4   udp:sourceport:remotehost:remoteport (Integrated UDP bridge support)\n");
fprintf (st, "   sim> ATTACH %s eth0\n\n", dptr->name);
fprintf (st, "or equivalently:\n\n");
fprintf (st, "   sim> ATTACH %s en0\n\n", dptr->name);
#if defined(HAVE_SLIRP_NETWORK)
sim_slirp_attach_help (st, dptr, uptr, flag, cptr);
#endif
return SCPE_OK;
}

static int _eth_rand_byte()
{
static int rand_initialized = 0;

2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
send.msg[25] = 0;

eth_filter(dev, 1, (ETH_MAC *)mac, 0, 0);

/* send the packet */
status = _eth_write (dev, &send, NULL);
if (status != SCPE_OK) {
  char *msg;
  msg = (dev->eth_api == ETH_API_PCAP) ?
      "Eth: Error Transmitting packet: %s\r\n"
        "You may need to run as root, or install a libpcap version\r\n"
        "which is at least 0.9 from your OS vendor or www.tcpdump.org\r\n" :
      "Eth: Error Transmitting packet: %s\r\n"
        "You may need to run as root.\r\n";
  sim_printf(msg, strerror(errno));







|







2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
send.msg[25] = 0;

eth_filter(dev, 1, (ETH_MAC *)mac, 0, 0);

/* send the packet */
status = _eth_write (dev, &send, NULL);
if (status != SCPE_OK) {
  const char *msg;
  msg = (dev->eth_api == ETH_API_PCAP) ?
      "Eth: Error Transmitting packet: %s\r\n"
        "You may need to run as root, or install a libpcap version\r\n"
        "which is at least 0.9 from your OS vendor or www.tcpdump.org\r\n" :
      "Eth: Error Transmitting packet: %s\r\n"
        "You may need to run as root.\r\n";
  sim_printf(msg, strerror(errno));
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
#endif
  char errbuf[PCAP_ERRBUF_SIZE];
  t_stat r;

  _eth_close_port(dev->eth_api, (pcap_t *)dev->handle, dev->fd_handle);
  sim_os_sleep (ETH_ERROR_REOPEN_PAUSE);

  r = _eth_open_port(dev->name, &dev->eth_api, &dev->handle, &dev->fd_handle, errbuf, dev->bpf_filter);
  dev->error_needs_reset = FALSE;
  if (r == SCPE_OK)
    sim_printf ("%s ReOpened: %s \n", msg, dev->name);
  else
    sim_printf ("%s ReOpen Attempt Failed: %s - %s\n", msg, dev->name, errbuf);
  ++dev->error_reopen_count;
  }







|







2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
#endif
  char errbuf[PCAP_ERRBUF_SIZE];
  t_stat r;

  _eth_close_port(dev->eth_api, (pcap_t *)dev->handle, dev->fd_handle);
  sim_os_sleep (ETH_ERROR_REOPEN_PAUSE);

  r = _eth_open_port(dev->name, &dev->eth_api, &dev->handle, &dev->fd_handle, errbuf, dev->bpf_filter, (void *)dev, dev->dptr, dev->dbit);
  dev->error_needs_reset = FALSE;
  if (r == SCPE_OK)
    sim_printf ("%s ReOpened: %s \n", msg, dev->name);
  else
    sim_printf ("%s ReOpen Attempt Failed: %s - %s\n", msg, dev->name, errbuf);
  ++dev->error_reopen_count;
  }
2469
2470
2471
2472
2473
2474
2475









2476
2477
2478
2479
2480
2481
2482
        status = 0;
      else
        if ((status == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
          status = 0;
        else
          status = 1;
      break;









#endif
    case ETH_API_UDP:
      status = (((int32)packet->len == sim_write_sock (dev->fd_handle, (char *)packet->msg, (int32)packet->len)) ? 0 : -1);
      break;
    }
  ++dev->packets_sent;              /* basic bookkeeping */
  /* On error, correct loopback bookkeeping */







>
>
>
>
>
>
>
>
>







2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
        status = 0;
      else
        if ((status == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
          status = 0;
        else
          status = 1;
      break;
#endif
#ifdef HAVE_SLIRP_NETWORK
    case ETH_API_NAT:
      status = sim_slirp_send((SLIRP*)dev->handle, (char *)packet->msg, (size_t)packet->len, 0);
      if ((status == (int)packet->len) || (status == 0))
        status = 0;
      else
        status = 1;
      break;
#endif
    case ETH_API_UDP:
      status = (((int32)packet->len == sim_write_sock (dev->fd_handle, (char *)packet->msg, (int32)packet->len)) ? 0 : -1);
      break;
    }
  ++dev->packets_sent;              /* basic bookkeeping */
  /* On error, correct loopback bookkeeping */
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543

return ((status == 0) ? SCPE_OK : SCPE_IOERR);
}

t_stat eth_write(ETH_DEV* dev, ETH_PACK* packet, ETH_PCALLBACK routine)
{
#ifdef USE_READER_THREAD
struct write_request *request;
int write_queue_size = 1;

/* make sure device exists */
if ((!dev) || (dev->eth_api == ETH_API_NONE)) return SCPE_UNATT;

/* Get a buffer */
pthread_mutex_lock (&dev->writer_lock);
if (NULL != (request = dev->write_buffers))
  dev->write_buffers = request->next;
pthread_mutex_unlock (&dev->writer_lock);
if (NULL == request)
  request = (struct write_request *)malloc(sizeof(*request));

/* Copy buffer contents */
request->packet.len = packet->len;
request->packet.used = packet->used;
request->packet.status = packet->status;
request->packet.crc_len = packet->crc_len;
memcpy(request->packet.msg, packet->msg, packet->len);

/* Insert buffer at the end of the write list (to make sure that */
/* packets make it to the wire in the order they were presented here) */
pthread_mutex_lock (&dev->writer_lock);
request->next = NULL;
if (dev->write_requests) {
  struct write_request *last_request = dev->write_requests;

  ++write_queue_size;
  while (last_request->next) {
    last_request = last_request->next;
    ++write_queue_size;
    }
  last_request->next = request;







|











|













|







2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807

return ((status == 0) ? SCPE_OK : SCPE_IOERR);
}

t_stat eth_write(ETH_DEV* dev, ETH_PACK* packet, ETH_PCALLBACK routine)
{
#ifdef USE_READER_THREAD
ETH_WRITE_REQUEST *request;
int write_queue_size = 1;

/* make sure device exists */
if ((!dev) || (dev->eth_api == ETH_API_NONE)) return SCPE_UNATT;

/* Get a buffer */
pthread_mutex_lock (&dev->writer_lock);
if (NULL != (request = dev->write_buffers))
  dev->write_buffers = request->next;
pthread_mutex_unlock (&dev->writer_lock);
if (NULL == request)
  request = (ETH_WRITE_REQUEST *)malloc(sizeof(*request));

/* Copy buffer contents */
request->packet.len = packet->len;
request->packet.used = packet->used;
request->packet.status = packet->status;
request->packet.crc_len = packet->crc_len;
memcpy(request->packet.msg, packet->msg, packet->len);

/* Insert buffer at the end of the write list (to make sure that */
/* packets make it to the wire in the order they were presented here) */
pthread_mutex_lock (&dev->writer_lock);
request->next = NULL;
if (dev->write_requests) {
  ETH_WRITE_REQUEST *last_request = dev->write_requests;

  ++write_queue_size;
  while (last_request->next) {
    last_request = last_request->next;
    ++write_queue_size;
    }
  last_request->next = request;
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
sum += (sum >> 16);
    
/* Return the bitwise complement of the resulting mishmash  */
return (uint16)(~sum);
}

static void
_eth_fix_ip_jumbo_offload(ETH_DEV* dev, const u_char* msg, int len)
{
unsigned short* proto = (unsigned short*) &msg[12];
struct IPHeader *IP;
struct TCPHeader *TCP = NULL;
struct UDPHeader *UDP;
struct ICMPHeader *ICMP;
uint16 orig_checksum;
uint16 payload_len;
uint16 mtu_payload;







|

|







3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
sum += (sum >> 16);
    
/* Return the bitwise complement of the resulting mishmash  */
return (uint16)(~sum);
}

static void
_eth_fix_ip_jumbo_offload(ETH_DEV* dev, u_char* msg, int len)
{
const unsigned short* proto = (const unsigned short*) &msg[12];
struct IPHeader *IP;
struct TCPHeader *TCP = NULL;
struct UDPHeader *UDP;
struct ICMPHeader *ICMP;
uint16 orig_checksum;
uint16 payload_len;
uint16 mtu_payload;
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
    break;
  }
}

static void
_eth_fix_ip_xsum_offload(ETH_DEV* dev, const u_char* msg, int len)
{
unsigned short* proto = (unsigned short*) &msg[12];
struct IPHeader *IP;
struct TCPHeader *TCP;
struct UDPHeader *UDP;
struct ICMPHeader *ICMP;
uint16 orig_checksum;

/* Only need to process locally originated packets */







|







3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
    break;
  }
}

static void
_eth_fix_ip_xsum_offload(ETH_DEV* dev, const u_char* msg, int len)
{
const unsigned short* proto = (const unsigned short*) &msg[12];
struct IPHeader *IP;
struct TCPHeader *TCP;
struct UDPHeader *UDP;
struct ICMPHeader *ICMP;
uint16 orig_checksum;

/* Only need to process locally originated packets */
3082
3083
3084
3085
3086
3087
3088

3089
3090
3091
3092
3093
3094
3095
    if ((dev->hash_filter) && (data[0] & 0x01) && (!dev->promiscuous) && (!dev->all_multicast))
      to_me = _eth_hash_lookup(dev->hash, data);
    break;
#endif /* USE_BPF */
  case ETH_API_TAP:
  case ETH_API_VDE:
  case ETH_API_UDP:

    bpf_used = 0;
    to_me = 0;
    eth_packet_trace (dev, data, header->len, "received");

    for (i = 0; i < dev->addr_count; i++) {
      if (memcmp(data, dev->filter_address[i], 6) == 0) to_me = 1;
      if (memcmp(&data[6], dev->filter_address[i], 6) == 0) from_me = 1;







>







3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
    if ((dev->hash_filter) && (data[0] & 0x01) && (!dev->promiscuous) && (!dev->all_multicast))
      to_me = _eth_hash_lookup(dev->hash, data);
    break;
#endif /* USE_BPF */
  case ETH_API_TAP:
  case ETH_API_VDE:
  case ETH_API_UDP:
  case ETH_API_NAT:
    bpf_used = 0;
    to_me = 0;
    eth_packet_trace (dev, data, header->len, "received");

    for (i = 0; i < dev->addr_count; i++) {
      if (memcmp(data, dev->filter_address[i], 6) == 0) to_me = 1;
      if (memcmp(&data[6], dev->filter_address[i], 6) == 0) from_me = 1;
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137


3138


3139
3140
3141
3142
3143
3144
3145
    }
  else
    if (!bpf_used)
      from_me = 0;
#ifdef USE_READER_THREAD
  pthread_mutex_unlock (&dev->self_lock);
#endif
}

if (bpf_used ? to_me : (to_me && !from_me)) {
  if (header->len > ETH_MIN_JUMBO_FRAME) {
    if (header->len <= header->caplen) /* Whole Frame captured? */


      _eth_fix_ip_jumbo_offload(dev, data, header->len);


    else
      ++dev->jumbo_truncated;
    return;
    }
  if (_eth_process_loopback(dev, data, header->len))
    return;  
#if defined (USE_READER_THREAD)







|



|
>
>
|
>
>







3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
    }
  else
    if (!bpf_used)
      from_me = 0;
#ifdef USE_READER_THREAD
  pthread_mutex_unlock (&dev->self_lock);
#endif
  }

if (bpf_used ? to_me : (to_me && !from_me)) {
  if (header->len > ETH_MIN_JUMBO_FRAME) {
    if (header->len <= header->caplen) {/* Whole Frame captured? */
      u_char *datacopy = (u_char *)malloc(header->len);
      memcpy(datacopy, data, header->len);
      _eth_fix_ip_jumbo_offload(dev, datacopy, header->len);
      free(datacopy);
      }
    else
      ++dev->jumbo_truncated;
    return;
    }
  if (_eth_process_loopback(dev, data, header->len))
    return;  
#if defined (USE_READER_THREAD)
3551
3552
3553
3554
3555
3556
3557

3558
3559
3560
3561
3562
3563
3564

for (i=0; i<used; ++i) {
  /* Cull any non-ethernet interface types */
#if defined(HAVE_PCAP_NETWORK)
  conn = pcap_open_live(list[i].name, ETH_MAX_PACKET, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
  if (NULL != conn)
    datalink = pcap_datalink(conn), pcap_close(conn);

#endif
  if ((NULL == conn) || (datalink != DLT_EN10MB)) {
    for (j=i; j<used-1; ++j)
      list[j] = list[j+1];
    --used;
    --i;
    }







>







3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834

for (i=0; i<used; ++i) {
  /* Cull any non-ethernet interface types */
#if defined(HAVE_PCAP_NETWORK)
  conn = pcap_open_live(list[i].name, ETH_MAX_PACKET, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
  if (NULL != conn)
    datalink = pcap_datalink(conn), pcap_close(conn);
  list[i].eth_api = ETH_API_PCAP;
#endif
  if ((NULL == conn) || (datalink != DLT_EN10MB)) {
    for (j=i; j<used-1; ++j)
      list[j] = list[j+1];
    --used;
    --i;
    }
3609
3610
3611
3612
3613
3614
3615

3616
3617
3618
3619
3620
3621
3622









3623
3624
3625
3626
3627
3628
3629

3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
if (used < max) {
#if defined(__OpenBSD__)
  sprintf(list[used].name, "%s", "tap:tunN");
#else
  sprintf(list[used].name, "%s", "tap:tapN");
#endif
  sprintf(list[used].desc, "%s", "Integrated Tun/Tap support");

  ++used;
  }
#endif
#ifdef HAVE_VDE_NETWORK
if (used < max) {
  sprintf(list[used].name, "%s", "vde:device");
  sprintf(list[used].desc, "%s", "Integrated VDE support");









  ++used;
  }
#endif

if (used < max) {
  sprintf(list[used].name, "%s", "udp:sourceport:remotehost:remoteport");
  sprintf(list[used].desc, "%s", "Integrated UDP bridge support");

  ++used;
  }

#ifdef USE_SLIRP_NETWORK
if (used < max) {
  sprintf(list[used].name, "%s", "nat:device");
  sprintf(list[used].desc, "%s", "Integrated User Mode NAT support");
  ++used;
  }
#endif

return used;
}

int eth_devices(int max, ETH_LIST* list)
{
int i = 0;
char errbuf[PCAP_ERRBUF_SIZE];







>







>
>
>
>
>
>
>
>
>







>



<
<
<
<
<
<
<
<







3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913








3914
3915
3916
3917
3918
3919
3920
if (used < max) {
#if defined(__OpenBSD__)
  sprintf(list[used].name, "%s", "tap:tunN");
#else
  sprintf(list[used].name, "%s", "tap:tapN");
#endif
  sprintf(list[used].desc, "%s", "Integrated Tun/Tap support");
  list[used].eth_api = ETH_API_TAP;
  ++used;
  }
#endif
#ifdef HAVE_VDE_NETWORK
if (used < max) {
  sprintf(list[used].name, "%s", "vde:device");
  sprintf(list[used].desc, "%s", "Integrated VDE support");
  list[used].eth_api = ETH_API_VDE;
  ++used;
  }
#endif
#ifdef HAVE_SLIRP_NETWORK
if (used < max) {
  sprintf(list[used].name, "%s", "nat:{optional-nat-parameters}");
  sprintf(list[used].desc, "%s", "Integrated NAT (SLiRP) support");
  list[used].eth_api = ETH_API_NAT;
  ++used;
  }
#endif

if (used < max) {
  sprintf(list[used].name, "%s", "udp:sourceport:remotehost:remoteport");
  sprintf(list[used].desc, "%s", "Integrated UDP bridge support");
  list[used].eth_api = ETH_API_UDP;
  ++used;
  }









return used;
}

int eth_devices(int max, ETH_LIST* list)
{
int i = 0;
char errbuf[PCAP_ERRBUF_SIZE];
3727
3728
3729
3730
3731
3732
3733




3734
3735
fprintf(st, "  Read Queue: Count:       %d\n", dev->read_queue.count);
fprintf(st, "  Read Queue: High:        %d\n", dev->read_queue.high);
fprintf(st, "  Read Queue: Loss:        %d\n", dev->read_queue.loss);
fprintf(st, "  Peak Write Queue Size:   %d\n", dev->write_queue_peak);
#endif
if (dev->bpf_filter)
  fprintf(st, "  BPF Filter: %s\n", dev->bpf_filter);




}
#endif /* USE_NETWORK */







>
>
>
>


4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
fprintf(st, "  Read Queue: Count:       %d\n", dev->read_queue.count);
fprintf(st, "  Read Queue: High:        %d\n", dev->read_queue.high);
fprintf(st, "  Read Queue: Loss:        %d\n", dev->read_queue.loss);
fprintf(st, "  Peak Write Queue Size:   %d\n", dev->write_queue_peak);
#endif
if (dev->bpf_filter)
  fprintf(st, "  BPF Filter: %s\n", dev->bpf_filter);
#if defined(HAVE_SLIRP_NETWORK)
if (dev->eth_api == ETH_API_NAT)
  sim_slirp_show ((SLIRP *)dev->handle, st);
#endif
}
#endif /* USE_NETWORK */
Changes to src/sim_ether.h.
64
65
66
67
68
69
70




71
72
73
74
75
76
77
*/

#ifndef SIM_ETHER_H
#define SIM_ETHER_H

#include "sim_defs.h"
#include "sim_sock.h"





/* make common BSD code a bit easier to read in this file */
/* OS/X seems to define and compile using one of these BSD types */
#if defined(__NetBSD__) || defined (__OpenBSD__) || defined (__FreeBSD__)
#define xBSD 1
#endif
#if !defined(__FreeBSD__) && !defined(_WIN32) && !defined(VMS) && !defined(__CYGWIN__) && !defined(__APPLE__)







>
>
>
>







64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
*/

#ifndef SIM_ETHER_H
#define SIM_ETHER_H

#include "sim_defs.h"
#include "sim_sock.h"

#ifdef  __cplusplus
extern "C" {
#endif

/* make common BSD code a bit easier to read in this file */
/* OS/X seems to define and compile using one of these BSD types */
#if defined(__NetBSD__) || defined (__OpenBSD__) || defined (__FreeBSD__)
#define xBSD 1
#endif
#if !defined(__FreeBSD__) && !defined(_WIN32) && !defined(VMS) && !defined(__CYGWIN__) && !defined(__APPLE__)
221
222
223
224
225
226
227

228
229
230
231
232
233
234
235
236
237





238
239
240
241
242
243
244
  int                 high;
  struct eth_item*    item;
};

struct eth_list {
  char    name[ETH_DEV_NAME_MAX];
  char    desc[ETH_DEV_DESC_MAX];

};

typedef int ETH_BOOL;
typedef unsigned char ETH_MAC[6];
typedef unsigned char ETH_MULTIHASH[8];
typedef struct eth_packet  ETH_PACK;
typedef void (*ETH_PCALLBACK)(int status);
typedef struct eth_list ETH_LIST;
typedef struct eth_queue ETH_QUE;
typedef struct eth_item ETH_ITEM;






struct eth_device {
  char*         name;                                   /* name of ethernet device */
  void*         handle;                                 /* handle of implementation-specific device */
  SOCKET        fd_handle;                              /* fd to kernel device (where needed) */
  char*         bpf_filter;                             /* bpf filter currently in effect */
  int           eth_api;                                /* Designator for which API is being used to move packets */







>










>
>
>
>
>







225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
  int                 high;
  struct eth_item*    item;
};

struct eth_list {
  char    name[ETH_DEV_NAME_MAX];
  char    desc[ETH_DEV_DESC_MAX];
  int     eth_api;
};

typedef int ETH_BOOL;
typedef unsigned char ETH_MAC[6];
typedef unsigned char ETH_MULTIHASH[8];
typedef struct eth_packet  ETH_PACK;
typedef void (*ETH_PCALLBACK)(int status);
typedef struct eth_list ETH_LIST;
typedef struct eth_queue ETH_QUE;
typedef struct eth_item ETH_ITEM;
struct eth_write_request {
  struct eth_write_request *next;
  ETH_PACK packet;
  };
typedef struct eth_write_request ETH_WRITE_REQUEST;

struct eth_device {
  char*         name;                                   /* name of ethernet device */
  void*         handle;                                 /* handle of implementation-specific device */
  SOCKET        fd_handle;                              /* fd to kernel device (where needed) */
  char*         bpf_filter;                             /* bpf filter currently in effect */
  int           eth_api;                                /* Designator for which API is being used to move packets */
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
  ETH_QUE       read_queue;
  pthread_mutex_t     lock;
  pthread_t     reader_thread;                          /* Reader Thread Id */
  pthread_t     writer_thread;                          /* Writer Thread Id */
  pthread_mutex_t     writer_lock;
  pthread_mutex_t     self_lock;
  pthread_cond_t      writer_cond;
  struct write_request {
      struct write_request *next;
      ETH_PACK packet;
      } *write_requests;
  int write_queue_peak;
  struct write_request *write_buffers;
  t_stat write_status;
#endif
};

typedef struct eth_device  ETH_DEV;

/* prototype declarations*/

t_stat eth_open   (ETH_DEV* dev, char* name,            /* open ethernet interface */
                   DEVICE* dptr, uint32 dbit);
t_stat eth_close  (ETH_DEV* dev);                       /* close ethernet interface */
t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat eth_write  (ETH_DEV* dev, ETH_PACK* packet,      /* write sychronous packet; */
                   ETH_PCALLBACK routine);              /*  callback when done */
int eth_read      (ETH_DEV* dev, ETH_PACK* packet,      /* read single packet; */
                   ETH_PCALLBACK routine);              /*  callback when done*/







<
<
<
|

|








|







309
310
311
312
313
314
315



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
  ETH_QUE       read_queue;
  pthread_mutex_t     lock;
  pthread_t     reader_thread;                          /* Reader Thread Id */
  pthread_t     writer_thread;                          /* Writer Thread Id */
  pthread_mutex_t     writer_lock;
  pthread_mutex_t     self_lock;
  pthread_cond_t      writer_cond;



  ETH_WRITE_REQUEST *write_requests;
  int write_queue_peak;
  ETH_WRITE_REQUEST *write_buffers;
  t_stat write_status;
#endif
};

typedef struct eth_device  ETH_DEV;

/* prototype declarations*/

t_stat eth_open   (ETH_DEV* dev, const char* name,      /* open ethernet interface */
                   DEVICE* dptr, uint32 dbit);
t_stat eth_close  (ETH_DEV* dev);                       /* close ethernet interface */
t_stat eth_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat eth_write  (ETH_DEV* dev, ETH_PACK* packet,      /* write sychronous packet; */
                   ETH_PCALLBACK routine);              /*  callback when done */
int eth_read      (ETH_DEV* dev, ETH_PACK* packet,      /* read single packet; */
                   ETH_PCALLBACK routine);              /*  callback when done*/
342
343
344
345
346
347
348
349
350
351
352
353
354

355

356
357
358
359
360
361
362
363
364
365
366
367
368




369
t_stat eth_clr_async (ETH_DEV* dev);                    /* set read behavior to be not async */
t_stat eth_set_throttle (ETH_DEV* dev, uint32 time, uint32 burst, uint32 delay); /* set transmit throttle parameters */
uint32 eth_crc32(uint32 crc, const void* vbuf, size_t len); /* Compute Ethernet Autodin II CRC for buffer */

void eth_packet_trace (ETH_DEV* dev, const uint8 *msg, int len, const char* txt); /* trace ethernet packet header+crc */
void eth_packet_trace_ex (ETH_DEV* dev, const uint8 *msg, int len, const char* txt, int detail, uint32 reason); /* trace ethernet packet */
t_stat eth_show (FILE* st, UNIT* uptr,                  /* show ethernet devices */
                 int32 val, void* desc);
t_stat eth_show_devices (FILE* st, DEVICE *dptr,        /* show ethernet devices */
                         UNIT* uptr, int32 val, char* desc);
void eth_show_dev (FILE*st, ETH_DEV* dev);              /* show ethernet device state */

void eth_mac_fmt      (ETH_MAC* add, char* buffer);     /* format ethernet mac address */

t_stat eth_mac_scan (ETH_MAC* mac, char* strmac);       /* scan string for mac, put in mac */


t_stat ethq_init (ETH_QUE* que, int max);               /* initialize FIFO queue */
void ethq_clear  (ETH_QUE* que);                        /* clear FIFO queue */
void ethq_remove (ETH_QUE* que);                        /* remove item from FIFO queue */
void ethq_insert (ETH_QUE* que, int32 type,             /* insert item into FIFO queue */
                  ETH_PACK* packet, int32 status);
void ethq_insert_data(ETH_QUE* que, int32 type,         /* insert item into FIFO queue */
                  const uint8 *data, int used, size_t len, 
                  size_t crc_len, const uint8 *crc_data, int32 status);
t_stat ethq_destroy(ETH_QUE* que);                      /* release FIFO queue */

const char *eth_capabilities(void);





#endif                                                  /* _SIM_ETHER_H */







|

|


|
>
|
>













>
>
>
>

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
t_stat eth_clr_async (ETH_DEV* dev);                    /* set read behavior to be not async */
t_stat eth_set_throttle (ETH_DEV* dev, uint32 time, uint32 burst, uint32 delay); /* set transmit throttle parameters */
uint32 eth_crc32(uint32 crc, const void* vbuf, size_t len); /* Compute Ethernet Autodin II CRC for buffer */

void eth_packet_trace (ETH_DEV* dev, const uint8 *msg, int len, const char* txt); /* trace ethernet packet header+crc */
void eth_packet_trace_ex (ETH_DEV* dev, const uint8 *msg, int len, const char* txt, int detail, uint32 reason); /* trace ethernet packet */
t_stat eth_show (FILE* st, UNIT* uptr,                  /* show ethernet devices */
                 int32 val, CONST void* desc);
t_stat eth_show_devices (FILE* st, DEVICE *dptr,        /* show ethernet devices */
                         UNIT* uptr, int32 val, CONST char* desc);
void eth_show_dev (FILE*st, ETH_DEV* dev);              /* show ethernet device state */

void eth_mac_fmt (ETH_MAC* const add, char* buffer);    /* format ethernet mac address */
t_stat eth_mac_scan (ETH_MAC* mac, const char* strmac); /* scan string for mac, put in mac */
t_stat eth_mac_scan_ex (ETH_MAC* mac,                   /* scan string for mac, put in mac */
                        const char* strmac, UNIT *uptr);/* for specified unit */

t_stat ethq_init (ETH_QUE* que, int max);               /* initialize FIFO queue */
void ethq_clear  (ETH_QUE* que);                        /* clear FIFO queue */
void ethq_remove (ETH_QUE* que);                        /* remove item from FIFO queue */
void ethq_insert (ETH_QUE* que, int32 type,             /* insert item into FIFO queue */
                  ETH_PACK* packet, int32 status);
void ethq_insert_data(ETH_QUE* que, int32 type,         /* insert item into FIFO queue */
                  const uint8 *data, int used, size_t len, 
                  size_t crc_len, const uint8 *crc_data, int32 status);
t_stat ethq_destroy(ETH_QUE* que);                      /* release FIFO queue */

const char *eth_capabilities(void);

#ifdef  __cplusplus
}
#endif

#endif                                                  /* _SIM_ETHER_H */
Changes to src/sim_fio.c.
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
c = fread (bptr, size, count, fptr);                    /* read buffer */
if (sim_end || (size == sizeof (char)) || (c == 0))     /* le, byte, or err? */
    return c;                                           /* done */
sim_buf_swap_data (bptr, size, count);
return c;
}

void sim_buf_copy_swapped (void *dbuf, void *sbuf, size_t size, size_t count)
{
size_t j;
int32 k;
unsigned char *sptr = (unsigned char *)sbuf;
unsigned char *dptr = (unsigned char *)dbuf;

if (sim_end || (size == sizeof (char))) {
    memcpy (dptr, sptr, size * count);
    return;
    }
for (j = 0; j < count; j++) {                           /* loop on items */
    for (k = (int32)(size - 1); k >= 0; k--)
        *(dptr + k) = *sptr++;
    dptr = dptr + size;
    }
}

size_t sim_fwrite (void *bptr, size_t size, size_t count, FILE *fptr)
{
size_t c, nelem, nbuf, lcnt, total;
int32 i;
unsigned char *sptr;
unsigned char *sim_flip;

if ((size == 0) || (count == 0))                        /* check arguments */
    return 0;
if (sim_end || (size == sizeof (char)))                 /* le or byte? */
    return fwrite (bptr, size, count, fptr);            /* done */
sim_flip = (unsigned char *)malloc(FLIP_SIZE);
if (!sim_flip)
    return 0;
nelem = FLIP_SIZE / size;                               /* elements in buffer */
nbuf = count / nelem;                                   /* number buffers */
lcnt = count % nelem;                                   /* count in last buf */
if (lcnt) nbuf = nbuf + 1;
else lcnt = nelem;
total = 0;
sptr = (unsigned char *) bptr;                          /* init input ptr */
for (i = (int32)nbuf; i > 0; i--) {                     /* loop on buffers */
    c = (i == 1)? lcnt: nelem;
    sim_buf_copy_swapped (sim_flip, sptr, size, c);
    sptr = sptr + size * count;
    c = fwrite (sim_flip, size, c, fptr);
    if (c == 0) {
        free(sim_flip);







|



|













|



|















|







121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
c = fread (bptr, size, count, fptr);                    /* read buffer */
if (sim_end || (size == sizeof (char)) || (c == 0))     /* le, byte, or err? */
    return c;                                           /* done */
sim_buf_swap_data (bptr, size, count);
return c;
}

void sim_buf_copy_swapped (void *dbuf, const void *sbuf, size_t size, size_t count)
{
size_t j;
int32 k;
const unsigned char *sptr = (const unsigned char *)sbuf;
unsigned char *dptr = (unsigned char *)dbuf;

if (sim_end || (size == sizeof (char))) {
    memcpy (dptr, sptr, size * count);
    return;
    }
for (j = 0; j < count; j++) {                           /* loop on items */
    for (k = (int32)(size - 1); k >= 0; k--)
        *(dptr + k) = *sptr++;
    dptr = dptr + size;
    }
}

size_t sim_fwrite (const void *bptr, size_t size, size_t count, FILE *fptr)
{
size_t c, nelem, nbuf, lcnt, total;
int32 i;
const unsigned char *sptr;
unsigned char *sim_flip;

if ((size == 0) || (count == 0))                        /* check arguments */
    return 0;
if (sim_end || (size == sizeof (char)))                 /* le or byte? */
    return fwrite (bptr, size, count, fptr);            /* done */
sim_flip = (unsigned char *)malloc(FLIP_SIZE);
if (!sim_flip)
    return 0;
nelem = FLIP_SIZE / size;                               /* elements in buffer */
nbuf = count / nelem;                                   /* number buffers */
lcnt = count % nelem;                                   /* count in last buf */
if (lcnt) nbuf = nbuf + 1;
else lcnt = nelem;
total = 0;
sptr = (const unsigned char *) bptr;                    /* init input ptr */
for (i = (int32)nbuf; i > 0; i--) {                     /* loop on buffers */
    c = (i == 1)? lcnt: nelem;
    sim_buf_copy_swapped (sim_flip, sptr, size, c);
    sptr = sptr + size * count;
    c = fwrite (sim_flip, size, c, fptr);
    if (c == 0) {
        free(sim_flip);
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
pos = sim_ftell (fp);
sim_fseek (fp, 0, SEEK_END);
sz = sim_ftell (fp);
sim_fseeko (fp, pos, SEEK_SET);
return sz;
}

t_offset sim_fsize_name_ex (char *fname)
{
FILE *fp;
t_offset sz;

if ((fp = sim_fopen (fname, "rb")) == NULL)
    return 0;
sz = sim_fsize_ex (fp);
fclose (fp);
return sz;
}

uint32 sim_fsize_name (char *fname)
{
return (uint32)(sim_fsize_name_ex (fname));
}

uint32 sim_fsize (FILE *fp)
{
return (uint32)(sim_fsize_ex (fp));







|











|







194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
pos = sim_ftell (fp);
sim_fseek (fp, 0, SEEK_END);
sz = sim_ftell (fp);
sim_fseeko (fp, pos, SEEK_SET);
return sz;
}

t_offset sim_fsize_name_ex (const char *fname)
{
FILE *fp;
t_offset sz;

if ((fp = sim_fopen (fname, "rb")) == NULL)
    return 0;
sz = sim_fsize_ex (fp);
fclose (fp);
return sz;
}

uint32 sim_fsize_name (const char *fname)
{
return (uint32)(sim_fsize_name_ex (fname));
}

uint32 sim_fsize (FILE *fp)
{
return (uint32)(sim_fsize_ex (fp));
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
return (t_offset)(ftello64 (st));
}

#endif                                                  /* end Linux with LFS */

/* Apple OS/X */

#if defined (__APPLE__) || defined (__FreeBSD__) || defined(__NetBSD__) || defined (__OpenBSD__) 
#define S_SIM_IO_FSEEK_EXT_ 1
int sim_fseeko (FILE *st, t_offset xpos, int origin) 
{
return fseeko (st, (off_t)xpos, origin);
}

t_offset sim_ftell (FILE *st)







|







330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
return (t_offset)(ftello64 (st));
}

#endif                                                  /* end Linux with LFS */

/* Apple OS/X */

#if defined (__APPLE__) || defined (__FreeBSD__) || defined(__NetBSD__) || defined (__OpenBSD__) || defined (__CYGWIN__) 
#define S_SIM_IO_FSEEK_EXT_ 1
int sim_fseeko (FILE *st, t_offset xpos, int origin) 
{
return fseeko (st, (off_t)xpos, origin);
}

t_offset sim_ftell (FILE *st)
Changes to src/sim_fio.h.
28
29
30
31
32
33
34




35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


75


   15-May-06    RMS     Added sim_fsize_name
   16-Aug-05    RMS     Fixed C++ declaration and cast problems
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_FIO_H_
#define SIM_FIO_H_     0





#define FLIP_SIZE       (1 << 16)                       /* flip buf size */
#define fxread(a,b,c,d)         sim_fread (a, b, c, d)
#define fxwrite(a,b,c,d)        sim_fwrite (a, b, c, d)

int32 sim_finit (void);
#if (defined (__linux) || defined (__linux__) || defined (__hpux) || defined (_AIX) ||                           \
     (defined (VMS) && (defined (__ALPHA) || defined (__ia64)) && (__DECC_VER >= 60590001)) || \
     ((defined(__sun) || defined(__sun__)) && defined(_LARGEFILE_SOURCE)) ||                   \
     defined (_WIN32) || defined (__APPLE__) ||                                                \
     defined (__FreeBSD__) || defined(__NetBSD__) || defined (__OpenBSD__)) && !defined (DONT_DO_LARGEFILE)
typedef t_int64        t_offset;
#else
typedef int32        t_offset;
#if !defined (DONT_DO_LARGEFILE)
#define DONT_DO_LARGEFILE 1
#endif
#endif
FILE *sim_fopen (const char *file, const char *mode);
int sim_fseek (FILE *st, t_addr offset, int whence);
int sim_fseeko (FILE *st, t_offset offset, int whence);
int sim_set_fsize (FILE *fptr, t_addr size);
int sim_set_fifo_nonblock (FILE *fptr);
size_t sim_fread (void *bptr, size_t size, size_t count, FILE *fptr);
size_t sim_fwrite (void *bptr, size_t size, size_t count, FILE *fptr);
uint32 sim_fsize (FILE *fptr);
uint32 sim_fsize_name (char *fname);
t_offset sim_ftell (FILE *st);
t_offset sim_fsize_ex (FILE *fptr);
t_offset sim_fsize_name_ex (char *fname);
void sim_buf_swap_data (void *bptr, size_t size, size_t count);
void sim_buf_copy_swapped (void *dptr, void *bptr, size_t size, size_t count);
typedef struct SHMEM SHMEM;
t_stat sim_shmem_open (const char *name, size_t size, SHMEM **shmem, void **addr);
void sim_shmem_close (SHMEM *shmem);

extern t_bool sim_taddr_64;         /* t_addr is > 32b and Large File Support available */
extern t_bool sim_toffset_64;       /* Large File (>2GB) file I/O support */
extern t_bool sim_end;              /* TRUE = little endian, FALSE = big endian */



#endif









>
>
>
>






|


|














|

|


|

|








>
>

>
>
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
   15-May-06    RMS     Added sim_fsize_name
   16-Aug-05    RMS     Fixed C++ declaration and cast problems
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_FIO_H_
#define SIM_FIO_H_     0

#ifdef  __cplusplus
extern "C" {
#endif

#define FLIP_SIZE       (1 << 16)                       /* flip buf size */
#define fxread(a,b,c,d)         sim_fread (a, b, c, d)
#define fxwrite(a,b,c,d)        sim_fwrite (a, b, c, d)

int32 sim_finit (void);
#if (defined (__linux) || defined (__linux__) || defined (__hpux) || defined (_AIX) ||         \
     (defined (VMS) && (defined (__ALPHA) || defined (__ia64)) && (__DECC_VER >= 60590001)) || \
     ((defined(__sun) || defined(__sun__)) && defined(_LARGEFILE_SOURCE)) ||                   \
     defined (_WIN32) || defined (__APPLE__) || defined (__CYGWIN__) ||                        \
     defined (__FreeBSD__) || defined(__NetBSD__) || defined (__OpenBSD__)) && !defined (DONT_DO_LARGEFILE)
typedef t_int64        t_offset;
#else
typedef int32        t_offset;
#if !defined (DONT_DO_LARGEFILE)
#define DONT_DO_LARGEFILE 1
#endif
#endif
FILE *sim_fopen (const char *file, const char *mode);
int sim_fseek (FILE *st, t_addr offset, int whence);
int sim_fseeko (FILE *st, t_offset offset, int whence);
int sim_set_fsize (FILE *fptr, t_addr size);
int sim_set_fifo_nonblock (FILE *fptr);
size_t sim_fread (void *bptr, size_t size, size_t count, FILE *fptr);
size_t sim_fwrite (const void *bptr, size_t size, size_t count, FILE *fptr);
uint32 sim_fsize (FILE *fptr);
uint32 sim_fsize_name (const char *fname);
t_offset sim_ftell (FILE *st);
t_offset sim_fsize_ex (FILE *fptr);
t_offset sim_fsize_name_ex (const char *fname);
void sim_buf_swap_data (void *bptr, size_t size, size_t count);
void sim_buf_copy_swapped (void *dptr, const void *bptr, size_t size, size_t count);
typedef struct SHMEM SHMEM;
t_stat sim_shmem_open (const char *name, size_t size, SHMEM **shmem, void **addr);
void sim_shmem_close (SHMEM *shmem);

extern t_bool sim_taddr_64;         /* t_addr is > 32b and Large File Support available */
extern t_bool sim_toffset_64;       /* Large File (>2GB) file I/O support */
extern t_bool sim_end;              /* TRUE = little endian, FALSE = big endian */

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_frontpanel.h.
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
extern "C" {
#endif

#include <stdlib.h>

#if !defined(__VAX)         /* Unsupported platform */

#define SIM_FRONTPANEL_VERSION   1

/**

    sim_panel_start_simulator       A starts a simulator with a particular 
                                    configuration

        sim_path            the path to the simulator binary







|







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
extern "C" {
#endif

#include <stdlib.h>

#if !defined(__VAX)         /* Unsupported platform */

#define SIM_FRONTPANEL_VERSION   2

/**

    sim_panel_start_simulator       A starts a simulator with a particular 
                                    configuration

        sim_path            the path to the simulator binary
227
228
229
230
231
232
233

































234
235
236
237
238
239
240
sim_panel_exec_boot (PANEL *panel, const char *device);

int
sim_panel_exec_run (PANEL *panel);

int
sim_panel_exec_step (PANEL *panel);


































/**

    When a front panel application needs to change or access
    memory or a register one of the following routines should 
    be called:  
    







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
sim_panel_exec_boot (PANEL *panel, const char *device);

int
sim_panel_exec_run (PANEL *panel);

int
sim_panel_exec_step (PANEL *panel);

/**

    When a front panel application wants to describe conditions that 
    should stop instruction execution an execution or an output
    breakpoint should be used.  To established or clear a breakpoint, 
    one of the following routines should be called:  
    
    sim_panel_break_set          - Establish a simulation breakpoint
    sim_panel_break_clear        - Cancel/Delete a previously defined
                                   breakpoint
    sim_panel_break_output_set   - Establish a simulator output 
                                   breakpoint
    sim_panel_break_output_clear - Cancel/Delete a previously defined
                                   output breakpoint
    
    Note: Any breakpoint switches/flags must be located at the 
          beginning of the condition string

 */

int
sim_panel_break_set (PANEL *panel, const char *condition);

int
sim_panel_break_clear (PANEL *panel, const char *condition);

int
sim_panel_break_output_set (PANEL *panel, const char *condition);

int
sim_panel_break_output_clear (PANEL *panel, const char *condition);


/**

    When a front panel application needs to change or access
    memory or a register one of the following routines should 
    be called:  
    
Changes to src/sim_rev.h.
Changes to src/sim_serial.c.
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

   int sim_serial_devices (int max, SERIAL_LIST* list)
   ---------------------------------------------------

   enumerates the available host serial ports


   t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, void* desc)
   ---------------------------------

   displays the available host serial ports

*/









|







111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

   int sim_serial_devices (int max, SERIAL_LIST* list)
   ---------------------------------------------------

   enumerates the available host serial ports


   t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, const void* desc)
   ---------------------------------

   displays the available host serial ports

*/


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
sim_printf ("Serial: %s fails with error %d\n", routine, error);
return;
}

/* Used when sorting a list of serial port names */
static int _serial_name_compare (const void *pa, const void *pb)
{
SERIAL_LIST *a = (SERIAL_LIST *)pa;
SERIAL_LIST *b = (SERIAL_LIST *)pb;

return strcmp(a->name, b->name);
}

static int sim_serial_devices (int max, SERIAL_LIST *list)
{
int i, j, ports = sim_serial_os_devices(max, list);







|
|







218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
sim_printf ("Serial: %s fails with error %d\n", routine, error);
return;
}

/* Used when sorting a list of serial port names */
static int _serial_name_compare (const void *pa, const void *pb)
{
const SERIAL_LIST *a = (const SERIAL_LIST *)pa;
const SERIAL_LIST *b = (const SERIAL_LIST *)pb;

return strcmp(a->name, b->name);
}

static int sim_serial_devices (int max, SERIAL_LIST *list)
{
int i, j, ports = sim_serial_os_devices(max, list);
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
    strcpy(name, list[i].name);
    return name;
    }
/* not found */
return NULL;
}

/* strncasecmp() is not available on all platforms */
static int sim_serial_strncasecmp (char* string1, char* string2, size_t len)
{
size_t i;
unsigned char s1, s2;

for (i=0; i<len; i++) {
    s1 = string1[i];
    s2 = string2[i];
    if (islower (s1))
        s1 = (unsigned char)toupper (s1);
    if (islower (s2))
        s2 = (unsigned char)toupper (s2);
    if (s1 < s2)
        return -1;
    if (s1 > s2)
        return 1;
    if (s1 == 0)
        return 0;
}
return 0;
}

static char* sim_serial_getname_byname (char* name, char* temp)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;

found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_serial_strncasecmp(name, list[i].name, n) == 0)) {
        found = 1;
        strcpy(temp, list[i].name); /* only case might be different */
        }
    }
return (found ? temp : NULL);
}

char* sim_serial_getdesc_byname (char* name, char* temp)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;

found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_serial_strncasecmp(name, list[i].name, n) == 0)) {
        found = 1;
        strcpy(temp, list[i].desc);
        }
    }
  return (found ? temp : NULL);
}

t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int number = sim_serial_devices(SER_MAX_DEVICE, list);

fprintf(st, "Serial devices:\n");
if (number == -1)
    fprintf(st, "  serial support not available in simulator\n");







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<











|


















|







|







287
288
289
290
291
292
293























294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    strcpy(name, list[i].name);
    return name;
    }
/* not found */
return NULL;
}
























static char* sim_serial_getname_byname (char* name, char* temp)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;

found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_strncasecmp(name, list[i].name, n) == 0)) {
        found = 1;
        strcpy(temp, list[i].name); /* only case might be different */
        }
    }
return (found ? temp : NULL);
}

char* sim_serial_getdesc_byname (char* name, char* temp)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;

found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
    if ((n == strlen(list[i].name)) &&
        (sim_strncasecmp(name, list[i].name, n) == 0)) {
        found = 1;
        strcpy(temp, list[i].desc);
        }
    }
  return (found ? temp : NULL);
}

t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc)
{
SERIAL_LIST  list[SER_MAX_DEVICE];
int number = sim_serial_devices(SER_MAX_DEVICE, list);

fprintf(st, "Serial devices:\n");
if (number == -1)
    fprintf(st, "  serial support not available in simulator\n");
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
}

SERHANDLE sim_open_serial (char *name, TMLN *lp, t_stat *stat)
{
char temp1[1024], devname [1024];
char *savname = name;
SERHANDLE port = INVALID_HANDLE;
const char *config;
t_stat status;

config = get_glyph_nc (name, devname, ';');             /* separate port name from optional config params */

if ((config == NULL) || (*config == '\0'))
    config = "9600-8N1";








|







364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
}

SERHANDLE sim_open_serial (char *name, TMLN *lp, t_stat *stat)
{
char temp1[1024], devname [1024];
char *savname = name;
SERHANDLE port = INVALID_HANDLE;
CONST char *config;
t_stat status;

config = get_glyph_nc (name, devname, ';');             /* separate port name from optional config params */

if ((config == NULL) || (*config == '\0'))
    config = "9600-8N1";

411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    && (isdigit(devname[4]) || (devname[4] == '\0'))
   ) {
    int num = atoi(&devname[3]);
    savname = sim_serial_getname(num, temp1);
    if (savname == NULL) {                              /* didn't translate */
        if (stat)
            *stat = SCPE_OPENERR;
        return port;
        }
    }
else {
    /* are they trying to use device description? */
    savname = sim_serial_getname_bydesc(devname, temp1);
    if (savname == NULL) {                              /* didn't translate */
        /* probably is not serX and has no description */







|







388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    && (isdigit(devname[4]) || (devname[4] == '\0'))
   ) {
    int num = atoi(&devname[3]);
    savname = sim_serial_getname(num, temp1);
    if (savname == NULL) {                              /* didn't translate */
        if (stat)
            *stat = SCPE_OPENERR;
        return INVALID_HANDLE;
        }
    }
else {
    /* are they trying to use device description? */
    savname = sim_serial_getname_bydesc(devname, temp1);
    if (savname == NULL) {                              /* didn't translate */
        /* probably is not serX and has no description */
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

void sim_close_serial (SERHANDLE port)
{
sim_close_os_serial (port);
_serial_remove_from_open_list (port);
}

t_stat sim_config_serial  (SERHANDLE port, const char *sconfig)
{
const char *pptr;
const char *sptr, *tptr;
SERCONFIG config = { 0 };
t_bool arg_error = FALSE;
t_stat r;
struct open_serial_device *dev;

if ((sconfig == NULL) || (*sconfig == '\0'))
    sconfig = "9600-8N1";                               /* default settings */







|

|
|







441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

void sim_close_serial (SERHANDLE port)
{
sim_close_os_serial (port);
_serial_remove_from_open_list (port);
}

t_stat sim_config_serial  (SERHANDLE port, CONST char *sconfig)
{
CONST char *pptr;
CONST char *sptr, *tptr;
SERCONFIG config = { 0 };
t_bool arg_error = FALSE;
t_stat r;
struct open_serial_device *dev;

if ((sconfig == NULL) || (*sconfig == '\0'))
    sconfig = "9600-8N1";                               /* default settings */
518
519
520
521
522
523
524








525
526
527
528
529
530
531

   The serial port names are extracted from the appropriate place in the 
   windows registry (HKLM\HARDWARE\DEVICEMAP\SERIALCOMM\).  The resulting
   list is sorted alphabetically by device name (COMn).  The device description 
   is set to the OS internal name for the COM device.

*/









static int sim_serial_os_devices (int max, SERIAL_LIST* list)
{
int ports = 0;
HKEY hSERIALCOMM;

memset(list, 0, max*sizeof(*list));







>
>
>
>
>
>
>
>







495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516

   The serial port names are extracted from the appropriate place in the 
   windows registry (HKLM\HARDWARE\DEVICEMAP\SERIALCOMM\).  The resulting
   list is sorted alphabetically by device name (COMn).  The device description 
   is set to the OS internal name for the COM device.

*/

struct SERPORT {
    HANDLE hPort;
    DWORD dwEvtMask;
    OVERLAPPED oReadSync;
    OVERLAPPED oWriteReady;
    OVERLAPPED oWriteSync;
    };

static int sim_serial_os_devices (int max, SERIAL_LIST* list)
{
int ports = 0;
HKEY hSERIALCOMM;

memset(list, 0, max*sizeof(*list));
579
580
581
582
583
584
585

586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614



615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650










































651
652
653
654
655
656
657
       of the DCB fields are not set correctly, so we cannot use this directly
       in a call to "SetCommState".  Instead, we must copy the fields of
       interest to a DCB retrieved from a call to "GetCommState".
*/

static SERHANDLE sim_open_os_serial (char *name)
{

SERHANDLE port;
DCB dcb;
COMMCONFIG commdefault;
DWORD error;
DWORD commsize = sizeof (commdefault);
COMMTIMEOUTS cto;

if (!GetDefaultCommConfig (name, &commdefault, &commsize)) {    /* get default comm parameters */
    error = GetLastError ();                                    /* function failed; get error */

    if (error != ERROR_INVALID_PARAMETER)                       /* not a communications port name? */
        sim_error_serial ("GetDefaultCommConfig", (int) error); /* no, so report unexpected error */

    return INVALID_HANDLE;                                      /* indicate bad port name */
    }

port = CreateFile (name, GENERIC_READ | GENERIC_WRITE,  /* open the port */
                   0, NULL, OPEN_EXISTING, 0, 0);

if (port == INVALID_HANDLE_VALUE) {                     /* open failed? */
    error = GetLastError ();                            /* get error code */

    if ((error != ERROR_FILE_NOT_FOUND) &&              /* bad filename? */
        (error != ERROR_ACCESS_DENIED))                 /* already open? */
        sim_error_serial ("CreateFile", (int) error);   /* no, so report unexpected error */

    return INVALID_HANDLE;                              /* indicate bad port name */
    }




if (!GetCommState (port, &dcb)) {                       /* get the current comm parameters */
    error = GetLastError ();                            /* function failed; get error */

    if (error != ERROR_INVALID_PARAMETER)               /* not a serial port name? */
        sim_error_serial ("GetCommState", (int) error); /* no, so report unexpected error */

    CloseHandle (port);                                 /* close the port */
    return INVALID_HANDLE;                              /*   and indicate bad port name */
    }

dcb.BaudRate = commdefault.dcb.BaudRate;                /* copy default parameters of interest */
dcb.Parity   = commdefault.dcb.Parity;
dcb.ByteSize = commdefault.dcb.ByteSize;
dcb.StopBits = commdefault.dcb.StopBits;
dcb.fOutX    = commdefault.dcb.fOutX;
dcb.fInX     = commdefault.dcb.fInX;

dcb.fDtrControl = DTR_CONTROL_DISABLE;                  /* disable DTR initially until poll connects */

if (!SetCommState (port, &dcb)) {                       /* configure the port with default parameters */
    sim_error_serial ("SetCommState",                   /* function failed; report unexpected error */
                      (int) GetLastError ());
    CloseHandle (port);                                 /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

cto.ReadIntervalTimeout         = MAXDWORD;             /* set port to return immediately on read */
cto.ReadTotalTimeoutMultiplier  = 0;                    /* i.e., to enable polling */
cto.ReadTotalTimeoutConstant    = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant   = 0;

if (!SetCommTimeouts (port, &cto)) {                    /* configure port timeouts */
    sim_error_serial ("SetCommTimeouts",                /* function failed; report unexpected error */
                      (int) GetLastError ());
    CloseHandle (port);                                 /* close port */










































    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

return port;                                            /* return port handle on success */
}









>
















|
|

|









>
>
>
|





|












|


|









|


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
       of the DCB fields are not set correctly, so we cannot use this directly
       in a call to "SetCommState".  Instead, we must copy the fields of
       interest to a DCB retrieved from a call to "GetCommState".
*/

static SERHANDLE sim_open_os_serial (char *name)
{
HANDLE hPort;
SERHANDLE port;
DCB dcb;
COMMCONFIG commdefault;
DWORD error;
DWORD commsize = sizeof (commdefault);
COMMTIMEOUTS cto;

if (!GetDefaultCommConfig (name, &commdefault, &commsize)) {    /* get default comm parameters */
    error = GetLastError ();                                    /* function failed; get error */

    if (error != ERROR_INVALID_PARAMETER)                       /* not a communications port name? */
        sim_error_serial ("GetDefaultCommConfig", (int) error); /* no, so report unexpected error */

    return INVALID_HANDLE;                                      /* indicate bad port name */
    }

hPort = CreateFile (name, GENERIC_READ | GENERIC_WRITE, /* open the port */
                   0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

if (hPort == INVALID_HANDLE_VALUE) {                    /* open failed? */
    error = GetLastError ();                            /* get error code */

    if ((error != ERROR_FILE_NOT_FOUND) &&              /* bad filename? */
        (error != ERROR_ACCESS_DENIED))                 /* already open? */
        sim_error_serial ("CreateFile", (int) error);   /* no, so report unexpected error */

    return INVALID_HANDLE;                              /* indicate bad port name */
    }

port = (SERHANDLE)calloc (1, sizeof(*port));            /* instantiate the SERHANDLE */
port->hPort = hPort;

if (!GetCommState (port->hPort, &dcb)) {                /* get the current comm parameters */
    error = GetLastError ();                            /* function failed; get error */

    if (error != ERROR_INVALID_PARAMETER)               /* not a serial port name? */
        sim_error_serial ("GetCommState", (int) error); /* no, so report unexpected error */

    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate bad port name */
    }

dcb.BaudRate = commdefault.dcb.BaudRate;                /* copy default parameters of interest */
dcb.Parity   = commdefault.dcb.Parity;
dcb.ByteSize = commdefault.dcb.ByteSize;
dcb.StopBits = commdefault.dcb.StopBits;
dcb.fOutX    = commdefault.dcb.fOutX;
dcb.fInX     = commdefault.dcb.fInX;

dcb.fDtrControl = DTR_CONTROL_DISABLE;                  /* disable DTR initially until poll connects */

if (!SetCommState (port->hPort, &dcb)) {                /* configure the port with default parameters */
    sim_error_serial ("SetCommState",                   /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

cto.ReadIntervalTimeout         = MAXDWORD;             /* set port to return immediately on read */
cto.ReadTotalTimeoutMultiplier  = 0;                    /* i.e., to enable polling */
cto.ReadTotalTimeoutConstant    = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant   = 0;

if (!SetCommTimeouts (port->hPort, &cto)) {             /* configure port timeouts */
    sim_error_serial ("SetCommTimeouts",                /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

/* Create an event object for use by WaitCommEvent. */

port->oWriteReady.hEvent = CreateEvent(NULL,            /* default security attributes */
                                       TRUE,            /* manual-reset event */
                                       TRUE,            /* signaled */
                                       NULL);           /* no name */
if (port->oWriteReady.hEvent == NULL) {
    sim_error_serial ("CreateEvent",                    /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

port->oReadSync.hEvent = CreateEvent(NULL,              /* default security attributes */
                                     TRUE,              /* manual-reset event */
                                     FALSE,             /* not signaled */
                                     NULL);             /* no name */
if (port->oReadSync.hEvent == NULL) {
    sim_error_serial ("CreateEvent",                    /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

port->oWriteSync.hEvent = CreateEvent(NULL,             /* default security attributes */
                                      TRUE,             /* manual-reset event */
                                      FALSE,            /* not signaled */
                                      NULL);            /* no name */
if (port->oWriteSync.hEvent == NULL) {
    sim_error_serial ("CreateEvent",                    /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

if (!SetCommMask (port->hPort, EV_TXEMPTY)) {
    sim_error_serial ("SetCommMask",                    /* function failed; report unexpected error */
                      (int) GetLastError ());
    sim_close_os_serial (port);                         /* close port */
    return INVALID_HANDLE;                              /*   and indicate failure to caller */
    }

return port;                                            /* return port handle on success */
}


684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

static const int32 parity_count = sizeof (parity_map) / sizeof (parity_map [0]);

DCB dcb;
DWORD error;
int32 i;

if (!GetCommState (port, &dcb)) {                       /* get the current comm parameters */
    sim_error_serial ("GetCommState",                   /* function failed; report unexpected error */
                      (int) GetLastError ());
    return SCPE_IOERR;                                  /* return failure status */
    }

dcb.BaudRate = config.baudrate;                         /* assign baud rate */








|







715
716
717
718
719
720
721
722
723
724
725
726
727
728
729

static const int32 parity_count = sizeof (parity_map) / sizeof (parity_map [0]);

DCB dcb;
DWORD error;
int32 i;

if (!GetCommState (port->hPort, &dcb)) {                /* get the current comm parameters */
    sim_error_serial ("GetCommState",                   /* function failed; report unexpected error */
                      (int) GetLastError ());
    return SCPE_IOERR;                                  /* return failure status */
    }

dcb.BaudRate = config.baudrate;                         /* assign baud rate */

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
else if (config.stopbits == 2)
    dcb.StopBits = TWOSTOPBITS;
else if (config.stopbits == 0)                          /* 0 implies 1.5 stop bits */
    dcb.StopBits = ONE5STOPBITS;
else
    return SCPE_ARG;                                    /* not a valid number of stop bits */

if (!SetCommState (port, &dcb)) {                       /* set the configuration */
    error = GetLastError ();                            /* check for error */

    if (error == ERROR_INVALID_PARAMETER)               /* invalid configuration? */
        return SCPE_ARG;                                /* report as argument error */

    sim_error_serial ("SetCommState", (int) error);     /* function failed; report unexpected error */
    return SCPE_IOERR;                                  /* return failure status */







|







746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
else if (config.stopbits == 2)
    dcb.StopBits = TWOSTOPBITS;
else if (config.stopbits == 0)                          /* 0 implies 1.5 stop bits */
    dcb.StopBits = ONE5STOPBITS;
else
    return SCPE_ARG;                                    /* not a valid number of stop bits */

if (!SetCommState (port->hPort, &dcb)) {                /* set the configuration */
    error = GetLastError ();                            /* check for error */

    if (error == ERROR_INVALID_PARAMETER)               /* invalid configuration? */
        return SCPE_ARG;                                /* report as argument error */

    sim_error_serial ("SetCommState", (int) error);     /* function failed; report unexpected error */
    return SCPE_IOERR;                                  /* return failure status */
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
t_stat sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits)
{
if ((bits_to_set & ~(TMXR_MDM_OUTGOING)) ||         /* Assure only settable bits */
    (bits_to_clear & ~(TMXR_MDM_OUTGOING)) ||
    (bits_to_set & bits_to_clear))                  /* and can't set and clear the same bits */
    return SCPE_ARG;
if (bits_to_set&TMXR_MDM_DTR)
    if (!EscapeCommFunction (port, SETDTR)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_clear&TMXR_MDM_DTR)
    if (!EscapeCommFunction (port, CLRDTR)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_set&TMXR_MDM_RTS)
    if (!EscapeCommFunction (port, SETRTS)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_clear&TMXR_MDM_RTS)
    if (!EscapeCommFunction (port, CLRRTS)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (incoming_bits) {
    DWORD ModemStat;
    if (GetCommModemStatus (port, &ModemStat)) {
        sim_error_serial ("GetCommModemStatus", (int) GetLastError ());
        return SCPE_IOERR;
        }
    *incoming_bits = ((ModemStat&MS_CTS_ON)  ? TMXR_MDM_CTS : 0) |
                     ((ModemStat&MS_DSR_ON)  ? TMXR_MDM_DSR : 0) |
                     ((ModemStat&MS_RING_ON) ? TMXR_MDM_RNG : 0) |
                     ((ModemStat&MS_RLSD_ON) ? TMXR_MDM_DCD : 0);







|




|




|




|





|







779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
t_stat sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits)
{
if ((bits_to_set & ~(TMXR_MDM_OUTGOING)) ||         /* Assure only settable bits */
    (bits_to_clear & ~(TMXR_MDM_OUTGOING)) ||
    (bits_to_set & bits_to_clear))                  /* and can't set and clear the same bits */
    return SCPE_ARG;
if (bits_to_set&TMXR_MDM_DTR)
    if (!EscapeCommFunction (port->hPort, SETDTR)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_clear&TMXR_MDM_DTR)
    if (!EscapeCommFunction (port->hPort, CLRDTR)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_set&TMXR_MDM_RTS)
    if (!EscapeCommFunction (port->hPort, SETRTS)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (bits_to_clear&TMXR_MDM_RTS)
    if (!EscapeCommFunction (port->hPort, CLRRTS)) {
        sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
        return SCPE_IOERR;
        }
if (incoming_bits) {
    DWORD ModemStat;
    if (GetCommModemStatus (port->hPort, &ModemStat)) {
        sim_error_serial ("GetCommModemStatus", (int) GetLastError ());
        return SCPE_IOERR;
        }
    *incoming_bits = ((ModemStat&MS_CTS_ON)  ? TMXR_MDM_CTS : 0) |
                     ((ModemStat&MS_DSR_ON)  ? TMXR_MDM_DSR : 0) |
                     ((ModemStat&MS_RING_ON) ? TMXR_MDM_RNG : 0) |
                     ((ModemStat&MS_RLSD_ON) ? TMXR_MDM_DCD : 0);
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
{
DWORD read;
DWORD commerrors;
COMSTAT cs;
char *bptr;

if (!ClearCommError (port, &commerrors, &cs)) {         /* get the comm error flags  */
    sim_error_serial ("ClearCommError",                 /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                          /* return failure to caller */
    }

if (!ReadFile (port, (LPVOID) buffer,                   /* read any available characters */
               (DWORD) count, &read, NULL)) {
    sim_error_serial ("ReadFile",                       /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                          /* return failure to caller */
    }

if (commerrors & CE_BREAK) {                            /* was a BREAK detected? */
    bptr = (char *) memchr (buffer, 0, read);           /* search for the first NUL in the buffer */







|





|
|







840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
{
DWORD read;
DWORD commerrors;
COMSTAT cs;
char *bptr;

if (!ClearCommError (port->hPort, &commerrors, &cs)) {  /* get the comm error flags  */
    sim_error_serial ("ClearCommError",                 /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                          /* return failure to caller */
    }

if (!ReadFile (port->hPort, (LPVOID) buffer,            /* read any available characters */
               (DWORD) count, &read, &port->oReadSync)) {
    sim_error_serial ("ReadFile",                       /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                          /* return failure to caller */
    }

if (commerrors & CE_BREAK) {                            /* was a BREAK detected? */
    bptr = (char *) memchr (buffer, 0, read);           /* search for the first NUL in the buffer */
844
845
846
847
848
849
850
851
852
853
854

855
856
857
858
859




860


861
862
863
864
865
866
867
868
869
870







871
872
873
874
875
876
877




878
879
880
881
882
883
884
   "Count" characters are written from "buffer" to the serial port.  The actual
   number of characters written to the port is returned.  If an error occurred
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
DWORD written;

if (!WriteFile (port, (LPVOID) buffer,                  /* write the buffer to the serial port */
                (DWORD) count, &written, NULL)) {

    sim_error_serial ("WriteFile",                      /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                          /* return failure to caller */
    }
else




    return written;                                     /* return number of characters written */


}


/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{







CloseHandle (port);                                     /* close the port */
return;
}



#elif defined (__unix__) || defined(__APPLE__) || defined(__hpux)





#if defined(__linux) || defined(__linux__)
#include <dirent.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/stat.h>
#endif /* __linux__ */







|
|
|
|
>
|

|

<
>
>
>
>
|
>
>










>
>
>
>
>
>
>
|
|





>
>
>
>







875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890

891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
   "Count" characters are written from "buffer" to the serial port.  The actual
   number of characters written to the port is returned.  If an error occurred
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
if (WaitForSingleObject (port->oWriteReady.hEvent, 0) == WAIT_TIMEOUT)
    return 0;
if ((!WriteFile (port->hPort, (LPVOID) buffer,   /* write the buffer to the serial port */
                 (DWORD) count, NULL, &port->oWriteSync)) &&
    (GetLastError () != ERROR_IO_PENDING)) {
    sim_error_serial ("WriteFile",              /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                  /* return failure to caller */
    }

if ((!WaitCommEvent (port->hPort, &port->dwEvtMask, &port->oWriteReady)) &&
    (GetLastError () != ERROR_IO_PENDING)) {
    sim_error_serial ("WaitCommEvent",          /* function failed; report unexpected error */
                      (int) GetLastError ());
    return -1;                                  /* return failure to caller */
    }
return count;                                   /* return number of characters written/queued */
}


/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{
if (port->oWriteReady.hEvent)
    CloseHandle (port->oWriteReady.hEvent);               /* close the event handle */
if (port->oReadSync.hEvent)
    CloseHandle (port->oReadSync.hEvent);               /* close the event handle */
if (port->oWriteSync.hEvent)
    CloseHandle (port->oWriteSync.hEvent);              /* close the event handle */
if (port->hPort)
    CloseHandle (port->hPort);                          /* close the port */
free (port);
}



#elif defined (__unix__) || defined(__APPLE__) || defined(__hpux)

struct SERPORT {
    int port;
    };

#if defined(__linux) || defined(__linux__)
#include <dirent.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/stat.h>
#endif /* __linux__ */
970
971
972
973
974
975
976


















977
978
979
980
981
982
983
    port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */
    if (port != -1) {                                   /* open OK? */
        if (isatty (port))                              /* is device a TTY? */
            ++ports;
        close (port);
        }
    }


















#endif
return ports;
}

/* Open a serial port.

   The serial port designated by "name" is opened, and the handle to the port is







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
    port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */
    if (port != -1) {                                   /* open OK? */
        if (isatty (port))                              /* is device a TTY? */
            ++ports;
        close (port);
        }
    }
for (i=0; (ports < max) && (i < 64); ++i) {
    sprintf (list[ports].name, "/dev/tty%02d", i);
    port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */
    if (port != -1) {                                   /* open OK? */
        if (isatty (port))                              /* is device a TTY? */
            ++ports;
        close (port);
        }
    }
for (i=0; (ports < max) && (i < 8); ++i) {
    sprintf (list[ports].name, "/dev/ttyU%d", i);
    port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */
    if (port != -1) {                                   /* open OK? */
        if (isatty (port))                              /* is device a TTY? */
            ++ports;
        close (port);
        }
    }
#endif
return ports;
}

/* Open a serial port.

   The serial port designated by "name" is opened, and the handle to the port is
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
                                ECHOK   |               /* echo KILL */
                                ECHONL  |               /* echo NL */
                                NOFLSH  |               /* disable flush after interrupt */
                                TOSTOP  |               /* send SIGTTOU for background output */
                                IEXTEN;                 /* enable extended functions */

static const tcflag_t l_set   = 0;


SERHANDLE port;
struct termios tio;

port = open (name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */

if (port == -1) {                                       /* open failed? */
    if (errno != ENOENT && errno != EACCES)             /* file not found or can't open? */
        sim_error_serial ("open", errno);               /* no, so report unexpected error */







|
<
|







1095
1096
1097
1098
1099
1100
1101
1102

1103
1104
1105
1106
1107
1108
1109
1110
                                ECHOK   |               /* echo KILL */
                                ECHONL  |               /* echo NL */
                                NOFLSH  |               /* disable flush after interrupt */
                                TOSTOP  |               /* send SIGTTOU for background output */
                                IEXTEN;                 /* enable extended functions */

static const tcflag_t l_set   = 0;
int port;

SERHANDLE serport;
struct termios tio;

port = open (name, O_RDWR | O_NOCTTY | O_NONBLOCK);     /* open the port */

if (port == -1) {                                       /* open failed? */
    if (errno != ENOENT && errno != EACCES)             /* file not found or can't open? */
        sim_error_serial ("open", errno);               /* no, so report unexpected error */
1093
1094
1095
1096
1097
1098
1099


1100
1101
1102
1103
1104
1105
1106
1107

if (tcsetattr (port, TCSANOW, &tio)) {                  /* set the terminal attributes */
    sim_error_serial ("tcsetattr", errno);              /* function failed; report unexpected error */
    close (port);                                       /* close the port */
    return INVALID_HANDLE;                              /*   and return failure to caller */
    }



return port;                                            /* return port fd for success */
}


/* Configure a serial port.

   Port parameters are configured as specified in the "config" structure.  If
   "config" contains an invalid configuration value, or if the host system







>
>
|







1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174

if (tcsetattr (port, TCSANOW, &tio)) {                  /* set the terminal attributes */
    sim_error_serial ("tcsetattr", errno);              /* function failed; report unexpected error */
    close (port);                                       /* close the port */
    return INVALID_HANDLE;                              /*   and return failure to caller */
    }

serport = (SERHANDLE)calloc (1, sizeof(*serport));
serport->port = port;
return serport;                                         /* return port fd for success */
}


/* Configure a serial port.

   Port parameters are configured as specified in the "config" structure.  If
   "config" contains an invalid configuration value, or if the host system
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
          { 115200, B115200 } };

static const int32 baud_count = sizeof (baud_map) / sizeof (baud_map [0]);

static const tcflag_t charsize_map [4] = { CS5, CS6, CS7, CS8 };


if (tcgetattr (port, &tio)) {                           /* get the current configuration */
    sim_error_serial ("tcgetattr", errno);              /* function failed; report unexpected error */
    return SCPE_IOERR;                                  /* return failure status */
    }

for (i = 0; i < baud_count; i++)                        /* assign baud rate */
    if (config.baudrate == baud_map [i].rate) {         /* match mapping value? */
        cfsetispeed(&tio, baud_map [i].rate_code);      /* set input rate */







|







1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
          { 115200, B115200 } };

static const int32 baud_count = sizeof (baud_map) / sizeof (baud_map [0]);

static const tcflag_t charsize_map [4] = { CS5, CS6, CS7, CS8 };


if (tcgetattr (port->port, &tio)) {                     /* get the current configuration */
    sim_error_serial ("tcgetattr", errno);              /* function failed; report unexpected error */
    return SCPE_IOERR;                                  /* return failure status */
    }

for (i = 0; i < baud_count; i++)                        /* assign baud rate */
    if (config.baudrate == baud_map [i].rate) {         /* match mapping value? */
        cfsetispeed(&tio, baud_map [i].rate_code);      /* set input rate */
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
if (config.stopbits == 1)                               /* one stop bit? */
    tio.c_cflag = tio.c_cflag & ~CSTOPB;                /* clear two-bits flag */
else if (config.stopbits == 2)                          /* two stop bits? */
    tio.c_cflag = tio.c_cflag | CSTOPB;                 /* set two-bits flag */
else                                                    /* some other number? */
    return SCPE_ARG;                                    /* not a valid number of stop bits */

if (tcsetattr (port, TCSAFLUSH, &tio)) {                /* set the new configuration */
    sim_error_serial ("tcsetattr", errno);              /* function failed; report unexpected error */
    return SCPE_IERR;                                   /* return failure status */
    }

return SCPE_OK;                                         /* configuration set successfully */
}








|







1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
if (config.stopbits == 1)                               /* one stop bit? */
    tio.c_cflag = tio.c_cflag & ~CSTOPB;                /* clear two-bits flag */
else if (config.stopbits == 2)                          /* two stop bits? */
    tio.c_cflag = tio.c_cflag | CSTOPB;                 /* set two-bits flag */
else                                                    /* some other number? */
    return SCPE_ARG;                                    /* not a valid number of stop bits */

if (tcsetattr (port->port, TCSAFLUSH, &tio)) {          /* set the new configuration */
    sim_error_serial ("tcsetattr", errno);              /* function failed; report unexpected error */
    return SCPE_IERR;                                   /* return failure status */
    }

return SCPE_OK;                                         /* configuration set successfully */
}

1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
if ((bits_to_set & ~(TMXR_MDM_OUTGOING)) ||         /* Assure only settable bits */
    (bits_to_clear & ~(TMXR_MDM_OUTGOING)) ||
    (bits_to_set & bits_to_clear))                  /* and can't set and clear the same bits */
    return SCPE_ARG;
if (bits_to_set) {
    bits = ((bits_to_set&TMXR_MDM_DTR) ? TIOCM_DTR : 0) |
           ((bits_to_set&TMXR_MDM_RTS) ? TIOCM_RTS : 0);
    if (ioctl (port, TIOCMBIS, &bits)) {            /* set the desired bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    }
if (bits_to_clear) {
    bits = ((bits_to_clear&TMXR_MDM_DTR) ? TIOCM_DTR : 0) |
           ((bits_to_clear&TMXR_MDM_RTS) ? TIOCM_RTS : 0);
    if (ioctl (port, TIOCMBIC, &bits)) {            /* clear the desired bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    }
if (incoming_bits) {
    if (ioctl (port, TIOCMGET, &bits)) {            /* get the modem bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    *incoming_bits = ((bits&TIOCM_CTS) ? TMXR_MDM_CTS : 0) |
                     ((bits&TIOCM_DSR) ? TMXR_MDM_DSR : 0) |
                     ((bits&TIOCM_RNG) ? TMXR_MDM_RNG : 0) |
                     ((bits&TIOCM_CAR) ? TMXR_MDM_DCD : 0);







|







|





|







1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
if ((bits_to_set & ~(TMXR_MDM_OUTGOING)) ||         /* Assure only settable bits */
    (bits_to_clear & ~(TMXR_MDM_OUTGOING)) ||
    (bits_to_set & bits_to_clear))                  /* and can't set and clear the same bits */
    return SCPE_ARG;
if (bits_to_set) {
    bits = ((bits_to_set&TMXR_MDM_DTR) ? TIOCM_DTR : 0) |
           ((bits_to_set&TMXR_MDM_RTS) ? TIOCM_RTS : 0);
    if (ioctl (port->port, TIOCMBIS, &bits)) {      /* set the desired bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    }
if (bits_to_clear) {
    bits = ((bits_to_clear&TMXR_MDM_DTR) ? TIOCM_DTR : 0) |
           ((bits_to_clear&TMXR_MDM_RTS) ? TIOCM_RTS : 0);
    if (ioctl (port->port, TIOCMBIC, &bits)) {      /* clear the desired bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    }
if (incoming_bits) {
    if (ioctl (port->port, TIOCMGET, &bits)) {      /* get the modem bits */
        sim_error_serial ("ioctl", errno);          /* report unexpected error */
        return SCPE_IOERR;                          /* return failure status */
        }
    *incoming_bits = ((bits&TIOCM_CTS) ? TMXR_MDM_CTS : 0) |
                     ((bits&TIOCM_DSR) ? TMXR_MDM_DSR : 0) |
                     ((bits&TIOCM_RNG) ? TMXR_MDM_RNG : 0) |
                     ((bits&TIOCM_CAR) ? TMXR_MDM_DCD : 0);
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279

int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
{
int read_count;
char *bptr, *cptr;
int32 remaining;

read_count = read (port, (void *) buffer, (size_t) count);  /* read from the serial port */

if (read_count == -1)                                       /* read error? */
    if (errno == EAGAIN)                                    /* no characters available? */
        return 0;                                           /* return 0 to indicate */
    else                                                    /* some other problem */
        sim_error_serial ("read", errno);                   /* report unexpected error */








|







1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346

int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
{
int read_count;
char *bptr, *cptr;
int32 remaining;

read_count = read (port->port, (void *) buffer, (size_t) count);/* read from the serial port */

if (read_count == -1)                                       /* read error? */
    if (errno == EAGAIN)                                    /* no characters available? */
        return 0;                                           /* return 0 to indicate */
    else                                                    /* some other problem */
        sim_error_serial ("read", errno);                   /* report unexpected error */

1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
int written;

written = write (port, (void *) buffer, (size_t) count);    /* write the buffer to the serial port */

if (written == -1) {
    if (errno == EWOULDBLOCK)
        written = 0;                                        /* not an error, but nothing written */
#if defined(EAGAIN)
    else if (errno == EAGAIN)
        written = 0;                                        /* not an error, but nothing written */







|







1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
int written;

written = write (port->port, (void *) buffer, (size_t) count);/* write the buffer to the serial port */

if (written == -1) {
    if (errno == EWOULDBLOCK)
        written = 0;                                        /* not an error, but nothing written */
#if defined(EAGAIN)
    else if (errno == EAGAIN)
        written = 0;                                        /* not an error, but nothing written */
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{
close (port);                                           /* close the port */
return;
}


#elif defined (VMS)

/* VMS implementation */








|
|







1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{
close (port->port);                                           /* close the port */
free (port);
}


#elif defined (VMS)

/* VMS implementation */

1385
1386
1387
1388
1389
1390
1391





1392
1393
1394
1395
1396
1397
1398

typedef struct {
    unsigned short buffer_size;
    unsigned short item_code;
    void *buffer_address;
    void *return_length_address;
    } ITEM;






/* Enumerate the available serial ports.

   The serial port names generated by attempting to open /dev/ttyS0 thru
   /dev/ttyS53 and /dev/ttyUSB0 thru /dev/ttyUSB0.  Ones we can open and
   are ttys (as determined by isatty()) are added to the list.  The list 
   is sorted alphabetically by device name.







>
>
>
>
>







1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470

typedef struct {
    unsigned short buffer_size;
    unsigned short item_code;
    void *buffer_address;
    void *return_length_address;
    } ITEM;

struct SERPORT {
    uint32 port;
    IOSB write_iosb;
    };

/* Enumerate the available serial ports.

   The serial port names generated by attempting to open /dev/ttyS0 thru
   /dev/ttyS53 and /dev/ttyUSB0 thru /dev/ttyUSB0.  Ones we can open and
   are ttys (as determined by isatty()) are added to the list.  The list 
   is sorted alphabetically by device name.
1493
1494
1495
1496
1497
1498
1499

1500
1501
1502
1503
1504
1505
1506
IOSB iosb;
$DESCRIPTOR (devnam, name);
uint32 devclass;
ITEM items[] = { {sizeof (devclass), DVI$_DEVCLASS, &devclass, NULL},
                 {                0,             0,      NULL, NULL}};
SENSE_BUF start_mode = { 0 };
SENSE_BUF run_mode = { 0 };


devnam.dsc$w_length = strlen (devnam.dsc$a_pointer);
status = sys$assign (&devnam, &chan, 0, 0);
if (status != SS$_NORMAL) 
    return INVALID_HANDLE;
status = sys$getdviw (0, chan, NULL, items, &iosb, NULL, 0, NULL);
if ((status != SS$_NORMAL)      || 







>







1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
IOSB iosb;
$DESCRIPTOR (devnam, name);
uint32 devclass;
ITEM items[] = { {sizeof (devclass), DVI$_DEVCLASS, &devclass, NULL},
                 {                0,             0,      NULL, NULL}};
SENSE_BUF start_mode = { 0 };
SENSE_BUF run_mode = { 0 };
SERHANDLE port;

devnam.dsc$w_length = strlen (devnam.dsc$a_pointer);
status = sys$assign (&devnam, &chan, 0, 0);
if (status != SS$_NORMAL) 
    return INVALID_HANDLE;
status = sys$getdviw (0, chan, NULL, items, &iosb, NULL, 0, NULL);
if ((status != SS$_NORMAL)      || 
1520
1521
1522
1523
1524
1525
1526



1527
1528
1529
1530
1531
1532
1533
1534
run_mode.stat2 = start_mode.stat2 | TT2$M_PASTHRU;
status = sys$qiow (0, chan, IO$_SETMODE, &iosb, 0, 0,
    &run_mode, sizeof (run_mode), 0, 0, 0, 0);
if ((status != SS$_NORMAL) || (iosb.status != SS$_NORMAL)) {
    sys$dassgn (chan);
    return INVALID_HANDLE;
    }



return chan;                                            /* return channel for success */
}


/* Configure a serial port.

   Port parameters are configured as specified in the "config" structure.  If
   "config" contains an invalid configuration value, or if the host system







>
>
>
|







1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
run_mode.stat2 = start_mode.stat2 | TT2$M_PASTHRU;
status = sys$qiow (0, chan, IO$_SETMODE, &iosb, 0, 0,
    &run_mode, sizeof (run_mode), 0, 0, 0, 0);
if ((status != SS$_NORMAL) || (iosb.status != SS$_NORMAL)) {
    sys$dassgn (chan);
    return INVALID_HANDLE;
    }
port = (SERHANDLE)calloc (1, sizeof(*port));
port->port = chan;
port->write_iosb.status = 1;
return port;                                            /* return channel for success */
}


/* Configure a serial port.

   Port parameters are configured as specified in the "config" structure.  If
   "config" contains an invalid configuration value, or if the host system
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
          { 150,    TT$C_BAUD_150    }, { 300,    TT$C_BAUD_300    }, {  600,   TT$C_BAUD_600    }, {  1200,  TT$C_BAUD_1200  },
          { 1800,   TT$C_BAUD_1800   }, { 2000,   TT$C_BAUD_2000   }, { 2400,   TT$C_BAUD_2400   }, {  3600,  TT$C_BAUD_3600  },
          { 4800,   TT$C_BAUD_4800   }, { 7200,   TT$C_BAUD_7200   }, { 9600,   TT$C_BAUD_9600   }, { 19200,  TT$C_BAUD_19200 },
          { 38400,  TT$C_BAUD_38400  }, { 57600,  TT$C_BAUD_57600  }, { 76800,  TT$C_BAUD_76800  }, { 115200, TT$C_BAUD_115200} };

static const int32 baud_count = sizeof (baud_map) / sizeof (baud_map [0]);

status = sys$qiow (0, port, IO$_SENSEMODE, &iosb, 0, 0, &sense, sizeof(sense), 0, NULL, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("config-SENSEMODE", status);      /* report unexpected error */
    return SCPE_IOERR;
    }








|







1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
          { 150,    TT$C_BAUD_150    }, { 300,    TT$C_BAUD_300    }, {  600,   TT$C_BAUD_600    }, {  1200,  TT$C_BAUD_1200  },
          { 1800,   TT$C_BAUD_1800   }, { 2000,   TT$C_BAUD_2000   }, { 2400,   TT$C_BAUD_2400   }, {  3600,  TT$C_BAUD_3600  },
          { 4800,   TT$C_BAUD_4800   }, { 7200,   TT$C_BAUD_7200   }, { 9600,   TT$C_BAUD_9600   }, { 19200,  TT$C_BAUD_19200 },
          { 38400,  TT$C_BAUD_38400  }, { 57600,  TT$C_BAUD_57600  }, { 76800,  TT$C_BAUD_76800  }, { 115200, TT$C_BAUD_115200} };

static const int32 baud_count = sizeof (baud_map) / sizeof (baud_map [0]);

status = sys$qiow (0, port->port, IO$_SENSEMODE, &iosb, 0, 0, &sense, sizeof(sense), 0, NULL, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("config-SENSEMODE", status);      /* report unexpected error */
    return SCPE_IOERR;
    }

1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
            stopbits = TT$M_TWOSTOP;                    /* speeds 150baud or less */
            break;
            }
    default:
        return SCPE_ARG;                                /* not a valid number of stop bits */
    }

status = sys$qiow (0, port, IO$_SETMODE, &iosb, 0, 0,
    &sense, sizeof (sense), speed, 0, parity | charsize | stopbits, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("config-SETMODE", status);        /* report unexpected error */
    return SCPE_IOERR;
    }







|







1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
            stopbits = TT$M_TWOSTOP;                    /* speeds 150baud or less */
            break;
            }
    default:
        return SCPE_ARG;                                /* not a valid number of stop bits */
    }

status = sys$qiow (0, port->port, IO$_SETMODE, &iosb, 0, 0,
    &sense, sizeof (sense), speed, 0, parity | charsize | stopbits, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("config-SETMODE", status);        /* report unexpected error */
    return SCPE_IOERR;
    }
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
if (bits_to_set)
    bits[0] |= (((bits_to_set&TMXR_MDM_DTR) ? TT$M_DS_DTR : 0) |
                ((bits_to_set&TMXR_MDM_RTS) ? TT$M_DS_RTS : 0)) << 16;
if (bits_to_clear)
    bits[0] |= (((bits_to_clear&TMXR_MDM_DTR) ? TT$M_DS_DTR : 0) |
                ((bits_to_clear&TMXR_MDM_RTS) ? TT$M_DS_RTS : 0)) << 24;
if (bits_to_set || bits_to_clear) {
    status = sys$qiow (0, port, IO$_SETMODE|IO$M_SET_MODEM|IO$M_MAINT, &iosb, 0, 0,
                       bits, 0, 0, 0, 0, 0);
    if (status == SS$_NORMAL)
        status = iosb.status;
    if (status != SS$_NORMAL) {
        sim_error_serial ("control-SETMODE", status);      /* report unexpected error */
        return SCPE_IOERR;
        }
    }
if (incoming_bits) {
    uint32 modem;

    status = sys$qiow (0, port, IO$_SENSEMODE|IO$M_RD_MODEM, &iosb, 0, 0,
                       bits, 0, 0, 0, 0, 0);
    if (status == SS$_NORMAL)
        status = iosb.status;
    if (status != SS$_NORMAL) {
        sim_error_serial ("control-SENSEMODE", status);      /* report unexpected error */
        return SCPE_IOERR;
        }







|











|







1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
if (bits_to_set)
    bits[0] |= (((bits_to_set&TMXR_MDM_DTR) ? TT$M_DS_DTR : 0) |
                ((bits_to_set&TMXR_MDM_RTS) ? TT$M_DS_RTS : 0)) << 16;
if (bits_to_clear)
    bits[0] |= (((bits_to_clear&TMXR_MDM_DTR) ? TT$M_DS_DTR : 0) |
                ((bits_to_clear&TMXR_MDM_RTS) ? TT$M_DS_RTS : 0)) << 24;
if (bits_to_set || bits_to_clear) {
    status = sys$qiow (0, port->port, IO$_SETMODE|IO$M_SET_MODEM|IO$M_MAINT, &iosb, 0, 0,
                       bits, 0, 0, 0, 0, 0);
    if (status == SS$_NORMAL)
        status = iosb.status;
    if (status != SS$_NORMAL) {
        sim_error_serial ("control-SETMODE", status);      /* report unexpected error */
        return SCPE_IOERR;
        }
    }
if (incoming_bits) {
    uint32 modem;

    status = sys$qiow (0, port->port, IO$_SENSEMODE|IO$M_RD_MODEM, &iosb, 0, 0,
                       bits, 0, 0, 0, 0, 0);
    if (status == SS$_NORMAL)
        status = iosb.status;
    if (status != SS$_NORMAL) {
        sim_error_serial ("control-SENSEMODE", status);      /* report unexpected error */
        return SCPE_IOERR;
        }
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
int read_count = 0;
uint32 status;
static uint32 term[2] = {0, 0};
unsigned char buf[4];
IOSB iosb;
SENSE_BUF sense;

status = sys$qiow (0, port, IO$_SENSEMODE | IO$M_TYPEAHDCNT, &iosb,
    0, 0, &sense, 8, 0, term, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("read", status);                      /* report unexpected error */
    return -1;
    }
if (sense.sense_count == 0)                                 /* no characters available? */
    return 0;                                               /* return 0 to indicate */
status = sys$qiow (0, port, IO$_READLBLK | IO$M_NOECHO | IO$M_NOFILTR | IO$M_TIMED | IO$M_TRMNOECHO, 
                   &iosb, 0, 0, buffer, (count < sense.sense_count) ? count : sense.sense_count, 0, term, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("read", status);                      /* report unexpected error */
    return -1;
    }







|









|







1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
int read_count = 0;
uint32 status;
static uint32 term[2] = {0, 0};
unsigned char buf[4];
IOSB iosb;
SENSE_BUF sense;

status = sys$qiow (0, port->port, IO$_SENSEMODE | IO$M_TYPEAHDCNT, &iosb,
    0, 0, &sense, 8, 0, term, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("read", status);                      /* report unexpected error */
    return -1;
    }
if (sense.sense_count == 0)                                 /* no characters available? */
    return 0;                                               /* return 0 to indicate */
status = sys$qiow (0, port->port, IO$_READLBLK | IO$M_NOECHO | IO$M_NOFILTR | IO$M_TIMED | IO$M_TRMNOECHO, 
                   &iosb, 0, 0, buffer, (count < sense.sense_count) ? count : sense.sense_count, 0, term, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("read", status);                      /* report unexpected error */
    return -1;
    }
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
   number of characters written to the port is returned.  If an error occurred
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
uint32 status;
static uint32 term[2] = {0, 0};
unsigned char buf[4];
IOSB iosb;
uint32 devsts = 0;
#define UCB$M_BSY   0x100           /* Device I/O busy flag */
ITEM items[] = { {sizeof (devsts), DVI$_STS, &devsts, NULL},
                 {              0,        0,    NULL, NULL}};

status = sys$getdviw (0, port, NULL, items, &iosb, NULL, 0, 0);
if (status == SS$_NORMAL)
    status = iosb.status;
if (status != SS$_NORMAL) {
    sim_error_serial ("write-GETDVI", status);          /* report unexpected error */
    return -1;
    }
if (devsts & UCB$M_BSY)
    return 0;                                           /* Would block */
status = sys$qiow (0, port, IO$_WRITELBLK | IO$M_NOFORMAT,
                   NULL, 0, 0, buffer, count, 0, 0, 0, 0);
if (status != SS$_NORMAL) {
    sim_error_serial ("write", status);                 /* report unexpected error */
    return -1;
    }
return (int32)iosb.count;                               /* return number of characters written */
}


/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{
sys$dassgn (port);                                      /* close the port */
return;
}


#else

/* Non-implemented stubs */

/* Enumerate the available serial ports. */








<
<
<
<
<
<
<

<
<
|
<
<
|
<
<
<
|
|




|










|
|

<







1822
1823
1824
1825
1826
1827
1828







1829


1830


1831



1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851

1852
1853
1854
1855
1856
1857
1858
   number of characters written to the port is returned.  If an error occurred
   on writing, -1 is returned.
*/

int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
uint32 status;










if (port->write_iosb.status == 0)           /* Prior write not done yet? */


    return 0;



status = sys$qio (0, port->port, IO$_WRITELBLK | IO$M_NOFORMAT,
                  &port->write_iosb, 0, 0, buffer, count, 0, 0, 0, 0);
if (status != SS$_NORMAL) {
    sim_error_serial ("write", status);                 /* report unexpected error */
    return -1;
    }
return (int32)count;                                    /* return number of characters written */
}


/* Close a serial port.

   The serial port is closed.  Errors are ignored.
*/

static void sim_close_os_serial (SERHANDLE port)
{
sys$dassgn (port->port);                                /* close the port */
free (port);
}


#else

/* Non-implemented stubs */

/* Enumerate the available serial ports. */

1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
}


/* Close a serial port */

static void sim_close_os_serial (SERHANDLE port)
{
return;
}



#endif                                                  /* end else !implemented */







<





1901
1902
1903
1904
1905
1906
1907

1908
1909
1910
1911
1912
}


/* Close a serial port */

static void sim_close_os_serial (SERHANDLE port)
{

}



#endif                                                  /* end else !implemented */
Changes to src/sim_serial.h.
26
27
28
29
30
31
32









33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97




98
99
   07-Oct-08    JDB     [serial] Created file
*/


#ifndef SIM_SERIAL_H_
#define SIM_SERIAL_H_    0










#if defined (_WIN32)                        /* Windows definitions */

/* We need the basic Win32 definitions, but including "windows.h" also includes
   "winsock.h" as well.  However, "sim_sock.h" explicitly includes "winsock2.h,"
   and this file cannot coexist with "winsock.h".  So we set a guard definition
   that prevents "winsock.h" from being included.
*/

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  INVALID_HANDLE_VALUE
#endif /* !defined(INVALID_HANDLE) */

#elif defined (__unix__) || defined (__APPLE__) || defined (__hpux) /* UNIX definitions */

#include <fcntl.h>
#ifdef __hpux
#include <sys/modem.h>
#endif
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>

#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  -1
#endif /* !defined(INVALID_HANDLE) */

#elif defined (VMS)                             /* VMS definitions */
#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  (uint32)(-1)
#endif /* !defined(INVALID_HANDLE) */

#else                                           /* Non-implemented definitions */

#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  -1
#endif /* !defined(INVALID_HANDLE) */

#endif  /* OS variants */

#ifndef SIMH_SERHANDLE_DEFINED
#define SIMH_SERHANDLE_DEFINED 0
#if defined (_WIN32)                            /* Windows definitions */
typedef void *SERHANDLE;
#else                                           /* all other platforms */
typedef int SERHANDLE;
#endif
#endif /* SERHANDLE_DEFINED */


/* Common definitions */

/* Global routines */
#include "sim_tmxr.h"                           /* need TMLN definition and modem definitions */

extern SERHANDLE sim_open_serial    (char *name, TMLN *lp, t_stat *status);
extern t_stat    sim_config_serial  (SERHANDLE port, const char *config);
extern t_stat    sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits);
extern int32     sim_read_serial    (SERHANDLE port, char *buffer, int32 count, char *brk);
extern int32     sim_write_serial   (SERHANDLE port, char *buffer, int32 count);
extern void      sim_close_serial   (SERHANDLE port);
extern t_stat    sim_show_serial    (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc);





#endif







>
>
>
>
>
>
>
>
>













|













|




|





|




<
<
<
<
<
<
<
<
<







|




|
>
>
>
>


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84









85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
   07-Oct-08    JDB     [serial] Created file
*/


#ifndef SIM_SERIAL_H_
#define SIM_SERIAL_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

#ifndef SIMH_SERHANDLE_DEFINED
#define SIMH_SERHANDLE_DEFINED 0
typedef struct SERPORT *SERHANDLE;
#endif /* SERHANDLE_DEFINED */

#if defined (_WIN32)                        /* Windows definitions */

/* We need the basic Win32 definitions, but including "windows.h" also includes
   "winsock.h" as well.  However, "sim_sock.h" explicitly includes "winsock2.h,"
   and this file cannot coexist with "winsock.h".  So we set a guard definition
   that prevents "winsock.h" from being included.
*/

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  (SERHANDLE)INVALID_HANDLE_VALUE
#endif /* !defined(INVALID_HANDLE) */

#elif defined (__unix__) || defined (__APPLE__) || defined (__hpux) /* UNIX definitions */

#include <fcntl.h>
#ifdef __hpux
#include <sys/modem.h>
#endif
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>

#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  ((SERHANDLE)(void *)-1)
#endif /* !defined(INVALID_HANDLE) */

#elif defined (VMS)                             /* VMS definitions */
#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  ((SERHANDLE)(void *)-1)
#endif /* !defined(INVALID_HANDLE) */

#else                                           /* Non-implemented definitions */

#if !defined(INVALID_HANDLE)
#define INVALID_HANDLE  ((SERHANDLE)(void *)-1)
#endif /* !defined(INVALID_HANDLE) */

#endif  /* OS variants */











/* Common definitions */

/* Global routines */
#include "sim_tmxr.h"                           /* need TMLN definition and modem definitions */

extern SERHANDLE sim_open_serial    (char *name, TMLN *lp, t_stat *status);
extern t_stat    sim_config_serial  (SERHANDLE port, CONST char *config);
extern t_stat    sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits);
extern int32     sim_read_serial    (SERHANDLE port, char *buffer, int32 count, char *brk);
extern int32     sim_write_serial   (SERHANDLE port, char *buffer, int32 count);
extern void      sim_close_serial   (SERHANDLE port);
extern t_stat    sim_show_serial    (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc);

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_sock.c.
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
static int     WSAAPI s_getnameinfo (const struct sockaddr *sa, socklen_t salen,
                                     char *host, size_t hostlen,
                                     char *serv, size_t servlen,
                                     int flags)
{
struct hostent *he;
struct servent *se = NULL;
struct sockaddr_in *sin = (struct sockaddr_in *)sa;

if (sin->sin_family != PF_INET)
    return EAI_FAMILY;
if ((NULL == host) && (NULL == serv))
    return EAI_NONAME;
if ((serv) && (servlen > 0)) {
    if (flags & NI_NUMERICSERV)







|







380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
static int     WSAAPI s_getnameinfo (const struct sockaddr *sa, socklen_t salen,
                                     char *host, size_t hostlen,
                                     char *serv, size_t servlen,
                                     int flags)
{
struct hostent *he;
struct servent *se = NULL;
const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;

if (sin->sin_family != PF_INET)
    return EAI_FAMILY;
if ((NULL == host) && (NULL == serv))
    return EAI_NONAME;
if ((serv) && (servlen > 0)) {
    if (flags & NI_NUMERICSERV)
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
        strcpy(serv, buf);
        }
    }
if ((host) && (hostlen > 0)) {
    if (flags & NI_NUMERICHOST)
        he = NULL;
    else
        he = gethostbyaddr((char *)&sin->sin_addr, 4, AF_INET);
    if (he) {
        if (hostlen < strlen(he->h_name)+1)
            return EAI_OVERFLOW;
        strcpy(host, he->h_name);
        }
    else {
        if (flags & NI_NAMEREQD)







|







412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
        strcpy(serv, buf);
        }
    }
if ((host) && (hostlen > 0)) {
    if (flags & NI_NUMERICHOST)
        he = NULL;
    else
        he = gethostbyaddr((const char *)&sin->sin_addr, 4, AF_INET);
    if (he) {
        if (hostlen < strlen(he->h_name)+1)
            return EAI_OVERFLOW;
        strcpy(host, he->h_name);
        }
    else {
        if (flags & NI_NAMEREQD)
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0;                      /* handle to DLL */
#else
static void *hLib = NULL;                       /* handle to Library */
#endif
static int lib_loaded = 0;                      /* 0=not loaded, 1=loaded, 2=library load failed, 3=Func load failed */
static char* lib_name = "Ws2_32.dll";

/* load function pointer from DLL */
typedef int (*_func)();

static void load_function(char* function, _func* func_ptr) {
#ifdef _WIN32
    *func_ptr = (_func)GetProcAddress(hLib, function);
#else
    *func_ptr = (_func)dlsym(hLib, function);
#endif
    if (*func_ptr == 0) {
    char* msg = "Sockets: Failed to find function '%s' in %s\r\n";

    sim_printf (msg, function, lib_name);
    lib_loaded = 3;
  }
}

/* load Ws2_32.dll as required */
int load_ws2(void) {
  switch(lib_loaded) {
    case 0:                  /* not loaded */
            /* attempt to load DLL */
#ifdef _WIN32
      hLib = LoadLibraryA(lib_name);
#else
      hLib = dlopen(lib_name, RTLD_NOW);
#endif
      if (hLib == 0) {
        /* failed to load DLL */
        char* msg  = "Sockets: Failed to load %s\r\n";

        sim_printf (msg, lib_name);
        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */
        lib_loaded = 1;
      }








|




|






|
<
<
















|
<
<







441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460


461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477


478
479
480
481
482
483
484
/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0;                      /* handle to DLL */
#else
static void *hLib = NULL;                       /* handle to Library */
#endif
static int lib_loaded = 0;                      /* 0=not loaded, 1=loaded, 2=library load failed, 3=Func load failed */
static const char* lib_name = "Ws2_32.dll";

/* load function pointer from DLL */
typedef int (*_func)();

static void load_function(const char* function, _func* func_ptr) {
#ifdef _WIN32
    *func_ptr = (_func)GetProcAddress(hLib, function);
#else
    *func_ptr = (_func)dlsym(hLib, function);
#endif
    if (*func_ptr == 0) {
    sim_printf ("Sockets: Failed to find function '%s' in %s\r\n", function, lib_name);


    lib_loaded = 3;
  }
}

/* load Ws2_32.dll as required */
int load_ws2(void) {
  switch(lib_loaded) {
    case 0:                  /* not loaded */
            /* attempt to load DLL */
#ifdef _WIN32
      hLib = LoadLibraryA(lib_name);
#else
      hLib = dlopen(lib_name, RTLD_NOW);
#endif
      if (hLib == 0) {
        /* failed to load DLL */
        sim_printf ("Sockets: Failed to load %s\r\n", lib_name);


        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */
        lib_loaded = 1;
      }

536
537
538
539
540
541
542
543
544

545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562



563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                        out of range, a result can't fit into a result buffer, 
                        a service name doesn't exist, or a validation name 
                        doesn't match the parsed host)
*/

int sim_parse_addr (const char *cptr, char *host, size_t host_len, const char *default_host, char *port, size_t port_len, const char *default_port, const char *validate_addr)
{
char gbuf[CBUFSIZE];
char *hostp, *portp;

char *endc;
unsigned long portval;

if ((host != NULL) && (host_len != 0))
    memset (host, 0, host_len);
if ((port != NULL) && (port_len != 0))
    memset (port, 0, port_len);
if ((cptr == NULL) || (*cptr == 0)) {
    if (((default_host == NULL) || (*default_host == 0)) || ((default_port == NULL) || (*default_port == 0)))
        return -1;
    if ((host == NULL) || (port == NULL))
        return -1;                                  /* no place */
    if ((strlen(default_host) >= host_len) || (strlen(default_port) >= port_len))
        return -1;                                  /* no room */
    strcpy (host, default_host);
    strcpy (port, default_port);
    return 0;
    }



gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
hostp = gbuf;                                           /* default addr */
portp = NULL;
if ((portp = strrchr (gbuf, ':')) &&                    /* x:y? split */
    (NULL == strchr (portp, ']'))) {
    *portp++ = 0;
    if (*portp == '\0')
        portp = (char *)default_port;
    }
else {                                                  /* No colon in input */
    portp = gbuf;                                       /* Input is the port specifier */
    hostp = (char *)default_host;                       /* host is defaulted if provided */
    }
if (portp != NULL) {
    portval = strtoul(portp, &endc, 10);
    if ((*endc == '\0') && ((portval == 0) || (portval > 65535)))
        return -1;                                      /* numeric value too big */
    if (*endc != '\0') {
        struct servent *se = getservbyname(portp, "tcp");







|
|
>


















>
>
>








|



|







532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
                        out of range, a result can't fit into a result buffer, 
                        a service name doesn't exist, or a validation name 
                        doesn't match the parsed host)
*/

int sim_parse_addr (const char *cptr, char *host, size_t host_len, const char *default_host, char *port, size_t port_len, const char *default_port, const char *validate_addr)
{
char gbuf[CBUFSIZE], default_pbuf[CBUFSIZE];
const char *hostp;
char *portp;
char *endc;
unsigned long portval;

if ((host != NULL) && (host_len != 0))
    memset (host, 0, host_len);
if ((port != NULL) && (port_len != 0))
    memset (port, 0, port_len);
if ((cptr == NULL) || (*cptr == 0)) {
    if (((default_host == NULL) || (*default_host == 0)) || ((default_port == NULL) || (*default_port == 0)))
        return -1;
    if ((host == NULL) || (port == NULL))
        return -1;                                  /* no place */
    if ((strlen(default_host) >= host_len) || (strlen(default_port) >= port_len))
        return -1;                                  /* no room */
    strcpy (host, default_host);
    strcpy (port, default_port);
    return 0;
    }
memset (default_pbuf, 0, sizeof(default_pbuf));
if (default_port)
    strncpy (default_pbuf, default_port, sizeof(default_pbuf)-1);
gbuf[sizeof(gbuf)-1] = '\0';
strncpy (gbuf, cptr, sizeof(gbuf)-1);
hostp = gbuf;                                           /* default addr */
portp = NULL;
if ((portp = strrchr (gbuf, ':')) &&                    /* x:y? split */
    (NULL == strchr (portp, ']'))) {
    *portp++ = 0;
    if (*portp == '\0')
        portp = default_pbuf;
    }
else {                                                  /* No colon in input */
    portp = gbuf;                                       /* Input is the port specifier */
    hostp = (const char *)default_host;                 /* host is defaulted if provided */
    }
if (portp != NULL) {
    portval = strtoul(portp, &endc, 10);
    if ((*endc == '\0') && ((portval == 0) || (portval > 65535)))
        return -1;                                      /* numeric value too big */
    if (*endc != '\0') {
        struct servent *se = getservbyname(portp, "tcp");
594
595
596
597
598
599
600

601
602
603
604
605
606
607
608
609
        }
if (hostp != NULL) {
    if (']' == hostp[strlen(hostp)-1]) {
        if ('[' != hostp[0])
            return -1;                                  /* invalid domain literal */
        /* host may be the const default_host so move to temp buffer before modifying */
        strncpy(gbuf, hostp+1, sizeof(gbuf)-1);         /* remove brackets from domain literal host */

        hostp = gbuf;
        hostp[strlen(hostp)-1] = '\0';
        }
    }
if (host) {                                             /* host wanted? */
    if (hostp != NULL) {
        if (strlen(hostp) >= host_len)
            return -1;                                  /* no room */
        else







>

<







594
595
596
597
598
599
600
601
602

603
604
605
606
607
608
609
        }
if (hostp != NULL) {
    if (']' == hostp[strlen(hostp)-1]) {
        if ('[' != hostp[0])
            return -1;                                  /* invalid domain literal */
        /* host may be the const default_host so move to temp buffer before modifying */
        strncpy(gbuf, hostp+1, sizeof(gbuf)-1);         /* remove brackets from domain literal host */
        gbuf[strlen(gbuf)-1] = '\0';
        hostp = gbuf;

        }
    }
if (host) {                                             /* host wanted? */
    if (hostp != NULL) {
        if (strlen(hostp) >= host_len)
            return -1;                                  /* no room */
        else
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130

1131
1132
1133
1134
1135
1136
1137
1138
}

int sim_check_conn (SOCKET sock, int rd)
{
fd_set rw_set, er_set;
fd_set *rw_p = &rw_set;
fd_set *er_p = &er_set;
struct timeval tz;
struct sockaddr_storage peername;
#if defined (macintosh) || defined (__linux) || defined (__linux__) || \
    defined (__APPLE__) || defined (__OpenBSD__) || \
    defined(__NetBSD__) || defined(__FreeBSD__) || \
    (defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED)) || \
    defined (__HAIKU__)
socklen_t peernamesize = (socklen_t)sizeof(peername);
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int peernamesize = (int)sizeof(peername);
#else 
size_t peernamesize = sizeof(peername); 
#endif

timerclear (&tz);
FD_ZERO (rw_p);
FD_ZERO (er_p);
FD_SET (sock, rw_p);
FD_SET (sock, er_p);
if (rd)
    select ((int) sock + 1, rw_p, NULL, er_p, &tz);

else select ((int) sock + 1, NULL, rw_p, er_p, &tz);
if (FD_ISSET (sock, er_p))
    return -1;
if (FD_ISSET (sock, rw_p)) {
    if (0 == getpeername (sock, (struct sockaddr *)&peername, &peernamesize))
        return 1;
    else
        return -1;







|















|





|
>
|







1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
}

int sim_check_conn (SOCKET sock, int rd)
{
fd_set rw_set, er_set;
fd_set *rw_p = &rw_set;
fd_set *er_p = &er_set;
struct timeval zero;
struct sockaddr_storage peername;
#if defined (macintosh) || defined (__linux) || defined (__linux__) || \
    defined (__APPLE__) || defined (__OpenBSD__) || \
    defined(__NetBSD__) || defined(__FreeBSD__) || \
    (defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED)) || \
    defined (__HAIKU__)
socklen_t peernamesize = (socklen_t)sizeof(peername);
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int peernamesize = (int)sizeof(peername);
#else 
size_t peernamesize = sizeof(peername); 
#endif

memset (&zero, 0, sizeof(zero));
FD_ZERO (rw_p);
FD_ZERO (er_p);
FD_SET (sock, rw_p);
FD_SET (sock, er_p);
if (rd)
    select ((int) sock + 1, rw_p, NULL, er_p, &zero);
else
    select ((int) sock + 1, NULL, rw_p, er_p, &zero);
if (FD_ISSET (sock, er_p))
    return -1;
if (FD_ISSET (sock, rw_p)) {
    if (0 == getpeername (sock, (struct sockaddr *)&peername, &peernamesize))
        return 1;
    else
        return -1;
Changes to src/sim_sock.h.
41
42
43
44
45
46
47




48
49
50
51
52












53
54
55
56
57
58
59
   30-Apr-02    RMS     Changed VMS stropts include to ioctl
   06-Feb-02    RMS     Added VMS support from Robert Alan Byer
   16-Sep-01    RMS     Added Macintosh support from Peter Schorn
*/

#ifndef SIM_SOCK_H_
#define SIM_SOCK_H_    0





#if defined (_WIN32)                                    /* Windows */
#include <winsock2.h>

#elif !defined (__OS2__) || defined (__EMX__)           /* VMS, Mac, Unix, OS/2 EMX */












#define WSAGetLastError()       errno                   /* Windows macros */
#define WSASetLastError(err) errno = err
#define closesocket     close 
#define SOCKET          int
#if defined(__hpux)
#define WSAEWOULDBLOCK  EAGAIN
#else







>
>
>
>





>
>
>
>
>
>
>
>
>
>
>
>







41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
   30-Apr-02    RMS     Changed VMS stropts include to ioctl
   06-Feb-02    RMS     Added VMS support from Robert Alan Byer
   16-Sep-01    RMS     Added Macintosh support from Peter Schorn
*/

#ifndef SIM_SOCK_H_
#define SIM_SOCK_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

#if defined (_WIN32)                                    /* Windows */
#include <winsock2.h>

#elif !defined (__OS2__) || defined (__EMX__)           /* VMS, Mac, Unix, OS/2 EMX */
#include <sys/types.h>                                  /* for fcntl, getpid */
#include <sys/socket.h>                                 /* for sockets */
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>                                 /* for sockaddr_in */
#include <netinet/tcp.h>                                /* for TCP_NODELAY */
#include <arpa/inet.h>                                  /* for inet_addr and inet_ntoa */
#include <netdb.h>
#include <sys/time.h>                                   /* for EMX */

#define WSAGetLastError()       errno                   /* Windows macros */
#define WSASetLastError(err) errno = err
#define closesocket     close 
#define SOCKET          int
#if defined(__hpux)
#define WSAEWOULDBLOCK  EAGAIN
#else
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#if defined(EAFNOSUPPORT)
#define WSAEAFNOSUPPORT EAFNOSUPPORT
#endif
#define WSAEACCES       EACCES
#define WSAEINTR        EINTR
#define INVALID_SOCKET  ((SOCKET)-1) 
#define SOCKET_ERROR    -1
#include <sys/types.h>                                  /* for fcntl, getpid */
#include <sys/socket.h>                                 /* for sockets */
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>                                 /* for sockaddr_in */
#include <netinet/tcp.h>                                /* for TCP_NODELAY */
#include <arpa/inet.h>                                  /* for inet_addr and inet_ntoa */
#include <netdb.h>
#include <sys/time.h>                                   /* for EMX */
#endif

#if defined (VMS)                                       /* VMS unique */
#include <ioctl.h>                                      /* for ioctl */
#if !defined (timerclear)
#define timerclear(tvp)         (tvp)->tv_sec = (tvp)->tv_usec = 0
#endif
#if !defined (AI_NUMERICHOST)
#define AI_NUMERICHOST 0
#endif
#if defined (__VAX)
#define sockaddr_storage sockaddr
#endif
#endif
#if defined(__EMX__)                                    /* OS/2 unique */
#if !defined (timerclear)
#define timerclear(tvp)         (tvp)->tv_sec = (tvp)->tv_usec = 0
#endif
#endif

#if !defined(CBUFSIZE)
#define CBUFSIZE 1024
#define sim_printf printf
#endif








<
<
<
<
<
<
<
<
<
<
<




<
<
<






<
<
<
<
<







87
88
89
90
91
92
93











94
95
96
97



98
99
100
101
102
103





104
105
106
107
108
109
110
#if defined(EAFNOSUPPORT)
#define WSAEAFNOSUPPORT EAFNOSUPPORT
#endif
#define WSAEACCES       EACCES
#define WSAEINTR        EINTR
#define INVALID_SOCKET  ((SOCKET)-1) 
#define SOCKET_ERROR    -1











#endif

#if defined (VMS)                                       /* VMS unique */
#include <ioctl.h>                                      /* for ioctl */



#if !defined (AI_NUMERICHOST)
#define AI_NUMERICHOST 0
#endif
#if defined (__VAX)
#define sockaddr_storage sockaddr
#endif





#endif

#if !defined(CBUFSIZE)
#define CBUFSIZE 1024
#define sim_printf printf
#endif

128
129
130
131
132
133
134
135


136


int sim_write_sock (SOCKET sock, const char *msg, int nbytes);
void sim_close_sock (SOCKET sock);
const char *sim_get_err_sock (const char *emsg);
SOCKET sim_err_sock (SOCKET sock, const char *emsg);
int sim_getnames_sock (SOCKET sock, char **socknamebuf, char **peernamebuf);
void sim_init_sock (void);
void sim_cleanup_sock (void);



#endif










>
>

>
>
125
126
127
128
129
130
131
132
133
134
135
136
137
int sim_write_sock (SOCKET sock, const char *msg, int nbytes);
void sim_close_sock (SOCKET sock);
const char *sim_get_err_sock (const char *emsg);
SOCKET sim_err_sock (SOCKET sock, const char *emsg);
int sim_getnames_sock (SOCKET sock, char **socknamebuf, char **peernamebuf);
void sim_init_sock (void);
void sim_cleanup_sock (void);

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_tape.c.
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    6250                                                /*   5 = MT_DENS_6250 -- 6250 bpi GCR */
    };

#define BPI_COUNT       (sizeof (bpi) / sizeof (bpi [0]))   /* count of density table entries */

static t_stat sim_tape_ioerr (UNIT *uptr);
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat);
static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map);
static t_stat sim_tape_simh_check (UNIT *uptr);
static t_stat sim_tape_e11_check (UNIT *uptr);
static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map);
static void sim_tape_data_trace (UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason);


struct tape_context {
    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit */
    uint32              auto_format;        /* Format determined dynamically */
#if defined SIM_ASYNCH_IO
    int                 asynch_io;          /* Asynchronous Interrupt scheduling enabled */
    int                 asynch_io_latency;  /* instructions to delay pending interrupt */
    pthread_mutex_t     lock;
    pthread_t           io_thread;          /* I/O Thread Id */
    pthread_mutex_t     io_lock;







|








|







120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    6250                                                /*   5 = MT_DENS_6250 -- 6250 bpi GCR */
    };

#define BPI_COUNT       (sizeof (bpi) / sizeof (bpi [0]))   /* count of density table entries */

static t_stat sim_tape_ioerr (UNIT *uptr);
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat);
static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize);
static t_stat sim_tape_simh_check (UNIT *uptr);
static t_stat sim_tape_e11_check (UNIT *uptr);
static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map);
static void sim_tape_data_trace (UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason);


struct tape_context {
    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit for trace */
    uint32              auto_format;        /* Format determined dynamically */
#if defined SIM_ASYNCH_IO
    int                 asynch_io;          /* Asynchronous Interrupt scheduling enabled */
    int                 asynch_io_latency;  /* instructions to delay pending interrupt */
    pthread_mutex_t     lock;
    pthread_t           io_thread;          /* I/O Thread Id */
    pthread_mutex_t     io_lock;
159
160
161
162
163
164
165


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    };
#define tape_ctx up8                        /* Field in Unit structure which points to the tape_context */

#if defined SIM_ASYNCH_IO
#define AIO_CALLSETUP                                                   \
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;       \
                                                                        \


if ((!callback) || !ctx->asynch_io)

#define AIO_CALL(op, _buf, _bc, _fc, _max, _vbc, _gaplen, _bpi, _obj, _callback)\
    if (ctx->asynch_io) {                                               \
        struct tape_context *ctx =                                      \
                      (struct tape_context *)uptr->tape_ctx;            \
                                                                        \
        pthread_mutex_lock (&ctx->io_lock);                             \
                                                                        \
        sim_debug (ctx->dbit, ctx->dptr,                                \
      "sim_tape AIO_CALL(op=%d, unit=%d)\n", op, uptr-ctx->dptr->units);\
                                                                        \
        if (ctx->callback)                                              \
            abort(); /* horrible mistake, stop */                       \
        ctx->io_top = op;                                               \
        ctx->buf = _buf;                                                \
        ctx->bc = _bc;                                                  \
        ctx->fc = _fc;                                                  \







>
>










|







159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    };
#define tape_ctx up8                        /* Field in Unit structure which points to the tape_context */

#if defined SIM_ASYNCH_IO
#define AIO_CALLSETUP                                                   \
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;       \
                                                                        \
if (ctx == NULL)                                                        \
    return sim_messagef (SCPE_IERR, "Bad Attach\n");                    \
if ((!callback) || !ctx->asynch_io)

#define AIO_CALL(op, _buf, _bc, _fc, _max, _vbc, _gaplen, _bpi, _obj, _callback)\
    if (ctx->asynch_io) {                                               \
        struct tape_context *ctx =                                      \
                      (struct tape_context *)uptr->tape_ctx;            \
                                                                        \
        pthread_mutex_lock (&ctx->io_lock);                             \
                                                                        \
        sim_debug (ctx->dbit, ctx->dptr,                                \
      "sim_tape AIO_CALL(op=%d, unit=%d)\n", op, (int)(uptr-ctx->dptr->units));\
                                                                        \
        if (ctx->callback)                                              \
            abort(); /* horrible mistake, stop */                       \
        ctx->io_top = op;                                               \
        ctx->buf = _buf;                                                \
        ctx->bc = _bc;                                                  \
        ctx->fc = _fc;                                                  \
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#define TOP_RWND 16             /* sim_tape_rewind_a */
#define TOP_POSN 17             /* sim_tape_position_a */

static void *
_tape_io(void *arg)
{
UNIT* volatile uptr = (UNIT*)arg;
int sched_policy;
struct sched_param sched_priority;
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

    /* Boost Priority for this I/O thread vs the CPU instruction execution 
       thread which in general won't be readily yielding the processor when 
       this thread needs to run */
    pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
    ++sched_priority.sched_priority;
    pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

    sim_debug (ctx->dbit, ctx->dptr, "_tape_io(unit=%d) starting\n", uptr-ctx->dptr->units);

    pthread_mutex_lock (&ctx->io_lock);
    pthread_cond_signal (&ctx->startup_cond);   /* Signal we're ready to go */
    while (1) {
        pthread_cond_wait (&ctx->io_cond, &ctx->io_lock);
        if (ctx->io_top == TOP_DONE)
            break;







<
<





<
|
<

|







214
215
216
217
218
219
220


221
222
223
224
225

226

227
228
229
230
231
232
233
234
235
#define TOP_RWND 16             /* sim_tape_rewind_a */
#define TOP_POSN 17             /* sim_tape_position_a */

static void *
_tape_io(void *arg)
{
UNIT* volatile uptr = (UNIT*)arg;


struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

    /* Boost Priority for this I/O thread vs the CPU instruction execution 
       thread which in general won't be readily yielding the processor when 
       this thread needs to run */

    sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


    sim_debug (ctx->dbit, ctx->dptr, "_tape_io(unit=%d) starting\n", (int)(uptr-ctx->dptr->units));

    pthread_mutex_lock (&ctx->io_lock);
    pthread_cond_signal (&ctx->startup_cond);   /* Signal we're ready to go */
    while (1) {
        pthread_cond_wait (&ctx->io_cond, &ctx->io_lock);
        if (ctx->io_top == TOP_DONE)
            break;
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        pthread_mutex_lock (&ctx->io_lock);
        ctx->io_top = TOP_DONE;
        pthread_cond_signal (&ctx->io_done);
        sim_activate (uptr, ctx->asynch_io_latency);
    }
    pthread_mutex_unlock (&ctx->io_lock);

    sim_debug (ctx->dbit, ctx->dptr, "_tape_io(unit=%d) exiting\n", uptr-ctx->dptr->units);

    return NULL;
}

/* This routine is called in the context of the main simulator thread before 
   processing events for any unit. It is only called when an asynchronous 
   thread has called sim_activate() to activate a unit.  The job of this 
   routine is to put the unit in proper condition to digest what may have
   occurred in the asynchronous thread.
   
   Since tape processing only handles a single I/O at a time to a 
   particular tape device, we have the opportunity to possibly detect 
   improper attempts to issue multiple concurrent I/O requests. */
static void _tape_completion_dispatch (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
TAPE_PCALLBACK callback = ctx->callback;

sim_debug (ctx->dbit, ctx->dptr, "_tape_completion_dispatch(unit=%d, top=%d, callback=%p)\n", uptr-ctx->dptr->units, ctx->io_top, ctx->callback);

if (ctx->io_top != TOP_DONE)
    abort();                                            /* horribly wrong, stop */

if (ctx->callback && ctx->io_top == TOP_DONE) {
    ctx->callback = NULL;
    callback (uptr, ctx->io_status);
    }
}

static t_bool _tape_is_active (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_tape_is_active(unit=%d, top=%d)\n", uptr-ctx->dptr->units, ctx->io_top);
    return (ctx->io_top != TOP_DONE);
    }
return FALSE;
}

static void _tape_cancel (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_tape_cancel(unit=%d, top=%d)\n", uptr-ctx->dptr->units, ctx->io_top);
    if (ctx->asynch_io) {
        pthread_mutex_lock (&ctx->io_lock);
        while (ctx->io_top != TOP_DONE)
            pthread_cond_wait (&ctx->io_done, &ctx->io_lock);
        pthread_mutex_unlock (&ctx->io_lock);
        }
    }
}
#else
#define AIO_CALLSETUP


#define AIO_CALL(op, _buf, _fc, _bc, _max, _vbc, _gaplen, _bpi, _obj, _callback) \
    if (_callback)                                                    \
        (_callback) (uptr, r);
#endif


/* Enable asynchronous operation */

t_stat sim_tape_set_async (UNIT *uptr, int latency)
{
#if !defined(SIM_ASYNCH_IO)
char *msg = "Tape: can't operate asynchronously\r\n";
sim_printf ("%s", msg);
return SCPE_NOFNC;
#else
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
pthread_attr_t attr;

ctx->asynch_io = sim_asynch_enabled;
ctx->asynch_io_latency = latency;







|


















|















|










|









|
>
>











|
<







290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

368
369
370
371
372
373
374
        pthread_mutex_lock (&ctx->io_lock);
        ctx->io_top = TOP_DONE;
        pthread_cond_signal (&ctx->io_done);
        sim_activate (uptr, ctx->asynch_io_latency);
    }
    pthread_mutex_unlock (&ctx->io_lock);

    sim_debug (ctx->dbit, ctx->dptr, "_tape_io(unit=%d) exiting\n", (int)(uptr-ctx->dptr->units));

    return NULL;
}

/* This routine is called in the context of the main simulator thread before 
   processing events for any unit. It is only called when an asynchronous 
   thread has called sim_activate() to activate a unit.  The job of this 
   routine is to put the unit in proper condition to digest what may have
   occurred in the asynchronous thread.
   
   Since tape processing only handles a single I/O at a time to a 
   particular tape device, we have the opportunity to possibly detect 
   improper attempts to issue multiple concurrent I/O requests. */
static void _tape_completion_dispatch (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
TAPE_PCALLBACK callback = ctx->callback;

sim_debug (ctx->dbit, ctx->dptr, "_tape_completion_dispatch(unit=%d, top=%d, callback=%p)\n", (int)(uptr-ctx->dptr->units), ctx->io_top, ctx->callback);

if (ctx->io_top != TOP_DONE)
    abort();                                            /* horribly wrong, stop */

if (ctx->callback && ctx->io_top == TOP_DONE) {
    ctx->callback = NULL;
    callback (uptr, ctx->io_status);
    }
}

static t_bool _tape_is_active (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_tape_is_active(unit=%d, top=%d)\n", (int)(uptr-ctx->dptr->units), ctx->io_top);
    return (ctx->io_top != TOP_DONE);
    }
return FALSE;
}

static void _tape_cancel (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx) {
    sim_debug (ctx->dbit, ctx->dptr, "_tape_cancel(unit=%d, top=%d)\n", (int)(uptr-ctx->dptr->units), ctx->io_top);
    if (ctx->asynch_io) {
        pthread_mutex_lock (&ctx->io_lock);
        while (ctx->io_top != TOP_DONE)
            pthread_cond_wait (&ctx->io_done, &ctx->io_lock);
        pthread_mutex_unlock (&ctx->io_lock);
        }
    }
}
#else
#define AIO_CALLSETUP                                                       \
    if (uptr->tape_ctx == NULL)                                             \
        return sim_messagef (SCPE_IERR, "Bad Attach\n");
#define AIO_CALL(op, _buf, _fc, _bc, _max, _vbc, _gaplen, _bpi, _obj, _callback) \
    if (_callback)                                                    \
        (_callback) (uptr, r);
#endif


/* Enable asynchronous operation */

t_stat sim_tape_set_async (UNIT *uptr, int latency)
{
#if !defined(SIM_ASYNCH_IO)
sim_printf ("Tape: can't operate asynchronously\r\n");

return SCPE_NOFNC;
#else
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
pthread_attr_t attr;

ctx->asynch_io = sim_asynch_enabled;
ctx->asynch_io_latency = latency;
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    pthread_attr_destroy(&attr);
    pthread_cond_wait (&ctx->startup_cond, &ctx->io_lock); /* Wait for thread to stabilize */
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_cond_destroy (&ctx->startup_cond);
    }
uptr->a_check_completion = _tape_completion_dispatch;
uptr->a_is_active = _tape_is_active;
uptr->a_cancel = _tape_cancel;
return SCPE_OK;
#endif
}

/* Disable asynchronous operation */

t_stat sim_tape_clr_async (UNIT *uptr)







|







384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    pthread_attr_destroy(&attr);
    pthread_cond_wait (&ctx->startup_cond, &ctx->io_lock); /* Wait for thread to stabilize */
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_cond_destroy (&ctx->startup_cond);
    }
uptr->a_check_completion = _tape_completion_dispatch;
uptr->a_is_active = _tape_is_active;
uptr->cancel = _tape_cancel;
return SCPE_OK;
#endif
}

/* Disable asynchronous operation */

t_stat sim_tape_clr_async (UNIT *uptr)
434
435
436
437
438
439
440
441
442




443
444
445
446
447
448
449
450
451
452
453
    sim_tape_set_async (uptr, ctx->asynch_io_latency);
#endif
fflush (uptr->fileref);
}

/* Attach tape unit */

t_stat sim_tape_attach (UNIT *uptr, char *cptr)
{




return sim_tape_attach_ex (uptr, cptr, 0, 0);
}

t_stat sim_tape_attach_ex (UNIT *uptr, char *cptr, uint32 dbit, int completion_delay)
{
struct tape_context *ctx;
uint32 objc;
DEVICE *dptr;
char gbuf[CBUFSIZE];
t_stat r;
t_bool auto_format = FALSE;







|

>
>
>
>
|


|







433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
    sim_tape_set_async (uptr, ctx->asynch_io_latency);
#endif
fflush (uptr->fileref);
}

/* Attach tape unit */

t_stat sim_tape_attach (UNIT *uptr, CONST char *cptr)
{
DEVICE *dptr;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
return sim_tape_attach_ex (uptr, cptr, (dptr->flags & DEV_DEBUG) ? 0xFFFFFFFF : 0, 0);
}

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay)
{
struct tape_context *ctx;
uint32 objc;
DEVICE *dptr;
char gbuf[CBUFSIZE];
t_stat r;
t_bool auto_format = FALSE;
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    if (sim_tape_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Tape Format: %s\n", gbuf);
    sim_switches = sim_switches & ~(SWMASK ('F'));      /* Record Format specifier already processed */
    auto_format = TRUE;
    }
if (MT_GET_FMT (uptr) == MTUF_F_TPC)
    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC tapes */
r = attach_unit (uptr, cptr);                           /* attach unit */
if (r != SCPE_OK)                                       /* error? */
    return sim_messagef (r, "Can't open tape image: %s\n", cptr);
switch (MT_GET_FMT (uptr)) {                            /* case on format */

    case MTUF_F_STD:                                    /* SIMH */
        if (SCPE_OK != sim_tape_simh_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        break;

    case MTUF_F_E11:                                    /* E11 */
        if (SCPE_OK != sim_tape_e11_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        break;

    case MTUF_F_TPC:                                    /* TPC */
        objc = sim_tape_tpc_map (uptr, NULL);           /* get # objects */
        if (objc == 0) {                                /* tape empty? */
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        uptr->filebuf = calloc (objc + 1, sizeof (t_addr));
        if (uptr->filebuf == NULL) {                    /* map allocated? */
            sim_tape_detach (uptr);
            return SCPE_MEM;                            /* no, complain */
            }
        uptr->hwmark = objc + 1;                        /* save map size */
        sim_tape_tpc_map (uptr, (t_addr *) uptr->filebuf);      /* fill map */
        break;

    default:
        break;
        }

uptr->tape_ctx = ctx = (struct tape_context *)calloc(1, sizeof(struct tape_context));







|



















|










|







464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    if (sim_tape_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Tape Format: %s\n", gbuf);
    sim_switches = sim_switches & ~(SWMASK ('F'));      /* Record Format specifier already processed */
    auto_format = TRUE;
    }
if (MT_GET_FMT (uptr) == MTUF_F_TPC)
    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC tapes */
r = attach_unit (uptr, (CONST char *)cptr);             /* attach unit */
if (r != SCPE_OK)                                       /* error? */
    return sim_messagef (r, "Can't open tape image: %s\n", cptr);
switch (MT_GET_FMT (uptr)) {                            /* case on format */

    case MTUF_F_STD:                                    /* SIMH */
        if (SCPE_OK != sim_tape_simh_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        break;

    case MTUF_F_E11:                                    /* E11 */
        if (SCPE_OK != sim_tape_e11_check (uptr)) {
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        break;

    case MTUF_F_TPC:                                    /* TPC */
        objc = sim_tape_tpc_map (uptr, NULL, 0);        /* get # objects */
        if (objc == 0) {                                /* tape empty? */
            sim_tape_detach (uptr);
            return SCPE_FMT;                            /* yes, complain */
            }
        uptr->filebuf = calloc (objc + 1, sizeof (t_addr));
        if (uptr->filebuf == NULL) {                    /* map allocated? */
            sim_tape_detach (uptr);
            return SCPE_MEM;                            /* no, complain */
            }
        uptr->hwmark = objc + 1;                        /* save map size */
        sim_tape_tpc_map (uptr, (t_addr *) uptr->filebuf, objc);/* fill map */
        break;

    default:
        break;
        }

uptr->tape_ctx = ctx = (struct tape_context *)calloc(1, sizeof(struct tape_context));
521
522
523
524
525
526
527
528
529
530
531
532
533
534

535
536
537
538
539
540
541
542
/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_stat r;
t_bool auto_format;

if ((uptr == NULL) || !(uptr->flags & UNIT_ATT))
    return SCPE_IERR;

if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */

auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);

r = detach_unit (uptr);                                 /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */







|

|




>
|







524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_stat r;
t_bool auto_format = FALSE;

if ((ctx == NULL) || (uptr == NULL) || !(uptr->flags & UNIT_ATT))
    return SCPE_IERR;

if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */
if (ctx)
    auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);

r = detach_unit (uptr);                                 /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */
586
587
588
589
590
591
592


593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630

631
632
633
634
635
636
637
return SCPE_OK;
}

static void sim_tape_data_trace(UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;



if (sim_deb && (ctx->dptr->dctrl & reason))
    sim_data_trace(ctx->dptr, uptr, (detail ? data : NULL), "", len, txt, reason);
}

/* Read record length forward (internal routine)

   Inputs:
        uptr    =       pointer to tape unit
        bc      =       pointer to returned record length
   Outputs:
        status  =       operation status

   exit condition       tape position
   ------------------   -------------------------------------------
   unit unattached      unchanged
   read error           unchanged, PNU set
   end of file/medium   unchanged, PNU set
   tape mark            updated
   tape runaway         updated
   data record          updated, sim_fread will read record forward

   This routine is called to set up a record read or spacing in the forward
   direction.  On return, status is MTSE_OK and the tape is positioned at the
   first data byte if a record was encountered, or status is an MTSE error code
   giving the reason that the operation did not succeed and the tape position is
   as indicated above.

   The ANSI standards for magnetic tape recording (X3.32, X3.39, and X3.54) and
   the equivalent ECMA standard (ECMA-62) specify a maximum erase gap length of
   25 feet (7.6 meters).  While gaps of any length may be written, gaps longer
   than this are non-standard and may indicate that an unrecorded or erased tape
   is being read.

   If the tape density has been set via a previous "sim_tape_set_dens" call,
   then the length is monitored when skipping over erase gaps.  If the length
   reaches 25 feet, motion is terminated, and MTSE_RUNAWAY status is returned.
   Runaway status is also returned if an end-of-medium marker or the physical
   end of file is encountered while spacing over a gap.


   If the density has not been set, then a gap of any length is skipped, and
   MTSE_RUNAWAY status is never returned.  In effect, erase gaps present in the
   tape image file will be transparent to the caller.

   Erase gaps are currently supported only in SIMH (MTUF_F_STD) tape format.
   Because gaps may be partially overwritten with data records, gap metadata







>
>













|


|




















|
>







590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
return SCPE_OK;
}

static void sim_tape_data_trace(UNIT *uptr, const uint8 *data, size_t len, const char* txt, int detail, uint32 reason)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)
    return;
if (sim_deb && (ctx->dptr->dctrl & reason))
    sim_data_trace(ctx->dptr, uptr, (detail ? data : NULL), "", len, txt, reason);
}

/* Read record length forward (internal routine)

   Inputs:
        uptr    =       pointer to tape unit
        bc      =       pointer to returned record length
   Outputs:
        status  =       operation status

   exit condition       tape position
   ------------------   -----------------------------------------------------
   unit unattached      unchanged
   read error           unchanged, PNU set
   end of file/medium   updated if a gap precedes, else unchanged and PNU set
   tape mark            updated
   tape runaway         updated
   data record          updated, sim_fread will read record forward

   This routine is called to set up a record read or spacing in the forward
   direction.  On return, status is MTSE_OK and the tape is positioned at the
   first data byte if a record was encountered, or status is an MTSE error code
   giving the reason that the operation did not succeed and the tape position is
   as indicated above.

   The ANSI standards for magnetic tape recording (X3.32, X3.39, and X3.54) and
   the equivalent ECMA standard (ECMA-62) specify a maximum erase gap length of
   25 feet (7.6 meters).  While gaps of any length may be written, gaps longer
   than this are non-standard and may indicate that an unrecorded or erased tape
   is being read.

   If the tape density has been set via a previous "sim_tape_set_dens" call,
   then the length is monitored when skipping over erase gaps.  If the length
   reaches 25 feet, motion is terminated, and MTSE_RUNAWAY status is returned.
   Runaway status is also returned if an end-of-medium marker or the physical
   end of file is encountered while spacing over a gap; however, MTSE_EOM is
   returned if the tape is positioned at the EOM on entry.

   If the density has not been set, then a gap of any length is skipped, and
   MTSE_RUNAWAY status is never returned.  In effect, erase gaps present in the
   tape image file will be transparent to the caller.

   Erase gaps are currently supported only in SIMH (MTUF_F_STD) tape format.
   Because gaps may be partially overwritten with data records, gap metadata
665
666
667
668
669
670
671







672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690


691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732

733

734
735
736
737


738
739
740
741
742








743
744
745
746
747
748
749
750


751
752
753
754
755
756
757
758
759
         -----------    --------------
               1             7200
              32              783
             128              237
             256              203
             512              186
            1024              171







*/

static t_stat sim_tape_rdlntf (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint8 c;
t_bool all_eof;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;
t_tpclnt tpcbc;
t_mtrlnt buffer [256];                                  /* local tape buffer */
uint32 bufcntr, bufcap;                                 /* buffer counter and capacity */
int32 runaway_counter, sizeof_gap;                      /* bytes remaining before runaway and bytes per gap */
t_stat r = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */



sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set the initial tape position */

switch (f) {                                            /* the read method depends on the tape format */

    case MTUF_F_STD:
    case MTUF_F_E11:
        runaway_counter = 25 * 12 * bpi [MT_DENS (uptr->dynflags)]; /* set the largest legal gap size in bytes */

        if (runaway_counter == 0) {                     /* if tape density has not been not set */
            sizeof_gap = 0;                             /*   then disable runaway detection */
            runaway_counter = INT_MAX;                  /*     to allow gaps of any size */
            }
        else                                            /* otherwise */
            sizeof_gap = sizeof (t_mtrlnt);             /*   set the size of the gap */

        bufcntr = 0;                                    /* force an initial read */
        bufcap = 0;                                     /*   but of just one metadata marker */

        do {                                            /* loop until a record, gap, or error seen */
            if (bufcntr == bufcap) {                    /* if the buffer is empty then refill it */
                if (feof (uptr->fileref)) {             /* if we hit the EOF while reading gaps */
                    if (sizeof_gap > 0)                 /*   then if detection is enabled */
                        r = MTSE_RUNAWAY;               /*     then report a tape runaway */
                    else                                /*   otherwise report the physical EOF */
                        r = MTSE_EOM;                   /*     as the end-of-medium */
                    break;
                    }

                else if (bufcap == 0)                   /* otherwise if this is the initial read */
                    bufcap = 1;                         /*   then start with just one marker */

                else                                    /* otherwise reset the capacity */
                    bufcap = sizeof (buffer)            /*   to the full size of the buffer */
                               / sizeof (buffer [0]);

                bufcap = sim_fread (buffer,             /* fill the buffer */
                                    sizeof (t_mtrlnt),  /*   with tape metadata */
                                    bufcap,
                                    uptr->fileref);

                if (ferror (uptr->fileref)) {           /* if a file I/O error occurred */

                    MT_SET_PNU (uptr);                  /*   then set position not updated */

                    r = sim_tape_ioerr (uptr);          /*     report the error and quit */
                    break;
                    }



                else if (bufcap == 0) {                 /* otherwise if nothing was read */
                    MT_SET_PNU (uptr);                  /*   then set position not updated */
                    r = MTSE_EOM;                       /*     report the end of medium and quit */
                    break;
                    }









                else                                    /* otherwise reset the index */
                    bufcntr = 0;                        /*   to the start of the buffer */
                }

            *bc = buffer [bufcntr++];                   /* store the metadata marker value */

            if (*bc == MTR_EOM) {                       /* if an end-of-medium marker is seen */


                MT_SET_PNU (uptr);                      /*   then set position not updated */
                r = MTSE_EOM;                           /*     report the end of medium and quit */
                break;
                }

            uptr->pos = uptr->pos + sizeof (t_mtrlnt);  /* space over the marker */

            if (*bc == MTR_TMK) {                       /* if the value is a tape mark */
                r = MTSE_TMK;                           /*   then quit with tape mark status */







>
>
>
>
>
>
>



















>
>



















|

|




















>
|
>
|



>
>
|
|
|
|
|
>
>
>
>
>
>
>
>








>
>
|
|







672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
         -----------    --------------
               1             7200
              32              783
             128              237
             256              203
             512              186
            1024              171

    4. Because an erase gap may precede the logical end-of-medium, represented
       either by the physical end-of-file or by an EOM marker, the "position not
       updated" flag is set only if the tape is positioned at the EOM when the
       routine is entered.  If at least one gap marker precedes the EOM, then
       the PNU flag is not set.  This ensures that a backspace-and-retry
       sequence will work correctly in both cases.
*/

static t_stat sim_tape_rdlntf (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint8 c;
t_bool all_eof;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;
t_tpclnt tpcbc;
t_mtrlnt buffer [256];                                  /* local tape buffer */
uint32 bufcntr, bufcap;                                 /* buffer counter and capacity */
int32 runaway_counter, sizeof_gap;                      /* bytes remaining before runaway and bytes per gap */
t_stat r = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set the initial tape position */

switch (f) {                                            /* the read method depends on the tape format */

    case MTUF_F_STD:
    case MTUF_F_E11:
        runaway_counter = 25 * 12 * bpi [MT_DENS (uptr->dynflags)]; /* set the largest legal gap size in bytes */

        if (runaway_counter == 0) {                     /* if tape density has not been not set */
            sizeof_gap = 0;                             /*   then disable runaway detection */
            runaway_counter = INT_MAX;                  /*     to allow gaps of any size */
            }
        else                                            /* otherwise */
            sizeof_gap = sizeof (t_mtrlnt);             /*   set the size of the gap */

        bufcntr = 0;                                    /* force an initial read */
        bufcap = 0;                                     /*   but of just one metadata marker */

        do {                                            /* loop until a record, gap, or error is seen */
            if (bufcntr == bufcap) {                    /* if the buffer is empty then refill it */
                if (feof (uptr->fileref)) {             /* if we hit the EOF while reading a gap */
                    if (sizeof_gap > 0)                 /*   then if detection is enabled */
                        r = MTSE_RUNAWAY;               /*     then report a tape runaway */
                    else                                /*   otherwise report the physical EOF */
                        r = MTSE_EOM;                   /*     as the end-of-medium */
                    break;
                    }

                else if (bufcap == 0)                   /* otherwise if this is the initial read */
                    bufcap = 1;                         /*   then start with just one marker */

                else                                    /* otherwise reset the capacity */
                    bufcap = sizeof (buffer)            /*   to the full size of the buffer */
                               / sizeof (buffer [0]);

                bufcap = sim_fread (buffer,             /* fill the buffer */
                                    sizeof (t_mtrlnt),  /*   with tape metadata */
                                    bufcap,
                                    uptr->fileref);

                if (ferror (uptr->fileref)) {           /* if a file I/O error occurred */
                    if (bufcntr == 0)                   /*   then if this is the initial read */
                        MT_SET_PNU (uptr);              /*     then set position not updated */

                    r = sim_tape_ioerr (uptr);          /* report the error and quit */
                    break;
                    }

                else if (bufcap == 0                    /* otherwise if positioned at the physical EOF */
                  || buffer [0] == MTR_EOM)             /*   or at the logical EOM */
                    if (bufcntr == 0) {                 /*     then if this is the initial read */
                        MT_SET_PNU (uptr);              /*       then set position not updated */
                        r = MTSE_EOM;                   /*         and report the end-of-medium and quit */
                        break;
                        }

                    else {                              /*     otherwise some gap has already been skipped */
                        if (sizeof_gap > 0)             /*       so if detection is enabled */
                            r = MTSE_RUNAWAY;           /*         then report a tape runaway */
                        else                            /*       otherwise report the physical EOF */
                            r = MTSE_EOM;               /*         as the end-of-medium */
                        break;
                        }

                else                                    /* otherwise reset the index */
                    bufcntr = 0;                        /*   to the start of the buffer */
                }

            *bc = buffer [bufcntr++];                   /* store the metadata marker value */

            if (*bc == MTR_EOM) {                       /* if an end-of-medium marker is seen */
                if (sizeof_gap > 0)                     /*   then if detection is enabled */
                    r = MTSE_RUNAWAY;                   /*     then report a tape runaway */
                else                                    /*   otherwise report the physical EOF */
                    r = MTSE_EOM;                       /*     as the end-of-medium */
                break;
                }

            uptr->pos = uptr->pos + sizeof (t_mtrlnt);  /* space over the marker */

            if (*bc == MTR_TMK) {                       /* if the value is a tape mark */
                r = MTSE_TMK;                           /*   then quit with tape mark status */
880
881
882
883
884
885
886


887
888
889
890
891
892
893
int32 runaway_counter, sizeof_gap;                      /* bytes remaining before runaway and bytes per gap */
t_stat r = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */



if (sim_tape_bot (uptr))                                /* if the unit is positioned at the BOT */
    return MTSE_BOT;                                    /*   then reading backward is not possible */

switch (f) {                                            /* the read method depends on the tape format */

    case MTUF_F_STD:







>
>







910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
int32 runaway_counter, sizeof_gap;                      /* bytes remaining before runaway and bytes per gap */
t_stat r = MTSE_OK;

MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then quit with an error */
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */

if (sim_tape_bot (uptr))                                /* if the unit is positioned at the BOT */
    return MTSE_BOT;                                    /*   then reading backward is not possible */

switch (f) {                                            /* the read method depends on the tape format */

    case MTUF_F_STD:
1043
1044
1045
1046
1047
1048
1049


1050
1051
1052
1053
1054
1055
1056
1057
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt i, tbc, rbc;
t_addr opos;
t_stat st;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rdrecf(unit=%d, buf=%p, max=%d)\n", uptr-ctx->dptr->units, buf, max);

opos = uptr->pos;                                       /* old position */
if (MTSE_OK != (st = sim_tape_rdlntf (uptr, &tbc)))     /* read rec lnt */
    return st;
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);







>
>
|







1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt i, tbc, rbc;
t_addr opos;
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rdrecf(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

opos = uptr->pos;                                       /* old position */
if (MTSE_OK != (st = sim_tape_rdlntf (uptr, &tbc)))     /* read rec lnt */
    return st;
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);
1107
1108
1109
1110
1111
1112
1113


1114
1115
1116
1117
1118
1119
1120
1121
t_stat sim_tape_rdrecr (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt i, rbc, tbc;
t_stat st;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rdrecr(unit=%d, buf=%p, max=%d)\n", uptr-ctx->dptr->units, buf, max);

if (MTSE_OK != (st = sim_tape_rdlntr (uptr, &tbc)))     /* read rec lnt */
    return st;
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max)                                          /* rec out of range? */
    return MTSE_INVRL;
i = (t_mtrlnt)sim_fread (buf, sizeof (uint8), rbc, uptr->fileref);/* read record */







>
>
|







1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
t_stat sim_tape_rdrecr (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt i, rbc, tbc;
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rdrecr(unit=%d, buf=%p, max=%d)\n", (int)(uptr-ctx->dptr->units), buf, max);

if (MTSE_OK != (st = sim_tape_rdlntr (uptr, &tbc)))     /* read rec lnt */
    return st;
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max)                                          /* rec out of range? */
    return MTSE_INVRL;
i = (t_mtrlnt)sim_fread (buf, sizeof (uint8), rbc, uptr->fileref);/* read record */
1157
1158
1159
1160
1161
1162
1163


1164
1165
1166
1167
1168
1169
1170
1171

t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrrecf(unit=%d, buf=%p, bc=%d)\n", uptr-ctx->dptr->units, buf, bc);

sim_tape_data_trace(uptr, buf, bc, "Record Write", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
MT_CLR_PNU (uptr);
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */







>
>
|







1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209

t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 f = MT_GET_FMT (uptr);
t_mtrlnt sbc;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrrecf(unit=%d, buf=%p, bc=%d)\n", (int)(uptr-ctx->dptr->units), buf, bc);

sim_tape_data_trace(uptr, buf, bc, "Record Write", ctx->dptr->dctrl & MTSE_DBG_DAT, MTSE_DBG_STR);
MT_CLR_PNU (uptr);
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */
1217
1218
1219
1220
1221
1222
1223


1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242


1243
1244
1245
1246
1247
1248
1249
1250
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

MT_CLR_PNU (uptr);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;


if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */
sim_fwrite (&dat, sizeof (t_mtrlnt), 1, uptr->fileref);
if (ferror (uptr->fileref)) {                           /* error? */
    MT_SET_PNU (uptr);
    return sim_tape_ioerr (uptr);
    }
sim_debug (MTSE_DBG_STR, ctx->dptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */
return MTSE_OK;
}

/* Write tape mark */

t_stat sim_tape_wrtmk (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrtmk(unit=%d)\n", uptr-ctx->dptr->units);
if (MT_GET_FMT (uptr) == MTUF_F_P7B) {                  /* P7B? */
    uint8 buf = P7B_EOF;                                /* eof mark */
    return sim_tape_wrrecf (uptr, &buf, 1);             /* write char */
    }
return sim_tape_wrdata (uptr, MTR_TMK);
}








>
>



















>
>
|







1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
static t_stat sim_tape_wrdata (UNIT *uptr, uint32 dat)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

MT_CLR_PNU (uptr);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */
sim_fwrite (&dat, sizeof (t_mtrlnt), 1, uptr->fileref);
if (ferror (uptr->fileref)) {                           /* error? */
    MT_SET_PNU (uptr);
    return sim_tape_ioerr (uptr);
    }
sim_debug (MTSE_DBG_STR, ctx->dptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */
return MTSE_OK;
}

/* Write tape mark */

t_stat sim_tape_wrtmk (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrtmk(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B) {                  /* P7B? */
    uint8 buf = P7B_EOF;                                /* eof mark */
    return sim_tape_wrrecf (uptr, &buf, 1);             /* write char */
    }
return sim_tape_wrdata (uptr, MTR_TMK);
}

1260
1261
1262
1263
1264
1265
1266


1267
1268
1269
1270
1271
1272
1273
1274
/* Write end of medium */

t_stat sim_tape_wreom (UNIT *uptr)
{
t_stat result;
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wreom(unit=%d)\n", uptr-ctx->dptr->units);
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;

result = sim_tape_wrdata (uptr, MTR_EOM);               /* write the EOM marker */

uptr->pos = uptr->pos - sizeof (t_mtrlnt);              /* restore original tape position */
MT_SET_PNU (uptr);                                      /* indicate that position was not updated */







>
>
|







1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
/* Write end of medium */

t_stat sim_tape_wreom (UNIT *uptr)
{
t_stat result;
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wreom(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;

result = sim_tape_wrdata (uptr, MTR_EOM);               /* write the EOM marker */

uptr->pos = uptr->pos - sizeof (t_mtrlnt);              /* restore original tape position */
MT_SET_PNU (uptr);                                      /* indicate that position was not updated */
1288
1289
1290
1291
1292
1293
1294


1295
1296
1297
1298
1299
1300
1301
1302
/* Write end of medium-rewind */

t_stat sim_tape_wreomrw (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wreomrw(unit=%d)\n", uptr-ctx->dptr->units);
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;
r = sim_tape_wrdata (uptr, MTR_EOM);
if (r == MTSE_OK)
    r = sim_tape_rewind (uptr);
return r;
}







>
>
|







1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
/* Write end of medium-rewind */

t_stat sim_tape_wreomrw (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wreomrw(unit=%d)\n", (int)(uptr-ctx->dptr->units));
if (MT_GET_FMT (uptr) == MTUF_F_P7B)                    /* cant do P7B */
    return MTSE_FMT;
r = sim_tape_wrdata (uptr, MTR_EOM);
if (r == MTSE_OK)
    r = sim_tape_rewind (uptr);
return r;
}
1420
1421
1422
1423
1424
1425
1426


1427
1428
1429
1430
1431
1432
1433
1434
uint32 file_size, marker_count, tape_density;
int32 gap_needed;
uint32 gap_alloc = 0;                                   /* gap currently allocated from the tape */
const uint32 format = MT_GET_FMT (uptr);                /* tape format */
const uint32 meta_size = sizeof (t_mtrlnt);             /* bytes per metadatum */
const uint32 min_rec_size = 2 + sizeof (t_mtrlnt) * 2;  /* smallest data record size */



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrgap(unit=%d, gaplen=%p)\n", uptr-ctx->dptr->units, gaplen);

MT_CLR_PNU (uptr);

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then we cannot proceed */

else if (sim_tape_wrp (uptr))                           /* otherwise if the unit is write protected */







>
>
|







1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
uint32 file_size, marker_count, tape_density;
int32 gap_needed;
uint32 gap_alloc = 0;                                   /* gap currently allocated from the tape */
const uint32 format = MT_GET_FMT (uptr);                /* tape format */
const uint32 meta_size = sizeof (t_mtrlnt);             /* bytes per metadatum */
const uint32 min_rec_size = 2 + sizeof (t_mtrlnt) * 2;  /* smallest data record size */

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_wrgap(unit=%d, gaplen=%u)\n", (int)(uptr-ctx->dptr->units), gaplen);

MT_CLR_PNU (uptr);

if ((uptr->flags & UNIT_ATT) == 0)                      /* if the unit is not attached */
    return MTSE_UNATT;                                  /*   then we cannot proceed */

else if (sim_tape_wrp (uptr))                           /* otherwise if the unit is write protected */
1587
1588
1589
1590
1591
1592
1593


1594
1595
1596
1597
1598
1599
1600
1601
*/

t_stat sim_tape_sprecf (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecf(unit=%d)\n", uptr-ctx->dptr->units);

st = sim_tape_rdlntf (uptr, bc);                        /* get record length */
*bc = MTR_L (*bc);
return st;
}

t_stat sim_tape_sprecf_a (UNIT *uptr, t_mtrlnt *bc, TAPE_PCALLBACK callback)







>
>
|







1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
*/

t_stat sim_tape_sprecf (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecf(unit=%d)\n", (int)(uptr-ctx->dptr->units));

st = sim_tape_rdlntf (uptr, bc);                        /* get record length */
*bc = MTR_L (*bc);
return st;
}

t_stat sim_tape_sprecf_a (UNIT *uptr, t_mtrlnt *bc, TAPE_PCALLBACK callback)
1628
1629
1630
1631
1632
1633
1634


1635
1636
1637
1638
1639
1640
1641
1642

t_stat sim_tape_sprecsf (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_mtrlnt tbc;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecsf(unit=%d, count=%d)\n", uptr-ctx->dptr->units, count);

*skipped = 0;
while (*skipped < count) {                              /* loopo */
    st = sim_tape_sprecf (uptr, &tbc);                  /* spc rec */
    if (st != MTSE_OK)
        return st;
    *skipped = *skipped + 1;                            /* # recs skipped */







>
>
|







1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694

t_stat sim_tape_sprecsf (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_mtrlnt tbc;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecsf(unit=%d, count=%d)\n", (int)(uptr-ctx->dptr->units), count);

*skipped = 0;
while (*skipped < count) {                              /* loopo */
    st = sim_tape_sprecf (uptr, &tbc);                  /* spc rec */
    if (st != MTSE_OK)
        return st;
    *skipped = *skipped + 1;                            /* # recs skipped */
1673
1674
1675
1676
1677
1678
1679


1680
1681
1682
1683
1684
1685
1686
1687
*/

t_stat sim_tape_sprecr (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecr(unit=%d)\n", uptr-ctx->dptr->units);

if (MT_TST_PNU (uptr)) {
    MT_CLR_PNU (uptr);
    *bc = 0;
    return MTSE_OK;
    }
st = sim_tape_rdlntr (uptr, bc);                        /* get record length */







>
>
|







1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
*/

t_stat sim_tape_sprecr (UNIT *uptr, t_mtrlnt *bc)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecr(unit=%d)\n", (int)(uptr-ctx->dptr->units));

if (MT_TST_PNU (uptr)) {
    MT_CLR_PNU (uptr);
    *bc = 0;
    return MTSE_OK;
    }
st = sim_tape_rdlntr (uptr, bc);                        /* get record length */
1720
1721
1722
1723
1724
1725
1726


1727
1728
1729
1730
1731
1732
1733
1734

t_stat sim_tape_sprecsr (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_mtrlnt tbc;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecsr(unit=%d, count=%d)\n", uptr-ctx->dptr->units, count);

*skipped = 0;
while (*skipped < count) {                              /* loopo */
    st = sim_tape_sprecr (uptr, &tbc);                  /* spc rec rev */
    if (st != MTSE_OK)
        return st;
    *skipped = *skipped + 1;                            /* # recs skipped */







>
>
|







1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790

t_stat sim_tape_sprecsr (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_mtrlnt tbc;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_sprecsr(unit=%d, count=%d)\n", (int)(uptr-ctx->dptr->units), count);

*skipped = 0;
while (*skipped < count) {                              /* loopo */
    st = sim_tape_sprecr (uptr, &tbc);                  /* spc rec rev */
    if (st != MTSE_OK)
        return st;
    *skipped = *skipped + 1;                            /* # recs skipped */
1769
1770
1771
1772
1773
1774
1775


1776
1777
1778
1779
1780
1781
1782
1783
t_stat sim_tape_spfilebyrecf (UNIT *uptr, uint32 count, uint32 *skipped, uint32 *recsskipped, t_bool check_leot)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_bool last_tapemark = FALSE;
uint32 filerecsskipped;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilebyrecf(unit=%d, count=%d, check_leot=%d)\n", uptr-ctx->dptr->units, count, check_leot);

if (check_leot) {
    t_mtrlnt rbc;

    st = sim_tape_rdlntr (uptr, &rbc);
    last_tapemark = (MTSE_TMK == st);
    if ((st == MTSE_OK) || (st == MTSE_TMK))







>
>
|







1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
t_stat sim_tape_spfilebyrecf (UNIT *uptr, uint32 count, uint32 *skipped, uint32 *recsskipped, t_bool check_leot)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
t_bool last_tapemark = FALSE;
uint32 filerecsskipped;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilebyrecf(unit=%d, count=%d, check_leot=%d)\n", (int)(uptr-ctx->dptr->units), count, check_leot);

if (check_leot) {
    t_mtrlnt rbc;

    st = sim_tape_rdlntr (uptr, &rbc);
    last_tapemark = (MTSE_TMK == st);
    if ((st == MTSE_OK) || (st == MTSE_TMK))
1837
1838
1839
1840
1841
1842
1843


1844
1845
1846
1847
1848
1849
1850
1851
*/

t_stat sim_tape_spfilef (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 totalrecsskipped;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilef(unit=%d, count=%d)\n", uptr-ctx->dptr->units, count);

return sim_tape_spfilebyrecf (uptr, count, skipped, &totalrecsskipped, FALSE);
}

t_stat sim_tape_spfilef_a (UNIT *uptr, uint32 count, uint32 *skipped, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;







>
>
|







1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
*/

t_stat sim_tape_spfilef (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 totalrecsskipped;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilef(unit=%d, count=%d)\n", (int)(uptr-ctx->dptr->units), count);

return sim_tape_spfilebyrecf (uptr, count, skipped, &totalrecsskipped, FALSE);
}

t_stat sim_tape_spfilef_a (UNIT *uptr, uint32 count, uint32 *skipped, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
1878
1879
1880
1881
1882
1883
1884


1885
1886
1887
1888
1889
1890
1891
1892

t_stat sim_tape_spfilebyrecr (UNIT *uptr, uint32 count, uint32 *skipped, uint32 *recsskipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
uint32 filerecsskipped;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilebyrecr(unit=%d, count=%d)\n", uptr-ctx->dptr->units, count);

*skipped = 0;
*recsskipped = 0;
while (*skipped < count) {                              /* loopo */
    while (1) {
        st = sim_tape_sprecsr (uptr, 0x1ffffff, &filerecsskipped);/* spc recs rev */
        *recsskipped += filerecsskipped;







>
>
|







1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954

t_stat sim_tape_spfilebyrecr (UNIT *uptr, uint32 count, uint32 *skipped, uint32 *recsskipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat st;
uint32 filerecsskipped;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfilebyrecr(unit=%d, count=%d)\n", (int)(uptr-ctx->dptr->units), count);

*skipped = 0;
*recsskipped = 0;
while (*skipped < count) {                              /* loopo */
    while (1) {
        st = sim_tape_sprecsr (uptr, 0x1ffffff, &filerecsskipped);/* spc recs rev */
        *recsskipped += filerecsskipped;
1931
1932
1933
1934
1935
1936
1937


1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958


1959
1960
1961
1962
1963
1964
1965
1966
*/

t_stat sim_tape_spfiler (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 totalrecsskipped;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfiler(unit=%d, count=%d)\n", uptr-ctx->dptr->units, count);

return sim_tape_spfilebyrecr (uptr, count, skipped, &totalrecsskipped);
}

t_stat sim_tape_spfiler_a (UNIT *uptr, uint32 count, uint32 *skipped, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
    r = sim_tape_spfiler (uptr, count, skipped);
AIO_CALL(TOP_SPFR, NULL, skipped, NULL, 0, count, 0, 0, NULL, callback);
return r;
}

/* Rewind tape */

t_stat sim_tape_rewind (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (uptr->flags & UNIT_ATT) {


    sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rewind(unit=%d)\n", uptr-ctx->dptr->units);
    }
uptr->pos = 0;
MT_CLR_PNU (uptr);
return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)







>
>
|




















>
>
|







1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
*/

t_stat sim_tape_spfiler (UNIT *uptr, uint32 count, uint32 *skipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
uint32 totalrecsskipped;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_spfiler(unit=%d, count=%d)\n", (int)(uptr-ctx->dptr->units), count);

return sim_tape_spfilebyrecr (uptr, count, skipped, &totalrecsskipped);
}

t_stat sim_tape_spfiler_a (UNIT *uptr, uint32 count, uint32 *skipped, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
    r = sim_tape_spfiler (uptr, count, skipped);
AIO_CALL(TOP_SPFR, NULL, skipped, NULL, 0, count, 0, 0, NULL, callback);
return r;
}

/* Rewind tape */

t_stat sim_tape_rewind (UNIT *uptr)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

if (uptr->flags & UNIT_ATT) {
    if (ctx == NULL)                                    /* if not properly attached? */
        return sim_messagef (SCPE_IERR, "Bad Attach\n");/*   that's a problem */
    sim_debug (ctx->dbit, ctx->dptr, "sim_tape_rewind(unit=%d)\n", (int)(uptr-ctx->dptr->units));
    }
uptr->pos = 0;
MT_CLR_PNU (uptr);
return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)
1975
1976
1977
1978
1979
1980
1981


1982
1983
1984
1985
1986
1987
1988
1989
/* Position Tape */

t_stat sim_tape_position (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recsskipped, uint32 files, uint32 *filesskipped, uint32 *objectsskipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r = MTSE_OK;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_position(unit=%d, flags=0x%X, recs=%d, files=%d)\n", uptr-ctx->dptr->units, flags, recs, files);

*recsskipped = *filesskipped = *objectsskipped = 0;
if (flags & MTPOS_M_REW)
    r = sim_tape_rewind (uptr);
if (r != MTSE_OK)
    return r;
if (flags & MTPOS_M_OBJ) {







>
>
|







2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
/* Position Tape */

t_stat sim_tape_position (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recsskipped, uint32 files, uint32 *filesskipped, uint32 *objectsskipped)
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;
t_stat r = MTSE_OK;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_position(unit=%d, flags=0x%X, recs=%d, files=%d)\n", (int)(uptr-ctx->dptr->units), flags, recs, files);

*recsskipped = *filesskipped = *objectsskipped = 0;
if (flags & MTPOS_M_REW)
    r = sim_tape_rewind (uptr);
if (r != MTSE_OK)
    return r;
if (flags & MTPOS_M_OBJ) {
2039
2040
2041
2042
2043
2044
2045


2046
2047
2048
2049
2050
2051
2052
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

MT_CLR_PNU (uptr);
if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;



sim_debug (ctx->dbit, ctx->dptr, "sim_tape_reset(unit=%d)\n", (int)(uptr-ctx->dptr->units));

_sim_tape_io_flush(uptr);
AIO_VALIDATE;
AIO_UPDATE_QUEUE;
return SCPE_OK;
}







>
>







2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
{
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

MT_CLR_PNU (uptr);
if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;

if (ctx == NULL)                                        /* if not properly attached? */
    return sim_messagef (SCPE_IERR, "Bad Attach\n");    /*   that's a problem */
sim_debug (ctx->dbit, ctx->dptr, "sim_tape_reset(unit=%d)\n", (int)(uptr-ctx->dptr->units));

_sim_tape_io_flush(uptr);
AIO_VALIDATE;
AIO_UPDATE_QUEUE;
return SCPE_OK;
}
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
sim_printf ("%s: Magtape library I/O error: %s\n", sim_uname (uptr), strerror (errno));
clearerr (uptr->fileref);
return MTSE_IOERR;
}

/* Set tape format */

t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, char *cptr, void *desc)
{
uint32 f;

if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if (uptr == NULL)
    return SCPE_IERR;







|







2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
sim_printf ("%s: Magtape library I/O error: %s\n", sim_uname (uptr), strerror (errno));
clearerr (uptr->fileref);
return MTSE_IOERR;
}

/* Set tape format */

t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
uint32 f;

if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if (uptr == NULL)
    return SCPE_IERR;
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126

2127
2128



2129
2130
2131


2132

2133
2134
2135
2136
2137



2138
2139









2140
2141




2142
2143









2144













2145








2146



2147
2148
2149
2150
2151
2152
2153
        }
    }
return SCPE_ARG;
}

/* Show tape format */

t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, void *desc)
{
int32 f = MT_GET_FMT (uptr);

if (fmts[f].name)
    fprintf (st, "%s format", fmts[f].name);
else fprintf (st, "invalid format");
return SCPE_OK;
}

/* Map a TPC format tape image */

static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map)
{
t_addr tpos;
t_addr tape_size;
t_tpclnt bc, last_bc;

size_t i;
uint32 objc;




if ((uptr == NULL) || (uptr->fileref == NULL))
    return 0;


tape_size = (t_addr)sim_fsize (uptr->fileref);

for (objc = 0, tpos = 0;; ) {
    sim_fseek (uptr->fileref, tpos, SEEK_SET);
    i = sim_fread (&bc, sizeof (t_tpclnt), 1, uptr->fileref);
    if (i == 0)     /* past or at eof? */
        break;



    if (map)
        map[objc] = tpos;









    objc++;
    tpos = tpos + ((bc + 1) & ~1) + sizeof (t_tpclnt);




    last_bc = bc;
    }









if ((last_bc != 0xffff) && (tpos > tape_size))  /* Unreasonable format? */













    return 0;








if (map) map[objc] = tpos;



return objc;
}

/* Check the basic structure of a SIMH format tape image */

static t_stat sim_tape_simh_check (UNIT *uptr)
{







|











|

|

|
>

|
>
>
>



>
>

>
|




>
>
>
|

>
>
>
>
>
>
>
>
>


>
>
>
>


>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
|
>
>
>







2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
        }
    }
return SCPE_ARG;
}

/* Show tape format */

t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
int32 f = MT_GET_FMT (uptr);

if (fmts[f].name)
    fprintf (st, "%s format", fmts[f].name);
else fprintf (st, "invalid format");
return SCPE_OK;
}

/* Map a TPC format tape image */

static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize)
{
t_addr tpos, leot;
t_addr tape_size;
t_tpclnt bc, last_bc = 0xFFFF;
uint32 had_double_tape_mark = 0;
size_t i;
uint32 objc, sizec;
uint32 *countmap = NULL;
uint8 *recbuf = NULL;
DEVICE *dptr = find_dev_from_unit (uptr);

if ((uptr == NULL) || (uptr->fileref == NULL))
    return 0;
countmap = (uint32 *)calloc (65536, sizeof(*countmap));
recbuf = (uint8 *)malloc (65536);
tape_size = (t_addr)sim_fsize (uptr->fileref);
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: tape_size: %" T_ADDR_FMT "u\n", tape_size);
for (objc = 0, sizec = 0, tpos = 0;; ) {
    sim_fseek (uptr->fileref, tpos, SEEK_SET);
    i = sim_fread (&bc, sizeof (t_tpclnt), 1, uptr->fileref);
    if (i == 0)     /* past or at eof? */
        break;
    if (countmap[bc] == 0)
        sizec++;
    ++countmap[bc];
    if (map && (objc < mapsize))
        map[objc] = tpos;
    if (bc) {
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: %d byte count at pos: %" T_ADDR_FMT "u\n", bc, tpos);
        if (sim_deb && (dptr->dctrl & MTSE_DBG_STR)) {
            sim_fread (recbuf, 1, bc, uptr->fileref);
            sim_data_trace(dptr, uptr, ((dptr->dctrl & MTSE_DBG_DAT) ? recbuf : NULL), "", bc, "Data Record", MTSE_DBG_STR);
            }
        }
    else
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: tape mark at pos: %" T_ADDR_FMT "u\n", tpos);
    objc++;
    tpos = tpos + ((bc + 1) & ~1) + sizeof (t_tpclnt);
    if ((bc == 0) && (last_bc == 0)) {  /* double tape mark? */
        had_double_tape_mark = objc;
        leot = tpos;
        }
    last_bc = bc;
    }
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: objc: %u, different record sizes: %u\n", objc, sizec);
for (i=0; i<65535; i++) {
    if (countmap[i]) {
        if (i == 0)
            sim_debug (MTSE_DBG_STR, dptr, "tpc_map: summary - %u tape marks\n", countmap[i]);
        else
            sim_debug (MTSE_DBG_STR, dptr, "tpc_map: summary - %u %d byte record%s\n", countmap[i], (int)i, (countmap[i] > 1) ? "s" : "");
        }
    }
if (((last_bc != 0xffff) && 
     (tpos > tape_size) &&
     (!had_double_tape_mark))    ||
    (!had_double_tape_mark)      ||
    ((objc == countmap[0]) && 
     (countmap[0] != 2))) {     /* Unreasonable format? */
    if (last_bc != 0xffff)
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR unexpected EOT byte count: %d\n", last_bc);
    if (tpos > tape_size)
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR next record position %" T_ADDR_FMT "u beyond EOT: %" T_ADDR_FMT "u\n", tpos, tape_size);
    if (objc == countmap[0])
        sim_debug (MTSE_DBG_STR, dptr, "tpc_map: ERROR tape cnly contains tape marks\n");
    free (countmap);
    free (recbuf);
    return 0;
    }

if ((last_bc != 0xffff) && (tpos > tape_size)) {
    sim_debug (MTSE_DBG_STR, dptr, "tpc_map: WARNING unexpected EOT byte count: %d, double tape mark before %" T_ADDR_FMT "u provides logical EOT\n", last_bc, leot);
    objc = had_double_tape_mark;
    tpos = leot;
    }
if (map)
    map[objc] = tpos;
sim_debug (MTSE_DBG_STR, dptr, "tpc_map: OK objc: %d\n", objc);
free (countmap);
free (recbuf);
return objc;
}

/* Check the basic structure of a SIMH format tape image */

static t_stat sim_tape_simh_check (UNIT *uptr)
{
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
    }
while (lo <= hi);
return ((p == 0)? map[p]: map[p - 1]);
}

/* Set tape capacity */

t_stat sim_tape_set_capac (UNIT *uptr, int32 val, char *cptr, void *desc)
{
t_addr cap;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_ARG;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
cap = (t_addr) get_uint (cptr, 10, sim_taddr_64? 2000000: 2000, &r);
if (r != SCPE_OK)
    return SCPE_ARG;
uptr->capac = cap * ((t_addr) 1000000);
return SCPE_OK;
}

/* Show tape capacity */

t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, void *desc)
{
if (uptr->capac) {
    if (uptr->capac >= (t_addr) 1000000)
        fprintf (st, "capacity=%dMB", (uint32) (uptr->capac / ((t_addr) 1000000)));
    else {
        if (uptr->capac >= (t_addr) 1000)
            fprintf (st, "capacity=%dKB", (uint32) (uptr->capac / ((t_addr) 1000)));







|

















|







2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
    }
while (lo <= hi);
return ((p == 0)? map[p]: map[p - 1]);
}

/* Set tape capacity */

t_stat sim_tape_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
t_addr cap;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_ARG;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
cap = (t_addr) get_uint (cptr, 10, sim_taddr_64? 2000000: 2000, &r);
if (r != SCPE_OK)
    return SCPE_ARG;
uptr->capac = cap * ((t_addr) 1000000);
return SCPE_OK;
}

/* Show tape capacity */

t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
if (uptr->capac) {
    if (uptr->capac >= (t_addr) 1000000)
        fprintf (st, "capacity=%dMB", (uint32) (uptr->capac / ((t_addr) 1000000)));
    else {
        if (uptr->capac >= (t_addr) 1000)
            fprintf (st, "capacity=%dKB", (uint32) (uptr->capac / ((t_addr) 1000)));
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
   values.

   In either case, SCPE_ARG is returned if the density setting is not valid or
   allowed.  If the setting is OK, the new density is set into the unit
   structure, and SCPE_OK is returned.
*/

t_stat sim_tape_set_dens (UNIT *uptr, int32 val, char *cptr, void *desc)
{
uint32 density, new_bpi;
t_stat result = SCPE_OK;

if (uptr == NULL)                                               /* if the unit pointer is null */
    return SCPE_IERR;                                           /*   then the caller has screwed up */








|







2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
   values.

   In either case, SCPE_ARG is returned if the density setting is not valid or
   allowed.  If the setting is OK, the new density is set into the unit
   structure, and SCPE_OK is returned.
*/

t_stat sim_tape_set_dens (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
uint32 density, new_bpi;
t_stat result = SCPE_OK;

if (uptr == NULL)                                               /* if the unit pointer is null */
    return SCPE_IERR;                                           /*   then the caller has screwed up */

2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
    new_bpi = (uint32) get_uint (cptr, 10, UINT_MAX, &result);  /* convert the string value */

    if (result != SCPE_OK)                                      /* if the conversion failed */
        result = SCPE_ARG;                                      /*   then report a bad argument */

    else for (density = 0; density < BPI_COUNT; density++)      /* otherwise validate the density */
        if (new_bpi == bpi [density]                            /* if it matches a value in the list */
          && ((1 << density) & *(int32 *) desc)) {              /*   and it's an allowed value */
            uptr->dynflags = (uptr->dynflags & ~MTVF_DENS_MASK) /*     then store the index of the value */
                               | density << UNIT_V_DF_TAPE;     /*       in the unit flags */
            return SCPE_OK;                                     /*         and return success */
            }

    result = SCPE_ARG;                                          /* if no match, then report a bad argument */
    }

return result;                                                  /* return the result of the operation */
}

/* Show the tape density */

t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, void *desc)
{
uint32 tape_density;

if (uptr == NULL)                                       /* if the unit pointer is null */
    return SCPE_IERR;                                   /*   then the caller has screwed up */

else {                                                  /* otherwise get the density */







|













|







2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
    new_bpi = (uint32) get_uint (cptr, 10, UINT_MAX, &result);  /* convert the string value */

    if (result != SCPE_OK)                                      /* if the conversion failed */
        result = SCPE_ARG;                                      /*   then report a bad argument */

    else for (density = 0; density < BPI_COUNT; density++)      /* otherwise validate the density */
        if (new_bpi == bpi [density]                            /* if it matches a value in the list */
          && ((1 << density) & *(const int32 *) desc)) {        /*   and it's an allowed value */
            uptr->dynflags = (uptr->dynflags & ~MTVF_DENS_MASK) /*     then store the index of the value */
                               | density << UNIT_V_DF_TAPE;     /*       in the unit flags */
            return SCPE_OK;                                     /*         and return success */
            }

    result = SCPE_ARG;                                          /* if no match, then report a bad argument */
    }

return result;                                                  /* return the result of the operation */
}

/* Show the tape density */

t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
uint32 tape_density;

if (uptr == NULL)                                       /* if the unit pointer is null */
    return SCPE_IERR;                                   /*   then the caller has screwed up */

else {                                                  /* otherwise get the density */
Changes to src/sim_tape.h.
29
30
31
32
33
34
35




36
37
38
39
40
41
42
   14-Feb-06    RMS     Added variable tape capacity
   17-Dec-05    RMS     Added write support for Paul Pierce 7b format
   02-May-05    RMS     Added support for Paul Pierce 7b format
*/

#ifndef SIM_TAPE_H_
#define SIM_TAPE_H_    0





/* SIMH/E11 tape format */

typedef uint32          t_mtrlnt;                       /* magtape rec lnt */

#define MTR_TMK         0x00000000                      /* tape mark */
#define MTR_EOM         0xFFFFFFFF                      /* end of medium */







>
>
>
>







29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
   14-Feb-06    RMS     Added variable tape capacity
   17-Dec-05    RMS     Added write support for Paul Pierce 7b format
   02-May-05    RMS     Added support for Paul Pierce 7b format
*/

#ifndef SIM_TAPE_H_
#define SIM_TAPE_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

/* SIMH/E11 tape format */

typedef uint32          t_mtrlnt;                       /* magtape rec lnt */

#define MTR_TMK         0x00000000                      /* tape mark */
#define MTR_EOM         0xFFFFFFFF                      /* end of medium */
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

#define MTSE_DBG_DAT   0x0400000                        /* Debug Data */
#define MTSE_DBG_POS   0x0800000                        /* Debug Positioning activities */
#define MTSE_DBG_STR   0x1000000                        /* Debug Tape Structure */

/* Prototypes */

t_stat sim_tape_attach_ex (UNIT *uptr, char *cptr, uint32 dbit, int completion_delay);
t_stat sim_tape_attach (UNIT *uptr, char *cptr);
t_stat sim_tape_detach (UNIT *uptr);
t_stat sim_tape_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat sim_tape_rdrecf (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max);
t_stat sim_tape_rdrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback);
t_stat sim_tape_rdrecr (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max);
t_stat sim_tape_rdrecr_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback);
t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc);







|
|







148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

#define MTSE_DBG_DAT   0x0400000                        /* Debug Data */
#define MTSE_DBG_POS   0x0800000                        /* Debug Positioning activities */
#define MTSE_DBG_STR   0x1000000                        /* Debug Tape Structure */

/* Prototypes */

t_stat sim_tape_attach_ex (UNIT *uptr, const char *cptr, uint32 dbit, int completion_delay);
t_stat sim_tape_attach (UNIT *uptr, CONST char *cptr);
t_stat sim_tape_detach (UNIT *uptr);
t_stat sim_tape_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
t_stat sim_tape_rdrecf (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max);
t_stat sim_tape_rdrecf_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback);
t_stat sim_tape_rdrecr (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max);
t_stat sim_tape_rdrecr_a (UNIT *uptr, uint8 *buf, t_mtrlnt *bc, t_mtrlnt max, TAPE_PCALLBACK callback);
t_stat sim_tape_wrrecf (UNIT *uptr, uint8 *buf, t_mtrlnt bc);
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201


202


t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback);
t_stat sim_tape_position (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recskipped, uint32 files, uint32 *fileskipped, uint32 *objectsskipped);
t_stat sim_tape_position_a (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recsskipped, uint32 files, uint32 *filesskipped, uint32 *objectsskipped, TAPE_PCALLBACK callback);
t_stat sim_tape_reset (UNIT *uptr);
t_bool sim_tape_bot (UNIT *uptr);
t_bool sim_tape_wrp (UNIT *uptr);
t_bool sim_tape_eot (UNIT *uptr);
t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat sim_tape_set_capac (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat sim_tape_set_dens (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat sim_tape_set_asynch (UNIT *uptr, int latency);
t_stat sim_tape_clr_asynch (UNIT *uptr);



#endif









|
|
|
|
|
|



>
>

>
>
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback);
t_stat sim_tape_position (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recskipped, uint32 files, uint32 *fileskipped, uint32 *objectsskipped);
t_stat sim_tape_position_a (UNIT *uptr, uint32 flags, uint32 recs, uint32 *recsskipped, uint32 files, uint32 *filesskipped, uint32 *objectsskipped, TAPE_PCALLBACK callback);
t_stat sim_tape_reset (UNIT *uptr);
t_bool sim_tape_bot (UNIT *uptr);
t_bool sim_tape_wrp (UNIT *uptr);
t_bool sim_tape_eot (UNIT *uptr);
t_stat sim_tape_set_fmt (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_capac (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_dens (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_tape_show_dens (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat sim_tape_set_asynch (UNIT *uptr, int latency);
t_stat sim_tape_clr_asynch (UNIT *uptr);

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_timer.c.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
   02-Jan-04    RMS     Split out from SCP

   This library includes the following routines:

   sim_timer_init -         initialize timing system
   sim_rtc_init -           initialize calibration
   sim_rtc_calb -           calibrate clock
   sim_timer_init -         initialize timing system
   sim_idle -               virtual machine idle
   sim_os_msec  -           return elapsed time in msec
   sim_os_sleep -           sleep specified number of seconds
   sim_os_ms_sleep -        sleep specified number of milliseconds
   sim_idle_ms_sleep -      sleep specified number of milliseconds
                            or until awakened by an asynchronous
                            event







<







59
60
61
62
63
64
65

66
67
68
69
70
71
72
   02-Jan-04    RMS     Split out from SCP

   This library includes the following routines:

   sim_timer_init -         initialize timing system
   sim_rtc_init -           initialize calibration
   sim_rtc_calb -           calibrate clock

   sim_idle -               virtual machine idle
   sim_os_msec  -           return elapsed time in msec
   sim_os_sleep -           sleep specified number of seconds
   sim_os_ms_sleep -        sleep specified number of milliseconds
   sim_idle_ms_sleep -      sleep specified number of milliseconds
                            or until awakened by an asynchronous
                            event
81
82
83
84
85
86
87


























































88
89
90
91


92
93
94



95
96
97
98
99
100
101


102
103
104
105

106
107
108

109

110



111
112

113
114
115
116
117
118
119
120
121

122
123
124
125
126


127















128

129



130

131
132
133
134
135
136
137

#define NOT_MUX_USING_CODE /* sim_tmxr library provider or agnostic */

#include "sim_defs.h"
#include <ctype.h>
#include <math.h>



























































t_bool sim_idle_enab = FALSE;                       /* global flag */
volatile t_bool sim_idle_wait = FALSE;              /* global flag */

static int32 sim_calb_tmr = -1;                     /* the system calibrated timer */



static uint32 sim_idle_rate_ms = 0;
static uint32 sim_os_sleep_min_ms = 0;



static uint32 sim_idle_stable = SIM_IDLE_STDFLT;
static t_bool sim_idle_idled = FALSE;
static uint32 sim_throt_ms_start = 0;
static uint32 sim_throt_ms_stop = 0;
static uint32 sim_throt_type = 0;
static uint32 sim_throt_val = 0;
static uint32 sim_throt_state = 0;


static uint32 sim_throt_sleep_time = 0;
static int32 sim_throt_wait = 0;
static UNIT *sim_clock_unit[SIM_NTIMERS] = {NULL};
UNIT *sim_clock_cosched_queue[SIM_NTIMERS] = {NULL};

t_bool sim_asynch_timer = 
#if defined (SIM_ASYNCH_CLOCKS)
                                 TRUE;

#else

                                 FALSE;



#endif


t_stat sim_throt_svc (UNIT *uptr);
t_stat sim_timer_tick_svc (UNIT *uptr);

#define DBG_IDL       TIMER_DBG_IDLE        /* idling */
#define DBG_QUE       TIMER_DBG_QUEUE       /* queue activities */
#define DBG_TRC       0x004                 /* tracing */
#define DBG_CAL       0x008                 /* calibration activities */
#define DBG_TIM       0x010                 /* timer thread activities */
#define DBG_THR       0x020                 /* throttle activities */

DEBTAB sim_timer_debug[] = {
  {"TRACE",   DBG_TRC},
  {"IDLE",    DBG_IDL},
  {"QUEUE",   DBG_QUE},
  {"CALIB",   DBG_CAL},


  {"TIME",    DBG_TIM},















  {"THROT",   DBG_THR},

  {0}



};


#if defined(SIM_ASYNCH_IO)
uint32 sim_idle_ms_sleep (unsigned int msec)
{
uint32 start_time = sim_os_msec();
struct timespec done_time;
t_bool timedout = FALSE;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>
>



>
>
>

|




|
>
>


|
|
>
|
|
<
>
|
>
|
>
>
>


>
|
|
|
<
|
|
|
|
|
>
|
<
|
|
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
>
|
>







80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172

173
174
175
176
177
178
179
180
181
182
183
184
185

186
187
188
189
190
191
192

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

#define NOT_MUX_USING_CODE /* sim_tmxr library provider or agnostic */

#include "sim_defs.h"
#include <ctype.h>
#include <math.h>

#define SIM_INTERNAL_CLK (SIM_NTIMERS+(1<<30))
#define SIM_INTERNAL_UNIT sim_internal_timer_unit
#ifndef MIN
#define MIN(a,b)  (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b)  (((a) > (b)) ? (a) : (b))
#endif

uint32 sim_idle_ms_sleep (unsigned int msec);

/* MS_MIN_GRANULARITY exists here so that timing behavior for hosts systems  */
/* with slow clock ticks can be assessed and tested without actually having  */
/* that slow a clock tick on the development platform                        */
//#define MS_MIN_GRANULARITY 20   /* Uncomment to simulate 20ms host tick size.*/
                                /* some Solaris and BSD hosts come this way  */

#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
uint32 real_sim_idle_ms_sleep (unsigned int msec);
uint32 real_sim_os_msec (void);
uint32 real_sim_os_ms_sleep (unsigned int msec);
static uint32 real_sim_os_sleep_min_ms = 0;
static uint32 real_sim_os_sleep_inc_ms = 0;

uint32 sim_idle_ms_sleep (unsigned int msec)
{
uint32 real_start = real_sim_os_msec ();
uint32 start = (real_start / MS_MIN_GRANULARITY) * MS_MIN_GRANULARITY;
uint32 tick_left;

if (msec == 0)
    return 0;
if (real_start == start)
    tick_left = 0;
else
    tick_left = MS_MIN_GRANULARITY - (real_start - start);
if (msec <= tick_left)
    real_sim_idle_ms_sleep (tick_left);
else
    real_sim_idle_ms_sleep (((msec + MS_MIN_GRANULARITY - 1) / MS_MIN_GRANULARITY) * MS_MIN_GRANULARITY);

return (sim_os_msec () - start);
}

uint32 sim_os_msec (void)
{
return (real_sim_os_msec ()/MS_MIN_GRANULARITY)*MS_MIN_GRANULARITY;
}

uint32 sim_os_ms_sleep (unsigned int msec)
{
msec = MS_MIN_GRANULARITY*((msec+MS_MIN_GRANULARITY-1)/MS_MIN_GRANULARITY);

return real_sim_os_ms_sleep (msec);
}

#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */

t_bool sim_idle_enab = FALSE;                       /* global flag */
volatile t_bool sim_idle_wait = FALSE;              /* global flag */

static int32 sim_calb_tmr = -1;                     /* the system calibrated timer */
static int32 sim_calb_tmr_last = -1;                /* shadow value when at sim> prompt */
static double sim_inst_per_sec_last = 0;            /* shadow value when at sim> prompt */

static uint32 sim_idle_rate_ms = 0;
static uint32 sim_os_sleep_min_ms = 0;
static uint32 sim_os_sleep_inc_ms = 0;
static uint32 sim_os_clock_resoluton_ms = 0;
static uint32 sim_os_tick_hz = 0;
static uint32 sim_idle_stable = SIM_IDLE_STDFLT;
static uint32 sim_idle_calib_pct = 0;
static uint32 sim_throt_ms_start = 0;
static uint32 sim_throt_ms_stop = 0;
static uint32 sim_throt_type = 0;
static uint32 sim_throt_val = 0;
static uint32 sim_throt_state = SIM_THROT_STATE_INIT;
static double sim_throt_cps;
static double sim_throt_inst_start;
static uint32 sim_throt_sleep_time = 0;
static int32 sim_throt_wait = 0;
static UNIT *sim_clock_unit[SIM_NTIMERS+1] = {NULL};
UNIT * volatile sim_clock_cosched_queue[SIM_NTIMERS+1] = {NULL};
static int32 sim_cosched_interval[SIM_NTIMERS+1];
static t_bool sim_catchup_ticks = TRUE;
#if defined (SIM_ASYNCH_CLOCKS) && !defined (SIM_ASYNCH_IO)

#undef SIM_ASYNCH_CLOCKS
#endif
t_bool sim_asynch_timer = FALSE;

#if defined (SIM_ASYNCH_CLOCKS)
UNIT * volatile sim_wallclock_queue = QUEUE_LIST_END;
UNIT * volatile sim_wallclock_entry = NULL;
#endif

#define sleep1Samples       100

static uint32 _compute_minimum_sleep (void)
{

uint32 i, tot, tim;

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);
#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
real_sim_idle_ms_sleep (1);         /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
    tot += real_sim_idle_ms_sleep (1);

tim = tot / sleep1Samples;          /* Truncated average */
real_sim_os_sleep_min_ms = tim;
real_sim_idle_ms_sleep (1);         /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
    tot += real_sim_idle_ms_sleep (real_sim_os_sleep_min_ms + 1);
tim = tot / sleep1Samples;          /* Truncated average */
real_sim_os_sleep_inc_ms = tim - real_sim_os_sleep_min_ms;
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */
sim_idle_ms_sleep (1);              /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
    tot += sim_idle_ms_sleep (1);
tim = tot / sleep1Samples;          /* Truncated average */
sim_os_sleep_min_ms = tim;
sim_idle_ms_sleep (1);              /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++)
    tot += sim_idle_ms_sleep (sim_os_sleep_min_ms + 1);
tim = tot / sleep1Samples;          /* Truncated average */
sim_os_sleep_inc_ms = tim - sim_os_sleep_min_ms;
sim_os_set_thread_priority (PRIORITY_NORMAL);
return sim_os_sleep_min_ms;
}

#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)

#define sim_idle_ms_sleep   real_sim_idle_ms_sleep 
#define sim_os_msec         real_sim_os_msec 
#define sim_os_ms_sleep     real_sim_os_ms_sleep

#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */

#if defined(SIM_ASYNCH_IO)
uint32 sim_idle_ms_sleep (unsigned int msec)
{
uint32 start_time = sim_os_msec();
struct timespec done_time;
t_bool timedout = FALSE;
152
153
154
155
156
157
158

159




























160





161




















162

163
164
165
166
167
168
169
sim_idle_wait = FALSE;
pthread_mutex_unlock (&sim_asynch_lock);
if (!timedout) {
    AIO_UPDATE_QUEUE;
    }
return sim_os_msec() - start_time;
}

#define SIM_IDLE_MS_SLEEP sim_idle_ms_sleep




























#else





#define SIM_IDLE_MS_SLEEP sim_os_ms_sleep




















#endif


/* OS-dependent timer and clock routines */

/* VMS */

#if defined (VMS)








>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>







243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
sim_idle_wait = FALSE;
pthread_mutex_unlock (&sim_asynch_lock);
if (!timedout) {
    AIO_UPDATE_QUEUE;
    }
return sim_os_msec() - start_time;
}
#else
uint32 sim_idle_ms_sleep (unsigned int msec)
{
return sim_os_ms_sleep (msec);
}
#endif

/* Mark the need for the sim_os_set_thread_priority routine, */
/* allowing the feature and/or platform dependent code to provide it */
#define NEED_THREAD_PRIORITY

/* If we've got pthreads support then use pthreads mechanisms */
#if defined(USE_READER_THREAD)

#undef NEED_THREAD_PRIORITY

#if defined(_WIN32)
/* On Windows there are several potentially disjoint threading APIs */
/* in use (base win32 pthreads, libSDL provided threading, and direct */
/* calls to beginthreadex), so go directly to the Win32 threading APIs */
/* to manage thread priority */
t_stat sim_os_set_thread_priority (int below_normal_above)
{
const static int val[3] = {THREAD_PRIORITY_BELOW_NORMAL, THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL};

if ((below_normal_above < -1) || (below_normal_above > 1))
    return SCPE_ARG;
SetThreadPriority (GetCurrentThread(), val[1 + below_normal_above]);
return SCPE_OK;
}
#else
/* Native pthreads priority implementation */
t_stat sim_os_set_thread_priority (int below_normal_above)
{
int sched_policy, min_prio, max_prio;
struct sched_param sched_priority;

if ((below_normal_above < -1) || (below_normal_above > 1))
    return SCPE_ARG;

pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
min_prio = sched_get_priority_min(sched_policy);
max_prio = sched_get_priority_max(sched_policy);
switch (below_normal_above) {
    case PRIORITY_BELOW_NORMAL:
        sched_priority.sched_priority = min_prio;
        break;
    case PRIORITY_NORMAL:
        sched_priority.sched_priority = (max_prio + min_prio) / 2;
        break;
    case PRIORITY_ABOVE_NORMAL:
        sched_priority.sched_priority = max_prio;
        break;
    }
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);
return SCPE_OK;
}
#endif
#endif  /* defined(USE_READER_THREAD) */

/* OS-dependent timer and clock routines */

/* VMS */

#if defined (VMS)

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
#if defined (__VAX)
sim_os_sleep_min_ms = 10;                               /* VAX/VMS is 10ms */
#else
sim_os_sleep_min_ms = 1;                                /* Alpha/VMS is 1ms */
#endif
return sim_os_sleep_min_ms;
}

uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec ();
uint32 qtime[2];
int32 nsfactor = -10000;







<
<
<
<
<
|







358
359
360
361
362
363
364





365
366
367
368
369
370
371
372
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{





return _compute_minimum_sleep ();
}

uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec ();
uint32 qtime[2];
int32 nsfactor = -10000;
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
}
#endif /* CLOCK_REALTIME */

#elif defined (_WIN32)

/* Win32 routines */

#include <windows.h>

const t_bool rtc_avail = TRUE;

uint32 sim_os_msec (void)
{
if (sim_idle_rate_ms)
    return timeGetTime ();
else return GetTickCount ();
}

void sim_os_sleep (unsigned int sec)
{
Sleep (sec * 1000);
return;
}

void sim_timer_exit (void)
{
timeEndPeriod (sim_idle_rate_ms);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
TIMECAPS timers;

if (timeGetDevCaps (&timers, sizeof (timers)) != TIMERR_NOERROR)
    return 0;
sim_os_sleep_min_ms = timers.wPeriodMin;
if ((timers.wPeriodMin == 0) || (timers.wPeriodMin > SIM_IDLE_MAX))
    return 0;
if (timeBeginPeriod (timers.wPeriodMin) != TIMERR_NOERROR)
    return 0;
atexit (sim_timer_exit);
Sleep (1);
Sleep (1);
Sleep (1);
Sleep (1);
Sleep (1);
return sim_os_sleep_min_ms;                             /* sim_idle_rate_ms */
}

uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec();

Sleep (msec);







<
<




<
|
<




















|
<




|
|
<
<
<
<







395
396
397
398
399
400
401


402
403
404
405

406

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

428
429
430
431
432
433




434
435
436
437
438
439
440
}
#endif /* CLOCK_REALTIME */

#elif defined (_WIN32)

/* Win32 routines */



const t_bool rtc_avail = TRUE;

uint32 sim_os_msec (void)
{

return timeGetTime ();

}

void sim_os_sleep (unsigned int sec)
{
Sleep (sec * 1000);
return;
}

void sim_timer_exit (void)
{
timeEndPeriod (sim_idle_rate_ms);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
TIMECAPS timers;

if (timeGetDevCaps (&timers, sizeof (timers)) != TIMERR_NOERROR)
    return 0;
if (timers.wPeriodMin == 0)

    return 0;
if (timeBeginPeriod (timers.wPeriodMin) != TIMERR_NOERROR)
    return 0;
atexit (sim_timer_exit);
/* return measured actual minimum sleep time */
return _compute_minimum_sleep ();




}

uint32 sim_os_ms_sleep (unsigned int msec)
{
uint32 stime = sim_os_msec();

Sleep (msec);
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
return sim_os_sleep_min_ms = 1;
}

uint32 sim_os_ms_sleep (unsigned int milliseconds)
{
uint32 stime = sim_os_msec ();
struct timespec treq;

treq.tv_sec = milliseconds / MILLIS_PER_SEC;
treq.tv_nsec = (milliseconds % MILLIS_PER_SEC) * NANOS_PER_MILLI;
(void) nanosleep (&treq, NULL);
return sim_os_msec () - stime;
}

#if defined(NEED_CLOCK_GETTIME)
int clock_gettime(int clk_id, struct timespec *tp)
{
struct timeval cur;
struct timezone foo;

if (clk_id != CLOCK_REALTIME)
  return -1;
gettimeofday (&cur, &foo);
tp->tv_sec = cur.tv_sec;
tp->tv_nsec = cur.tv_usec*1000;
return 0;
}
#endif

#else

/* UNIX routines */

#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#define NANOS_PER_MILLI     1000000
#define MILLIS_PER_SEC      1000
#define sleep1Samples       100

const t_bool rtc_avail = TRUE;

uint32 sim_os_msec (void)
{
struct timeval cur;
struct timezone foo;







|

















<



|















<







514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557

558
559
560
561
562
563
564
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
return _compute_minimum_sleep ();
}

uint32 sim_os_ms_sleep (unsigned int milliseconds)
{
uint32 stime = sim_os_msec ();
struct timespec treq;

treq.tv_sec = milliseconds / MILLIS_PER_SEC;
treq.tv_nsec = (milliseconds % MILLIS_PER_SEC) * NANOS_PER_MILLI;
(void) nanosleep (&treq, NULL);
return sim_os_msec () - stime;
}

#if defined(NEED_CLOCK_GETTIME)
int clock_gettime(int clk_id, struct timespec *tp)
{
struct timeval cur;


if (clk_id != CLOCK_REALTIME)
  return -1;
gettimeofday (&cur, NULL);
tp->tv_sec = cur.tv_sec;
tp->tv_nsec = cur.tv_usec*1000;
return 0;
}
#endif

#else

/* UNIX routines */

#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#define NANOS_PER_MILLI     1000000
#define MILLIS_PER_SEC      1000


const t_bool rtc_avail = TRUE;

uint32 sim_os_msec (void)
{
struct timeval cur;
struct timezone foo;
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{
uint32 i, t1, t2, tot, tim;

SIM_IDLE_MS_SLEEP (1);                  /* Start sampling on a tick boundary */
for (i = 0, tot = 0; i < sleep1Samples; i++) {
    t1 = sim_os_msec ();
    SIM_IDLE_MS_SLEEP (1);
    t2 = sim_os_msec ();
    tot += (t2 - t1);
    }
tim = (tot + (sleep1Samples - 1)) / sleep1Samples;
sim_os_sleep_min_ms = tim;
if (tim > SIM_IDLE_MAX)
    tim = 0;
return tim;
}
#if !defined(_POSIX_SOURCE)
#ifdef NEED_CLOCK_GETTIME
typedef int clockid_t;
int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
struct timeval cur;
struct timezone foo;







<
|
<
<
<
<
<
<
|
<
<
<
<
<
|







573
574
575
576
577
578
579

580






581





582
583
584
585
586
587
588
589
{
sleep (sec);
return;
}

uint32 sim_os_ms_sleep_init (void)
{

return _compute_minimum_sleep ();






}






#if !defined(_POSIX_SOURCE)
#ifdef NEED_CLOCK_GETTIME
typedef int clockid_t;
int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
struct timeval cur;
struct timezone foo;
487
488
489
490
491
492
493































494
495















496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515












516
517
518
519
520
521
522
523

treq.tv_sec = milliseconds / MILLIS_PER_SEC;
treq.tv_nsec = (milliseconds % MILLIS_PER_SEC) * NANOS_PER_MILLI;
(void) nanosleep (&treq, NULL);
return sim_os_msec () - stime;
}
































#endif
















/* diff = min - sub */
void
sim_timespec_diff (struct timespec *diff, struct timespec *min, struct timespec *sub)
{
/* move the minuend value to the difference and operate there. */
*diff = *min;
/* Borrow as needed for the nsec value */
while (sub->tv_nsec > diff->tv_nsec) {
    --diff->tv_sec;
    diff->tv_nsec += 1000000000;
    }
diff->tv_nsec -= sub->tv_nsec;
diff->tv_sec -= sub->tv_sec;
/* Normalize the result */
while (diff->tv_nsec > 1000000000) {
    ++diff->tv_sec;
    diff->tv_nsec -= 1000000000;
    }
}













#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
static int sim_timespec_compare (struct timespec *a, struct timespec *b)
{
while (a->tv_nsec > 1000000000) {
    a->tv_nsec -= 1000000000;
    ++a->tv_sec;
    }
while (b->tv_nsec > 1000000000) {







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




















>
>
>
>
>
>
>
>
>
>
>
>
|







605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699

treq.tv_sec = milliseconds / MILLIS_PER_SEC;
treq.tv_nsec = (milliseconds % MILLIS_PER_SEC) * NANOS_PER_MILLI;
(void) nanosleep (&treq, NULL);
return sim_os_msec () - stime;
}

#if defined(NEED_THREAD_PRIORITY)
#undef NEED_THREAD_PRIORITY
#include <sys/time.h>
#include <sys/resource.h>

t_stat sim_os_set_thread_priority (int below_normal_above)
{
if ((below_normal_above < -1) || (below_normal_above > 1))
    return SCPE_ARG;

errno = 0;
switch (below_normal_above) {
    case PRIORITY_BELOW_NORMAL:
        if ((getpriority (PRIO_PROCESS, 0) <= 0) &&     /* at or above normal pri? */
            (errno == 0))
            setpriority (PRIO_PROCESS, 0, 10);
        break;
    case PRIORITY_NORMAL:
        if (getpriority (PRIO_PROCESS, 0) != 0)         /* at or above normal pri? */
            setpriority (PRIO_PROCESS, 0, 0);
        break;
    case PRIORITY_ABOVE_NORMAL:
        if ((getpriority (PRIO_PROCESS, 0) <= 0) &&     /* at or above normal pri? */
            (errno == 0))
            setpriority (PRIO_PROCESS, 0, -10);
        break;
    }
return SCPE_OK;
}
#endif  /* defined(NEED_THREAD_PRIORITY) */

#endif

/* If one hasn't been provided yet, then just stub it */
#if defined(NEED_THREAD_PRIORITY)
t_stat sim_os_set_thread_priority (int below_normal_above)
{
return SCPE_OK;
}
#endif

#if defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1)
/* Make sure to use the substitute routines */
#undef sim_idle_ms_sleep
#undef sim_os_msec
#undef sim_os_ms_sleep
#endif /* defined(MS_MIN_GRANULARITY) && (MS_MIN_GRANULARITY != 1) */

/* diff = min - sub */
void
sim_timespec_diff (struct timespec *diff, struct timespec *min, struct timespec *sub)
{
/* move the minuend value to the difference and operate there. */
*diff = *min;
/* Borrow as needed for the nsec value */
while (sub->tv_nsec > diff->tv_nsec) {
    --diff->tv_sec;
    diff->tv_nsec += 1000000000;
    }
diff->tv_nsec -= sub->tv_nsec;
diff->tv_sec -= sub->tv_sec;
/* Normalize the result */
while (diff->tv_nsec > 1000000000) {
    ++diff->tv_sec;
    diff->tv_nsec -= 1000000000;
    }
}

/* Forward declarations */

static double _timespec_to_double (struct timespec *time);
static void _double_to_timespec (struct timespec *time, double dtime);
static t_bool _rtcn_tick_catchup_check (int32 tmr, int32 time);
static void _rtcn_configure_calibrated_clock (int32 newtmr);
static void _sim_coschedule_cancel(UNIT *uptr);
static void _sim_wallclock_cancel (UNIT *uptr);
static t_bool _sim_wallclock_is_active (UNIT *uptr);
t_stat sim_timer_show_idle_mode (FILE* st, UNIT* uptr, int32 val, CONST void *  desc);


#if defined(SIM_ASYNCH_CLOCKS)
static int sim_timespec_compare (struct timespec *a, struct timespec *b)
{
while (a->tv_nsec > 1000000000) {
    a->tv_nsec -= 1000000000;
    ++a->tv_sec;
    }
while (b->tv_nsec > 1000000000) {
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553





















554
555






























556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577



578
579











580
581
582
583

584
585
586
587
588
589
590
591
592
593










594

595
596
597
598
599
600
601
602
603
604

605



606
607




608

















609
610
611
612
613
614



615

616
617
618
619


620
621
622
623
624
625
626
627



628



629
630

631
632
633
634
635
636
637







638

639
640
641













642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
if (a->tv_nsec < b->tv_nsec)
    return -1;
if (a->tv_nsec > b->tv_nsec)
    return 1;
else
    return 0;
}
#endif /* defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS) */

/* OS independent clock calibration package */

static int32 rtc_ticks[SIM_NTIMERS] = { 0 };            /* ticks */
static int32 rtc_hz[SIM_NTIMERS] = { 0 };               /* tick rate */
static uint32 rtc_rtime[SIM_NTIMERS] = { 0 };           /* real time */
static uint32 rtc_vtime[SIM_NTIMERS] = { 0 };           /* virtual time */
static double rtc_gtime[SIM_NTIMERS] = { 0 };           /* instruction time */
static uint32 rtc_nxintv[SIM_NTIMERS] = { 0 };          /* next interval */
static int32 rtc_based[SIM_NTIMERS] = { 0 };            /* base delay */
static int32 rtc_currd[SIM_NTIMERS] = { 0 };            /* current delay */
static int32 rtc_initd[SIM_NTIMERS] = { 0 };            /* initial delay */
static uint32 rtc_elapsed[SIM_NTIMERS] = { 0 };         /* sec since init */
static uint32 rtc_calibrations[SIM_NTIMERS] = { 0 };    /* calibration count */
static double rtc_clock_skew_max[SIM_NTIMERS] = { 0 };  /* asynchronous max skew */






















UNIT sim_timer_units[SIM_NTIMERS+1];                    /* one for each timer and one for throttle */
































void sim_rtcn_init_all (void)
{
uint32 i;

for (i = 0; i < SIM_NTIMERS; i++)
    if (rtc_initd[i] != 0)
        sim_rtcn_init (rtc_initd[i], i);
return;
}

int32 sim_rtcn_init (int32 time, int32 tmr)
{
return sim_rtcn_init_unit (NULL, time, tmr);
}

int32 sim_rtcn_init_unit (UNIT *uptr, int32 time, int32 tmr)
{
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_init(time=%d, tmr=%d)\n", time, tmr);
if (time == 0)
    time = 1;



if ((tmr < 0) || (tmr >= SIM_NTIMERS))
    return time;











if (uptr) {
    sim_clock_unit[tmr] = uptr;
    sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;
    }

rtc_rtime[tmr] = sim_os_msec ();
rtc_vtime[tmr] = rtc_rtime[tmr];
rtc_nxintv[tmr] = 1000;
rtc_ticks[tmr] = 0;
rtc_hz[tmr] = 0;
rtc_based[tmr] = time;
rtc_currd[tmr] = time;
rtc_initd[tmr] = time;
rtc_elapsed[tmr] = 0;
rtc_calibrations[tmr] = 0;










if (sim_calb_tmr == -1)                 /* save first initialized clock as the system timer */

    sim_calb_tmr  = tmr;
return time;
}

int32 sim_rtcn_calb (int32 ticksper, int32 tmr)
{
uint32 new_rtime, delta_rtime;
int32 delta_vtime;
double new_gtime;
int32 new_currd;





if ((tmr < 0) || (tmr >= SIM_NTIMERS))
    return 10000;




rtc_hz[tmr] = ticksper;

















rtc_ticks[tmr] = rtc_ticks[tmr] + 1;                    /* count ticks */
if (rtc_ticks[tmr] < ticksper) {                        /* 1 sec yet? */
    return rtc_currd[tmr];
    }
rtc_ticks[tmr] = 0;                                     /* reset ticks */
rtc_elapsed[tmr] = rtc_elapsed[tmr] + 1;                /* count sec */



if (!rtc_avail) {                                       /* no timer? */

    return rtc_currd[tmr];
    }
new_rtime = sim_os_msec ();                             /* wall time */
sim_debug (DBG_TRC, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d, tmr=%d) rtime=%d\n", ticksper, tmr, new_rtime);


if (sim_idle_idled) {
    rtc_rtime[tmr] = new_rtime;                         /* save wall time */
    rtc_vtime[tmr] = rtc_vtime[tmr] + 1000;             /* adv sim time */
    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
    sim_idle_idled = FALSE;                             /* reset idled flag */
    sim_debug (DBG_CAL, &sim_timer_dev, "skipping calibration due to idling - result: %d\n", rtc_currd[tmr]);
    return rtc_currd[tmr];                              /* avoid calibrating idle checks */
    }



if (new_rtime < rtc_rtime[tmr]) {                       /* time running backwards? */



    rtc_rtime[tmr] = new_rtime;                         /* reset wall time */
    sim_debug (DBG_CAL, &sim_timer_dev, "time running backwards - result: %d\n", rtc_currd[tmr]);

    return rtc_currd[tmr];                              /* can't calibrate */
    }
++rtc_calibrations[tmr];                                /* count calibrations */
delta_rtime = new_rtime - rtc_rtime[tmr];               /* elapsed wtime */
rtc_rtime[tmr] = new_rtime;                             /* adv wall time */
rtc_vtime[tmr] = rtc_vtime[tmr] + 1000;                 /* adv sim time */
if (delta_rtime > 30000) {                              /* gap too big? */







    rtc_currd[tmr] = rtc_initd[tmr];

    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
    sim_debug (DBG_CAL, &sim_timer_dev, "gap too big: delta = %d - result: %d\n", delta_rtime, rtc_initd[tmr]);
    return rtc_initd[tmr];                              /* can't calibr */













    }
new_gtime = sim_gtime();
if (sim_asynch_enabled && sim_asynch_timer) {
    if (rtc_elapsed[tmr] > sim_idle_stable) {
        /* An asynchronous clock, merely needs to divide the number of */
        /* instructions actually executed by the clock rate. */
        new_currd = (int32)((new_gtime - rtc_gtime[tmr])/ticksper);
        /* avoid excessive swings in the calibrated result */
        if (new_currd > 10*rtc_currd[tmr])              /* don't swing big too fast */
            new_currd = 10*rtc_currd[tmr];
        else
            if (new_currd < rtc_currd[tmr]/10)          /* don't swing small too fast */
                new_currd = rtc_currd[tmr]/10;
        rtc_currd[tmr] = new_currd;
        rtc_gtime[tmr] = new_gtime;                     /* save instruction time */
        if (rtc_currd[tmr] == 127) {
            sim_debug (DBG_CAL, &sim_timer_dev, "asynch calibration small: %d\n", rtc_currd[tmr]);
            }
        sim_debug (DBG_CAL, &sim_timer_dev, "asynch calibration result: %d\n", rtc_currd[tmr]);
        return rtc_currd[tmr];                          /* calibrated result */
        }
    else {
        rtc_currd[tmr] = rtc_initd[tmr];
        rtc_gtime[tmr] = new_gtime;                     /* save instruction time */
        sim_debug (DBG_CAL, &sim_timer_dev, "asynch not stable calibration result: %d\n", rtc_initd[tmr]);
        return rtc_initd[tmr];                          /* initial result until stable */
        }
    }
rtc_gtime[tmr] = new_gtime;                             /* save instruction time */
/* This self regulating algorithm depends directly on the assumption */
/* that this routine is called back after processing the number of */
/* instructions which was returned the last time it was called. */
if (delta_rtime == 0)                                   /* gap too small? */
    rtc_based[tmr] = rtc_based[tmr] * ticksper;         /* slew wide */







|



|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|

|
|
|










<


>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>

|
|

>










>
>
>
>
>
>
>
>
>
>
|
>
|





|



>

>
>
>
|
|
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|

<


>
>
>
|
>


<
<
>
>
|
|
<
<
<
|
|

>
>
>

>
>
>
|
|
>


<




>
>
>
>
>
>
>
|
>

|
|
>
>
>
>
>
>
>
>
>
>
>
>
>


|
<
|
|
|
|
|
|
|
|
|
|
|
<
<
<
|
|
<
<
<
<
<
<
<







707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801

802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888

889
890
891
892
893
894
895
896
897


898
899
900
901



902
903
904
905
906
907
908
909
910
911
912
913
914
915
916

917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948

949
950
951
952
953
954
955
956
957
958
959



960
961







962
963
964
965
966
967
968
if (a->tv_nsec < b->tv_nsec)
    return -1;
if (a->tv_nsec > b->tv_nsec)
    return 1;
else
    return 0;
}
#endif /* defined(SIM_ASYNCH_CLOCKS) */

/* OS independent clock calibration package */

static int32 rtc_ticks[SIM_NTIMERS+1] = { 0 };            /* ticks */
static uint32 rtc_hz[SIM_NTIMERS+1] = { 0 };              /* tick rate */
static uint32 rtc_rtime[SIM_NTIMERS+1] = { 0 };           /* real time */
static uint32 rtc_vtime[SIM_NTIMERS+1] = { 0 };           /* virtual time */
static double rtc_gtime[SIM_NTIMERS+1] = { 0 };           /* instruction time */
static uint32 rtc_nxintv[SIM_NTIMERS+1] = { 0 };          /* next interval */
static int32 rtc_based[SIM_NTIMERS+1] = { 0 };            /* base delay */
static int32 rtc_currd[SIM_NTIMERS+1] = { 0 };            /* current delay */
static int32 rtc_initd[SIM_NTIMERS+1] = { 0 };            /* initial delay */
static uint32 rtc_elapsed[SIM_NTIMERS+1] = { 0 };         /* sec since init */
static uint32 rtc_calibrations[SIM_NTIMERS+1] = { 0 };    /* calibration count */
static double rtc_clock_skew_max[SIM_NTIMERS+1] = { 0 };  /* asynchronous max skew */
static double rtc_clock_start_gtime[SIM_NTIMERS+1] = { 0 };/* reference instruction time for clock */
static double rtc_clock_tick_size[SIM_NTIMERS+1] = { 0 }; /* 1/hz */
static uint32 rtc_calib_initializations[SIM_NTIMERS+1] = { 0 };/* Initialization Count */
static double rtc_calib_tick_time[SIM_NTIMERS+1] = { 0 }; /* ticks time */
static double rtc_calib_tick_time_tot[SIM_NTIMERS+1] = { 0 };/* ticks time - total*/
static uint32 rtc_calib_ticks_acked[SIM_NTIMERS+1] = { 0 };/* ticks Acked */
static uint32 rtc_calib_ticks_acked_tot[SIM_NTIMERS+1] = { 0 };/* ticks Acked - total */
static uint32 rtc_clock_ticks[SIM_NTIMERS+1] = { 0 };/* ticks delivered since catchup base */
static uint32 rtc_clock_ticks_tot[SIM_NTIMERS+1] = { 0 };/* ticks delivered since catchup base - total */
static double rtc_clock_init_base_time[SIM_NTIMERS+1] = { 0 };/* reference time for clock initialization */
static double rtc_clock_tick_start_time[SIM_NTIMERS+1] = { 0 };/* reference time when ticking started */
static double rtc_clock_catchup_base_time[SIM_NTIMERS+1] = { 0 };/* reference time for catchup ticks */
static uint32 rtc_clock_catchup_ticks[SIM_NTIMERS+1] = { 0 };/* Record of catchups */
static uint32 rtc_clock_catchup_ticks_tot[SIM_NTIMERS+1] = { 0 };/* Record of catchups - total */
static t_bool rtc_clock_catchup_pending[SIM_NTIMERS+1] = { 0 };/* clock tick catchup pending */
static t_bool rtc_clock_catchup_eligible[SIM_NTIMERS+1] = { 0 };/* clock tick catchup eligible */
static uint32 rtc_clock_time_idled[SIM_NTIMERS+1] = { 0 };/* total time idled */
static uint32 rtc_clock_time_idled_last[SIM_NTIMERS+1] = { 0 };/* total time idled */
static uint32 rtc_clock_calib_skip_idle[SIM_NTIMERS+1] = { 0 };/* Calibrations skipped due to idling */
static uint32 rtc_clock_calib_gap2big[SIM_NTIMERS+1] = { 0 };/* Calibrations skipped Gap Too Big */
static uint32 rtc_clock_calib_backwards[SIM_NTIMERS+1] = { 0 };/* Calibrations skipped Clock Running Backwards */

UNIT sim_timer_units[SIM_NTIMERS+1];                    /* one for each timer and one for an */
                                                        /* internal clock if no clocks are registered */
UNIT sim_internal_timer_unit;                           /* Internal calibration timer */
UNIT sim_throttle_unit;                                 /* one for throttle */

t_stat sim_throt_svc (UNIT *uptr);
t_stat sim_timer_tick_svc (UNIT *uptr);

#define DBG_IDL       TIMER_DBG_IDLE        /* idling */
#define DBG_QUE       TIMER_DBG_QUEUE       /* queue activities */
#define DBG_MUX       TIMER_DBG_MUX         /* tmxr queue activities */
#define DBG_TRC       0x008                 /* tracing */
#define DBG_CAL       0x010                 /* calibration activities */
#define DBG_TIM       0x020                 /* timer thread activities */
#define DBG_THR       0x040                 /* throttle activities */
#define DBG_ACK       0x080                 /* interrupt acknowledgement activities */
DEBTAB sim_timer_debug[] = {
  {"TRACE",   DBG_TRC, "Trace routine calls"},
  {"IDLE",    DBG_IDL, "Idling activities"},
  {"QUEUE",   DBG_QUE, "Event queuing activities"},
  {"IACK",    DBG_ACK, "interrupt acknowledgement activities"},
  {"CALIB",   DBG_CAL, "Calibration activities"},
  {"TIME",    DBG_TIM, "Activation and scheduling activities"},
  {"THROT",   DBG_THR, "Throttling activities"},
  {"MUX",     DBG_MUX, "Tmxr scheduling activities"},
  {0}
};

/* Forward device declarations */
extern DEVICE sim_timer_dev;
extern DEVICE sim_throttle_dev;


void sim_rtcn_init_all (void)
{
int32 tmr;

for (tmr = 0; tmr <= SIM_NTIMERS; tmr++)
    if (rtc_initd[tmr] != 0)
        sim_rtcn_init (rtc_initd[tmr], tmr);
return;
}

int32 sim_rtcn_init (int32 time, int32 tmr)
{
return sim_rtcn_init_unit (NULL, time, tmr);
}

int32 sim_rtcn_init_unit (UNIT *uptr, int32 time, int32 tmr)
{

if (time == 0)
    time = 1;
if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr >= SIM_NTIMERS))
        return time;
    }
/*
 * If we'd previously succeeded in calibrating a tick value, then use that
 * delay as a better default to setup when we're re-initialized.
 * Re-initializing happens on any boot or after any breakpoint/continue.
 */
if (rtc_currd[tmr])
    time = rtc_currd[tmr];
if (!uptr)
    uptr = sim_clock_unit[tmr];
sim_debug (DBG_CAL, &sim_timer_dev, "_sim_rtcn_init_unit(unit=%s, time=%d, tmr=%d)\n", sim_uname(uptr), time, tmr);
if (uptr) {
    if (!sim_clock_unit[tmr])
        sim_register_clock_unit_tmr (uptr, tmr);
    }
rtc_clock_start_gtime[tmr] = sim_gtime();
rtc_rtime[tmr] = sim_os_msec ();
rtc_vtime[tmr] = rtc_rtime[tmr];
rtc_nxintv[tmr] = 1000;
rtc_ticks[tmr] = 0;
rtc_hz[tmr] = 0;
rtc_based[tmr] = time;
rtc_currd[tmr] = time;
rtc_initd[tmr] = time;
rtc_elapsed[tmr] = 0;
rtc_calibrations[tmr] = 0;
rtc_clock_ticks_tot[tmr] += rtc_clock_ticks[tmr];
rtc_clock_ticks[tmr] = 0;
rtc_calib_tick_time_tot[tmr] += rtc_calib_tick_time[tmr];
rtc_calib_tick_time[tmr] = 0;
rtc_clock_catchup_pending[tmr] = FALSE;
rtc_clock_catchup_eligible[tmr] = FALSE;
rtc_clock_catchup_ticks_tot[tmr] += rtc_clock_catchup_ticks[tmr];
rtc_clock_catchup_ticks[tmr] = 0;
rtc_calib_ticks_acked_tot[tmr] += rtc_calib_ticks_acked[tmr];
rtc_calib_ticks_acked[tmr] = 0;
++rtc_calib_initializations[tmr];
rtc_clock_init_base_time[tmr] = sim_timenow_double ();
_rtcn_configure_calibrated_clock (tmr);
return time;
}

int32 sim_rtcn_calb (int32 ticksper, int32 tmr)
{
uint32 new_rtime, delta_rtime, last_idle_pct;
int32 delta_vtime;
double new_gtime;
int32 new_currd;
int32 itmr;

if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr >= SIM_NTIMERS))
        return 10000;
    }
if (rtc_hz[tmr] != ticksper) {                          /* changing tick rate? */
    if (rtc_hz[tmr] == 0)
        rtc_clock_tick_start_time[tmr] = sim_timenow_double ();
    rtc_hz[tmr] = ticksper;
    _rtcn_configure_calibrated_clock (tmr);
    if (ticksper != 0) {
        rtc_clock_tick_size[tmr] = 1.0/ticksper;
        rtc_currd[tmr] = (int32)(sim_timer_inst_per_sec()/ticksper);
        }
    }
if (ticksper == 0) {                                    /* running? */
    return 10000;
    }
if (sim_clock_unit[tmr] == NULL) {                      /* Not using TIMER units? */
    rtc_clock_ticks[tmr] += 1;
    rtc_calib_tick_time[tmr] += rtc_clock_tick_size[tmr];
    }
if (rtc_clock_catchup_pending[tmr]) {                   /* catchup tick? */
    ++rtc_clock_catchup_ticks[tmr];                     /* accumulating which were catchups */
    rtc_clock_catchup_pending[tmr] = FALSE;
    }
rtc_ticks[tmr] = rtc_ticks[tmr] + 1;                    /* count ticks */
if (rtc_ticks[tmr] < ticksper)                          /* 1 sec yet? */
    return rtc_currd[tmr];

rtc_ticks[tmr] = 0;                                     /* reset ticks */
rtc_elapsed[tmr] = rtc_elapsed[tmr] + 1;                /* count sec */
if (sim_throt_type != SIM_THROT_NONE) {
    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
    rtc_currd[tmr] = (int32)(sim_throt_cps / ticksper); /* use throttle calibration */
    ++rtc_calibrations[tmr];                            /* count calibrations */
    sim_debug (DBG_CAL, &sim_timer_dev, "using throttle calibrated value - result: %d\n", rtc_currd[tmr]);
    return rtc_currd[tmr];
    }


if (!rtc_avail)                                         /* no timer? */
    return rtc_currd[tmr];
if (sim_calb_tmr != tmr) {
    rtc_currd[tmr] = (int32)(sim_timer_inst_per_sec()/ticksper);



    sim_debug (DBG_CAL, &sim_timer_dev, "calibrated calibrated tmr=%d against system tmr=%d, tickper=%d (result: %d)\n", tmr, sim_calb_tmr, ticksper, rtc_currd[tmr]);
    return rtc_currd[tmr];
    }
new_rtime = sim_os_msec ();                             /* wall time */
++rtc_calibrations[tmr];                                /* count calibrations */
sim_debug (DBG_TRC, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d, tmr=%d)\n", ticksper, tmr);
if (new_rtime < rtc_rtime[tmr]) {                       /* time running backwards? */
    /* This happens when the value returned by sim_os_msec wraps (as an uint32) */
    /* Wrapping will happen initially sometime before a simulator has been running */
    /* for 49 days approximately every 49 days thereafter. */
    ++rtc_clock_calib_backwards[tmr];                   /* Count statistic */
    sim_debug (DBG_CAL, &sim_timer_dev, "time running backwards - OldTime: %u, NewTime: %u, result: %d\n", rtc_rtime[tmr], new_rtime, rtc_currd[tmr]);
    rtc_rtime[tmr] = new_rtime;                         /* reset wall time */
    return rtc_currd[tmr];                              /* can't calibrate */
    }

delta_rtime = new_rtime - rtc_rtime[tmr];               /* elapsed wtime */
rtc_rtime[tmr] = new_rtime;                             /* adv wall time */
rtc_vtime[tmr] = rtc_vtime[tmr] + 1000;                 /* adv sim time */
if (delta_rtime > 30000) {                              /* gap too big? */
    /* This simulator process has somehow been suspended for a significant */
    /* amount of time.  This will certainly happen if the host system has  */
    /* slept or hibernated.  It also might happen when a simulator         */
    /* developer stops the simulator at a breakpoint (a process, not simh  */
    /* breakpoint).  To accomodate this, we set the calibration state to   */
    /* ignore what happened and proceed from here.                         */
    ++rtc_clock_calib_gap2big[tmr];                     /* Count statistic */
    rtc_vtime[tmr] = rtc_rtime[tmr];                    /* sync virtual and real time */
    rtc_nxintv[tmr] = 1000;                             /* reset next interval */
    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
    sim_debug (DBG_CAL, &sim_timer_dev, "gap too big: delta = %d - result: %d\n", delta_rtime, rtc_currd[tmr]);
    return rtc_currd[tmr];                              /* can't calibr */
    }
if (delta_rtime == 0)                                   /* avoid divide by zero  */
    last_idle_pct = 0;                                  /* force calibration */
else
    last_idle_pct = MIN(100, (uint32)(100.0 * (((double)(rtc_clock_time_idled[tmr] - rtc_clock_time_idled_last[tmr])) / ((double)delta_rtime))));
rtc_clock_time_idled_last[tmr] = rtc_clock_time_idled[tmr];
if (last_idle_pct > (100 - sim_idle_calib_pct)) {
    rtc_rtime[tmr] = new_rtime;                         /* save wall time */
    rtc_vtime[tmr] = rtc_vtime[tmr] + 1000;             /* adv sim time */
    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
    ++rtc_clock_calib_skip_idle[tmr];
    sim_debug (DBG_CAL, &sim_timer_dev, "skipping calibration due to idling (%d%%) - result: %d\n", last_idle_pct, rtc_currd[tmr]);
    return rtc_currd[tmr];                              /* avoid calibrating idle checks */
    }
new_gtime = sim_gtime();
if (sim_asynch_timer) {

    /* An asynchronous clock, merely needs to divide the number of */
    /* instructions actually executed by the clock rate. */
    new_currd = (int32)((new_gtime - rtc_gtime[tmr])/ticksper);
    /* avoid excessive swings in the calibrated result */
    if (new_currd > 10*rtc_currd[tmr])              /* don't swing big too fast */
        new_currd = 10*rtc_currd[tmr];
    else
        if (new_currd < rtc_currd[tmr]/10)          /* don't swing small too fast */
            new_currd = rtc_currd[tmr]/10;
    rtc_currd[tmr] = new_currd;
    rtc_gtime[tmr] = new_gtime;                     /* save instruction time */



    sim_debug (DBG_CAL, &sim_timer_dev, "asynch calibration result: %d\n", rtc_currd[tmr]);
    return rtc_currd[tmr];                          /* calibrated result */







    }
rtc_gtime[tmr] = new_gtime;                             /* save instruction time */
/* This self regulating algorithm depends directly on the assumption */
/* that this routine is called back after processing the number of */
/* instructions which was returned the last time it was called. */
if (delta_rtime == 0)                                   /* gap too small? */
    rtc_based[tmr] = rtc_based[tmr] * ticksper;         /* slew wide */
683
684
685
686
687
688
689
690




691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711

712
713
714
715
716


717


718
719













720
721
722
723
724
725
726
727
728


729
730
731
732
733
734
735
736




737






















738
739
740
741
742
743
744



745
746
747
748
749

750
751
752

753










754
755
756
757
758
759
760
761
762


763
764



































765
766
767
768
769
770
771
772
773
774
775

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793




















794
795
796
797


798
799

800
801
802
803
804
805

806




807

808
809
810
811

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841





842
843
844
845
846
847























848



849
850

851
852
853
854

855



856
857
858
859
860
861
862
863
864
865
866
867
868







869
870
871












872
873
874
875
876
877




























878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897







898
899
900
901
902
903
904
905
906
907










908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944








945
946
947
948
949
950
951
952
953
954
955
956

957
958
959
960
961

962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038


1039
1040
1041
1042
1043
1044
1045
1046
1047

1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066

1067
1068





1069
1070
1071


1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083


1084
1085
1086
1087


1088
1089
1090
1091


1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135

1136
1137
1138
1139
1140
1141
1142
1143
1144
1145

1146

1147
1148

1149
1150
1151
1152
1153
1154
1155
1156


1157
1158

1159
1160

1161
1162
1163
1164
1165
1166
1167
1168
1169
1170



1171
1172

1173
1174
1175
1176

1177
1178


1179
1180

1181
1182
1183








1184
1185
1186
1187
1188
1189
1190
1191



1192




1193
1194


1195






1196
1197
1198
1199
1200
1201
1202

1203
1204















1205






1206


1207
























1208




















































































1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
rtc_nxintv[tmr] = 1000 + delta_vtime;                   /* next wtime */
rtc_currd[tmr] = (int32) (((double) rtc_based[tmr] * (double) rtc_nxintv[tmr]) /
    1000.0);                                            /* next delay */
if (rtc_based[tmr] <= 0)                                /* never negative or zero! */
    rtc_based[tmr] = 1;
if (rtc_currd[tmr] <= 0)                                /* never negative or zero! */
    rtc_currd[tmr] = 1;
sim_debug (DBG_CAL, &sim_timer_dev, "calibrated result: %d\n", rtc_currd[tmr]);




AIO_SET_INTERRUPT_LATENCY(rtc_currd[tmr]*ticksper);     /* set interrrupt latency */
return rtc_currd[tmr];
}

/* Prior interfaces - default to timer 0 */

int32 sim_rtc_init (int32 time)
{
return sim_rtcn_init (time, 0);
}

int32 sim_rtc_calb (int32 ticksper)
{
return sim_rtcn_calb (ticksper, 0);
}

/* sim_timer_init - get minimum sleep time available on this host */

t_bool sim_timer_init (void)
{
int i;


sim_debug (DBG_TRC, &sim_timer_dev, "sim_timer_init()\n");
for (i=0; i<SIM_NTIMERS; i++)
    sim_timer_units[i].action = &sim_timer_tick_svc;
sim_timer_units[SIM_NTIMERS].action = &sim_throt_svc;


sim_register_internal_device (&sim_timer_dev);


sim_idle_enab = FALSE;                                  /* init idle off */
sim_idle_rate_ms = sim_os_ms_sleep_init ();             /* get OS timer rate */













return (sim_idle_rate_ms != 0);
}

/* sim_timer_idle_capable - tell if the host is Idle capable and what the host OS tick size is */

uint32 sim_timer_idle_capable (uint32 *host_tick_ms)
{
if (host_tick_ms)
    *host_tick_ms = sim_os_sleep_min_ms;


return sim_idle_rate_ms;
}

/* sim_show_timers - show running timer information */

t_stat sim_show_timers (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc)
{
int tmr, clocks;



























for (tmr=clocks=0; tmr<SIM_NTIMERS; ++tmr) {
    if (0 == rtc_initd[tmr])
        continue;
    
    if (sim_clock_unit[tmr]) {
        ++clocks;
        fprintf (st, "%s clock device is %s\n", sim_name, sim_uname(sim_clock_unit[tmr]));



        }

    fprintf (st, "%s%sTimer %d:\n", (sim_asynch_enabled && sim_asynch_timer) ? "Asynchronous " : "", rtc_hz[tmr] ? "Calibrated " : "Uncalibrated ", tmr);
    if (rtc_hz[tmr]) {
        fprintf (st, "  Running at:              %dhz\n", rtc_hz[tmr]);

        fprintf (st, "  Ticks in current second: %d\n",   rtc_ticks[tmr]);
        }
    fprintf (st, "  Seconds Running:         %u\n",   rtc_elapsed[tmr]);

    fprintf (st, "  Calibrations:            %u\n",   rtc_calibrations[tmr]);










    fprintf (st, "  Instruction Time:        %.0f\n", rtc_gtime[tmr]);
    if (!(sim_asynch_enabled && sim_asynch_timer)) {
        fprintf (st, "  Real Time:               %u\n",   rtc_rtime[tmr]);
        fprintf (st, "  Virtual Time:            %u\n",   rtc_vtime[tmr]);
        fprintf (st, "  Next Interval:           %u\n",   rtc_nxintv[tmr]);
        fprintf (st, "  Base Tick Delay:         %d\n",   rtc_based[tmr]);
        fprintf (st, "  Initial Insts Per Tick:  %d\n",   rtc_initd[tmr]);
        }
    fprintf (st, "  Current Insts Per Tick:  %d\n",   rtc_currd[tmr]);


    if (rtc_clock_skew_max[tmr] != 0.0)
        fprintf (st, "  Peak Clock Skew:         %.0fms\n",   rtc_clock_skew_max[tmr]);



































    }
if (clocks == 0)
    fprintf (st, "%s clock device is not specified, co-scheduling is unavailable\n", sim_name);
return SCPE_OK;
}

t_stat sim_show_clock_queues (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr)
{
#if defined (SIM_ASYNCH_IO)
int tmr;


pthread_mutex_lock (&sim_timer_lock);
if (sim_wallclock_queue == QUEUE_LIST_END)
    fprintf (st, "%s wall clock event queue empty\n", sim_name);
else {
    fprintf (st, "%s wall clock event queue status\n", sim_name);
    for (uptr = sim_wallclock_queue; uptr != QUEUE_LIST_END; uptr = uptr->a_next) {
        if ((dptr = find_dev_from_unit (uptr)) != NULL) {
            fprintf (st, "  %s", sim_dname (dptr));
            if (dptr->numunits > 1)
                fprintf (st, " unit %d", (int32) (uptr - dptr->units));
            }
        else fprintf (st, "  Unknown");
        fprintf (st, " after ");
        fprint_val (st, (t_value)uptr->a_usec_delay, 10, 0, PV_RCOMMA);
        fprintf (st, " usec\n");
        }
    }
if (sim_asynch_timer) {




















    for (tmr=0; tmr<SIM_NTIMERS; ++tmr) {
        if (sim_clock_unit[tmr] == NULL)
            continue;
        if (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {


            fprintf (st, "%s clock (%s) co-schedule event queue status\n",
                     sim_name, sim_uname(sim_clock_unit[tmr]));

            for (uptr = sim_clock_cosched_queue[tmr]; uptr != QUEUE_LIST_END; uptr = uptr->a_next) {
                if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                    fprintf (st, "  %s", sim_dname (dptr));
                    if (dptr->numunits > 1)
                        fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                    }

                else fprintf (st, "  Unknown");




                fprintf (st, "\n");

                }
            }
        }
    }

pthread_mutex_unlock (&sim_timer_lock);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}

REG sim_timer_reg[] = {
    { DRDATAD (TICKS_PER_SEC,    rtc_hz[0],              32, "Ticks Per Second"), PV_RSPC|REG_RO},
    { DRDATAD (INSTS_PER_TICK,   rtc_currd[0],           32, "Instructions Per Tick"), PV_RSPC|REG_RO},
    { FLDATAD (IDLE_ENAB,        sim_idle_enab,           0, "Idle Enabled"), REG_RO},
    { DRDATAD (IDLE_RATE_MS,     sim_idle_rate_ms,       32, "Idle Rate Milliseconds"), PV_RSPC|REG_RO},
    { DRDATAD (OS_SLEEP_MIN_MS,  sim_os_sleep_min_ms,    32, "Minimum Sleep Resolution"), PV_RSPC|REG_RO},
    { DRDATAD (IDLE_STABLE,      sim_idle_stable,        32, "Idle Stable"), PV_RSPC},
    { FLDATAD (IDLE_IDLED,       sim_idle_idled,          0, ""), REG_RO},
    { DRDATAD (TMR,              sim_calb_tmr,           32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_MS_START,   sim_throt_ms_start,     32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_MS_STOP,    sim_throt_ms_stop,      32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_TYPE,       sim_throt_type,         32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_VAL,        sim_throt_val,          32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_STATE,      sim_throt_state,        32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_SLEEP_TIME, sim_throt_sleep_time,   32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_WAIT,       sim_throt_wait,         32, ""), PV_RSPC|REG_RO},
    { NULL }
    };

/* Clear, Set and show asynch */

/* Clear asynch */

t_stat sim_timer_clr_async (UNIT *uptr, int32 val, char *cptr, void *desc)
{





if (sim_asynch_timer) {
    sim_asynch_timer = FALSE;
    sim_timer_change_asynch ();
    }
return SCPE_OK;
}



























t_stat sim_timer_set_async (UNIT *uptr, int32 val, char *cptr, void *desc)
{

if (!sim_asynch_timer) {
    sim_asynch_timer = TRUE;
    sim_timer_change_asynch ();
    }

return SCPE_OK;



}

t_stat sim_timer_show_async (FILE *st, UNIT *uptr, int32 val, void *desc)
{
fprintf (st, "%s", (sim_asynch_enabled && sim_asynch_timer) ? "Asynchronous" : "Synchronous");
return SCPE_OK;
}

MTAB sim_timer_mod[] = {
#if defined (SIM_ASYNCH_IO) && defined (SIM_ASYNCH_CLOCKS)
  { MTAB_VDV,          MTAB_VDV, "ASYNC", "ASYNC",   &sim_timer_set_async, &sim_timer_show_async, NULL, "Enables/Displays Asynchronous Timer operation mode" },
  { MTAB_VDV,                 0,    NULL, "NOASYNC", &sim_timer_clr_async, NULL,                  NULL, "Disables Asynchronous Timer operation" },
#endif







  { 0 },
};













DEVICE sim_timer_dev = {
    "TIMER", sim_timer_units, sim_timer_reg, sim_timer_mod, 
    SIM_NTIMERS+1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_DEBUG | DEV_NOSAVE, 0, sim_timer_debug};






























/* sim_idle - idle simulator until next event or for specified interval

   Inputs:
        tmr =   calibrated timer to use

   Must solve the linear equation

        ms_to_wait = w * ms_per_wait

   Or
        w = ms_to_wait / ms_per_wait
*/

t_bool sim_idle (uint32 tmr, t_bool sin_cyc)
{
static uint32 cyc_ms = 0;
uint32 w_ms, w_idle, act_ms;
int32 act_cyc;








if ((!sim_idle_enab)                             ||     /* idling disabled */
    ((sim_clock_queue == QUEUE_LIST_END) &&             /* or clock queue empty? */
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
     (!(sim_asynch_enabled && sim_asynch_timer)))||     /*     and not asynch? */
#else
     (TRUE))                                     ||
#endif
    ((sim_clock_queue != QUEUE_LIST_END) && 
     ((sim_clock_queue->flags & UNIT_IDLE) == 0))||     /* or event not idle-able? */
    (rtc_elapsed[tmr] < sim_idle_stable)) {             /* or timer not stable? */










    if (sin_cyc)
        sim_interval = sim_interval - 1;
    return FALSE;
    }
/*
   When a simulator is in an instruction path (or under other conditions 
   which would indicate idling), the countdown of sim_interval will not 
   be happening at a pace which is consistent with the rate it happens 
   when not in the 'idle capable' state.  The consequence of this is that 
   the clock calibration may produce calibrated results which vary much 
   more than they do when not in the idle able state.  Sim_idle also uses 
   the calibrated tick size to approximate an adjustment to sim_interval
   to reflect the number of instructions which would have executed during 
   the actual idle time, so consistent calibrated numbers produce better 
   adjustments. 
   
   To negate this effect, we set a flag (sim_idle_idled) here and the 
   sim_rtcn_calb routine checks this flag before performing an actual 
   calibration and skips calibration if the flag was set and then clears 
   the flag.  Thus recalibration only happens if things didn't idle.


   we also check check sim_idle_enab above so that all simulators can avoid
   directly checking sim_idle_enab before calling sim_idle so that all of 
   the bookkeeping on sim_idle_idled is done here in sim_timer where it 
   means something, while not idling when it isn't enabled.  
   */
//sim_idle_idled = TRUE;                                  /* record idle attempt */
sim_debug (DBG_TRC, &sim_timer_dev, "sim_idle(tmr=%d, sin_cyc=%d)\n", tmr, sin_cyc);
if (cyc_ms == 0)                                        /* not computed yet? */
    cyc_ms = (rtc_currd[tmr] * rtc_hz[tmr]) / 1000;     /* cycles per msec */
if ((sim_idle_rate_ms == 0) || (cyc_ms == 0)) {         /* not possible? */
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    sim_debug (DBG_IDL, &sim_timer_dev, "not possible %d - %d\n", sim_idle_rate_ms, cyc_ms);
    return FALSE;
    }
w_ms = (uint32) sim_interval / cyc_ms;                  /* ms to wait */








w_idle = w_ms / sim_idle_rate_ms;                       /* intervals to wait */
if (w_idle == 0) {                                      /* none? */
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    sim_debug (DBG_IDL, &sim_timer_dev, "no wait\n");
    return FALSE;
    }
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event in %d instructions\n", w_ms, sim_interval);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event on %s in %d instructions\n", w_ms, sim_uname(sim_clock_queue), sim_interval);
act_ms = SIM_IDLE_MS_SLEEP (w_ms);                      /* wait */

act_cyc = act_ms * cyc_ms;
if (act_ms < w_ms)                                      /* awakened early? */
    act_cyc += (cyc_ms * sim_idle_rate_ms) / 2;         /* account for half an interval's worth of cycles */
if (sim_interval > act_cyc)
    sim_interval = sim_interval - act_cyc;              /* count down sim_interval */

else sim_interval = 0;                                  /* or fire immediately */
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event in %d instructions\n", act_ms, sim_interval);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event on %s in %d instructions\n", act_ms, sim_uname(sim_clock_queue), sim_interval);
return TRUE;
}

/* Set idling - implicitly disables throttling */

t_stat sim_set_idle (UNIT *uptr, int32 val, char *cptr, void *desc)
{
t_stat r;
uint32 v;

if (sim_idle_rate_ms == 0) {
    sim_printf ("Idling is not available, Minimum OS sleep time is %dms\n", sim_os_sleep_min_ms);
    return SCPE_NOFNC;
    }
if ((val != 0) && (sim_idle_rate_ms > (uint32) val)) {
    sim_printf ("Idling is not available, Minimum OS sleep time is %dms, Requied minimum OS sleep is %dms\n", sim_os_sleep_min_ms, val);
    return SCPE_NOFNC;
    }
if (cptr) {
    v = (uint32) get_uint (cptr, 10, SIM_IDLE_STMAX, &r);
    if ((r != SCPE_OK) || (v < SIM_IDLE_STMIN))
        return SCPE_ARG;
    sim_idle_stable = v;
    }
sim_idle_enab = TRUE;
if (sim_throt_type != SIM_THROT_NONE) {
    sim_set_throt (0, NULL);
    sim_printf ("Throttling disabled\n");
    }
return SCPE_OK;
}

/* Clear idling */

t_stat sim_clr_idle (UNIT *uptr, int32 val, char *cptr, void *desc)
{
sim_idle_enab = FALSE;
return SCPE_OK;
}

/* Show idling */

t_stat sim_show_idle (FILE *st, UNIT *uptr, int32 val, void *desc)
{
if (sim_idle_enab)
    fprintf (st, "idle enabled");
else
    fprintf (st, "idle disabled");
if (sim_switches & SWMASK ('D'))
    fprintf (st, ", stability wait = %ds, minimum sleep resolution = %dms", sim_idle_stable, sim_os_sleep_min_ms);
return SCPE_OK;
}

/* Throttling package */

t_stat sim_set_throt (int32 arg, char *cptr)
{
const char *tptr;
char c;
t_value val, val2 = 0;

if (arg == 0) {
    if ((cptr != 0) && (*cptr != 0))
        return SCPE_ARG;
    sim_throt_type = SIM_THROT_NONE;
    sim_throt_cancel ();
    }
else if (sim_idle_rate_ms == 0) {
    sim_printf ("Throttling is not available, Minimum OS sleep time is %dms\n", sim_os_sleep_min_ms);
    return SCPE_NOFNC;
    }
else {


    val = strtotv (cptr, &tptr, 10);
    if (cptr == tptr)
        return SCPE_ARG;
    sim_throt_sleep_time = sim_idle_rate_ms;
    c = (char)toupper (*tptr++);
    if (c == '/')
        val2 = strtotv (tptr, &tptr, 10);
    if ((*tptr != 0) || (val == 0))
        return SCPE_ARG;

    if (c == 'M') 
        sim_throt_type = SIM_THROT_MCYC;
    else if (c == 'K')
        sim_throt_type = SIM_THROT_KCYC;
    else if ((c == '%') && (val > 0) && (val < 100))
        sim_throt_type = SIM_THROT_PCT;
    else if ((c == '/') && (val2 != 0)) {
        sim_throt_type = SIM_THROT_SPC;
        }
    else return SCPE_ARG;
    if (sim_idle_enab) {
        sim_printf ("Idling disabled\n");
        sim_clr_idle (NULL, 0, NULL, NULL);
        }
    sim_throt_val = (uint32) val;
    if (sim_throt_type == SIM_THROT_SPC) {
        if (val2 >= sim_idle_rate_ms)
            sim_throt_sleep_time = (uint32) val2;
        else {

            sim_throt_sleep_time = (uint32) (val2 * sim_idle_rate_ms);
            sim_throt_val = (uint32) (val * sim_idle_rate_ms);





            }
        }
    }


return SCPE_OK;
}

t_stat sim_show_throt (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr)
{
if (sim_idle_rate_ms == 0)
    fprintf (st, "Throttling not available\n");
else {
    switch (sim_throt_type) {

    case SIM_THROT_MCYC:
        fprintf (st, "Throttle = %d megacycles\n", sim_throt_val);


        break;

    case SIM_THROT_KCYC:
        fprintf (st, "Throttle = %d kilocycles\n", sim_throt_val);


        break;

    case SIM_THROT_PCT:
        fprintf (st, "Throttle = %d%%\n", sim_throt_val);


        break;

    case SIM_THROT_SPC:
        fprintf (st, "Throttle = %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_val);
        break;

    default:
        fprintf (st, "Throttling disabled\n");
        break;
        }

    if (sim_switches & SWMASK ('D')) {
        if (sim_throt_type != 0)

            fprintf (st, "Throttle interval = %d cycles\n", sim_throt_wait);
        }
    }
if (sim_switches & SWMASK ('D'))
    fprintf (st, "minimum sleep resolution = %d ms\n", sim_os_sleep_min_ms);
return SCPE_OK;
}

void sim_throt_sched (void)
{
sim_throt_state = 0;
if (sim_throt_type)
    sim_activate (&sim_timer_units[SIM_NTIMERS], SIM_THROT_WINIT);
}

void sim_throt_cancel (void)
{
sim_cancel (&sim_timer_units[SIM_NTIMERS]);
}

/* Throttle service

   Throttle service has three distinct states used while dynamically
   determining a throttling interval:

       0    take initial measurement
       1    take final measurement, calculate wait values
       2    periodic waits to slow down the CPU
*/
t_stat sim_throt_svc (UNIT *uptr)
{

uint32 delta_ms;
double a_cps, d_cps;

if (sim_throt_type == SIM_THROT_SPC) {                  /* Non dynamic? */
    sim_throt_state = 2;                                /* force state */
    sim_throt_wait = sim_throt_val;
    }
switch (sim_throt_state) {

    case 0:                                             /* take initial reading */

        sim_throt_ms_start = sim_os_msec ();

        sim_throt_wait = SIM_THROT_WST;
        sim_throt_state = 1;                            /* next state */

        break;                                          /* reschedule */

    case 1:                                             /* take final reading */
        sim_throt_ms_stop = sim_os_msec ();
        delta_ms = sim_throt_ms_stop - sim_throt_ms_start;
        if (delta_ms < SIM_THROT_MSMIN) {               /* not enough time? */
            if (sim_throt_wait >= 100000000) {          /* too many inst? */
                sim_throt_state = 0;                    /* fails in 32b! */


                return SCPE_OK;
                }

            sim_throt_wait = sim_throt_wait * SIM_THROT_WMUL;
            sim_throt_ms_start = sim_throt_ms_stop;

            }
        else {                                          /* long enough */
            a_cps = ((double) sim_throt_wait) * 1000.0 / (double) delta_ms;
            if (sim_throt_type == SIM_THROT_MCYC)       /* calc desired cps */
                d_cps = (double) sim_throt_val * 1000000.0;
            else if (sim_throt_type == SIM_THROT_KCYC)
                d_cps = (double) sim_throt_val * 1000.0;
            else d_cps = (a_cps * ((double) sim_throt_val)) / 100.0;
            if (d_cps >= a_cps) {
                sim_throt_sched ();                     /* start over */



                return SCPE_OK;
                }

            sim_throt_wait = (int32)                    /* time between waits */
                ((a_cps * d_cps * ((double) sim_idle_rate_ms)) /
                 (1000.0 * (a_cps - d_cps)));
            if (sim_throt_wait < SIM_THROT_WMIN) {      /* not long enough? */

                sim_throt_sched ();                     /* start over */
                return SCPE_OK;


                }
            sim_throt_ms_start = sim_throt_ms_stop;

            sim_throt_state = 2;
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Throttle values a_cps = %f, d_cps = %f, wait = %d\n", 
                                                a_cps, d_cps, sim_throt_wait);








            }
        break;

    case 2:                                             /* throttling */
        SIM_IDLE_MS_SLEEP (sim_throt_sleep_time);
        delta_ms = sim_os_msec () - sim_throt_ms_start;
        if ((sim_throt_type != SIM_THROT_SPC) &&        /* when dynamic throttling */
            (delta_ms >= 10000)) {                      /* recompute every 10 sec */



            sim_throt_ms_start = sim_os_msec ();




            sim_throt_wait = SIM_THROT_WST;
            sim_throt_state = 1;                        /* next state */


            }






        break;
        }

sim_activate (uptr, sim_throt_wait);                    /* reschedule */
return SCPE_OK;
}


t_stat sim_timer_tick_svc (UNIT *uptr)
{















return SCPE_OK;






}



























#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)





















































































static double _timespec_to_double (struct timespec *time)
{
return ((double)time->tv_sec)+(double)(time->tv_nsec)/1000000000.0;
}

static void _double_to_timespec (struct timespec *time, double dtime)
{
time->tv_sec = (time_t)floor(dtime);
time->tv_nsec = (long)((dtime-floor(dtime))*1000000000.0);
}

double sim_timenow_double (void)
{
struct timespec now;

clock_gettime(CLOCK_REALTIME, &now);
return _timespec_to_double (&now);
}

extern UNIT * volatile sim_wallclock_queue;
extern UNIT * volatile sim_wallclock_entry;

pthread_t           sim_timer_thread;           /* Wall Clock Timing Thread Id */
pthread_cond_t      sim_timer_startup_cond;
t_bool              sim_timer_thread_running = FALSE;
t_bool              sim_timer_event_canceled = FALSE;

static void *
_timer_thread(void *arg)
{
int sched_policy;
struct sched_param sched_priority;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - starting\n");

pthread_mutex_lock (&sim_timer_lock);
pthread_cond_signal (&sim_timer_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_enabled && sim_asynch_timer && sim_is_running) {
    struct timespec start_time, stop_time;
    struct timespec due_time;
    double wait_usec;
    int32 inst_delay;
    double inst_per_sec;
    UNIT *uptr;

    if (sim_wallclock_entry) {                          /* something to insert in queue? */
        UNIT *cptr, *prvptr;

        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - timing %s for %d usec\n", 
                   sim_uname(sim_wallclock_entry), sim_wallclock_entry->time);

        uptr = sim_wallclock_entry;
        sim_wallclock_entry = NULL;

        prvptr = NULL;
        for (cptr = sim_wallclock_queue; cptr != QUEUE_LIST_END; cptr = cptr->a_next) {
            if (uptr->a_due_time < cptr->a_due_time)







|
>
>
>
>
|



















|
>


|
|
|
>
>

>
>


>
>
>
>
>
>
>
>
>
>
>
>
>





|


|
>
>
|



<
|


>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|





|
>
>
>


|

|
>
|

|
>
|
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|

|
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|

<


>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
>
>
|
|
>
|
|
|
|
|
|
>
|
>
>
>
>
|
>
|
|
|
<
>






|
|
|
<
<
<
|
<










|

|

|

>
>
>
>
>
|
|
<



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|

>
|
|
|
|
>
|
>
>
>
|
|
<
<
<



|
|
|
|

>
>
>
>
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>

|

|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
















|



>
>
>
>
>
>
>


<
<
<
|
<
|
|

>
>
>
>
>
>
>
>
>
>
















|
|
|
|
>






<

<
|



|



>
>
>
>
>
>
>
>
|
|









|
>





>
|









|




<
<
<
<
<
<
<
<
|


|












|







|












|

|




|
|




|
<


>
>


|


|

|
|
>






|

<
|









>
|
|
>
>
>
>
>



>
>



|


|




|
>
>



|
>
>



|
>
>



|



|


<
<
|
>
|


<
<





|

|




|







|
|
|



>




|




|
>

>

|
>


|




|
>
>


>

|
>









|
>
>
>


>
|
|
|
|
>
|
<
>
>


>
|
|
|
>
>
>
>
>
>
>
>



|
|

|
|
>
>
>
|
>
>
>
>
|
|
>
>
|
>
>
>
>
>
>







>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
















|



|
<




<


















|





|


<

|
|







976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166

1167
1168
1169
1170
















1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217

1218
1219
1220
1221
1222
1223
1224
1225
1226
1227



1228

1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251

1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295



1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388



1389

1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429

1430

1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480








1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531

1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553

1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612


1613
1614
1615
1616
1617


1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698

1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907

1908
1909
1910
1911

1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938

1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
rtc_nxintv[tmr] = 1000 + delta_vtime;                   /* next wtime */
rtc_currd[tmr] = (int32) (((double) rtc_based[tmr] * (double) rtc_nxintv[tmr]) /
    1000.0);                                            /* next delay */
if (rtc_based[tmr] <= 0)                                /* never negative or zero! */
    rtc_based[tmr] = 1;
if (rtc_currd[tmr] <= 0)                                /* never negative or zero! */
    rtc_currd[tmr] = 1;
sim_debug (DBG_CAL, &sim_timer_dev, "calibrated tmr=%d, tickper=%d (base=%d, nxintv=%u, result: %d)\n", tmr, ticksper, rtc_based[tmr], rtc_nxintv[tmr], rtc_currd[tmr]);
/* Adjust calibration for other timers which depend on this timer's calibration */
for (itmr=0; itmr<=SIM_NTIMERS; itmr++)
    if ((itmr != tmr) && (rtc_hz[itmr] != 0))
        rtc_currd[itmr] = (rtc_currd[tmr] * ticksper) / rtc_hz[itmr];
AIO_SET_INTERRUPT_LATENCY(rtc_currd[tmr] * ticksper);   /* set interrrupt latency */
return rtc_currd[tmr];
}

/* Prior interfaces - default to timer 0 */

int32 sim_rtc_init (int32 time)
{
return sim_rtcn_init (time, 0);
}

int32 sim_rtc_calb (int32 ticksper)
{
return sim_rtcn_calb (ticksper, 0);
}

/* sim_timer_init - get minimum sleep time available on this host */

t_bool sim_timer_init (void)
{
int tmr;
uint32 clock_start, clock_last, clock_now;

sim_debug (DBG_TRC, &sim_timer_dev, "sim_timer_init()\n");
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    sim_timer_units[tmr].action = &sim_timer_tick_svc;
    sim_timer_units[tmr].flags = UNIT_DIS | UNIT_IDLE;
    }
SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
sim_register_internal_device (&sim_timer_dev);
sim_throttle_unit.action = &sim_throt_svc;
sim_register_clock_unit_tmr (&SIM_INTERNAL_UNIT, SIM_INTERNAL_CLK);
sim_idle_enab = FALSE;                                  /* init idle off */
sim_idle_rate_ms = sim_os_ms_sleep_init ();             /* get OS timer rate */

clock_last = clock_start = sim_os_msec ();
sim_os_clock_resoluton_ms = 1000;
do {
    uint32 clock_diff;
    
    clock_now = sim_os_msec ();
    clock_diff = clock_now - clock_last;
    if ((clock_diff > 0) && (clock_diff < sim_os_clock_resoluton_ms))
        sim_os_clock_resoluton_ms = clock_diff;
    clock_last = clock_now;
    } while (clock_now < clock_start + 100);
sim_os_tick_hz = 1000/(sim_os_clock_resoluton_ms * (sim_idle_rate_ms/sim_os_clock_resoluton_ms));
return (sim_idle_rate_ms != 0);
}

/* sim_timer_idle_capable - tell if the host is Idle capable and what the host OS tick size is */

t_bool sim_timer_idle_capable (uint32 *host_ms_sleep_1, uint32 *host_tick_ms)
{
if (host_tick_ms)
    *host_tick_ms = sim_os_clock_resoluton_ms;
if (host_ms_sleep_1)
    *host_ms_sleep_1 = sim_os_sleep_min_ms;
return (sim_idle_rate_ms != 0);
}

/* sim_show_timers - show running timer information */

t_stat sim_show_timers (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc)
{
int tmr, clocks;
struct timespec now;
time_t time_t_now;
int32 calb_tmr = (sim_calb_tmr == -1) ? sim_calb_tmr_last : sim_calb_tmr;
double inst_per_sec = (sim_calb_tmr == -1) ? sim_inst_per_sec_last : sim_timer_inst_per_sec ();

fprintf (st, "Minimum Host Sleep Time:       %d ms (%dHz)\n", sim_os_sleep_min_ms, sim_os_tick_hz);
if (sim_os_sleep_min_ms != sim_os_sleep_inc_ms)
    fprintf (st, "Minimum Host Sleep Incr Time:  %d ms\n", sim_os_sleep_inc_ms);
fprintf (st, "Host Clock Resolution:         %d ms\n", sim_os_clock_resoluton_ms);
fprintf (st, "Execution Rate:                %s instructions/sec\n", sim_fmt_numeric (inst_per_sec));
if (sim_idle_enab) {
    fprintf (st, "Idling:                        Enabled\n");
    fprintf (st, "Time before Idling starts:     %d seconds\n", sim_idle_stable);
    }
if (sim_throt_type != SIM_THROT_NONE) {
    sim_show_throt (st, NULL, uptr, val, desc);
    }
fprintf (st, "Calibrated Timer:              %s\n", (calb_tmr == -1) ? "Undetermined" : 
                                                    ((calb_tmr == SIM_NTIMERS) ? "Internal Timer" : 
                                                    (sim_clock_unit[calb_tmr] ? sim_uname(sim_clock_unit[calb_tmr]) : "")));
if (calb_tmr == SIM_NTIMERS)
    fprintf (st, "Catchup Ticks:                 %s for clocks ticking faster than %d Hz\n", sim_catchup_ticks ? "Enabled" : "Disabled", sim_os_tick_hz);
if (sim_idle_calib_pct == 0)
    fprintf (st, "Calibration:                   Always\n");
else
    fprintf (st, "Calibration:                   Skipped when Idle exceeds %d%%\n", sim_idle_calib_pct);
fprintf (st, "\n");
for (tmr=clocks=0; tmr<=SIM_NTIMERS; ++tmr) {
    if (0 == rtc_initd[tmr])
        continue;
    
    if (sim_clock_unit[tmr]) {
        ++clocks;
        fprintf (st, "%s clock device is %s%s%s\n", sim_name, 
                                                    (tmr == SIM_NTIMERS) ? "Internal Calibrated Timer(" : "", 
                                                    sim_uname(sim_clock_unit[tmr]), 
                                                    (tmr == SIM_NTIMERS) ? ")" : "");
        }

    fprintf (st, "%s%sTimer %d:\n", sim_asynch_timer ? "Asynchronous " : "", rtc_hz[tmr] ? "Calibrated " : "Uncalibrated ", tmr);
    if (rtc_hz[tmr]) {
        fprintf (st, "  Running at:                %d Hz\n", rtc_hz[tmr]);
        fprintf (st, "  Tick Size:                 %s\n", sim_fmt_secs (rtc_clock_tick_size[tmr]));
        fprintf (st, "  Ticks in current second:   %d\n",   rtc_ticks[tmr]);
        }
    fprintf (st, "  Seconds Running:           %s (%s)\n",   sim_fmt_numeric ((double)rtc_elapsed[tmr]), sim_fmt_secs ((double)rtc_elapsed[tmr]));
    if (tmr == calb_tmr) {
        fprintf (st, "  Calibration Opportunities: %s\n",   sim_fmt_numeric ((double)rtc_calibrations[tmr]));
        if (sim_idle_calib_pct)
            fprintf (st, "  Calib Skip Idle Thresh %%:  %u\n",   sim_idle_calib_pct);
        if (rtc_clock_calib_skip_idle[tmr])
            fprintf (st, "  Calibs Skip While Idle:    %u\n",   rtc_clock_calib_skip_idle[tmr]);
        if (rtc_clock_calib_backwards[tmr])
            fprintf (st, "  Calibs Skip Backwards:     %u\n",   rtc_clock_calib_backwards[tmr]);
        if (rtc_clock_calib_gap2big[tmr])
            fprintf (st, "  Calibs Skip Gap Too Big:   %u\n",   rtc_clock_calib_gap2big[tmr]);
        }
    if (rtc_gtime[tmr])
        fprintf (st, "  Instruction Time:          %.0f\n", rtc_gtime[tmr]);
    if ((!sim_asynch_timer) && (sim_throt_type == SIM_THROT_NONE)) {
        fprintf (st, "  Real Time:                 %u\n",   rtc_rtime[tmr]);
        fprintf (st, "  Virtual Time:              %u\n",   rtc_vtime[tmr]);
        fprintf (st, "  Next Interval:             %s\n",   sim_fmt_numeric ((double)rtc_nxintv[tmr]));
        fprintf (st, "  Base Tick Delay:           %s\n",   sim_fmt_numeric ((double)rtc_based[tmr]));
        fprintf (st, "  Initial Insts Per Tick:    %s\n",   sim_fmt_numeric ((double)rtc_initd[tmr]));
        }
    fprintf (st, "  Current Insts Per Tick:    %s\n",   sim_fmt_numeric ((double)rtc_currd[tmr]));
    fprintf (st, "  Initializations:           %d\n",   rtc_calib_initializations[tmr]);
    fprintf (st, "  Total Ticks:               %s\n", sim_fmt_numeric ((double)(rtc_clock_ticks_tot[tmr]+rtc_clock_ticks[tmr])));
    if (rtc_clock_skew_max[tmr] != 0.0)
        fprintf (st, "  Peak Clock Skew:           %s%s\n", sim_fmt_secs (fabs(rtc_clock_skew_max[tmr])), (rtc_clock_skew_max[tmr] < 0) ? " fast" : " slow");
    if (rtc_calib_ticks_acked[tmr])
        fprintf (st, "  Ticks Acked:               %s\n",   sim_fmt_numeric ((double)rtc_calib_ticks_acked[tmr]));
    if (rtc_calib_ticks_acked_tot[tmr]+rtc_calib_ticks_acked[tmr] != rtc_calib_ticks_acked[tmr])
        fprintf (st, "  Total Ticks Acked:         %s\n",   sim_fmt_numeric ((double)(rtc_calib_ticks_acked_tot[tmr]+rtc_calib_ticks_acked[tmr])));
    if (rtc_calib_tick_time[tmr])
        fprintf (st, "  Tick Time:                 %s\n",   sim_fmt_secs (rtc_calib_tick_time[tmr]));
    if (rtc_calib_tick_time_tot[tmr]+rtc_calib_tick_time[tmr] != rtc_calib_tick_time[tmr])
        fprintf (st, "  Total Tick Time:           %s\n",   sim_fmt_secs (rtc_calib_tick_time_tot[tmr]+rtc_calib_tick_time[tmr]));
    if (rtc_clock_catchup_ticks[tmr])
        fprintf (st, "  Catchup Ticks Sched:       %s\n",   sim_fmt_numeric ((double)rtc_clock_catchup_ticks[tmr]));
    if (rtc_clock_catchup_ticks_tot[tmr]+rtc_clock_catchup_ticks[tmr] != rtc_clock_catchup_ticks[tmr])
        fprintf (st, "  Total Catchup Ticks Sched: %s\n",   sim_fmt_numeric ((double)(rtc_clock_catchup_ticks_tot[tmr]+rtc_clock_catchup_ticks[tmr])));
    if (rtc_clock_init_base_time[tmr]) {
        _double_to_timespec (&now, rtc_clock_init_base_time[tmr]);
        time_t_now = (time_t)now.tv_sec;
        fprintf (st, "  Initialize Base Time:      %8.8s.%03d\n", 11+ctime(&time_t_now), (int)(now.tv_nsec/1000000));
        }
    if (rtc_clock_tick_start_time[tmr]) {
        _double_to_timespec (&now, rtc_clock_tick_start_time[tmr]);
        time_t_now = (time_t)now.tv_sec;
        fprintf (st, "  Tick Start Time:           %8.8s.%03d\n", 11+ctime(&time_t_now), (int)(now.tv_nsec/1000000));
        }
    clock_gettime (CLOCK_REALTIME, &now);
    time_t_now = (time_t)now.tv_sec;
    fprintf (st, "  Wall Clock Time Now:       %8.8s.%03d\n", 11+ctime(&time_t_now), (int)(now.tv_nsec/1000000));
    if (rtc_clock_catchup_eligible[tmr]) {
        _double_to_timespec (&now, rtc_clock_catchup_base_time[tmr]+rtc_calib_tick_time[tmr]);
        time_t_now = (time_t)now.tv_sec;
        fprintf (st, "  Catchup Tick Time:         %8.8s.%03d\n", 11+ctime(&time_t_now), (int)(now.tv_nsec/1000000));
        _double_to_timespec (&now, rtc_clock_catchup_base_time[tmr]);
        time_t_now = (time_t)now.tv_sec;
        fprintf (st, "  Catchup Base Time:         %8.8s.%03d\n", 11+ctime(&time_t_now), (int)(now.tv_nsec/1000000));
        }
    if (rtc_clock_time_idled[tmr])
        fprintf (st, "  Total Time Idled:          %s\n",   sim_fmt_secs (rtc_clock_time_idled[tmr]/1000.0));
    }
if (clocks == 0)
    fprintf (st, "%s clock device is not specified, co-scheduling is unavailable\n", sim_name);
return SCPE_OK;
}

t_stat sim_show_clock_queues (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{

int tmr;

#if defined (SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
















if (sim_asynch_timer) {
    const char *tim;

    if (sim_wallclock_queue == QUEUE_LIST_END)
        fprintf (st, "%s wall clock event queue empty\n", sim_name);
    else {
        fprintf (st, "%s wall clock event queue status\n", sim_name);
        for (uptr = sim_wallclock_queue; uptr != QUEUE_LIST_END; uptr = uptr->a_next) {
            if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                fprintf (st, "  %s", sim_dname (dptr));
                if (dptr->numunits > 1)
                    fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                }
            else
                fprintf (st, "  Unknown");
            tim = sim_fmt_secs(uptr->a_usec_delay/1000000.0);
            fprintf (st, " after %s\n", tim);
            }
        }
    }
#endif /* SIM_ASYNCH_CLOCKS */
for (tmr=0; tmr<=SIM_NTIMERS; ++tmr) {
    if (sim_clock_unit[tmr] == NULL)
        continue;
    if (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
        int32 accum;

        fprintf (st, "%s clock (%s) co-schedule event queue status\n",
                 sim_name, sim_uname(sim_clock_unit[tmr]));
        accum = 0;
        for (uptr = sim_clock_cosched_queue[tmr]; uptr != QUEUE_LIST_END; uptr = uptr->next) {
            if ((dptr = find_dev_from_unit (uptr)) != NULL) {
                fprintf (st, "  %s", sim_dname (dptr));
                if (dptr->numunits > 1)
                    fprintf (st, " unit %d", (int32) (uptr - dptr->units));
                }
            else
                fprintf (st, "  Unknown");
            if (accum == 0)
                fprintf (st, " on next tick");
            else
                fprintf (st, " after %d tick%s", accum, (accum > 1) ? "s" : "");
            fprintf (st, "\n");
            accum = accum + uptr->time;
            }
        }
    }

#if defined (SIM_ASYNCH_IO)
pthread_mutex_unlock (&sim_timer_lock);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}

REG sim_timer_reg[] = {
    { NULL }
    };




REG sim_throttle_reg[] = {

    { DRDATAD (THROT_MS_START,   sim_throt_ms_start,     32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_MS_STOP,    sim_throt_ms_stop,      32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_TYPE,       sim_throt_type,         32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_VAL,        sim_throt_val,          32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_STATE,      sim_throt_state,        32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_SLEEP_TIME, sim_throt_sleep_time,   32, ""), PV_RSPC|REG_RO},
    { DRDATAD (THROT_WAIT,       sim_throt_wait,         32, ""), PV_RSPC|REG_RO},
    { NULL }
    };

/* Clear, Set and show catchup */

/* Set/Clear catchup */

t_stat sim_timer_set_catchup (int32 flag, CONST char *cptr)
{
if (flag) {
    if (!sim_catchup_ticks)
        sim_catchup_ticks = TRUE;
    }
else {
    if (sim_catchup_ticks)
        sim_catchup_ticks = FALSE;

    }
return SCPE_OK;
}

t_stat sim_timer_show_catchup (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
fprintf (st, "Calibrated Ticks%s", sim_catchup_ticks ? " with Catchup Ticks" : "");
return SCPE_OK;
}

/* Set idle calibration threshold */

t_stat sim_timer_set_idle_pct (int32 flag, CONST char *cptr)
{
t_stat r;
int32 newpct;

if (cptr == NULL)
    return SCPE_ARG;
newpct = (int32) get_uint (cptr, 10, 100, &r);
if ((r != SCPE_OK) || (newpct == (int32)(sim_idle_calib_pct)))
    return r;
if (newpct == 0)
    return SCPE_ARG;
sim_idle_calib_pct = (uint32)newpct;
return SCPE_OK;
}

/* Set/Clear asynch */

t_stat sim_timer_set_async (int32 flag, CONST char *cptr)
{
if (flag) {
    if (sim_asynch_enabled && (!sim_asynch_timer)) {
        sim_asynch_timer = TRUE;
        sim_timer_change_asynch ();
        }
    }
else {
    if (sim_asynch_timer) {
        sim_asynch_timer = FALSE;
        sim_timer_change_asynch ();
        }
    }



return SCPE_OK;
}

static CTAB set_timer_tab[] = {
#if defined (SIM_ASYNCH_CLOCKS)
    { "ASYNCH",     &sim_timer_set_async, 1 },
    { "NOASYNCH",   &sim_timer_set_async, 0 },
#endif
    { "CATCHUP",    &sim_timer_set_catchup,  1 },
    { "NOCATCHUP",  &sim_timer_set_catchup,  0 },
    { "CALIB",      &sim_timer_set_idle_pct, 0 },
    { NULL, NULL, 0 }
    };

MTAB sim_timer_mod[] = {
  { 0 },
};

static t_stat sim_timer_clock_reset (DEVICE *dptr);

static const char *sim_timer_description (DEVICE *dptr)
{
return "Internal Timer facilities";
}

static const char *sim_throttle_description (DEVICE *dptr)
{
return "Internal Throttle facility";
}

DEVICE sim_timer_dev = {
    "INT-TMR", sim_timer_units, sim_timer_reg, sim_timer_mod, 
    SIM_NTIMERS+1, 0, 0, 0, 0, 0, 
    NULL, NULL, &sim_timer_clock_reset, NULL, NULL, NULL, 
    NULL, DEV_DEBUG | DEV_NOSAVE, 0, sim_timer_debug};

DEVICE sim_throttle_dev = {
    "INT-THR", &sim_throttle_unit, sim_throttle_reg};


/* SET CLOCK command */

t_stat sim_set_timers (int32 arg, CONST char *cptr)
{
char *cvptr, gbuf[CBUFSIZE];
CTAB *ctptr;
t_stat r;

if ((cptr == NULL) || (*cptr == 0))
    return SCPE_2FARG;
while (*cptr != 0) {                                    /* do all mods */
    cptr = get_glyph_nc (cptr, gbuf, ',');              /* get modifier */
    if ((cvptr = strchr (gbuf, '=')))                   /* = value? */
        *cvptr++ = 0;
    get_glyph (gbuf, gbuf, 0);                          /* modifier to UC */
    if ((ctptr = find_ctab (set_timer_tab, gbuf))) {    /* match? */
        r = ctptr->action (ctptr->arg, cvptr);          /* do the rest */
        if (r != SCPE_OK)
            return r;
        }
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

/* sim_idle - idle simulator until next event or for specified interval

   Inputs:
        tmr =   calibrated timer to use

   Must solve the linear equation

        ms_to_wait = w * ms_per_wait

   Or
        w = ms_to_wait / ms_per_wait
*/

t_bool sim_idle (uint32 tmr, t_bool sin_cyc)
{
uint32 cyc_ms = 0;
uint32 w_ms, w_idle, act_ms;
int32 act_cyc;

if (rtc_clock_catchup_pending[tmr]) {                   /* Catchup clock tick pending? */
    sim_debug (DBG_CAL, &sim_timer_dev, "sim_idle(tmr=%d, sin_cyc=%d) - accelerating pending catch-up tick before idling %s\n", tmr, sin_cyc, sim_uname (sim_clock_unit[tmr]));
    sim_activate_abs (&sim_timer_units[tmr], 0);
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    return FALSE;
    }
if ((!sim_idle_enab)                             ||     /* idling disabled */
    ((sim_clock_queue == QUEUE_LIST_END) &&             /* or clock queue empty? */



     (!sim_asynch_timer))||                             /*     and not asynch? */

    ((sim_clock_queue != QUEUE_LIST_END) &&             /* or clock queue not empty */
     ((sim_clock_queue->flags & UNIT_IDLE) == 0))||     /*   and event not idle-able? */
    (rtc_elapsed[tmr] < sim_idle_stable)) {             /* or timer not stable? */
    sim_debug (DBG_IDL, &sim_timer_dev, "Can't idle: %s - elapsed: %d.%03d\n", !sim_idle_enab ? "idle disabled" : 
                                                                             ((rtc_elapsed[tmr] < sim_idle_stable) ? "not stable" : 
                                                                                                                     ((sim_clock_queue != QUEUE_LIST_END) ? sim_uname (sim_clock_queue) : 
                                                                                                                                                            "")), rtc_elapsed[tmr], rtc_ticks[tmr]);
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    return FALSE;
    }
if (_rtcn_tick_catchup_check(tmr, 0)) {
    sim_debug (DBG_CAL, &sim_timer_dev, "sim_idle(tmr=%d, sin_cyc=%d) - rescheduling catchup tick for %s\n", tmr, sin_cyc, sim_uname (sim_clock_unit[tmr]));
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    return FALSE;
    }
/*
   When a simulator is in an instruction path (or under other conditions 
   which would indicate idling), the countdown of sim_interval will not 
   be happening at a pace which is consistent with the rate it happens 
   when not in the 'idle capable' state.  The consequence of this is that 
   the clock calibration may produce calibrated results which vary much 
   more than they do when not in the idle able state.  Sim_idle also uses 
   the calibrated tick size to approximate an adjustment to sim_interval
   to reflect the number of instructions which would have executed during 
   the actual idle time, so consistent calibrated numbers produce better 
   adjustments. 
   
   To negate this effect, we accumulate the time actually idled here.
   sim_rtcn_calb compares the accumulated idle time during the most recent 
   second and if it exceeds the percentage defined by and sim_idle_calib_pct
   calibration is suppressed. Thus recalibration only happens if things 
   didn't idle too much.

   we also check check sim_idle_enab above so that all simulators can avoid
   directly checking sim_idle_enab before calling sim_idle so that all of 
   the bookkeeping on sim_idle_idled is done here in sim_timer where it 
   means something, while not idling when it isn't enabled.  
   */

sim_debug (DBG_TRC, &sim_timer_dev, "sim_idle(tmr=%d, sin_cyc=%d)\n", tmr, sin_cyc);

cyc_ms = (rtc_currd[tmr] * rtc_hz[tmr]) / 1000;         /* cycles per msec */
if ((sim_idle_rate_ms == 0) || (cyc_ms == 0)) {         /* not possible? */
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    sim_debug (DBG_IDL, &sim_timer_dev, "not possible idle_rate_ms=%d - cyc/ms=%d\n", sim_idle_rate_ms, cyc_ms);
    return FALSE;
    }
w_ms = (uint32) sim_interval / cyc_ms;                  /* ms to wait */
/* When the host system has a clock tick which is less frequent than the    */
/* simulated system's clock, idling will cause delays which will miss       */
/* simulated clock ticks.  To accomodate this, and still allow idling, if   */
/* the simulator acknowledges the processing of clock ticks, then catchup   */
/* ticks can be used to make up for missed ticks. */
if (rtc_clock_catchup_eligible[tmr])
    w_idle = (sim_interval * 1000) / rtc_currd[tmr];    /* 1000 * pending fraction of tick */
else
    w_idle = (w_ms * 1000) / sim_idle_rate_ms;          /* 1000 * intervals to wait */
if (w_idle < 500) {                                     /* shorter than 1/2 the interval? */
    if (sin_cyc)
        sim_interval = sim_interval - 1;
    sim_debug (DBG_IDL, &sim_timer_dev, "no wait\n");
    return FALSE;
    }
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event in %d instructions\n", w_ms, sim_interval);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event on %s in %d instructions\n", w_ms, sim_uname(sim_clock_queue), sim_interval);
act_ms = sim_idle_ms_sleep (w_ms);                      /* wait */
rtc_clock_time_idled[tmr] += act_ms;
act_cyc = act_ms * cyc_ms;
if (act_ms < w_ms)                                      /* awakened early? */
    act_cyc += (cyc_ms * sim_idle_rate_ms) / 2;         /* account for half an interval's worth of cycles */
if (sim_interval > act_cyc)
    sim_interval = sim_interval - act_cyc;              /* count down sim_interval */
else
    sim_interval = 0;                                   /* or fire immediately */
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event in %d instructions\n", act_ms, sim_interval);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event on %s in %d instructions\n", act_ms, sim_uname(sim_clock_queue), sim_interval);
return TRUE;
}

/* Set idling - implicitly disables throttling */

t_stat sim_set_idle (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
t_stat r;
uint32 v;









if (cptr && *cptr) {
    v = (uint32) get_uint (cptr, 10, SIM_IDLE_STMAX, &r);
    if ((r != SCPE_OK) || (v < SIM_IDLE_STMIN))
        return sim_messagef (SCPE_ARG, "Invalid Stability value: %s.  Valid values range from %d to %d.\n", cptr, SIM_IDLE_STMIN, SIM_IDLE_STMAX);
    sim_idle_stable = v;
    }
sim_idle_enab = TRUE;
if (sim_throt_type != SIM_THROT_NONE) {
    sim_set_throt (0, NULL);
    sim_printf ("Throttling disabled\n");
    }
return SCPE_OK;
}

/* Clear idling */

t_stat sim_clr_idle (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
sim_idle_enab = FALSE;
return SCPE_OK;
}

/* Show idling */

t_stat sim_show_idle (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
if (sim_idle_enab)
    fprintf (st, "idle enabled");
else
    fprintf (st, "idle disabled");
if (sim_switches & SWMASK ('D'))
    fprintf (st, ", stability wait = %ds, minimum sleep resolution = %dms", sim_idle_stable, sim_os_sleep_min_ms);
return SCPE_OK;
}

/* Throttling package */

t_stat sim_set_throt (int32 arg, CONST char *cptr)
{
CONST char *tptr;
char c;
t_value val, val2 = 0;

if (arg == 0) {
    if ((cptr != NULL) && (*cptr != 0))
        return sim_messagef (SCPE_ARG, "Unexpected NOTHROTTLE argument: %s\n", cptr);
    sim_throt_type = SIM_THROT_NONE;
    sim_throt_cancel ();
    }
else if (sim_idle_rate_ms == 0) {
    return sim_messagef (SCPE_NOFNC, "Throttling is not available, Minimum OS sleep time is %dms\n", sim_os_sleep_min_ms);

    }
else {
    if (*cptr == '\0')
        return sim_messagef (SCPE_ARG, "Missing throttle mode specification\n");
    val = strtotv (cptr, &tptr, 10);
    if (cptr == tptr)
        return sim_messagef (SCPE_ARG, "Invalid throttle specification: %s\n", cptr);
    sim_throt_sleep_time = sim_idle_rate_ms;
    c = (char)toupper (*tptr++);
    if (c == '/') {
        val2 = strtotv (tptr, &tptr, 10);
        if ((*tptr != '\0') || (val == 0))
            return sim_messagef (SCPE_ARG, "Invalid throttle delay specifier: %s\n", cptr);
        }
    if (c == 'M') 
        sim_throt_type = SIM_THROT_MCYC;
    else if (c == 'K')
        sim_throt_type = SIM_THROT_KCYC;
    else if ((c == '%') && (val > 0) && (val < 100))
        sim_throt_type = SIM_THROT_PCT;
    else if ((c == '/') && (val2 != 0))
        sim_throt_type = SIM_THROT_SPC;

    else return sim_messagef (SCPE_ARG, "Invalid throttle specification: %s\n", cptr);
    if (sim_idle_enab) {
        sim_printf ("Idling disabled\n");
        sim_clr_idle (NULL, 0, NULL, NULL);
        }
    sim_throt_val = (uint32) val;
    if (sim_throt_type == SIM_THROT_SPC) {
        if (val2 >= sim_idle_rate_ms)
            sim_throt_sleep_time = (uint32) val2;
        else {
            if ((sim_idle_rate_ms % val2) == 0) {
                sim_throt_sleep_time = sim_idle_rate_ms;
                sim_throt_val = (uint32) (val * (sim_idle_rate_ms / val2));
                }
            else {
                sim_throt_sleep_time = sim_idle_rate_ms;
                sim_throt_val = (uint32) (val * (1 + (sim_idle_rate_ms / val2)));
                }
            }
        }
    }
sim_register_internal_device (&sim_throttle_dev);
sim_throt_cps = SIM_INITIAL_IPS;    /* Initial value while correct one is determined */
return SCPE_OK;
}

t_stat sim_show_throt (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
if (sim_idle_rate_ms == 0)
    fprintf (st, "Throttling:                    Not Available\n");
else {
    switch (sim_throt_type) {

    case SIM_THROT_MCYC:
        fprintf (st, "Throttle:                      %d megacycles\n", sim_throt_val);
        if (sim_throt_wait)
            fprintf (st, "Throttling by sleeping for:    %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_wait);
        break;

    case SIM_THROT_KCYC:
        fprintf (st, "Throttle:                      %d kilocycles\n", sim_throt_val);
        if (sim_throt_wait)
            fprintf (st, "Throttling by sleeping for:    %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_wait);
        break;

    case SIM_THROT_PCT:
        fprintf (st, "Throttle:                      %d%%\n", sim_throt_val);
        if (sim_throt_wait)
            fprintf (st, "Throttling by sleeping for:    %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_wait);
        break;

    case SIM_THROT_SPC:
        fprintf (st, "Throttle:                      sleep %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_val);
        break;

    default:
        fprintf (st, "Throttling:                    Disabled\n");
        break;
        }


    if (sim_throt_type != SIM_THROT_NONE) {
        if (sim_throt_state != SIM_THROT_STATE_THROTTLE)
            fprintf (st, "Throttle State:                %s - wait: %d\n", (sim_throt_state == SIM_THROT_STATE_INIT) ? "Waiting for Init" : "Timing", sim_throt_wait);
        }
    }


return SCPE_OK;
}

void sim_throt_sched (void)
{
sim_throt_state = SIM_THROT_STATE_INIT;
if (sim_throt_type)
    sim_activate (&sim_throttle_unit, SIM_THROT_WINIT);
}

void sim_throt_cancel (void)
{
sim_cancel (&sim_throttle_unit);
}

/* Throttle service

   Throttle service has three distinct states used while dynamically
   determining a throttling interval:

       SIM_THROT_STATE_INIT     take initial measurement
       SIM_THROT_STATE_TIME     take final measurement, calculate wait values
       SIM_THROT_STATE_THROTTLE periodic waits to slow down the CPU
*/
t_stat sim_throt_svc (UNIT *uptr)
{
int32 tmr;
uint32 delta_ms;
double a_cps, d_cps;

if (sim_throt_type == SIM_THROT_SPC) {                  /* Non dynamic? */
    sim_throt_state = SIM_THROT_STATE_THROTTLE;         /* force state */
    sim_throt_wait = sim_throt_val;
    }
switch (sim_throt_state) {

    case SIM_THROT_STATE_INIT:                          /* take initial reading */
        sim_idle_ms_sleep (sim_idle_rate_ms);           /* start on a tick boundart to calibrate */
        sim_throt_ms_start = sim_os_msec ();
        sim_throt_inst_start = sim_gtime();
        sim_throt_wait = SIM_THROT_WST;
        sim_throt_state = SIM_THROT_STATE_TIME;         /* next state */
        sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Starting.  Values wait = %d\n", sim_throt_wait);
        break;                                          /* reschedule */

    case SIM_THROT_STATE_TIME:                          /* take final reading */
        sim_throt_ms_stop = sim_os_msec ();
        delta_ms = sim_throt_ms_stop - sim_throt_ms_start;
        if (delta_ms < SIM_THROT_MSMIN) {               /* not enough time? */
            if (sim_throt_wait >= 100000000) {          /* too many inst? */
                sim_throt_state = SIM_THROT_STATE_INIT; /* fails in 32b! */
                sim_printf ("Can't throttle.  Host CPU is too fast with a minimum sleep time of %d ms\n", sim_idle_rate_ms);
                sim_set_throt (0, NULL);                /* disable throttling */
                return SCPE_OK;
                }
            sim_idle_ms_sleep (sim_idle_rate_ms);       /* start on a tick boundart to calibrate */
            sim_throt_wait = sim_throt_wait * SIM_THROT_WMUL;
            sim_throt_ms_start = sim_os_msec ();
            sim_throt_inst_start = sim_gtime();
            }
        else {                                          /* long enough */
            a_cps = ((double) sim_throt_wait) * 1000.0 / (double) delta_ms;
            if (sim_throt_type == SIM_THROT_MCYC)       /* calc desired cps */
                d_cps = (double) sim_throt_val * 1000000.0;
            else if (sim_throt_type == SIM_THROT_KCYC)
                d_cps = (double) sim_throt_val * 1000.0;
            else d_cps = (a_cps * ((double) sim_throt_val)) / 100.0;
            if (d_cps >= a_cps) {
                sim_throt_state = SIM_THROT_STATE_INIT;
                sim_printf ("Host CPU is too slow to simulate %s instructions per second\n", sim_fmt_numeric(d_cps));
                sim_printf ("Throttling disabled.\n");
                sim_set_throt (0, NULL);
                return SCPE_OK;
                }
            while (1) {
                sim_throt_wait = (int32)                /* time between waits */
                    ((a_cps * d_cps * ((double) sim_throt_sleep_time)) /
                     (1000.0 * (a_cps - d_cps)));
                if (sim_throt_wait >= SIM_THROT_WMIN)   /* long enough? */
                    break;
                sim_throt_sleep_time += sim_os_sleep_inc_ms;

                sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Wait too small, increasing sleep time to %d ms.  Values a_cps = %f, d_cps = %f, wait = %d\n", 
                                                    sim_throt_sleep_time, a_cps, d_cps, sim_throt_wait);
                }
            sim_throt_ms_start = sim_throt_ms_stop;
            sim_throt_inst_start = sim_gtime();
            sim_throt_state = SIM_THROT_STATE_THROTTLE;
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Throttle values a_cps = %f, d_cps = %f, wait = %d, sleep = %d ms\n", 
                                                a_cps, d_cps, sim_throt_wait, sim_throt_sleep_time);
            sim_throt_cps = d_cps;                  /* save the desired rate */
            /* Run through all timers and adjust the calibration for each */
            /* one that is running to reflect the throttle rate */
            for (tmr=0; tmr<=SIM_NTIMERS; tmr++)
                if (rtc_hz[tmr]) {                                      /* running? */
                    rtc_gtime[tmr] = sim_gtime();                       /* save instruction time */
                    rtc_currd[tmr] = (int32)(sim_throt_cps / rtc_hz[tmr]);/* use throttle calibration */
                    }
            }
        break;

    case SIM_THROT_STATE_THROTTLE:                      /* throttling */
        sim_idle_ms_sleep (sim_throt_sleep_time);
        delta_ms = sim_os_msec () - sim_throt_ms_start;
        if (sim_throt_type != SIM_THROT_SPC) {          /* when not dynamic throttling */
            if (delta_ms >= 10000) {                    /* recompute every 10 sec */
                double delta_insts = sim_gtime() - sim_throt_inst_start;
                a_cps = (delta_insts * 1000.0) / (double) delta_ms;
                if (sim_throt_type == SIM_THROT_MCYC)   /* calc desired cps */
                    d_cps = (double) sim_throt_val * 1000000.0;
                else if (sim_throt_type == SIM_THROT_KCYC)
                    d_cps = (double) sim_throt_val * 1000.0;
                else d_cps = (a_cps * ((double) sim_throt_val)) / 100.0;
                if (fabs(100.0 * (d_cps - a_cps) / a_cps) > (double)SIM_THROT_DRIFT_PCT) {
                    sim_throt_wait = sim_throt_val;
                    sim_throt_state = SIM_THROT_STATE_TIME;/* next state to recalibrate */
                    sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Recalibrating throttle based on values a_cps = %f, d_cps = %f\n", 
                                                        a_cps, d_cps);
                    }
                sim_throt_ms_start = sim_os_msec ();
                sim_throt_inst_start = sim_gtime();
                }
            }
        else                                            /* record instruction rate */
            sim_throt_cps = (int32)((1000.0 * sim_throt_val) / (double)delta_ms);
        break;
        }

sim_activate (uptr, sim_throt_wait);                    /* reschedule */
return SCPE_OK;
}

/* Clock assist activites */
t_stat sim_timer_tick_svc (UNIT *uptr)
{
int tmr = (int)(uptr-sim_timer_units);
t_stat stat;

rtc_clock_ticks[tmr] += 1;
rtc_calib_tick_time[tmr] += rtc_clock_tick_size[tmr];
/*
 * Some devices may depend on executing during the same instruction or 
 * immediately after the clock tick event.  To satisfy this, we directly 
 * run the clock event here and if it completes successfully, schedule any
 * currently coschedule units to run now.  Ticks should never return a 
 * non-success status, while co-schedule activities might, so they are 
 * queued to run from sim_process_event
 */
sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_tick_svc - scheduling %s - cosched interval: %d\n", sim_uname (sim_clock_unit[tmr]), sim_cosched_interval[tmr]);
if (sim_clock_unit[tmr]->action == NULL)
    return SCPE_IERR;
stat = sim_clock_unit[tmr]->action (sim_clock_unit[tmr]);
--sim_cosched_interval[tmr];                    /* Countdown ticks */
if (stat == SCPE_OK) {
    if (rtc_clock_catchup_eligible[tmr]) {      /* calibration started? */
        struct timespec now;
        double skew;

        clock_gettime(CLOCK_REALTIME, &now);
        skew = (_timespec_to_double(&now) - (rtc_calib_tick_time[tmr]+rtc_clock_catchup_base_time[tmr]));

        if (fabs(skew) > fabs(rtc_clock_skew_max[tmr]))
            rtc_clock_skew_max[tmr] = skew;
        }
    while ((sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) &&
           (sim_cosched_interval[tmr] <= 0)) {
        UNIT *cptr = sim_clock_cosched_queue[tmr];
        sim_clock_cosched_queue[tmr] = cptr->next;
        cptr->next = NULL;
        cptr->cancel = NULL;
        cptr->time = 0;
        if (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END)
            sim_cosched_interval[tmr] = sim_clock_cosched_queue[tmr]->time;
        else
            sim_cosched_interval[tmr]  = 0;
        sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_tick_svc(tmr=%d) - coactivating %s - cosched interval: %d\n", tmr, sim_uname (cptr), sim_cosched_interval[tmr]);
        _sim_activate (cptr, 0);
        }
    if (sim_clock_cosched_queue[tmr] == QUEUE_LIST_END)
        sim_cosched_interval[tmr] = 0;
    }
if (rtc_hz[tmr])                                        /* Still running? */
    sim_timer_activate_after (uptr, 1000000/rtc_hz[tmr]);
return stat;
}

void sim_rtcn_get_time (struct timespec *now, int tmr)
{
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_get_time(tmr=%d)\n", tmr);
clock_gettime (CLOCK_REALTIME, now);
}

/* 
 * If the host system has a relatively large clock tick (as compared to
 * the desired simulated hz) ticks will naturally be scheduled late and
 * these delays will accumulate.  The net result will be unreasonably
 * slow ticks being delivered to the simulated system.
 * Additionally, when a simulator is idling and/or throttling, it will
 * deliberately call sim_os_ms_sleep and those sleep operations will be
 * variable and subject to the host system's minimum sleep resolution
 * which can exceed the desired sleep interval and add to the concept
 * of slow tick delivery to the simulated system.
 * We accomodate these problems and make up for lost ticks by injecting
 * catch-up ticks to the simulator.
 *
 * When necessary, catch-up ticks are scheduled to run under one 
 * of two conditions:
 *   1) after indicated number of instructions in a call by the simulator
 *      to sim_rtcn_tick_ack.  sim_rtcn_tick_ack exists to provide a 
 *      mechanism to inform the simh timer facilities when the simulated 
 *      system has accepted the most recent clock tick interrupt.
 *   2) immediately when the simulator calls sim_idle
 *
 * catchup ticks are only scheduled (eligible to happen) under these 
 * conditions after at least one tick has been acknowledged.
 */

/* _rtcn_tick_catchup_check - idle simulator until next event or for specified interval

   Inputs:
        tmr =   calibrated timer to check/schedule
        time =  instruction delay for next tick

   Returns TRUE if a catchup tick has been scheduled
*/

static t_bool _rtcn_tick_catchup_check (int32 tmr, int32 time)
{
double tnow;

if ((!sim_catchup_ticks) || 
    ((tmr < 0) || (tmr >= SIM_NTIMERS)))
    return FALSE;
tnow = sim_timenow_double();
if ((rtc_hz[tmr] > sim_os_tick_hz) &&           /* faster than host tick */
    (!rtc_clock_catchup_eligible[tmr]) &&       /* not eligible yet? */
    (time != -1)) {                             /* called from ack? */
    rtc_clock_catchup_base_time[tmr] = tnow;
    rtc_clock_ticks_tot[tmr] += rtc_clock_ticks[tmr];
    rtc_clock_ticks[tmr] = 0;
    rtc_calib_tick_time_tot[tmr] += rtc_calib_tick_time[tmr];
    rtc_calib_tick_time[tmr] = 0.0;
    rtc_clock_catchup_ticks_tot[tmr] += rtc_clock_catchup_ticks[tmr];
    rtc_clock_catchup_ticks[tmr] = 0;
    rtc_calib_ticks_acked_tot[tmr] += rtc_calib_ticks_acked[tmr];
    rtc_calib_ticks_acked[tmr] = 0;
    rtc_clock_catchup_eligible[tmr] = TRUE;
    sim_debug (DBG_QUE, &sim_timer_dev, "_rtcn_tick_catchup_check() - Enabling catchup ticks for %s\n", sim_uname (sim_clock_unit[tmr]));
    return TRUE;
    }
if (rtc_clock_catchup_eligible[tmr] &&
    (tnow > (rtc_clock_catchup_base_time[tmr] + (rtc_calib_tick_time[tmr] + rtc_clock_tick_size[tmr])))) {
    sim_debug (DBG_QUE, &sim_timer_dev, "_rtcn_tick_catchup_check(%d) - scheduling catchup tick for %s which is behind %s\n", time, sim_uname (sim_clock_unit[tmr]), sim_fmt_secs (tnow > (rtc_clock_catchup_base_time[tmr] + (rtc_calib_tick_time[tmr] + rtc_clock_tick_size[tmr]))));
    rtc_clock_catchup_pending[tmr] = TRUE;
    sim_activate_abs (&sim_timer_units[tmr], (time < 0) ? 0 : time);
    return TRUE;
    }
return FALSE;
}

t_stat sim_rtcn_tick_ack (uint32 time, int32 tmr)
{
if ((tmr < 0) || (tmr >= SIM_NTIMERS))
    return SCPE_TIMER;
sim_debug (DBG_ACK, &sim_timer_dev, "sim_rtcn_tick_ack - for %s\n", sim_uname (sim_clock_unit[tmr]));
_rtcn_tick_catchup_check (tmr, (int32)time);
++rtc_calib_ticks_acked[tmr];
return SCPE_OK;
}


static double _timespec_to_double (struct timespec *time)
{
return ((double)time->tv_sec)+(double)(time->tv_nsec)/1000000000.0;
}

static void _double_to_timespec (struct timespec *time, double dtime)
{
time->tv_sec = (time_t)floor(dtime);
time->tv_nsec = (long)((dtime-floor(dtime))*1000000000.0);
}

double sim_timenow_double (void)
{
struct timespec now;

clock_gettime (CLOCK_REALTIME, &now);
return _timespec_to_double (&now);
}

#if defined(SIM_ASYNCH_CLOCKS)


pthread_t           sim_timer_thread;           /* Wall Clock Timing Thread Id */
pthread_cond_t      sim_timer_startup_cond;
t_bool              sim_timer_thread_running = FALSE;


static void *
_timer_thread(void *arg)
{
int sched_policy;
struct sched_param sched_priority;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - starting\n");

pthread_mutex_lock (&sim_timer_lock);
pthread_cond_signal (&sim_timer_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_timer && sim_is_running) {
    struct timespec start_time, stop_time;
    struct timespec due_time;
    double wait_usec;
    int32 inst_delay;
    double inst_per_sec;
    UNIT *uptr, *cptr, *prvptr;

    if (sim_wallclock_entry) {                          /* something to insert in queue? */


        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - timing %s for %s\n", 
                   sim_uname(sim_wallclock_entry), sim_fmt_secs (sim_wallclock_entry->time/1000000.0));

        uptr = sim_wallclock_entry;
        sim_wallclock_entry = NULL;

        prvptr = NULL;
        for (cptr = sim_wallclock_queue; cptr != QUEUE_LIST_END; cptr = cptr->a_next) {
            if (uptr->a_due_time < cptr->a_due_time)
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357



















































































































1358
1359


1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396






























1397
1398
1399
1400
1401
1402
1403
1404


















1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452






1453
1454
1455
1456
1457
1458






1459
1460
1461
1462














1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513



1514
1515
1516
1517
1518
1519
1520

1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532


1533
1534
1535
1536
1537
1538
1539
1540















1541



1542




1543























1544
1545
1546
1547



1548
1549
1550









1551
1552












1553
1554
1555


1556
1557
1558
1559
1560
1561




1562




1563
1564
1565











1566

1567




















1568

1569



1570

















1571


1572












1573






1574



1575

1576



1577




1578
1579

1580
1581



























1582
1583




1584

1585
1586

1587

1588





















































    wait_usec = floor(1000000.0*(_timespec_to_double (&due_time) - _timespec_to_double (&start_time)));
    if (sim_wallclock_queue == QUEUE_LIST_END)
        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - waiting forever\n");
    else
        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - waiting for %.0f usecs until %.6f for %s\n", wait_usec, sim_wallclock_queue->a_due_time, sim_uname(sim_wallclock_queue));
    if ((wait_usec <= 0.0) || 
        (0 != pthread_cond_timedwait (&sim_timer_wake, &sim_timer_lock, &due_time))) {
        int tmr;

        if (sim_wallclock_queue == QUEUE_LIST_END)      /* queue empty? */
            continue;                                   /* wait again */
        inst_per_sec = sim_timer_inst_per_sec ();

        uptr = sim_wallclock_queue;
        sim_wallclock_queue = uptr->a_next;
        uptr->a_next = NULL;                            /* hygiene */

        clock_gettime(CLOCK_REALTIME, &stop_time);
        if (1 != sim_timespec_compare (&due_time, &stop_time)) {
            inst_delay = 0;
            uptr->a_last_fired_time = _timespec_to_double(&stop_time);
            }
        else {
            inst_delay = (int32)(inst_per_sec*(_timespec_to_double(&due_time)-_timespec_to_double(&stop_time)));
            uptr->a_last_fired_time = uptr->a_due_time;
            }
        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - slept %.0fms - activating(%s,%d)\n", 
                   1000.0*(_timespec_to_double (&stop_time)-_timespec_to_double (&start_time)), sim_uname(uptr), inst_delay);
        for (tmr=0; tmr<SIM_NTIMERS; tmr++)
            if (sim_clock_unit[tmr] == uptr)
                break;
        if (tmr != SIM_NTIMERS) {
            /*
             * Some devices may depend on executing during the same instruction or immediately 
             * after the clock tick event.  To satisfy this, we link the clock unit to the head
             * of the clock coschedule queue and then insert that list in the asynch event 
             * queue in a single operation
             */
            uptr->a_next = sim_clock_cosched_queue[tmr];
            sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;
            AIO_ACTIVATE_LIST(sim_activate, uptr, inst_delay);
            }
        else
            sim_activate (uptr, inst_delay);
        }
    else {/* Something wants to adjust the queue since the wait condition was signaled */
        if (sim_timer_event_canceled)
            sim_timer_event_canceled = FALSE;           /* reset flag and continue */
        }
    }
pthread_mutex_unlock (&sim_timer_lock);

sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - exiting\n");

return NULL;
}

#endif /* defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS) */




















































































































void sim_start_timer_services (void)
{


#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_asynch_enabled && sim_asynch_timer) {
    pthread_attr_t attr;
    UNIT *cptr;
    double delta_due_time = 0;

    /* when restarting after being manually stopped the due times for all */
    /* timer events needs to slide so they fire in the future. (clock ticks */
    /* don't accumulate when the simulator is stopped) */
    for (cptr = sim_wallclock_queue; cptr != QUEUE_LIST_END; cptr = cptr->a_next) {
        if (cptr == sim_wallclock_queue) { /* Handle first entry */
            struct timespec now;
            double due_time;

            clock_gettime(CLOCK_REALTIME, &now);
            due_time = _timespec_to_double(&now) + ((double)(cptr->a_usec_delay)/1000000.0);
            delta_due_time = due_time - cptr->a_due_time;
            }
        cptr->a_due_time += delta_due_time;
        }
    sim_debug (DBG_TRC, &sim_timer_dev, "sim_start_timer_services() - starting\n");
    pthread_cond_init (&sim_timer_startup_cond, NULL);
    pthread_attr_init (&attr);
    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
    pthread_create (&sim_timer_thread, &attr, _timer_thread, NULL);
    pthread_attr_destroy( &attr);
    pthread_cond_wait (&sim_timer_startup_cond, &sim_timer_lock); /* Wait for thread to stabilize */
    pthread_cond_destroy (&sim_timer_startup_cond);
    sim_timer_thread_running = TRUE;
    }
pthread_mutex_unlock (&sim_timer_lock);
#endif
}

void sim_stop_timer_services (void)
{






























#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_timer_thread_running) {
    sim_debug (DBG_TRC, &sim_timer_dev, "sim_stop_timer_services() - stopping\n");
    pthread_cond_signal (&sim_timer_wake);
    pthread_mutex_unlock (&sim_timer_lock);
    pthread_join (sim_timer_thread, NULL);
    sim_timer_thread_running = FALSE;


















    }
else
    pthread_mutex_unlock (&sim_timer_lock);
#endif
}

t_stat sim_timer_change_asynch (void)
{
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
if (sim_asynch_enabled && sim_asynch_timer)
    sim_start_timer_services ();
else {
    UNIT *uptr;
    int32 accum = 0;

    sim_stop_timer_services ();
    while (1) {
        uptr = sim_wallclock_queue;
        if (uptr == QUEUE_LIST_END)
            break;
        sim_wallclock_queue = uptr->a_next;
        accum += uptr->time;
        uptr->a_next = NULL;
        uptr->a_due_time = 0;
        uptr->a_usec_delay = 0;
        sim_activate_after (uptr, accum);
        }
    }
#endif
return SCPE_OK;
}

/* Instruction Execution rate. */
/*  returns a double since it is mostly used in double expressions and
    to avoid overflow if/when strange timing delays might produce unexpected results */

double sim_timer_inst_per_sec (void)
{
double inst_per_sec = SIM_INITIAL_IPS;

if (sim_calb_tmr == -1)
    return inst_per_sec;
inst_per_sec = ((double)rtc_currd[sim_calb_tmr])*rtc_hz[sim_calb_tmr];
if (0 == inst_per_sec)
    inst_per_sec = SIM_INITIAL_IPS;
return inst_per_sec;
}







t_stat sim_timer_activate_after (UNIT *uptr, int32 usec_delay)
{
int32 inst_delay;
double inst_per_sec;

AIO_VALIDATE;






if (sim_is_active (uptr))                               /* already active? */
    return SCPE_OK;
inst_per_sec = sim_timer_inst_per_sec ();
inst_delay = (int32)((inst_per_sec*usec_delay)/1000000.0);














#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
if ((sim_calb_tmr == -1) ||                             /* if No timer initialized */
    (inst_delay < rtc_currd[sim_calb_tmr]) ||           /*    or sooner than next clock tick? */
    (rtc_elapsed[sim_calb_tmr] < sim_idle_stable) ||    /*    or not idle stable yet */
    (!(sim_asynch_enabled && sim_asynch_timer))) {      /*    or asynch disabled */
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - activating %s after %d instructions\n", 
               sim_uname(uptr), inst_delay);
    return _sim_activate (uptr, inst_delay);            /* queue it now */
    }
if (1) {
    struct timespec now;
    double d_now;

    clock_gettime (CLOCK_REALTIME, &now);
    d_now = _timespec_to_double (&now);
    /* Determine if this is a clock tick like invocation 
       or an ocaisional measured device delay */
    if ((uptr->a_usec_delay == usec_delay) &&
        (uptr->a_due_time != 0.0)          &&
        (1)) {
        double d_delay = ((double)usec_delay)/1000000.0;

        uptr->a_due_time += d_delay;
        if (uptr->a_due_time < (d_now + d_delay*0.1)) { /* Accumulate lost time */
            uptr->a_skew += (d_now + d_delay*0.1) - uptr->a_due_time;
            uptr->a_due_time = d_now + d_delay/10.0;
            if (uptr->a_skew > 30.0) { /* Gap too big? */
                uptr->a_usec_delay = usec_delay;
                uptr->a_skew = uptr->a_last_fired_time = 0.0;
                uptr->a_due_time = d_now + (double)(usec_delay)/1000000.0;
                }
            if (uptr->a_skew > rtc_clock_skew_max[sim_calb_tmr])
                rtc_clock_skew_max[sim_calb_tmr] = uptr->a_skew;
            }
        else {
            if (uptr->a_skew > 0.0) { /* Lost time to make up? */
                if (uptr->a_skew > d_delay*0.9) {
                    uptr->a_skew -= d_delay*0.9;
                    uptr->a_due_time -= d_delay*0.9;
                    }
                else {
                    uptr->a_due_time -= uptr->a_skew;
                    uptr->a_skew = 0.0;
                    }
                }
            }
        }
    else {
        uptr->a_usec_delay = usec_delay;
        uptr->a_skew = uptr->a_last_fired_time = 0.0;
        uptr->a_due_time = d_now + (double)(usec_delay)/1000000.0;



        }
    uptr->time = usec_delay;

    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - queue addition %s at %.6f\n", 
               sim_uname(uptr), uptr->a_due_time);
    }
pthread_mutex_lock (&sim_timer_lock);

while (sim_wallclock_entry) {
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - queue insert entry %s busy waiting for 1ms\n", 
               sim_uname(sim_wallclock_entry));
    pthread_mutex_unlock (&sim_timer_lock);
    sim_os_ms_sleep (1);
    pthread_mutex_lock (&sim_timer_lock);
    }
sim_wallclock_entry = uptr;
pthread_mutex_unlock (&sim_timer_lock);
pthread_cond_signal (&sim_timer_wake);                  /* wake the timer thread to deal with it */
return SCPE_OK;
#else


return _sim_activate (uptr, inst_delay);                /* queue it now */
#endif
}

/* Clock coscheduling routines */

t_stat sim_register_clock_unit (UNIT *uptr)
{















sim_clock_unit[0] = uptr;



sim_clock_cosched_queue[0] = QUEUE_LIST_END;




return SCPE_OK;























}

t_stat sim_clock_coschedule (UNIT *uptr, int32 interval)
{



return sim_clock_coschedule_tmr (uptr, 0, interval);
}










t_stat sim_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 interval)
{












if (NULL == sim_clock_unit[tmr])
    return sim_activate (uptr, interval);
else


    if (sim_asynch_enabled && sim_asynch_timer) {
        if (!sim_is_active (uptr)) {               /* already active? */
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_CLOCKS)
            if ((sim_calb_tmr != -1) &&
                (rtc_elapsed[sim_calb_tmr ] >= sim_idle_stable))  {
                sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule() - queueing %s for clock co-schedule\n", sim_uname (uptr));




                pthread_mutex_lock (&sim_timer_lock);




                uptr->a_next = sim_clock_cosched_queue[tmr];
                sim_clock_cosched_queue[tmr] = uptr;
                pthread_mutex_unlock (&sim_timer_lock);











                return SCPE_OK;

                }




















            else {

#else



            if (1) {

















#endif


                int32 t;



















                t = sim_activate_time (sim_clock_unit[tmr]);



                return sim_activate (uptr, t? t - 1: interval);

                }



            }




        sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule() - %s is already active\n", sim_uname (uptr));
        return SCPE_OK;

        }
    else {



























        int32 t;





        t = sim_activate_time (sim_clock_unit[tmr]);

        return sim_activate (uptr, t? t - 1: interval);
        }

}






























































<










|

<
<
|

<
<


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|


<
<









|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
|

|

<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|


|
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
















|



>
>
>
>
>
>
|

|
|


>
>
>
>
>
>



|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|


|
|





<
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
|
|
>
>
>

<

|



>
|











>
>






|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>
>
>
|


>
>
>
>
>
>
>
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>

|
|
>
>
|
<
<
<
<
|
>
>
>
>
|
>
>
>
>
|
|
<
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
>
>
>
|
>
|
>
>
>
|
>
>
>
>
|
<
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

>
>
>
>
|
>
|
|
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1974
1975
1976
1977
1978
1979
1980

1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992


1993
1994


1995
1996















1997
1998
1999


2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133


2134














2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218



2219












2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285

2286
2287














2288

2289








2290









2291
2292
2293
2294
2295
2296
2297

2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412




2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424

2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521

2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
    wait_usec = floor(1000000.0*(_timespec_to_double (&due_time) - _timespec_to_double (&start_time)));
    if (sim_wallclock_queue == QUEUE_LIST_END)
        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - waiting forever\n");
    else
        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - waiting for %.0f usecs until %.6f for %s\n", wait_usec, sim_wallclock_queue->a_due_time, sim_uname(sim_wallclock_queue));
    if ((wait_usec <= 0.0) || 
        (0 != pthread_cond_timedwait (&sim_timer_wake, &sim_timer_lock, &due_time))) {


        if (sim_wallclock_queue == QUEUE_LIST_END)      /* queue empty? */
            continue;                                   /* wait again */
        inst_per_sec = sim_timer_inst_per_sec ();

        uptr = sim_wallclock_queue;
        sim_wallclock_queue = uptr->a_next;
        uptr->a_next = NULL;                            /* hygiene */

        clock_gettime(CLOCK_REALTIME, &stop_time);
        if (1 != sim_timespec_compare (&due_time, &stop_time))
            inst_delay = 0;


        else
            inst_delay = (int32)(inst_per_sec*(_timespec_to_double(&due_time)-_timespec_to_double(&stop_time)));


        sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - slept %.0fms - activating(%s,%d)\n", 
                   1000.0*(_timespec_to_double (&stop_time)-_timespec_to_double (&start_time)), sim_uname(uptr), inst_delay);















        sim_activate (uptr, inst_delay);
        }
    else {/* Something wants to adjust the queue since the wait condition was signaled */


        }
    }
pthread_mutex_unlock (&sim_timer_lock);

sim_debug (DBG_TIM, &sim_timer_dev, "_timer_thread() - exiting\n");

return NULL;
}

#endif /* defined(SIM_ASYNCH_CLOCKS) */

/*
   In the event that there are no active clock devices, no instruction 
   rate calibration will be performed.  This is more likely on simpler
   simulators which don't have a full spectrum of standard devices or 
   possibly when a clock device exists but its use is optional.

   Additonally, when a host system has a natural clock tick (or minimal 
   sleep time) which is greater than the tick size that a simulator 
   wants to run a clock at, we run this clock at the rate implied by
   the host system's minimal sleep time or 50Hz.
   
   To solve this we merely run an internal clock at 10Hz.
 */

#define CLK_TPS 10
#define CLK_INIT (SIM_INITIAL_IPS/CLK_TPS)
static int32 sim_int_clk_tps;

static t_stat sim_timer_clock_tick_svc (UNIT *uptr)
{
sim_rtcn_calb (sim_int_clk_tps, SIM_INTERNAL_CLK);
sim_activate_after (uptr, 1000000/sim_int_clk_tps);     /* reactivate unit */
return SCPE_OK;
}

/* 
  This routine exists to assure that there is a single reliably calibrated 
  clock properly counting instruction execution relative to time.  The best 
  way to assure reliable calibration is to use a clock which ticks no 
  faster than the host system's clock.  This is optimal so that accurate 
  time measurements are taken.  If the simulated system doesn't have a 
  clock with an appropriate tick rate, an internal clock is run that meets 
  this requirement, 
 */
static void _rtcn_configure_calibrated_clock (int32 newtmr)
{
int32 tmr;

/* Look for a timer running slower than the host system clock */
sim_int_clk_tps = MIN(CLK_TPS, sim_os_tick_hz);
for (tmr=0; tmr<SIM_NTIMERS; tmr++) {
    if ((rtc_hz[tmr]) &&
        (rtc_hz[tmr] <= (uint32)sim_os_tick_hz))
        break;
    }
if (tmr == SIM_NTIMERS) {                   /* None found? */
    if ((tmr != newtmr) && (!sim_is_active (&SIM_INTERNAL_UNIT))) {
        if ((sim_calb_tmr != SIM_NTIMERS) &&/* non internal timer */
            (sim_calb_tmr != -1) &&         /* previously active? */
            (!rtc_hz[sim_calb_tmr])) {      /* now stopped? */
            sim_debug (DBG_CAL, &sim_timer_dev, "_rtcn_configure_calibrated_clock() - Cleaning up stopped timer %s support\n", sim_uname(sim_clock_unit[sim_calb_tmr]));
            if (sim_clock_unit[sim_calb_tmr])
                sim_cancel (sim_clock_unit[sim_calb_tmr]);
            sim_cancel (&sim_timer_units[sim_calb_tmr]);
            /* Migrate any coscheduled devices to the standard queue */
            /* they will fire and subsequently requeue themselves */
            while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
                UNIT *uptr = sim_clock_cosched_queue[tmr];

                _sim_coschedule_cancel (uptr);
                _sim_activate (uptr, 1);
                }
            }
        /* Start the internal timer */
        sim_calb_tmr = SIM_NTIMERS;
        sim_debug (DBG_CAL, &sim_timer_dev, "_rtcn_configure_calibrated_clock() - Starting Internal Calibrated Timer at %dHz\n", sim_int_clk_tps);
        SIM_INTERNAL_UNIT.action = &sim_timer_clock_tick_svc;
        SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
        sim_activate_abs (&SIM_INTERNAL_UNIT, 0);
        sim_rtcn_init_unit (&SIM_INTERNAL_UNIT, (CLK_INIT*CLK_TPS)/sim_int_clk_tps, SIM_INTERNAL_CLK);
        }
    return;
    }
if ((tmr == newtmr) && 
    (sim_calb_tmr == newtmr))               /* already set? */
    return;
if (sim_calb_tmr == SIM_NTIMERS) {      /* was old the internal timer? */
    sim_debug (DBG_CAL, &sim_timer_dev, "_rtcn_configure_calibrated_clock() - Stopping Internal Calibrated Timer, New Timer = %d (%dHz)\n", tmr, rtc_hz[tmr]);
    rtc_initd[SIM_NTIMERS] = 0;
    rtc_hz[SIM_NTIMERS] = 0;
    sim_cancel (&SIM_INTERNAL_UNIT);
    sim_cancel (&sim_timer_units[SIM_NTIMERS]);
    sim_register_clock_unit_tmr (NULL, SIM_INTERNAL_CLK);
    }
else {
    if ((sim_calb_tmr != -1) &&
        (rtc_hz[sim_calb_tmr] == 0)) {
        /* Migrate any coscheduled devices to the standard queue */
        /* they will fire and subsequently requeue themselves */
        while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
            UNIT *uptr = sim_clock_cosched_queue[tmr];

            _sim_coschedule_cancel (uptr);
            _sim_activate (uptr, 1);
            }
        }
    sim_debug (DBG_CAL, &sim_timer_dev, "_rtcn_configure_calibrated_clock() - Changing Calibrated Timer from %d (%dHz) to %d (%dHz)\n", sim_calb_tmr, rtc_hz[sim_calb_tmr], tmr, rtc_hz[tmr]);
    sim_calb_tmr = tmr;
    }
sim_calb_tmr = tmr;
}

static t_stat sim_timer_clock_reset (DEVICE *dptr)
{
sim_debug (DBG_TRC, &sim_timer_dev, "sim_timer_clock_reset()\n");
_rtcn_configure_calibrated_clock (sim_calb_tmr);
sim_timer_dev.description = &sim_timer_description;
sim_throttle_dev.description = &sim_throttle_description;
if (sim_switches & SWMASK ('P')) {
    sim_cancel (&SIM_INTERNAL_UNIT);
    sim_calb_tmr = -1;
    }
return SCPE_OK;
}

void sim_start_timer_services (void)
{
sim_debug (DBG_TRC, &sim_timer_dev, "sim_start_timer_services()\n");
_rtcn_configure_calibrated_clock (sim_calb_tmr);
#if defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_asynch_timer) {
    pthread_attr_t attr;

















    sim_debug (DBG_TRC, &sim_timer_dev, "sim_start_timer_services() - starting\n");
    pthread_cond_init (&sim_timer_startup_cond, NULL);
    pthread_attr_init (&attr);
    pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
    pthread_create (&sim_timer_thread, &attr, _timer_thread, NULL);
    pthread_attr_destroy( &attr);
    pthread_cond_wait (&sim_timer_startup_cond, &sim_timer_lock); /* Wait for thread to stabilize */
    pthread_cond_destroy (&sim_timer_startup_cond);
    sim_timer_thread_running = TRUE;
    }
pthread_mutex_unlock (&sim_timer_lock);
#endif
}

void sim_stop_timer_services (void)
{
int tmr;

sim_debug (DBG_TRC, &sim_timer_dev, "sim_stop_timer_services()\n");

for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    int32 accum;

    if (sim_clock_unit[tmr]) {
        /* Stop clock assist unit and make sure the clock unit has a tick queued */
        sim_cancel (&sim_timer_units[tmr]);
        if (rtc_hz[tmr])
            _sim_activate (sim_clock_unit[tmr], rtc_currd[tmr]);
        /* Move coscheduled units to the standard event queue */
        accum = 1;
        while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
            UNIT *cptr = sim_clock_cosched_queue[tmr];

            sim_clock_cosched_queue[tmr] = cptr->next;
            cptr->next = NULL;
            cptr->cancel = NULL;
            accum += cptr->time;
            _sim_activate (cptr, accum*rtc_currd[tmr]);
            }
        }
    }
sim_cancel (&SIM_INTERNAL_UNIT);                    /* Make sure Internal Timer is stopped */
sim_cancel (&sim_timer_units[SIM_NTIMERS]);
sim_calb_tmr_last = sim_calb_tmr;                   /* Save calibrated timer value for display */
sim_inst_per_sec_last = sim_timer_inst_per_sec ();  /* Save execution rate for display */
sim_calb_tmr = -1;
#if defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_timer_thread_running) {
    sim_debug (DBG_TRC, &sim_timer_dev, "sim_stop_timer_services() - stopping\n");
    pthread_cond_signal (&sim_timer_wake);
    pthread_mutex_unlock (&sim_timer_lock);
    pthread_join (sim_timer_thread, NULL);
    sim_timer_thread_running = FALSE;
    /* Any wallclock queued events are now migrated to the normal event queue */
    while (sim_wallclock_queue != QUEUE_LIST_END) {
        UNIT *uptr = sim_wallclock_queue;
        double inst_delay_d = uptr->a_due_gtime - sim_gtime ();
        int32 inst_delay;

        uptr->cancel (uptr);
        if (inst_delay_d < 0.0)
            inst_delay_d = 0.0;
        /* Bound delay to avoid overflow.  */
        /* Long delays are usually canceled before they expire */
        if (inst_delay_d > (double)0x7FFFFFFF)
            inst_delay_d = (double)0x7FFFFFFF;
        inst_delay = (int32)inst_delay_d;
        if ((inst_delay == 0) && (inst_delay_d != 0.0))
            inst_delay = 1;     /* Minimum non-zero delay is 1 instruction */
        _sim_activate (uptr, inst_delay);            /* queue it now */
        }
    }
else
    pthread_mutex_unlock (&sim_timer_lock);
#endif
}

t_stat sim_timer_change_asynch (void)
{
#if defined(SIM_ASYNCH_CLOCKS)
if (sim_asynch_enabled && sim_asynch_timer)
    sim_start_timer_services ();
else



    sim_stop_timer_services ();












#endif
return SCPE_OK;
}

/* Instruction Execution rate. */
/*  returns a double since it is mostly used in double expressions and
    to avoid overflow if/when strange timing delays might produce unexpected results */

double sim_timer_inst_per_sec (void)
{
double inst_per_sec = SIM_INITIAL_IPS;

if (sim_calb_tmr == -1)
    return inst_per_sec;
inst_per_sec = ((double)rtc_currd[sim_calb_tmr])*rtc_hz[sim_calb_tmr];
if (0 == inst_per_sec)
    inst_per_sec = ((double)rtc_currd[sim_calb_tmr])*sim_int_clk_tps;
return inst_per_sec;
}

t_stat sim_timer_activate (UNIT *uptr, int32 interval)
{
AIO_VALIDATE;
return sim_timer_activate_after (uptr, (uint32)((interval * 1000000.0) / sim_timer_inst_per_sec ()));
}

t_stat sim_timer_activate_after (UNIT *uptr, uint32 usec_delay)
{
int inst_delay, tmr;
double inst_delay_d, inst_per_sec;

AIO_VALIDATE;
/* If this is a clock unit, we need to schedule the related timer unit instead */
for (tmr=0; tmr<=SIM_NTIMERS; tmr++)
    if (sim_clock_unit[tmr] == uptr) {
        uptr = &sim_timer_units[tmr];
        break;
        }
if (sim_is_active (uptr))                               /* already active? */
    return SCPE_OK;
inst_per_sec = sim_timer_inst_per_sec ();
inst_delay_d = ((inst_per_sec*usec_delay)/1000000.0);
/* Bound delay to avoid overflow.  */
/* Long delays are usually canceled before they expire */
if (inst_delay_d > (double)0x7fffffff)
    inst_delay_d = (double)0x7fffffff;
inst_delay = (int32)inst_delay_d;
if ((inst_delay == 0) && (usec_delay != 0))
    inst_delay = 1;     /* Minimum non-zero delay is 1 instruction */
if ((sim_calb_tmr != -1) &&                             /* calibrated timer available? */
    (inst_delay > 2*rtc_currd[sim_calb_tmr]) &&         /* delay > 2 * calibrated timer's ticks */
    (uptr->flags & UNIT_IDLE)) {                        /* idleable unit? */
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - coscheduling %s with calibrated timer after %d instructions (%d usecs)\n", 
               sim_uname(uptr), inst_delay, usec_delay);
    return sim_clock_coschedule (uptr, inst_delay);     /* coschedule with the calibrated timer */
    }
#if defined(SIM_ASYNCH_CLOCKS)
if ((sim_calb_tmr == -1) ||                             /* if No timer initialized */
    (inst_delay < rtc_currd[sim_calb_tmr]) ||           /*    or sooner than next clock tick? */
    (rtc_calibrations[sim_calb_tmr] == 0) ||            /*    or haven't calibrated yet */
    (!sim_asynch_timer)) {                              /*    or asynch disabled */
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - activating %s after %d instructions\n", 
               sim_uname(uptr), inst_delay);
    return _sim_activate (uptr, inst_delay);            /* queue it now */
    }
if (1) {

    double d_now = sim_timenow_double ();















    uptr->a_usec_delay = usec_delay;

    uptr->a_due_time = d_now + (double)(usec_delay)/1000000.0;








    uptr->a_due_gtime = sim_gtime () + (sim_timer_inst_per_sec () * (double)(usec_delay)/1000000.0);









    uptr->time = usec_delay;
    uptr->cancel = &_sim_wallclock_cancel;              /* bind cleanup method */
    uptr->a_is_active = &_sim_wallclock_is_active;
    if (tmr < SIM_NTIMERS) {                            /* Timer Unit? */
        sim_clock_unit[tmr]->cancel = &_sim_wallclock_cancel;
        sim_clock_unit[tmr]->a_is_active = &_sim_wallclock_is_active;
        }


    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - queue wallclock addition %s at %.6f\n", 
               sim_uname(uptr), uptr->a_due_time);
    }
pthread_mutex_lock (&sim_timer_lock);
uptr->a_next = QUEUE_LIST_END;                          /* Temporarily mark as active */
while (sim_wallclock_entry) {                           /* wait for any prior entry has been digested */
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - queue insert entry %s busy waiting for 1ms\n", 
               sim_uname(sim_wallclock_entry));
    pthread_mutex_unlock (&sim_timer_lock);
    sim_os_ms_sleep (1);
    pthread_mutex_lock (&sim_timer_lock);
    }
sim_wallclock_entry = uptr;
pthread_mutex_unlock (&sim_timer_lock);
pthread_cond_signal (&sim_timer_wake);                  /* wake the timer thread to deal with it */
return SCPE_OK;
#else
sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after() - queue addition %s at %d (%d usecs)\n", 
           sim_uname(uptr), inst_delay, usec_delay);
return _sim_activate (uptr, inst_delay);                /* queue it now */
#endif
}

/* Clock coscheduling routines */

t_stat sim_register_clock_unit_tmr (UNIT *uptr, int32 tmr)
{
if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr >= SIM_NTIMERS))
        return SCPE_IERR;
    }
if (NULL == uptr) {                         /* deregistering? */
    /* Migrate any coscheduled devices to the standard queue */
    /* they will fire and subsequently requeue themselves */
    while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
        UNIT *uptr = sim_clock_cosched_queue[tmr];

        _sim_coschedule_cancel (uptr);
        _sim_activate (uptr, 1);
        }
    sim_clock_unit[tmr] = NULL;
    return SCPE_OK;
    }
if (NULL == sim_clock_unit[tmr])
    sim_clock_cosched_queue[tmr] = QUEUE_LIST_END;
sim_clock_unit[tmr] = uptr;
uptr->dynflags |= UNIT_TMR_UNIT;
sim_timer_units[tmr].flags = ((tmr == SIM_NTIMERS) ? 0 : UNIT_DIS) | 
                             (sim_clock_unit[tmr] ? UNIT_IDLE : 0);
return SCPE_OK;
}

/* Default timer is 0, otherwise use a calibrated one if it exists */
static int32 _default_tmr ()
{
return ((rtc_currd[0] && rtc_hz[0]) ? 0 : ((sim_calb_tmr != -1) ? sim_calb_tmr : 0));
}

static int32 _tick_size ()
{
int32 tmr = _default_tmr ();

return ((rtc_currd[tmr] && rtc_hz[tmr]) ? rtc_currd[tmr] : 10000);
}

int32 sim_rtcn_tick_size (int32 tmr)
{
return (rtc_currd[tmr]) ? rtc_currd[tmr] : 10000;
}

t_stat sim_register_clock_unit (UNIT *uptr)
{
return sim_register_clock_unit_tmr (uptr, 0);
}

t_stat sim_clock_coschedule (UNIT *uptr, int32 interval)
{
int32 ticks = (interval + (_tick_size ()/2))/_tick_size ();/* Convert to ticks */

sim_debug (DBG_QUE, &sim_timer_dev, "sim_clock_coschedule(%s, interval=%d, ticks=%d)\n", sim_uname(uptr), interval, ticks);
return sim_clock_coschedule_tmr (uptr, _default_tmr (), ticks);
}

t_stat sim_clock_coschedule_abs (UNIT *uptr, int32 interval)
{
int32 ticks = (interval + (_tick_size ()/2))/_tick_size ();/* Convert to ticks */

sim_debug (DBG_QUE, &sim_timer_dev, "sim_clock_coschedule_abs(%s, interval=%d, ticks=%d)\n", sim_uname(uptr), interval, ticks);
sim_cancel (uptr);
return sim_clock_coschedule_tmr (uptr, _default_tmr (), ticks);
}

t_stat sim_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks)
{
if (ticks < 0)
    return SCPE_ARG;
if (sim_is_active (uptr)) {
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule_tmr(tmr=%d) - %s is already active\n", tmr, sim_uname (uptr));
    return SCPE_OK;
    }
if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr > SIM_NTIMERS))
        return sim_activate (uptr, MAX(1, ticks) * 10000);
    }
if (NULL == sim_clock_unit[tmr])
    return sim_activate (uptr, ticks * (rtc_currd[tmr] ? rtc_currd[tmr] : _tick_size ()));
else {
    UNIT *cptr, *prvptr;
    int32 accum;





    sim_debug (DBG_QUE, &sim_timer_dev, "sim_clock_coschedule_tmr(tmr=%d) - queueing %s for clock co-schedule (ticks=%d)\n", tmr, sim_uname (uptr), ticks);
    prvptr = NULL;
    accum = 0;
    for (cptr = sim_clock_cosched_queue[tmr]; cptr != QUEUE_LIST_END; cptr = cptr->next) {
        if (ticks < (accum + cptr->time))
            break;
        accum = accum + cptr->time;
        prvptr = cptr;
        }
    if (prvptr == NULL) {
        cptr = uptr->next = sim_clock_cosched_queue[tmr];
        sim_clock_cosched_queue[tmr] = uptr;

        }
    else {
        cptr = uptr->next = prvptr->next;
        prvptr->next = uptr;
        }
    uptr->time = ticks - accum;
    if (cptr != QUEUE_LIST_END)
        cptr->time = cptr->time - uptr->time;
    uptr->cancel = &_sim_coschedule_cancel;             /* bind cleanup method */
    sim_cosched_interval[tmr] = sim_clock_cosched_queue[tmr]->time;
    }
return SCPE_OK;
}

t_stat sim_clock_coschedule_tmr_abs (UNIT *uptr, int32 tmr, int32 ticks)
{
sim_cancel (uptr);
return sim_clock_coschedule_tmr (uptr, tmr, ticks);
}

/* Cancel a unit on the coschedule queue */
static void _sim_coschedule_cancel (UNIT *uptr)
{
AIO_UPDATE_QUEUE;
if (uptr->next) {                           /* On a queue? */
    int tmr;
    UNIT *nptr;

    for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
        if (sim_clock_unit[tmr]) {
            if (uptr == sim_clock_cosched_queue[tmr]) {
                nptr = sim_clock_cosched_queue[tmr] = uptr->next;
                uptr->next = NULL;
                }
            else {
                UNIT *cptr;

                for (cptr = sim_clock_cosched_queue[tmr];
                     (cptr != QUEUE_LIST_END);
                     cptr = cptr->next) {
                    if (cptr->next == uptr) {
                        nptr = cptr->next = (uptr)->next;
                        uptr->next = NULL;
                        break;
                        }
                    }
                }
            if (uptr->next == NULL) {           /* found? */
                uptr->cancel = NULL;
                if (nptr != QUEUE_LIST_END)
                    nptr->time += uptr->time;
                sim_debug (DBG_QUE, &sim_timer_dev, "Canceled Clock Coscheduled Event for %s\n", sim_uname(uptr));
                return;
                }
            }
        }
    }
}

t_bool sim_timer_is_active (UNIT *uptr)
{
int32 tmr;

if (!(uptr->dynflags & UNIT_TMR_UNIT))
    return FALSE;
for (tmr=0; tmr<SIM_NTIMERS; tmr++) {
    if (sim_clock_unit[tmr] == uptr)
        return sim_is_active (&sim_timer_units[tmr]);
    }
return FALSE;
}

#if defined(SIM_ASYNCH_CLOCKS)
static void _sim_wallclock_cancel (UNIT *uptr)
{
int32 tmr;

AIO_UPDATE_QUEUE;
pthread_mutex_lock (&sim_timer_lock);
/* If this is a clock unit, we need to cancel both this and the related timer unit */
for (tmr=0; tmr<SIM_NTIMERS; tmr++)
    if (sim_clock_unit[tmr] == uptr) {
        uptr = &sim_timer_units[tmr];
        break;
        }
if (uptr->a_next) {
    UNIT *cptr;

    if (uptr == sim_wallclock_entry) {  /* Pending on the queue? */
        sim_wallclock_entry = NULL;
        uptr->a_next = NULL;
        }
    else {
        if (uptr == sim_wallclock_queue) {
            sim_wallclock_queue = uptr->a_next;
            uptr->a_next = NULL;
            sim_debug (DBG_QUE, &sim_timer_dev, "Canceling Timer Event for %s\n", sim_uname(uptr));

            pthread_cond_signal (&sim_timer_wake);
            }
        else {
            for (cptr = sim_wallclock_queue;
                (cptr != QUEUE_LIST_END);
                cptr = cptr->a_next) {
                if (cptr->a_next == (uptr)) {
                    cptr->a_next = (uptr)->a_next;
                    uptr->a_next = NULL;
                    sim_debug (DBG_QUE, &sim_timer_dev, "Canceled Timer Event for %s\n", sim_uname(uptr));
                    break;
                    }
                }
            }
        }
    if (uptr->a_next == NULL) {
        uptr->a_due_time = uptr->a_due_gtime = uptr->a_usec_delay = 0;
        uptr->cancel = NULL;
        uptr->a_is_active = NULL;
        if (tmr < SIM_NTIMERS) {                        /* Timer Unit? */
            sim_clock_unit[tmr]->cancel = NULL;
            sim_clock_unit[tmr]->a_is_active = NULL;
            }
        }
    }
pthread_mutex_unlock (&sim_timer_lock);
}

static t_bool _sim_wallclock_is_active (UNIT *uptr)
{
int32 tmr;

if (uptr->a_next)
    return TRUE;
/* If this is a clock unit, we need to examine the related timer unit instead */
for (tmr=0; tmr<SIM_NTIMERS; tmr++)
    if (sim_clock_unit[tmr] == uptr)
        return (sim_timer_units[tmr].a_next != NULL);
return FALSE;
}
#endif /* defined(SIM_ASYNCH_CLOCKS) */

int32 sim_timer_activate_time (UNIT *uptr)
{
UNIT *cptr;
int32 tmr;

#if defined(SIM_ASYNCH_CLOCKS)
if (uptr->a_is_active == &_sim_wallclock_is_active) {
    double d_result;

    pthread_mutex_lock (&sim_timer_lock);
    if (uptr == sim_wallclock_entry) {
        d_result = uptr->a_due_gtime - sim_gtime ();
        if (d_result < 0.0)
            d_result = 0.0;
        if (d_result > (double)0x7FFFFFFE)
            d_result = (double)0x7FFFFFFE;
        pthread_mutex_unlock (&sim_timer_lock);
        return ((int32)d_result) + 1;
        }
    for (cptr = sim_wallclock_queue;
         cptr != QUEUE_LIST_END;
         cptr = cptr->a_next)
        if (uptr == cptr) {
            d_result = uptr->a_due_gtime - sim_gtime ();
            if (d_result < 0.0)
                d_result = 0.0;
            if (d_result > (double)0x7FFFFFFE)
                d_result = (double)0x7FFFFFFE;
            pthread_mutex_unlock (&sim_timer_lock);
            return ((int32)d_result) + 1;
            }
    pthread_mutex_unlock (&sim_timer_lock);
    }
if (uptr->a_next)
    return uptr->a_event_time + 1;
#endif /* defined(SIM_ASYNCH_CLOCKS) */

if (uptr->cancel == &_sim_coschedule_cancel) {
    for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
        int32 accum;

        accum = sim_cosched_interval[tmr];
        for (cptr = sim_clock_cosched_queue[tmr]; cptr != QUEUE_LIST_END; cptr = cptr->next) {
            if (cptr != sim_clock_cosched_queue[tmr])
                accum += cptr->time;
            if (cptr == uptr)
                return (rtc_currd[tmr] * accum) + sim_activate_time (&sim_timer_units[tmr]);
            }
        }
    }
for (tmr=0; tmr<SIM_NTIMERS; tmr++)
    if (sim_clock_unit[tmr] == uptr)
        return sim_activate_time (&sim_timer_units[tmr]);
return -1;                                          /* Not found. */    
}
Changes to src/sim_timer.h.
27
28
29
30
31
32
33





34
35



36
37
38
39
40
41
42
   17-Oct-06    RMS     Added idle support
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_TIMER_H_
#define SIM_TIMER_H_   0






/* Pick up a struct timespec definition if it is available */
#include <time.h>



#if defined(SIM_ASYNCH_IO) || defined(USE_READER_THREAD)
#include <pthread.h>
#endif

#if defined (__APPLE__)
#define HAVE_STRUCT_TIMESPEC 1   /* OSX defined the structure but doesn't tell us */
#endif







>
>
>
>
>


>
>
>







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
   17-Oct-06    RMS     Added idle support
   02-Jan-04    RMS     Split out from SCP
*/

#ifndef SIM_TIMER_H_
#define SIM_TIMER_H_   0


#ifdef  __cplusplus
extern "C" {
#endif

/* Pick up a struct timespec definition if it is available */
#include <time.h>
#if defined(__struct_timespec_defined)
#define _TIMESPEC_DEFINED
#endif
#if defined(SIM_ASYNCH_IO) || defined(USE_READER_THREAD)
#include <pthread.h>
#endif

#if defined (__APPLE__)
#define HAVE_STRUCT_TIMESPEC 1   /* OSX defined the structure but doesn't tell us */
#endif
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

84
85
86
87
88
89



90
91
92

93
94
95
96
97
98
99
100


101
102
103
104

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

122


123

124

125

126

127




128
129
130
131
132


133


134


#endif /* _MSC_VER >= 1900 */
#endif /* defined(_MSC_VER) */
#if !defined(HAVE_STRUCT_TIMESPEC)
#define HAVE_STRUCT_TIMESPEC 1
#if !defined(_TIMESPEC_DEFINED)
#define _TIMESPEC_DEFINED
struct timespec {
    long   tv_sec;
    long   tv_nsec;
};
#endif /* !defined(_TIMESPEC_DEFINED) */
#endif /* !defined(HAVE_STRUCT_TIMESPEC) */
int clock_gettime(int clock_id, struct timespec *tp);
#endif


#define SIM_NTIMERS     8                           /* # timers */
#define SIM_TMAX        500                         /* max timer makeup */

#define SIM_INITIAL_IPS 50000                       /* uncalibrated assumption */
                                                    /* about instructions per second */

#define SIM_IDLE_CAL    10                          /* ms to calibrate */
#define SIM_IDLE_MAX    10                          /* max granularity idle */
#define SIM_IDLE_STMIN  10                          /* min sec for stability */
#define SIM_IDLE_STDFLT 20                          /* dft sec for stability */
#define SIM_IDLE_STMAX  600                         /* max sec for stability */

#define SIM_THROT_WINIT 1000                        /* cycles to skip */
#define SIM_THROT_WST   10000                       /* initial wait */
#define SIM_THROT_WMUL  4                           /* multiplier */
#define SIM_THROT_WMIN  100                         /* min wait */

#define SIM_THROT_MSMIN 10                          /* min for measurement */
#define SIM_THROT_NONE  0                           /* throttle parameters */
#define SIM_THROT_MCYC  1                           /* MegaCycles Per Sec */
#define SIM_THROT_KCYC  2                           /* KiloCycles Per Sec */
#define SIM_THROT_PCT   3                           /* Max Percent of host CPU */
#define SIM_THROT_SPC   4                           /* Specific periodic Delay */




#define TIMER_DBG_IDLE  1                           /* Debug Flag for Idle Debugging */
#define TIMER_DBG_QUEUE 2                           /* Debug Flag for Asynch Queue Debugging */


t_bool sim_timer_init (void);
void sim_timespec_diff (struct timespec *diff, struct timespec *min, struct timespec *sub);
#if defined(SIM_ASYNCH_CLOCKS)
double sim_timenow_double (void);
#endif
int32 sim_rtcn_init (int32 time, int32 tmr);
int32 sim_rtcn_init_unit (UNIT *uptr, int32 time, int32 tmr);


void sim_rtcn_init_all (void);
int32 sim_rtcn_calb (int32 ticksper, int32 tmr);
int32 sim_rtc_init (int32 time);
int32 sim_rtc_calb (int32 ticksper);

t_stat sim_show_timers (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc);
t_stat sim_show_clock_queues (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, char *cptr);
t_bool sim_idle (uint32 tmr, t_bool sin_cyc);
t_stat sim_set_throt (int32 arg, char *cptr);
t_stat sim_show_throt (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, char *cptr);
t_stat sim_set_idle (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_clr_idle (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat sim_show_idle (FILE *st, UNIT *uptr, int32 val, void *desc);
void sim_throt_sched (void);
void sim_throt_cancel (void);
uint32 sim_os_msec (void);
void sim_os_sleep (unsigned int sec);
uint32 sim_os_ms_sleep (unsigned int msec);
uint32 sim_os_ms_sleep_init (void);
void sim_start_timer_services (void);
void sim_stop_timer_services (void);
t_stat sim_timer_change_asynch (void);

t_stat sim_timer_activate_after (UNIT *uptr, int32 usec_delay);


t_stat sim_register_clock_unit (UNIT *uptr);

t_stat sim_clock_coschedule (UNIT *uptr, int32 interval);

t_stat sim_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 interval);

double sim_timer_inst_per_sec (void);

uint32 sim_timer_idle_capable (uint32 *hoat_tick_ms);





extern t_bool sim_idle_enab;                        /* idle enabled flag */
extern volatile t_bool sim_idle_wait;               /* idle waiting flag */
extern t_bool sim_asynch_timer;
extern DEVICE sim_timer_dev;





#endif









|











|



<
|



|
|
|
|
>
|
|
|
|
|
|
>
>
>

|
|
>



<

<


>
>




>
|
|

|
|
|
|
|









>
|
>
>

>

>
|
>

>
|
>
>
>
>





>
>

>
>

>
>
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

108

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#endif /* _MSC_VER >= 1900 */
#endif /* defined(_MSC_VER) */
#if !defined(HAVE_STRUCT_TIMESPEC)
#define HAVE_STRUCT_TIMESPEC 1
#if !defined(_TIMESPEC_DEFINED)
#define _TIMESPEC_DEFINED
struct timespec {
    time_t tv_sec;
    long   tv_nsec;
};
#endif /* !defined(_TIMESPEC_DEFINED) */
#endif /* !defined(HAVE_STRUCT_TIMESPEC) */
int clock_gettime(int clock_id, struct timespec *tp);
#endif


#define SIM_NTIMERS     8                           /* # timers */
#define SIM_TMAX        500                         /* max timer makeup */

#define SIM_INITIAL_IPS 500000                      /* uncalibrated assumption */
                                                    /* about instructions per second */

#define SIM_IDLE_CAL    10                          /* ms to calibrate */

#define SIM_IDLE_STMIN  2                           /* min sec for stability */
#define SIM_IDLE_STDFLT 20                          /* dft sec for stability */
#define SIM_IDLE_STMAX  600                         /* max sec for stability */

#define SIM_THROT_WINIT     1000                    /* cycles to skip */
#define SIM_THROT_WST       10000                   /* initial wait */
#define SIM_THROT_WMUL      4                       /* multiplier */
#define SIM_THROT_WMIN      50                      /* min wait */
#define SIM_THROT_DRIFT_PCT 5                       /* drift percentage for recalibrate */
#define SIM_THROT_MSMIN     10                      /* min for measurement */
#define SIM_THROT_NONE      0                       /* throttle parameters */
#define SIM_THROT_MCYC      1                       /* MegaCycles Per Sec */
#define SIM_THROT_KCYC      2                       /* KiloCycles Per Sec */
#define SIM_THROT_PCT       3                       /* Max Percent of host CPU */
#define SIM_THROT_SPC       4                       /* Specific periodic Delay */
#define SIM_THROT_STATE_INIT      0                 /* Starting */
#define SIM_THROT_STATE_TIME      1                 /* Checking Time */
#define SIM_THROT_STATE_THROTTLE  2                 /* Throttling  */

#define TIMER_DBG_IDLE  0x001                       /* Debug Flag for Idle Debugging */
#define TIMER_DBG_QUEUE 0x002                       /* Debug Flag for Asynch Queue Debugging */
#define TIMER_DBG_MUX   0x004                       /* Debug Flag for Asynch Queue Debugging */

t_bool sim_timer_init (void);
void sim_timespec_diff (struct timespec *diff, struct timespec *min, struct timespec *sub);

double sim_timenow_double (void);

int32 sim_rtcn_init (int32 time, int32 tmr);
int32 sim_rtcn_init_unit (UNIT *uptr, int32 time, int32 tmr);
void sim_rtcn_get_time (struct timespec *now, int tmr);
t_stat sim_rtcn_tick_ack (uint32 time, int32 tmr);
void sim_rtcn_init_all (void);
int32 sim_rtcn_calb (int32 ticksper, int32 tmr);
int32 sim_rtc_init (int32 time);
int32 sim_rtc_calb (int32 ticksper);
t_stat sim_set_timers (int32 arg, CONST char *cptr);
t_stat sim_show_timers (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc);
t_stat sim_show_clock_queues (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_bool sim_idle (uint32 tmr, t_bool sin_cyc);
t_stat sim_set_throt (int32 arg, CONST char *cptr);
t_stat sim_show_throt (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr);
t_stat sim_set_idle (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_clr_idle (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat sim_show_idle (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
void sim_throt_sched (void);
void sim_throt_cancel (void);
uint32 sim_os_msec (void);
void sim_os_sleep (unsigned int sec);
uint32 sim_os_ms_sleep (unsigned int msec);
uint32 sim_os_ms_sleep_init (void);
void sim_start_timer_services (void);
void sim_stop_timer_services (void);
t_stat sim_timer_change_asynch (void);
t_stat sim_timer_activate (UNIT *uptr, int32 interval);
t_stat sim_timer_activate_after (UNIT *uptr, uint32 usec_delay);
int32 sim_timer_activate_time (UNIT *uptr);
t_bool sim_timer_is_active (UNIT *uptr);
t_stat sim_register_clock_unit (UNIT *uptr);
t_stat sim_register_clock_unit_tmr (UNIT *uptr, int32 tmr);
t_stat sim_clock_coschedule (UNIT *uptr, int32 interval);
t_stat sim_clock_coschedule_abs (UNIT *uptr, int32 interval);
t_stat sim_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks);
t_stat sim_clock_coschedule_tmr_abs (UNIT *uptr, int32 tmr, int32 ticks);
double sim_timer_inst_per_sec (void);
int32 sim_rtcn_tick_size (int32 tmr);
t_bool sim_timer_idle_capable (uint32 *host_ms_sleep_1, uint32 *host_tick_ms);
#define PRIORITY_BELOW_NORMAL  -1
#define PRIORITY_NORMAL         0
#define PRIORITY_ABOVE_NORMAL   1
t_stat sim_os_set_thread_priority (int below_normal_above);

extern t_bool sim_idle_enab;                        /* idle enabled flag */
extern volatile t_bool sim_idle_wait;               /* idle waiting flag */
extern t_bool sim_asynch_timer;
extern DEVICE sim_timer_dev;
extern UNIT * volatile sim_clock_cosched_queue[SIM_NTIMERS+1];
extern const t_bool rtc_avail;

#ifdef  __cplusplus
}
#endif

#endif
Changes to src/sim_tmxr.c.
336
337
338
339
340
341
342

343
344
345
346
347
348
349
#include "sim_serial.h"
#include "sim_sock.h"
#include "sim_timer.h"
#include "sim_tmxr.h"
#include "scp.h"

#include <ctype.h>


/* Telnet protocol constants - negatives are for init'ing signed char data */

/* Commands */
#define TN_IAC          0xFFu /* -1 */                  /* protocol delim */
#define TN_DONT         0xFEu /* -2 */                  /* dont */
#define TN_DO           0xFDu /* -3 */                  /* do */







>







336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#include "sim_serial.h"
#include "sim_sock.h"
#include "sim_timer.h"
#include "sim_tmxr.h"
#include "scp.h"

#include <ctype.h>
#include <math.h>

/* Telnet protocol constants - negatives are for init'ing signed char data */

/* Commands */
#define TN_IAC          0xFFu /* -1 */                  /* protocol delim */
#define TN_DONT         0xFEu /* -2 */                  /* dont */
#define TN_DO           0xFDu /* -3 */                  /* do */
425
426
427
428
429
430
431










432
433
434
435
436
437
438
  BIT(RTS),                                 /* Request To Send     */
  BIT(DCD),                                 /* Data Carrier Detect */
  BIT(RNG),                                 /* Ring Indicator      */
  BIT(CTS),                                 /* Clear To Send       */
  BIT(DSR),                                 /* Data Set Ready      */
  ENDBITS
};











/* Local routines */

static void tmxr_add_to_open_list (TMXR* mux);

/* Initialize the line state.








>
>
>
>
>
>
>
>
>
>







426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
  BIT(RTS),                                 /* Request To Send     */
  BIT(DCD),                                 /* Data Carrier Detect */
  BIT(RNG),                                 /* Ring Indicator      */
  BIT(CTS),                                 /* Clear To Send       */
  BIT(DSR),                                 /* Data Set Ready      */
  ENDBITS
};

static u_char mantra[] = {                  /* Telnet Option Negotiation Mantra */
    TN_IAC, TN_WILL, TN_LINE,
    TN_IAC, TN_WILL, TN_SGA,
    TN_IAC, TN_WILL, TN_ECHO,
    TN_IAC, TN_WILL, TN_BIN,
    TN_IAC, TN_DO, TN_BIN
    };

#define TMXR_GUARD  ((int32)(lp->serport ? 1 : sizeof(mantra)))/* buffer guard */

/* Local routines */

static void tmxr_add_to_open_list (TMXR* mux);

/* Initialize the line state.

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
   here, because the disconnect routines will do that just after calling us.
*/

static void tmxr_report_disconnection (TMLN *lp)
{
if (lp->notelnet)
    return;
tmxr_linemsgf (lp, "\nDisconnected from the %s simulator\n\n", sim_name);/* report disconnection */
return;
}

static int32 loop_write_ex (TMLN *lp, char *buf, int32 length, t_bool prefix_datagram)
{
int32 written = 0;
int32 loopfree = lp->lpbsz - lp->lpbcnt;







|







566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
   here, because the disconnect routines will do that just after calling us.
*/

static void tmxr_report_disconnection (TMLN *lp)
{
if (lp->notelnet)
    return;
tmxr_linemsgf (lp, "\r\nDisconnected from the %s simulator\r\n\n", sim_name);/* report disconnection */
return;
}

static int32 loop_write_ex (TMLN *lp, char *buf, int32 length, t_bool prefix_datagram)
{
int32 written = 0;
int32 loopfree = lp->lpbsz - lp->lpbcnt;
681
682
683
684
685
686
687
688


689



690
691
692
693
694
695
696
697
{
int32 written;
int32 i = lp->txbpr;

if (lp->loopback)
    return loop_write (lp, &(lp->txb[i]), length);

if (lp->serport)                                        /* serial port connection? */


    return sim_write_serial (lp->serport, &(lp->txb[i]), length);




else {                                                  /* Telnet connection */
    written = sim_write_sock (lp->sock, &(lp->txb[i]), length);

    if (written == SOCKET_ERROR)                        /* did an error occur? */
        if (lp->datagram)
            return written;                             /* ignore errors on datagram sockets */
        else







|
>
>
|
>
>
>
|







692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
{
int32 written;
int32 i = lp->txbpr;

if (lp->loopback)
    return loop_write (lp, &(lp->txb[i]), length);

if (lp->serport) {                                      /* serial port connection? */
    if (sim_gtime () < lp->txnexttime)
        return 0;
    written = sim_write_serial (lp->serport, &(lp->txb[i]), length);
    if (written > 0)
        lp->txnexttime = floor (sim_gtime () + (lp->txdelta * sim_timer_inst_per_sec ()));
    return written;
    }
else {                                                  /* Telnet connection */
    written = sim_write_sock (lp->sock, &(lp->txb[i]), length);

    if (written == SOCKET_ERROR)                        /* did an error occur? */
        if (lp->datagram)
            return written;                             /* ignore errors on datagram sockets */
        else
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
   Note: This routine may be called with a UNIT that does not belong to the
   device indicated in the TMXR structure.  That is, the multiplexer lines may
   belong to a device other than the one attached to the socket (the HP 2100 MUX
   device is one example).  Therefore, we must look up the device from the unit
   at each call, rather than depending on the DEVICE pointer stored in the TMXR.
*/

static TMLN *tmxr_find_ldsc (UNIT *uptr, int32 val, TMXR *mp)
{
if (mp == NULL)                                         /* invalid multiplexer descriptor? */
    return NULL;                                        /* programming error! */
if (uptr) {                                             /* called from SET? */
    DEVICE *dptr = find_dev_from_unit (uptr);           /* find device */
    if (dptr == NULL)                                   /* what?? */
        return NULL;







|







749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
   Note: This routine may be called with a UNIT that does not belong to the
   device indicated in the TMXR structure.  That is, the multiplexer lines may
   belong to a device other than the one attached to the socket (the HP 2100 MUX
   device is one example).  Therefore, we must look up the device from the unit
   at each call, rather than depending on the DEVICE pointer stored in the TMXR.
*/

static TMLN *tmxr_find_ldsc (UNIT *uptr, int32 val, const TMXR *mp)
{
if (mp == NULL)                                         /* invalid multiplexer descriptor? */
    return NULL;                                        /* programming error! */
if (uptr) {                                             /* called from SET? */
    DEVICE *dptr = find_dev_from_unit (uptr);           /* find device */
    if (dptr == NULL)                                   /* what?? */
        return NULL;
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796

   Implementation note:

    1. A return status of SCPE_IERR implies a programming error (passing an
       invalid pointer or an invalid unit).
*/

static TMLN *tmxr_get_ldsc (UNIT *uptr, char *cptr, TMXR *mp, t_stat *status)
{
t_value  ln;
TMLN    *lp = NULL;
t_stat   code = SCPE_OK;

if (mp == NULL)                                         /* missing mux descriptor? */
    code = SCPE_IERR;                                   /* programming error! */

else if (uptr) {                                        /* implied line form? */
    lp = tmxr_find_ldsc (uptr, mp->lines, mp);          /* determine line from unit */

    if (lp == NULL)                                     /* invalid line number? */
        code = SCPE_IERR;                               /* programming error! */
    }

else if (cptr == NULL)                                  /* named line form, parameter supplied? */
    code = SCPE_ARG;                                    /* no, so report missing */

else {
    ln = get_uint (cptr, 10, mp->lines - 1, &code);     /* get line number */

    if (code == SCPE_OK)                                /* line number OK? */
        lp = mp->ldsc + (int32) ln;                     /* use as index to determine line */
    }







|
















|







781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812

   Implementation note:

    1. A return status of SCPE_IERR implies a programming error (passing an
       invalid pointer or an invalid unit).
*/

static TMLN *tmxr_get_ldsc (UNIT *uptr, const char *cptr, TMXR *mp, t_stat *status)
{
t_value  ln;
TMLN    *lp = NULL;
t_stat   code = SCPE_OK;

if (mp == NULL)                                         /* missing mux descriptor? */
    code = SCPE_IERR;                                   /* programming error! */

else if (uptr) {                                        /* implied line form? */
    lp = tmxr_find_ldsc (uptr, mp->lines, mp);          /* determine line from unit */

    if (lp == NULL)                                     /* invalid line number? */
        code = SCPE_IERR;                               /* programming error! */
    }

else if (cptr == NULL)                                  /* named line form, parameter supplied? */
    code = SCPE_MISVAL;                                 /* no, so report missing */

else {
    ln = get_uint (cptr, 10, mp->lines - 1, &code);     /* get line number */

    if (code == SCPE_OK)                                /* line number OK? */
        lp = mp->ldsc + (int32) ln;                     /* use as index to determine line */
    }
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
SOCKET newsock;
TMLN *lp;
int32 *op;
int32 i, j;
char *address;
char msg[512];
uint32 poll_time = sim_os_msec ();
static u_char mantra[] = {
    TN_IAC, TN_WILL, TN_LINE,
    TN_IAC, TN_WILL, TN_SGA,
    TN_IAC, TN_WILL, TN_ECHO,
    TN_IAC, TN_WILL, TN_BIN,
    TN_IAC, TN_DO, TN_BIN
    };

if (mp->last_poll_time == 0) {                          /* first poll initializations */
    UNIT *uptr = mp->uptr;

    if (!uptr)                                          /* Attached ? */
        return -1;                                      /* No connections are possinle! */








<
<
<
<
<
<
<







968
969
970
971
972
973
974







975
976
977
978
979
980
981
SOCKET newsock;
TMLN *lp;
int32 *op;
int32 i, j;
char *address;
char msg[512];
uint32 poll_time = sim_os_msec ();








if (mp->last_poll_time == 0) {                          /* first poll initializations */
    UNIT *uptr = mp->uptr;

    if (!uptr)                                          /* Attached ? */
        return -1;                                      /* No connections are possinle! */

994
995
996
997
998
999
1000







1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020

1021
1022
1023
1024












































1025
1026
1027
1028
1029

1030
1031
1032
1033
1034
1035

1036
1037
1038
1039
1040
1041
1042
tmxr_debug_trace (mp, "tmxr_poll_conn()");

mp->last_poll_time = poll_time;

/* Check for a pending Telnet/tcp connection */

if (mp->master) {







    newsock = sim_accept_conn_ex (mp->master, &address, (mp->packet ? SIM_SOCK_OPT_NODELAY : 0));/* poll connect */

    if (newsock != INVALID_SOCKET) {                    /* got a live one? */
        sprintf (msg, "tmxr_poll_conn() - Connection from %s", address);
        tmxr_debug_connect (mp, msg);
        op = mp->lnorder;                               /* get line connection order list pointer */
        i = mp->lines;                                  /* play it safe in case lines == 0 */
        ++mp->sessions;                                 /* count the new session */

        for (j = 0; j < mp->lines; j++, i++) {          /* find next avail line */
            if (op && (*op >= 0) && (*op < mp->lines))  /* order list present and valid? */
                i = *op++;                              /* get next line in list to try */
            else                                        /* no list or not used or range error */
                i = j;                                  /* get next sequential line */

            lp = mp->ldsc + i;                          /* get pointer to line descriptor */
            if ((lp->conn == FALSE) &&                  /* is the line available? */
                (lp->destination == NULL) &&
                (lp->master == 0) &&
                (lp->ser_connect_pending == FALSE))

                break;                                  /* yes, so stop search */
            }

        if (i >= mp->lines) {                           /* all busy? */












































            tmxr_msg (newsock, "All connections busy\r\n");
            tmxr_debug_connect (mp, "tmxr_poll_conn() - All connections busy");
            sim_close_sock (newsock);
            free (address);
            }

        else {
            lp = mp->ldsc + i;                          /* get line desc */
            tmxr_init_line (lp);                        /* init line */
            lp->conn = TRUE;                            /* record connection */
            lp->sock = newsock;                         /* save socket */
            lp->ipad = address;                         /* ip address */

            lp->notelnet = mp->notelnet;                /* apply mux default telnet setting */
            if (!lp->notelnet) {
                sim_write_sock (newsock, (char *)mantra, sizeof(mantra));
                tmxr_debug (TMXR_DBG_XMT, lp, "Sending", (char *)mantra, sizeof(mantra));
                lp->telnet_sent_opts = (uint8 *)realloc (lp->telnet_sent_opts, 256);
                memset (lp->telnet_sent_opts, 0, 256);
                }







>
>
>
>
>
>
>
|


















|
>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
>


<



>







1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
tmxr_debug_trace (mp, "tmxr_poll_conn()");

mp->last_poll_time = poll_time;

/* Check for a pending Telnet/tcp connection */

if (mp->master) {
    if (mp->ring_sock != INVALID_SOCKET) {  /* Use currently 'ringing' socket if one is active */
        newsock = mp->ring_sock;
        mp->ring_sock = INVALID_SOCKET;
        address = mp->ring_ipad;
        mp->ring_ipad = NULL;
        }
    else
        newsock = sim_accept_conn_ex (mp->master, &address, (mp->packet ? SIM_SOCK_OPT_NODELAY : 0));/* poll connect */

    if (newsock != INVALID_SOCKET) {                    /* got a live one? */
        sprintf (msg, "tmxr_poll_conn() - Connection from %s", address);
        tmxr_debug_connect (mp, msg);
        op = mp->lnorder;                               /* get line connection order list pointer */
        i = mp->lines;                                  /* play it safe in case lines == 0 */
        ++mp->sessions;                                 /* count the new session */

        for (j = 0; j < mp->lines; j++, i++) {          /* find next avail line */
            if (op && (*op >= 0) && (*op < mp->lines))  /* order list present and valid? */
                i = *op++;                              /* get next line in list to try */
            else                                        /* no list or not used or range error */
                i = j;                                  /* get next sequential line */

            lp = mp->ldsc + i;                          /* get pointer to line descriptor */
            if ((lp->conn == FALSE) &&                  /* is the line available? */
                (lp->destination == NULL) &&
                (lp->master == 0) &&
                (lp->ser_connect_pending == FALSE) &&
                (lp->modem_control ? ((lp->modembits & TMXR_MDM_DTR) != 0) : TRUE))
                break;                                  /* yes, so stop search */
            }

        if (i >= mp->lines) {                           /* all busy? */
            int32 ringable_count = 0;

            for (j = 0; j < mp->lines; j++, i++) {      /* find next avail line */
                lp = mp->ldsc + j;                      /* get pointer to line descriptor */
                if ((lp->conn == FALSE) &&              /* is the line available? */
                    (lp->destination == NULL) &&
                    (lp->master == 0) &&
                    (lp->ser_connect_pending == FALSE) &&
                    ((lp->modembits & TMXR_MDM_DTR) == 0)) {
                    ++ringable_count;
                    tmxr_set_get_modem_bits (lp, TMXR_MDM_RNG, 0, NULL);
                    tmxr_debug_connect_line (lp, "tmxr_poll_conn() - Ringing line");
                    }
                }
            if (ringable_count > 0) {
                if (mp->ring_start_time == 0) {
                    mp->ring_start_time = poll_time;
                    mp->ring_sock = newsock;
                    mp->ring_ipad = address;
                    }
                else {
                    if ((poll_time - mp->ring_start_time) < TMXR_MODEM_RING_TIME*1000) {
                        mp->ring_sock = newsock;
                        mp->ring_ipad = address;
                        }
                    else {                                      /* Timeout waiting for DTR */
                        int ln;

                        /* turn off pending ring signals */
                        for (ln = 0; ln < lp->mp->lines; ln++) {
                            TMLN *tlp = lp->mp->ldsc + ln;
                            if (((tlp->destination == NULL) && (tlp->master == 0)) &&
                                (tlp->modembits & TMXR_MDM_RNG) && (tlp->conn == FALSE))
                                tlp->modembits &= ~TMXR_MDM_RNG;
                            }
                        mp->ring_start_time = 0;
                        tmxr_msg (newsock, "No answer on any connection\r\n");
                        tmxr_debug_connect (mp, "tmxr_poll_conn() - No Answer - All connections busy");
                        sim_close_sock (newsock);
                        free (address);
                        }
                    }
                }
            else {
                tmxr_msg (newsock, "All connections busy\r\n");
                tmxr_debug_connect (mp, "tmxr_poll_conn() - All connections busy");
                sim_close_sock (newsock);
                free (address);
                }
            }
        else {
            lp = mp->ldsc + i;                          /* get line desc */

            lp->conn = TRUE;                            /* record connection */
            lp->sock = newsock;                         /* save socket */
            lp->ipad = address;                         /* ip address */
            tmxr_init_line (lp);                        /* init line */
            lp->notelnet = mp->notelnet;                /* apply mux default telnet setting */
            if (!lp->notelnet) {
                sim_write_sock (newsock, (char *)mantra, sizeof(mantra));
                tmxr_debug (TMXR_DBG_XMT, lp, "Sending", (char *)mantra, sizeof(mantra));
                lp->telnet_sent_opts = (uint8 *)realloc (lp->telnet_sent_opts, 256);
                memset (lp->telnet_sent_opts, 0, 256);
                }
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141

1142
1143
1144


1145
1146
1147
1148
1149
1150
1151
                                tmxr_debug_connect_line (lp, msg);
                                sim_close_sock (lp->connecting);    /* abort our as yet unconnnected socket */
                                lp->connecting = 0;
                                }
                            }
                        if (lp->conn == FALSE) {                    /* is the line available? */
                            if ((!lp->modem_control) || (lp->modembits & TMXR_MDM_DTR)) {
                                tmxr_init_line (lp);                /* init line */
                                lp->conn = TRUE;                    /* record connection */
                                lp->sock = newsock;                 /* save socket */
                                lp->ipad = address;                 /* ip address */

                                if (!lp->notelnet) {
                                    sim_write_sock (newsock, (char *)mantra, sizeof(mantra));
                                    tmxr_debug (TMXR_DBG_XMT, lp, "Sending", (char *)mantra, sizeof(mantra));


                                    }
                                tmxr_report_connection (mp, lp);
                                lp->cnms = sim_os_msec ();          /* time of connection */
                                return i;
                                }
                            else {
                                tmxr_msg (newsock, "Line connection not available\r\n");







<



>



>
>







1193
1194
1195
1196
1197
1198
1199

1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
                                tmxr_debug_connect_line (lp, msg);
                                sim_close_sock (lp->connecting);    /* abort our as yet unconnnected socket */
                                lp->connecting = 0;
                                }
                            }
                        if (lp->conn == FALSE) {                    /* is the line available? */
                            if ((!lp->modem_control) || (lp->modembits & TMXR_MDM_DTR)) {

                                lp->conn = TRUE;                    /* record connection */
                                lp->sock = newsock;                 /* save socket */
                                lp->ipad = address;                 /* ip address */
                                tmxr_init_line (lp);                /* init line */
                                if (!lp->notelnet) {
                                    sim_write_sock (newsock, (char *)mantra, sizeof(mantra));
                                    tmxr_debug (TMXR_DBG_XMT, lp, "Sending", (char *)mantra, sizeof(mantra));
                                    lp->telnet_sent_opts = (uint8 *)realloc (lp->telnet_sent_opts, 256);
                                    memset (lp->telnet_sent_opts, 0, 256);
                                    }
                                tmxr_report_connection (mp, lp);
                                lp->cnms = sim_os_msec ();          /* time of connection */
                                return i;
                                }
                            else {
                                tmxr_msg (newsock, "Line connection not available\r\n");
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384



































1385
1386
1387
1388
1389

1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410


1411

1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425







1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
            if (incoming_state & TMXR_MDM_CTS)
                incoming_state |= TMXR_MDM_DCD;
            }
        else
            incoming_state |= TMXR_MDM_DCD;
        }
    else
        incoming_state = TMXR_MDM_RNG | TMXR_MDM_DCD | TMXR_MDM_DSR;
    }
else



































    if ((lp->master) || (lp->mp && lp->mp->master) ||
        (lp->port && lp->destination))
        incoming_state = TMXR_MDM_DSR;
    else
        incoming_state = 0;

lp->modembits |= incoming_state;
dptr = (lp->dptr ? lp->dptr : (lp->mp ? lp->mp->dptr : NULL));
if ((lp->modembits != before_modem_bits) && (sim_deb && lp->mp && dptr)) {
    sim_debug_bits (TMXR_DBG_MDM, dptr, tmxr_modem_bits, before_modem_bits, lp->modembits, FALSE);
    sim_debug (TMXR_DBG_MDM, dptr, " - Line %d - %p\n", (int)(lp-lp->mp->ldsc), lp->txb);
    }
if (incoming_bits)
    *incoming_bits = lp->modembits;
if (lp->mp && lp->modem_control) {                  /* This API ONLY works on modem_control enabled multiplexer lines */
    if (bits_to_set | bits_to_clear) {              /* Anything to do? */
        if (lp->loopback) {
            if ((lp->modembits ^ before_modem_bits) & TMXR_MDM_DTR) { /* DTR changed? */
                lp->ser_connect_pending = (lp->modembits & TMXR_MDM_DTR);
                lp->conn = !(lp->modembits & TMXR_MDM_DTR);
                }
            return SCPE_OK;
            }
        if (lp->serport)
            return sim_control_serial (lp->serport, bits_to_set, bits_to_clear, incoming_bits);
        if ((lp->sock) || (lp->connecting)) {
            if (bits_to_clear&TMXR_MDM_DTR)             /* drop DTR? */


                tmxr_reset_ln (lp);

            }
        else {
            if ((lp->destination) &&                    /* Virtual Null Modem Cable */
                ((bits_to_set ^ before_modem_bits) &    /* and DTR being Raised */
                 TMXR_MDM_DTR)) {
                char msg[512];

                sprintf (msg, "tmxr_set_get_modem_bits() - establishing outgoing connection to: %s", lp->destination);
                tmxr_debug_connect_line (lp, msg);
                lp->connecting = sim_connect_sock_ex (lp->datagram ? lp->port : NULL, lp->destination, "localhost", NULL, (lp->datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (lp->mp->packet ? SIM_SOCK_OPT_NODELAY : 0));
                }
            }
        }
    return SCPE_OK;







    }
if ((lp->serport) && (!lp->loopback))
    sim_control_serial (lp->serport, 0, 0, incoming_bits);
return SCPE_IERR;
}

/* Enable or Disable loopback mode on a line

   Inputs:
        lp -                the line to change
        enable_loopback -   enable or disable flag







|

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>




















|
>
>

>



|










>
>
>
>
>
>
>



|







1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
            if (incoming_state & TMXR_MDM_CTS)
                incoming_state |= TMXR_MDM_DCD;
            }
        else
            incoming_state |= TMXR_MDM_DCD;
        }
    else
        incoming_state = TMXR_MDM_DCD | TMXR_MDM_DSR | ((lp->modembits & TMXR_MDM_DTR) ? 0 : TMXR_MDM_RNG);
    }
else {
    if (((before_modem_bits & TMXR_MDM_DTR) == 0) &&    /* Upward transition of DTR? */
        ((lp->modembits & TMXR_MDM_DTR) != 0)     &&
        (lp->conn == FALSE)                       &&    /* Not connected */ 
        (lp->modembits & TMXR_MDM_RNG)) {               /* and Ring Signal Present */
        if ((lp->destination == NULL) && 
            (lp->master == 0) &&
            (lp->mp && (lp->mp->ring_sock))) {
            int ln;
            
            lp->conn = TRUE;                            /* record connection */
            lp->sock = lp->mp->ring_sock;               /* save socket */
            lp->mp->ring_sock = INVALID_SOCKET;
            lp->ipad = lp->mp->ring_ipad;               /* ip address */
            lp->mp->ring_ipad = NULL;
            lp->mp->ring_start_time = 0;
            tmxr_init_line (lp);                        /* init line */
            lp->notelnet = lp->mp->notelnet;            /* apply mux default telnet setting */
            if (!lp->notelnet) {
                sim_write_sock (lp->sock, (char *)mantra, sizeof(mantra));
                tmxr_debug (TMXR_DBG_XMT, lp, "Sending", (char *)mantra, sizeof(mantra));
                lp->telnet_sent_opts = (uint8 *)realloc (lp->telnet_sent_opts, 256);
                memset (lp->telnet_sent_opts, 0, 256);
                }
            tmxr_report_connection (lp->mp, lp);
            lp->cnms = sim_os_msec ();                  /* time of connection */
            lp->modembits &= ~TMXR_MDM_RNG;             /* turn off ring on this line*/
            /* turn off other pending ring signals */
            for (ln = 0; ln < lp->mp->lines; ln++) {
                TMLN *tlp = lp->mp->ldsc + ln;
                if (((tlp->destination == NULL) && (tlp->master == 0)) &&
                    (tlp->modembits & TMXR_MDM_RNG) && (tlp->conn == FALSE))
                    tlp->modembits &= ~TMXR_MDM_RNG;
                }
            }
        }
    if ((lp->master) || (lp->mp && lp->mp->master) ||
        (lp->port && lp->destination))
        incoming_state = TMXR_MDM_DSR;
    else
        incoming_state = 0;
    }
lp->modembits |= incoming_state;
dptr = (lp->dptr ? lp->dptr : (lp->mp ? lp->mp->dptr : NULL));
if ((lp->modembits != before_modem_bits) && (sim_deb && lp->mp && dptr)) {
    sim_debug_bits (TMXR_DBG_MDM, dptr, tmxr_modem_bits, before_modem_bits, lp->modembits, FALSE);
    sim_debug (TMXR_DBG_MDM, dptr, " - Line %d - %p\n", (int)(lp-lp->mp->ldsc), lp->txb);
    }
if (incoming_bits)
    *incoming_bits = lp->modembits;
if (lp->mp && lp->modem_control) {                  /* This API ONLY works on modem_control enabled multiplexer lines */
    if (bits_to_set | bits_to_clear) {              /* Anything to do? */
        if (lp->loopback) {
            if ((lp->modembits ^ before_modem_bits) & TMXR_MDM_DTR) { /* DTR changed? */
                lp->ser_connect_pending = (lp->modembits & TMXR_MDM_DTR);
                lp->conn = !(lp->modembits & TMXR_MDM_DTR);
                }
            return SCPE_OK;
            }
        if (lp->serport)
            return sim_control_serial (lp->serport, bits_to_set, bits_to_clear, incoming_bits);
        if ((lp->sock) || (lp->connecting)) {
            if ((before_modem_bits & bits_to_clear & TMXR_MDM_DTR) != 0) { /* drop DTR? */
                if (lp->sock)
                    tmxr_report_disconnection (lp);     /* report closure */
                tmxr_reset_ln (lp);
                }
            }
        else {
            if ((lp->destination) &&                    /* Virtual Null Modem Cable */
                (bits_to_set & ~before_modem_bits &     /* and DTR being Raised */
                 TMXR_MDM_DTR)) {
                char msg[512];

                sprintf (msg, "tmxr_set_get_modem_bits() - establishing outgoing connection to: %s", lp->destination);
                tmxr_debug_connect_line (lp, msg);
                lp->connecting = sim_connect_sock_ex (lp->datagram ? lp->port : NULL, lp->destination, "localhost", NULL, (lp->datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (lp->mp->packet ? SIM_SOCK_OPT_NODELAY : 0));
                }
            }
        }
    return SCPE_OK;
    }
if ((lp->sock) || (lp->connecting)) {
    if ((before_modem_bits & bits_to_clear & TMXR_MDM_DTR) != 0) { /* drop DTR? */
        if (lp->sock)
            tmxr_report_disconnection (lp);     /* report closure */
        tmxr_reset_ln (lp);
        }
    }
if ((lp->serport) && (!lp->loopback))
    sim_control_serial (lp->serport, 0, 0, incoming_bits);
return SCPE_INCOMP;
}

/* Enable or Disable loopback mode on a line

   Inputs:
        lp -                the line to change
        enable_loopback -   enable or disable flag
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512

1513


1514

1515
1516
1517
1518
1519
1520
1521
1522
}

t_bool tmxr_get_line_halfduplex (TMLN *lp)
{
return (lp->halfduplex != FALSE);
}

t_stat tmxr_set_config_line (TMLN *lp, const char *config)
{
t_stat r;

tmxr_debug_trace_line (lp, "tmxr_set_config_line()");
if (!lp->modem_control)                             /* This API ONLY works on modem_control enabled multiplexer lines */
    return SCPE_IERR;
if (lp->serport)
    r = sim_config_serial (lp->serport, config);
else {
    lp->serconfig = (char *)realloc (lp->serconfig, 1 + strlen (config));
    strcpy (lp->serconfig, config);

    r = SCPE_OK;


    }

if (r == SCPE_OK)                                   /* Record port state for proper restore */
    lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return r;
}


/* Get character from specific line








|




<
<





>
|
>
>
|
>
|







1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615


1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
}

t_bool tmxr_get_line_halfduplex (TMLN *lp)
{
return (lp->halfduplex != FALSE);
}

t_stat tmxr_set_config_line (TMLN *lp, CONST char *config)
{
t_stat r;

tmxr_debug_trace_line (lp, "tmxr_set_config_line()");


if (lp->serport)
    r = sim_config_serial (lp->serport, config);
else {
    lp->serconfig = (char *)realloc (lp->serconfig, 1 + strlen (config));
    strcpy (lp->serconfig, config);
    r = tmxr_set_line_speed (lp, lp->serconfig);;
    if (r != SCPE_OK) {
        free (lp->serconfig);
        lp->serconfig = NULL;
        }
    }
if ((r == SCPE_OK) && (lp->mp) && (lp->mp->uptr))   /* Record port state for proper restore */
    lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return r;
}


/* Get character from specific line

1540
1541
1542
1543
1544
1545
1546
1547


1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562




1563
1564
1565
1566
1567
1568
1569
int32 tmxr_getc_ln (TMLN *lp)
{
int32 j; 
t_stat val = 0;
uint32 tmp;

tmxr_debug_trace_line (lp, "tmxr_getc_ln()");
if (lp->conn && lp->rcve) {                             /* conn & enb? */


    if (!sim_send_poll_data (&lp->send, &val)) {        /* injected input characters available? */
        j = lp->rxbpi - lp->rxbpr;                      /* # input chrs */
        if (j) {                                        /* any? */
            tmp = lp->rxb[lp->rxbpr];                   /* get char */
            val = TMXR_VALID | (tmp & 0377);            /* valid + chr */
            if (lp->rbr[lp->rxbpr]) {                   /* break? */
                lp->rbr[lp->rxbpr] = 0;                 /* clear status */
                val = val | SCPE_BREAK;                 /* indicate to caller */
                }
            lp->rxbpr = lp->rxbpr + 1;                  /* adv pointer */
            }
        }
    }                                                   /* end if conn */
if (lp->rxbpi == lp->rxbpr)                             /* empty? zero ptrs */
    lp->rxbpi = lp->rxbpr = 0;




tmxr_debug_return(lp, val);
return val;
}

/* Get packet from specific line

   Inputs:







|
>
>















>
>
>
>







1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
int32 tmxr_getc_ln (TMLN *lp)
{
int32 j; 
t_stat val = 0;
uint32 tmp;

tmxr_debug_trace_line (lp, "tmxr_getc_ln()");
if ((lp->conn && lp->rcve) &&                           /* conn & enb & */
    ((!lp->rxbps) ||                                    /* (!rate limited || enough time passed)? */
     (sim_gtime () >= lp->rxnexttime))) {
    if (!sim_send_poll_data (&lp->send, &val)) {        /* injected input characters available? */
        j = lp->rxbpi - lp->rxbpr;                      /* # input chrs */
        if (j) {                                        /* any? */
            tmp = lp->rxb[lp->rxbpr];                   /* get char */
            val = TMXR_VALID | (tmp & 0377);            /* valid + chr */
            if (lp->rbr[lp->rxbpr]) {                   /* break? */
                lp->rbr[lp->rxbpr] = 0;                 /* clear status */
                val = val | SCPE_BREAK;                 /* indicate to caller */
                }
            lp->rxbpr = lp->rxbpr + 1;                  /* adv pointer */
            }
        }
    }                                                   /* end if conn */
if (lp->rxbpi == lp->rxbpr)                             /* empty? zero ptrs */
    lp->rxbpi = lp->rxbpr = 0;
if (lp->rxbps) {
    if (val)
        lp->rxnexttime = floor (sim_gtime () + ((lp->rxdelta * sim_timer_inst_per_sec ())/lp->rxbpsfactor));
    }
tmxr_debug_return(lp, val);
return val;
}

/* Get packet from specific line

   Inputs:
1874
1875
1876
1877
1878
1879
1880
1881
1882






1883
1884





1885
1886
1887
1888
1889
1890
1891
    }                                                   /* end for */
return;
}


/* Return count of available characters for line */

int32 tmxr_rqln (TMLN *lp)
{






return (lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz: 0));
}







/* Store character in line buffer

   Inputs:
        *lp     =       pointer to line descriptor
        chr     =       character







|

>
>
>
>
>
>


>
>
>
>
>







1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
    }                                                   /* end for */
return;
}


/* Return count of available characters for line */

int32 tmxr_rqln_bare (const TMLN *lp, t_bool speed)
{
if ((speed) && (lp->rxbps)) {                   /* consider speed and rate limiting? */
    if (sim_gtime () < lp->rxnexttime)          /* too soon? */
        return 0;
    else
        return (lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz : 0)) ? 1 : 0;
    }
return (lp->rxbpi - lp->rxbpr + ((lp->rxbpi < lp->rxbpr)? lp->rxbsz: 0));
}

int32 tmxr_rqln (const TMLN *lp)
{
return tmxr_rqln_bare (lp, TRUE);
}


/* Store character in line buffer

   Inputs:
        *lp     =       pointer to line descriptor
        chr     =       character
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
{
if ((lp->conn == FALSE) &&                              /* no conn & not buffered telnet? */
    (!lp->txbfd || lp->notelnet)) {
    ++lp->txdrp;                                        /* lost */
    return SCPE_LOST;
    }
tmxr_debug_trace_line (lp, "tmxr_putc_ln()");
#define TXBUF_AVAIL(lp) (lp->txbsz - tmxr_tqln (lp))
#define TXBUF_CHAR(lp, c) {                               \
    lp->txb[lp->txbpi++] = (char)(c);                     \
    lp->txbpi %= lp->txbsz;                               \
    if (lp->txbpi == lp->txbpr)                           \
        lp->txbpr = (1+lp->txbpr)%lp->txbsz, ++lp->txdrp; \
    }
if ((lp->txbfd && !lp->notelnet) || (TXBUF_AVAIL(lp) > 1)) {/* room for char (+ IAC)? */







|







2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
{
if ((lp->conn == FALSE) &&                              /* no conn & not buffered telnet? */
    (!lp->txbfd || lp->notelnet)) {
    ++lp->txdrp;                                        /* lost */
    return SCPE_LOST;
    }
tmxr_debug_trace_line (lp, "tmxr_putc_ln()");
#define TXBUF_AVAIL(lp) ((lp->serport ? 2: lp->txbsz) - tmxr_tqln (lp))
#define TXBUF_CHAR(lp, c) {                               \
    lp->txb[lp->txbpi++] = (char)(c);                     \
    lp->txbpi %= lp->txbsz;                               \
    if (lp->txbpi == lp->txbpr)                           \
        lp->txbpr = (1+lp->txbpr)%lp->txbsz, ++lp->txdrp; \
    }
if ((lp->txbfd && !lp->notelnet) || (TXBUF_AVAIL(lp) > 1)) {/* room for char (+ IAC)? */
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
tmxr_debug_trace (mp, "tmxr_poll_tx()");
for (i = 0; i < mp->lines; i++) {                       /* loop thru lines */
    lp = mp->ldsc + i;                                  /* get line desc */
    if (!lp->conn)                                      /* skip if !conn */
        continue;
    nbytes = tmxr_send_buffered_data (lp);              /* buffered bytes */
    if (nbytes == 0) {                                  /* buf empty? enab line */
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
        UNIT *ruptr = lp->uptr ? lp->uptr : lp->mp->uptr;
        if ((ruptr->dynflags & UNIT_TM_POLL) &&
            sim_asynch_enabled &&
            tmxr_rqln (lp))
            _sim_activate (ruptr, 0);
#endif
        lp->xmte = 1;                                   /* enable line transmit */







|







2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
tmxr_debug_trace (mp, "tmxr_poll_tx()");
for (i = 0; i < mp->lines; i++) {                       /* loop thru lines */
    lp = mp->ldsc + i;                                  /* get line desc */
    if (!lp->conn)                                      /* skip if !conn */
        continue;
    nbytes = tmxr_send_buffered_data (lp);              /* buffered bytes */
    if (nbytes == 0) {                                  /* buf empty? enab line */
#if defined(SIM_ASYNCH_MUX)
        UNIT *ruptr = lp->uptr ? lp->uptr : lp->mp->uptr;
        if ((ruptr->dynflags & UNIT_TM_POLL) &&
            sim_asynch_enabled &&
            tmxr_rqln (lp))
            _sim_activate (ruptr, 0);
#endif
        lp->xmte = 1;                                   /* enable line transmit */
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
    return tmxr_send_buffered_data (lp);
return tmxr_tqln(lp) + tmxr_tpqln(lp);
}


/* Return count of buffered characters for line */

int32 tmxr_tqln (TMLN *lp)
{
return (lp->txbpi - lp->txbpr + ((lp->txbpi < lp->txbpr)? lp->txbsz: 0));
}

/* Return count of buffered packet characters for line */

int32 tmxr_tpqln (TMLN *lp)
{
return (lp->txppsize - lp->txppoffset);
}

/* Return transmit packet busy status for line */

t_bool tmxr_tpbusyln (TMLN *lp)
{
return (0 != (lp->txppsize - lp->txppoffset));
}

static void _mux_detach_line (TMLN *lp, t_bool close_listener, t_bool close_connecting)
{
if (close_listener && lp->master) {







|






|






|







2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
    return tmxr_send_buffered_data (lp);
return tmxr_tqln(lp) + tmxr_tpqln(lp);
}


/* Return count of buffered characters for line */

int32 tmxr_tqln (const TMLN *lp)
{
return (lp->txbpi - lp->txbpr + ((lp->txbpi < lp->txbpr)? lp->txbsz: 0));
}

/* Return count of buffered packet characters for line */

int32 tmxr_tpqln (const TMLN *lp)
{
return (lp->txppsize - lp->txppoffset);
}

/* Return transmit packet busy status for line */

t_bool tmxr_tpbusyln (const TMLN *lp)
{
return (0 != (lp->txppsize - lp->txppoffset));
}

static void _mux_detach_line (TMLN *lp, t_bool close_listener, t_bool close_connecting)
{
if (close_listener && lp->master) {
2146
2147
2148
2149
2150
2151
2152















































































2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184


2185




2186
2187
2188
2189
2190
2191
2192
2193
2194

2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291







2292
2293
2294
2295
2296

2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336


2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
    uptr->filename = tmxr_mux_attach_string (uptr->filename, lp->mp);
    /* No connections or listeners exist, then we're equivalent to being fully detached.  We should reflect that */
    if (uptr->filename == NULL)
        tmxr_detach (lp->mp, uptr);
    }
return SCPE_OK;
}
















































































/* Open a master listening socket (and all of the other variances of connections).

   A listening socket for the port number described by "cptr" is opened for the
   multiplexer associated with descriptor "mp".  If the open is successful, all
   lines not currently otherwise connected (via serial, outgoing or direct 
   listener) are initialized for Telnet connections.

   Initialization for all connection styles (MUX wide listener, per line serial, 
   listener, outgoing, logging, buffering) are handled by this routine.

*/

t_stat tmxr_open_master (TMXR *mp, char *cptr)
{
int32 i, line, nextline = -1;
char tbuf[CBUFSIZE], listen[CBUFSIZE], destination[CBUFSIZE], 
     logfiletmpl[CBUFSIZE], buffered[CBUFSIZE], hostport[CBUFSIZE], 
     port[CBUFSIZE], option[CBUFSIZE];
SOCKET sock;
SERHANDLE serport;
char *tptr = cptr;
t_bool nolog, notelnet, listennotelnet, modem_control, loopback, datagram, packet;
TMLN *lp;
t_stat r = SCPE_OK;

if (*tptr == '\0')
    return SCPE_ARG;
for (i = 0; i < mp->lines; i++) {               /* initialize lines */
    lp = mp->ldsc + i;
    lp->mp = mp;                                /* set the back pointer */
    lp->modem_control = mp->modem_control;


    }




tmxr_debug_trace (mp, "tmxr_open_master()");
while (*tptr) {
    line = nextline;
    memset(logfiletmpl, '\0', sizeof(logfiletmpl));
    memset(listen,      '\0', sizeof(listen));
    memset(destination, '\0', sizeof(destination));
    memset(buffered,    '\0', sizeof(buffered));
    memset(port,        '\0', sizeof(port));
    memset(option,      '\0', sizeof(option));

    nolog = notelnet = listennotelnet = loopback = FALSE;
    datagram = mp->datagram;
    packet = mp->packet;
    if (mp->buffered)
        sprintf(buffered, "%d", mp->buffered);
    if (line != -1)
        notelnet = listennotelnet = mp->notelnet;
    modem_control = mp->modem_control;
    while (*tptr) {
        tptr = get_glyph_nc (tptr, tbuf, ',');
        if (!tbuf[0])
            break;
        cptr = tbuf;
        if (!isdigit(*cptr)) {
            char gbuf[CBUFSIZE];
            char *init_cptr = cptr;

            cptr = get_glyph (cptr, gbuf, '=');
            if (0 == MATCH_CMD (gbuf, "LINE")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return SCPE_ARG;
                nextline = (int32) get_uint (cptr, 10, mp->lines-1, &r);
                if (r)
                    return SCPE_ARG;
                break;
                }
            if (0 == MATCH_CMD (gbuf, "LOG")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return SCPE_2FARG;
                strncpy(logfiletmpl, cptr, sizeof(logfiletmpl)-1);
                continue;
                }
             if (0 == MATCH_CMD (gbuf, "LOOPBACK")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                loopback = TRUE;
                continue;
                }
           if ((0 == MATCH_CMD (gbuf, "NOBUFFERED")) || 
                (0 == MATCH_CMD (gbuf, "UNBUFFERED"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                buffered[0] = '\0';
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "BUFFERED")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    strcpy (buffered, "32768");
                else {
                    i = (int32) get_uint (cptr, 10, 1024*1024, &r);
                    if (r || (i == 0))
                        return SCPE_ARG;
                    sprintf(buffered, "%d", i);
                    }
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "NOLOG")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                nolog = TRUE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "NOMODEM")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                modem_control = FALSE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "MODEM")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                modem_control = TRUE;
                continue;
                }
            if ((0 == MATCH_CMD (gbuf, "DATAGRAM")) || (0 == MATCH_CMD (gbuf, "UDP"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                notelnet = datagram = TRUE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "PACKET")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                packet = TRUE;
                continue;
                }
            if ((0 == MATCH_CMD (gbuf, "STREAM")) || (0 == MATCH_CMD (gbuf, "TCP"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return SCPE_2MARG;
                datagram = FALSE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "CONNECT")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return SCPE_ARG;
                strcpy (destination, cptr);
                continue;







                }
            cptr = get_glyph (gbuf, port, ';');
            if (sim_parse_addr (port, NULL, 0, NULL, NULL, 0, NULL, NULL))
                return SCPE_ARG;
            if (cptr) {

                get_glyph (cptr, cptr, 0);                  /* upcase this string */
                if (0 == MATCH_CMD (cptr, "NOTELNET"))
                    listennotelnet = TRUE;
                else
                    if (0 == MATCH_CMD (cptr, "TELNET"))
                        listennotelnet = FALSE;
                    else
                        return SCPE_ARG;
                }
            cptr = init_cptr;
            }
        cptr = get_glyph_nc (cptr, port, ';');
        sock = sim_master_sock (port, &r);                      /* make master socket to validate port */
        if (r)
            return SCPE_ARG;
        if (sock == INVALID_SOCKET)                             /* open error */
            return SCPE_OPENERR;
        sim_close_sock (sock);
        sim_os_ms_sleep (2);                                    /* let the close finish (required on some platforms) */
        strcpy (listen, port);
        cptr = get_glyph (cptr, option, ';');
        if (option[0]) {
            if (0 == MATCH_CMD (option, "NOTELNET"))
                listennotelnet = TRUE;
            else
                if (0 == MATCH_CMD (option, "TELNET"))
                    listennotelnet = FALSE;
                else
                    return SCPE_ARG;
            }
        }
    if (destination[0]) {
        /* Validate destination */
        serport = sim_open_serial (destination, NULL, &r);
        if (serport != INVALID_HANDLE) {
            sim_close_serial (serport);
            if (strchr (destination, ';') && mp->modem_control)
                return SCPE_ARG;
            }
        else {


            memset (hostport, '\0', sizeof(hostport));
            strncpy (hostport, destination, sizeof(hostport)-1);
            if ((cptr = strchr (hostport, ';')))
                *(cptr++) = '\0';
            if (cptr) {
                get_glyph (cptr, cptr, 0);          /* upcase this string */
                if (0 == MATCH_CMD (cptr, "NOTELNET"))
                    notelnet = TRUE;
                else
                    if (0 == MATCH_CMD (cptr, "TELNET"))
                        if (datagram)
                            return SCPE_ARG;
                        else
                            notelnet = FALSE;
                    else
                        return SCPE_ARG;
                }
            sock = sim_connect_sock_ex (NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
            if (sock != INVALID_SOCKET)
                sim_close_sock (sock);
            else
                return SCPE_ARG;
            }
        }
    if (line == -1) {
        if (modem_control != mp->modem_control)
            return SCPE_ARG;
        if (logfiletmpl[0]) {
            strncpy(mp->logfiletmpl, logfiletmpl, sizeof(mp->logfiletmpl)-1);







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>













|




|


|










>
>

>
>
>
>









>















|




|


|




|





|






|









|






|





|





|





|





|





|





|


>
>
>
>
>
>
>



|

>
|






|






|

|











|







|
|


>
>


|
|
|
|
|


|

|



|





|







2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
    uptr->filename = tmxr_mux_attach_string (uptr->filename, lp->mp);
    /* No connections or listeners exist, then we're equivalent to being fully detached.  We should reflect that */
    if (uptr->filename == NULL)
        tmxr_detach (lp->mp, uptr);
    }
return SCPE_OK;
}

static int32 _tmln_speed_delta (CONST char *cptr)
{
struct {
    const char *bps;
    int32 delta;
    } *spd, speeds[] = {
    {"50",      TMLN_SPD_50_BPS},
    {"75",      TMLN_SPD_75_BPS},
    {"110",     TMLN_SPD_110_BPS},
    {"134",     TMLN_SPD_134_BPS},
    {"150",     TMLN_SPD_150_BPS},
    {"300",     TMLN_SPD_300_BPS},
    {"600",     TMLN_SPD_600_BPS},
    {"1200",    TMLN_SPD_1200_BPS},
    {"1800",    TMLN_SPD_1800_BPS},
    {"2000",    TMLN_SPD_2000_BPS},
    {"2400",    TMLN_SPD_2400_BPS},
    {"3600",    TMLN_SPD_3600_BPS},
    {"4800",    TMLN_SPD_4800_BPS},
    {"7200",    TMLN_SPD_7200_BPS},
    {"9600",    TMLN_SPD_9600_BPS},
    {"19200",   TMLN_SPD_19200_BPS},
    {"38400",   TMLN_SPD_38400_BPS},
    {"57600",   TMLN_SPD_57600_BPS},
    {"76800",   TMLN_SPD_76800_BPS},
    {"115200",  TMLN_SPD_115200_BPS},
    {"0",       0}};                    /* End of List, last valid value */
int nspeed;
char speed[24];

nspeed = (uint32)strtotv (cptr, &cptr, 10);
if ((*cptr != '\0') && (*cptr != '-') && (*cptr != '*'))
    return -1;
sprintf (speed, "%d", nspeed);

spd = speeds;
while (1) {
    if (0 == strcmp(spd->bps, speed))
        return spd->delta;
    if (spd->delta == 0)
        break;
    ++spd;
    }
return -1;
}

t_stat tmxr_set_line_speed (TMLN *lp, CONST char *speed)
{
UNIT *uptr;
CONST char *cptr;
t_stat r;

if (!speed || !*speed)
    return SCPE_2FARG;
if (_tmln_speed_delta (speed) < 0)
    return SCPE_ARG;
lp->rxbps = (uint32)strtotv (speed, &cptr, 10);
if (*cptr == '*') {
    uint32 rxbpsfactor = (uint32) get_uint (cptr+1, 10, 32, &r);
    if (r != SCPE_OK)
        return r;
    lp->rxbpsfactor = TMXR_RX_BPS_UNIT_SCALE * rxbpsfactor;
    }
lp->rxdelta = _tmln_speed_delta (speed);
lp->rxnexttime = 0.0;
uptr = lp->uptr;
if ((!uptr) && (lp->mp))
    uptr = lp->mp->uptr;
if (uptr)
    uptr->wait = lp->rxdelta;
if (lp->rxbpsfactor == 0.0)
    lp->rxbpsfactor = TMXR_RX_BPS_UNIT_SCALE;
lp->txbps = lp->rxbps;
lp->txdelta = lp->rxdelta;
lp->txnexttime = lp->rxnexttime;
return SCPE_OK;
}


/* Open a master listening socket (and all of the other variances of connections).

   A listening socket for the port number described by "cptr" is opened for the
   multiplexer associated with descriptor "mp".  If the open is successful, all
   lines not currently otherwise connected (via serial, outgoing or direct 
   listener) are initialized for Telnet connections.

   Initialization for all connection styles (MUX wide listener, per line serial, 
   listener, outgoing, logging, buffering) are handled by this routine.

*/

t_stat tmxr_open_master (TMXR *mp, CONST char *cptr)
{
int32 i, line, nextline = -1;
char tbuf[CBUFSIZE], listen[CBUFSIZE], destination[CBUFSIZE], 
     logfiletmpl[CBUFSIZE], buffered[CBUFSIZE], hostport[CBUFSIZE], 
     port[CBUFSIZE], option[CBUFSIZE], speed[CBUFSIZE];
SOCKET sock;
SERHANDLE serport;
CONST char *tptr = cptr;
t_bool nolog, notelnet, listennotelnet, modem_control, loopback, datagram, packet;
TMLN *lp;
t_stat r = SCPE_OK;

if (*tptr == '\0')
    return SCPE_ARG;
for (i = 0; i < mp->lines; i++) {               /* initialize lines */
    lp = mp->ldsc + i;
    lp->mp = mp;                                /* set the back pointer */
    lp->modem_control = mp->modem_control;
    if (lp->rxbpsfactor == 0.0)
        lp->rxbpsfactor = TMXR_RX_BPS_UNIT_SCALE;
    }
mp->ring_sock = INVALID_SOCKET;
free (mp->ring_ipad);
mp->ring_ipad = NULL;
mp->ring_start_time = 0;
tmxr_debug_trace (mp, "tmxr_open_master()");
while (*tptr) {
    line = nextline;
    memset(logfiletmpl, '\0', sizeof(logfiletmpl));
    memset(listen,      '\0', sizeof(listen));
    memset(destination, '\0', sizeof(destination));
    memset(buffered,    '\0', sizeof(buffered));
    memset(port,        '\0', sizeof(port));
    memset(option,      '\0', sizeof(option));
    memset(speed,       '\0', sizeof(speed));
    nolog = notelnet = listennotelnet = loopback = FALSE;
    datagram = mp->datagram;
    packet = mp->packet;
    if (mp->buffered)
        sprintf(buffered, "%d", mp->buffered);
    if (line != -1)
        notelnet = listennotelnet = mp->notelnet;
    modem_control = mp->modem_control;
    while (*tptr) {
        tptr = get_glyph_nc (tptr, tbuf, ',');
        if (!tbuf[0])
            break;
        cptr = tbuf;
        if (!isdigit(*cptr)) {
            char gbuf[CBUFSIZE];
            CONST char *init_cptr = cptr;

            cptr = get_glyph (cptr, gbuf, '=');
            if (0 == MATCH_CMD (gbuf, "LINE")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return sim_messagef (SCPE_2FARG, "Missing Line Specifier\n");
                nextline = (int32) get_uint (cptr, 10, mp->lines-1, &r);
                if (r)
                    return sim_messagef (SCPE_ARG, "Invalid Line Specifier: %s\n", cptr);
                break;
                }
            if (0 == MATCH_CMD (gbuf, "LOG")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return sim_messagef (SCPE_2FARG, "Missing Log Specifier\n");
                strncpy(logfiletmpl, cptr, sizeof(logfiletmpl)-1);
                continue;
                }
             if (0 == MATCH_CMD (gbuf, "LOOPBACK")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Loopback Specifier: %s\n", cptr);
                loopback = TRUE;
                continue;
                }
           if ((0 == MATCH_CMD (gbuf, "NOBUFFERED")) || 
                (0 == MATCH_CMD (gbuf, "UNBUFFERED"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Unbuffered Specifier: %s\n", cptr);
                buffered[0] = '\0';
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "BUFFERED")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    strcpy (buffered, "32768");
                else {
                    i = (int32) get_uint (cptr, 10, 1024*1024, &r);
                    if (r || (i == 0))
                        return sim_messagef (SCPE_ARG, "Invalid Buffered Specifier: %s\n", cptr);
                    sprintf(buffered, "%d", i);
                    }
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "NOLOG")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected NoLog Specifier: %s\n", cptr);
                nolog = TRUE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "NOMODEM")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected NoModem Specifier: %s\n", cptr);
                modem_control = FALSE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "MODEM")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Modem Specifier: %s\n", cptr);
                modem_control = TRUE;
                continue;
                }
            if ((0 == MATCH_CMD (gbuf, "DATAGRAM")) || (0 == MATCH_CMD (gbuf, "UDP"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Datagram Specifier: %s\n", cptr);
                notelnet = datagram = TRUE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "PACKET")) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Packet Specifier: %s\n", cptr);
                packet = TRUE;
                continue;
                }
            if ((0 == MATCH_CMD (gbuf, "STREAM")) || (0 == MATCH_CMD (gbuf, "TCP"))) {
                if ((NULL != cptr) && ('\0' != *cptr))
                    return sim_messagef (SCPE_2MARG, "Unexpected Stream Specifier: %s\n", cptr);
                datagram = FALSE;
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "CONNECT")) {
                if ((NULL == cptr) || ('\0' == *cptr))
                    return sim_messagef (SCPE_2FARG, "Missing Connect Specifier\n");
                strcpy (destination, cptr);
                continue;
                }
            if (0 == MATCH_CMD (gbuf, "SPEED")) {
                if ((NULL == cptr) || ('\0' == *cptr) || 
                    (_tmln_speed_delta (cptr) < 0))
                    return sim_messagef (SCPE_ARG, "Invalid Speed Specifier: %s\n", (cptr ? cptr : ""));
                strcpy (speed, cptr);
                continue;
                }
            cptr = get_glyph (gbuf, port, ';');
            if (sim_parse_addr (port, NULL, 0, NULL, NULL, 0, NULL, NULL))
                return sim_messagef (SCPE_ARG, "Invalid Port Specifier: %s\n", port);
            if (cptr) {
                char *tptr = gbuf + (cptr - gbuf);
                get_glyph (cptr, tptr, 0);                  /* upcase this string */
                if (0 == MATCH_CMD (cptr, "NOTELNET"))
                    listennotelnet = TRUE;
                else
                    if (0 == MATCH_CMD (cptr, "TELNET"))
                        listennotelnet = FALSE;
                    else
                        return sim_messagef (SCPE_ARG, "Invalid Specifier: %s\n", tptr);
                }
            cptr = init_cptr;
            }
        cptr = get_glyph_nc (cptr, port, ';');
        sock = sim_master_sock (port, &r);                      /* make master socket to validate port */
        if (r)
            return sim_messagef (SCPE_ARG, "Invalid Port Specifier: %s\n", port);
        if (sock == INVALID_SOCKET)                             /* open error */
            return sim_messagef (SCPE_OPENERR, "Can't open network port: %s\n", port);
        sim_close_sock (sock);
        sim_os_ms_sleep (2);                                    /* let the close finish (required on some platforms) */
        strcpy (listen, port);
        cptr = get_glyph (cptr, option, ';');
        if (option[0]) {
            if (0 == MATCH_CMD (option, "NOTELNET"))
                listennotelnet = TRUE;
            else
                if (0 == MATCH_CMD (option, "TELNET"))
                    listennotelnet = FALSE;
                else
                    return sim_messagef (SCPE_ARG, "Invalid Specifier: %s\n", option);
            }
        }
    if (destination[0]) {
        /* Validate destination */
        serport = sim_open_serial (destination, NULL, &r);
        if (serport != INVALID_HANDLE) {
            sim_close_serial (serport);
            if (strchr (destination, ';') && mp->modem_control && !(sim_switches & SIM_SW_REST))
                return sim_messagef (SCPE_ARG, "Serial line parameters must be set within simulated OS: %s\n", 1 + strchr (destination, ';'));
            }
        else {
            char *eptr;

            memset (hostport, '\0', sizeof(hostport));
            strncpy (hostport, destination, sizeof(hostport)-1);
            if ((eptr = strchr (hostport, ';')))
                *(eptr++) = '\0';
            if (eptr) {
                get_glyph (eptr, eptr, 0);          /* upcase this string */
                if (0 == MATCH_CMD (eptr, "NOTELNET"))
                    notelnet = TRUE;
                else
                    if (0 == MATCH_CMD (eptr, "TELNET"))
                        if (datagram)
                            return sim_messagef (SCPE_ARG, "Telnet invalid on Datagram socket\n");
                        else
                            notelnet = FALSE;
                    else
                        return sim_messagef (SCPE_ARG, "Unexpected specifier: %s\n", eptr);
                }
            sock = sim_connect_sock_ex (NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
            if (sock != INVALID_SOCKET)
                sim_close_sock (sock);
            else
                return sim_messagef (SCPE_ARG, "Invalid destination: %s\n", hostport);
            }
        }
    if (line == -1) {
        if (modem_control != mp->modem_control)
            return SCPE_ARG;
        if (logfiletmpl[0]) {
            strncpy(mp->logfiletmpl, logfiletmpl, sizeof(mp->logfiletmpl)-1);
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430




2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444




2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455


2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
                    lp->txlog = NULL;
                    }
                }
            }
        if ((listen[0]) && (!datagram)) {
            sock = sim_master_sock (listen, &r);            /* make master socket */
            if (r)
                return SCPE_ARG;
            if (sock == INVALID_SOCKET)                     /* open error */
                return SCPE_OPENERR;
            if (mp->port) {                                 /* close prior listener */
                sim_close_sock (mp->master);
                mp->master = 0;
                free (mp->port);
                mp->port = NULL;
                }
            sim_printf ("Listening on port %s\n", listen);
            mp->port = (char *)realloc (mp->port, 1 + strlen (listen));
            strcpy (mp->port, listen);                      /* save port */
            mp->master = sock;                              /* save master socket */




            mp->notelnet = listennotelnet;                  /* save desired telnet behavior flag */
            for (i = 0; i < mp->lines; i++) {               /* initialize lines */
                lp = mp->ldsc + i;
                lp->mp = mp;                                /* set the back pointer */
                lp->packet = mp->packet;

                if (lp->serport) {                          /* serial port attached? */
                    tmxr_reset_ln (lp);                     /* close current serial connection */
                    sim_control_serial (lp->serport, 0, TMXR_MDM_DTR|TMXR_MDM_RTS, NULL);/* drop DTR and RTS */
                    sim_close_serial (lp->serport);
                    lp->serport = 0;
                    free (lp->serconfig);
                    lp->serconfig = NULL;
                    }




                tmxr_init_line (lp);                        /* initialize line state */
                lp->sock = 0;                               /* clear the socket */
                }
            }
        if (loopback) {
            if (mp->lines > 1)
                return SCPE_ARG;                            /* ambiguous */
            sim_printf ("Operating in loopback mode\n");
            for (i = 0; i < mp->lines; i++) {
                lp = mp->ldsc + i;
                tmxr_set_line_loopback (lp, loopback);


                }
            }
        if (destination[0]) {
            if (mp->lines > 1)
                return SCPE_ARG;                            /* ambiguous */
            lp = &mp->ldsc[0];
            serport = sim_open_serial (destination, lp, &r);
            if (serport != INVALID_HANDLE) {
                _mux_detach_line (lp, TRUE, TRUE);
                if (lp->mp && lp->mp->master) {             /* if existing listener, close it */
                    sim_close_sock (lp->mp->master);
                    lp->mp->master = 0;







|

|










>
>
>
>














>
>
>
>






|




>
>




|







2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
                    lp->txlog = NULL;
                    }
                }
            }
        if ((listen[0]) && (!datagram)) {
            sock = sim_master_sock (listen, &r);            /* make master socket */
            if (r)
                return sim_messagef (SCPE_ARG, "Invalid network listen port: %s\n", listen);
            if (sock == INVALID_SOCKET)                     /* open error */
                return sim_messagef (SCPE_OPENERR, "Can't open network socket for listen port: %s\n", listen);
            if (mp->port) {                                 /* close prior listener */
                sim_close_sock (mp->master);
                mp->master = 0;
                free (mp->port);
                mp->port = NULL;
                }
            sim_printf ("Listening on port %s\n", listen);
            mp->port = (char *)realloc (mp->port, 1 + strlen (listen));
            strcpy (mp->port, listen);                      /* save port */
            mp->master = sock;                              /* save master socket */
            mp->ring_sock = INVALID_SOCKET;
            free (mp->ring_ipad);
            mp->ring_ipad = NULL;
            mp->ring_start_time = 0;
            mp->notelnet = listennotelnet;                  /* save desired telnet behavior flag */
            for (i = 0; i < mp->lines; i++) {               /* initialize lines */
                lp = mp->ldsc + i;
                lp->mp = mp;                                /* set the back pointer */
                lp->packet = mp->packet;

                if (lp->serport) {                          /* serial port attached? */
                    tmxr_reset_ln (lp);                     /* close current serial connection */
                    sim_control_serial (lp->serport, 0, TMXR_MDM_DTR|TMXR_MDM_RTS, NULL);/* drop DTR and RTS */
                    sim_close_serial (lp->serport);
                    lp->serport = 0;
                    free (lp->serconfig);
                    lp->serconfig = NULL;
                    }
                else {
                    if (speed[0])
                        tmxr_set_line_speed (lp, speed);
                    }
                tmxr_init_line (lp);                        /* initialize line state */
                lp->sock = 0;                               /* clear the socket */
                }
            }
        if (loopback) {
            if (mp->lines > 1)
                return sim_messagef (SCPE_ARG, "Ambiguous Loopback specification\n");
            sim_printf ("Operating in loopback mode\n");
            for (i = 0; i < mp->lines; i++) {
                lp = mp->ldsc + i;
                tmxr_set_line_loopback (lp, loopback);
                if (speed[0])
                    tmxr_set_line_speed (lp, speed);
                }
            }
        if (destination[0]) {
            if (mp->lines > 1)
                return sim_messagef (SCPE_ARG, "Ambiguous Destination specification\n");
            lp = &mp->ldsc[0];
            serport = sim_open_serial (destination, lp, &r);
            if (serport != INVALID_HANDLE) {
                _mux_detach_line (lp, TRUE, TRUE);
                if (lp->mp && lp->mp->master) {             /* if existing listener, close it */
                    sim_close_sock (lp->mp->master);
                    lp->mp->master = 0;
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511


2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
                lp->datagram = datagram;
                if (datagram) {
                    if (listen[0]) {
                        lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
                        strcpy (lp->port, listen);           /* save port */
                        }
                    else
                        return SCPE_ARG;
                    }
                lp->packet = packet;
                sock = sim_connect_sock_ex (datagram ? listen : NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
                if (sock != INVALID_SOCKET) {
                    _mux_detach_line (lp, FALSE, TRUE);
                    lp->destination = (char *)malloc(1+strlen(hostport));
                    strcpy (lp->destination, hostport);
                    lp->mp = mp;
                    if (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR)) {
                        lp->connecting = sock;
                        lp->ipad = (char *)malloc (1 + strlen (lp->destination));
                        strcpy (lp->ipad, lp->destination);
                        }
                    else
                        sim_close_sock (sock);
                    lp->notelnet = notelnet;
                    tmxr_init_line (lp);                    /* init the line state */


                    return SCPE_OK;
                    }
                else
                    return SCPE_ARG;
                }
            }
        }
    else {                                                  /* line specific attach */
        lp = &mp->ldsc[line];
        lp->mp = mp;
        if (logfiletmpl[0]) {
            sim_close_logfile (&lp->txlogref);
            lp->txlog = NULL;
            lp->txlogname = (char *)realloc (lp->txlogname, 1 + strlen (logfiletmpl));
            strcpy (lp->txlogname, logfiletmpl);
            r = sim_open_logfile (lp->txlogname, TRUE, &lp->txlog, &lp->txlogref);
            if (r == SCPE_OK)
                setvbuf(lp->txlog, NULL, _IOFBF, 65536);
            else {
                free (lp->txlogname);
                lp->txlogname = NULL;
                return r;
                }
            }
        if (buffered[0] == '\0') {
            lp->rxbsz = lp->txbsz = TMXR_MAXBUF;
            lp->txbfd = 0;
            }
        else {







|

















>
>



|

















|







2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
                lp->datagram = datagram;
                if (datagram) {
                    if (listen[0]) {
                        lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
                        strcpy (lp->port, listen);           /* save port */
                        }
                    else
                        return sim_messagef (SCPE_ARG, "Missing listen port for Datagram socket\n");
                    }
                lp->packet = packet;
                sock = sim_connect_sock_ex (datagram ? listen : NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
                if (sock != INVALID_SOCKET) {
                    _mux_detach_line (lp, FALSE, TRUE);
                    lp->destination = (char *)malloc(1+strlen(hostport));
                    strcpy (lp->destination, hostport);
                    lp->mp = mp;
                    if (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR)) {
                        lp->connecting = sock;
                        lp->ipad = (char *)malloc (1 + strlen (lp->destination));
                        strcpy (lp->ipad, lp->destination);
                        }
                    else
                        sim_close_sock (sock);
                    lp->notelnet = notelnet;
                    tmxr_init_line (lp);                    /* init the line state */
                    if (speed[0] && (!datagram))
                        tmxr_set_line_speed (lp, speed);
                    return SCPE_OK;
                    }
                else
                    return sim_messagef (SCPE_ARG, "Can't open %s socket on %s%s%s\n", datagram ? "Datagram" : "Stream", datagram ? listen : "", datagram ? "<->" : "", hostport);
                }
            }
        }
    else {                                                  /* line specific attach */
        lp = &mp->ldsc[line];
        lp->mp = mp;
        if (logfiletmpl[0]) {
            sim_close_logfile (&lp->txlogref);
            lp->txlog = NULL;
            lp->txlogname = (char *)realloc (lp->txlogname, 1 + strlen (logfiletmpl));
            strcpy (lp->txlogname, logfiletmpl);
            r = sim_open_logfile (lp->txlogname, TRUE, &lp->txlog, &lp->txlogref);
            if (r == SCPE_OK)
                setvbuf(lp->txlog, NULL, _IOFBF, 65536);
            else {
                free (lp->txlogname);
                lp->txlogname = NULL;
                return sim_messagef (r, "Can't open log file: %s\n", logfiletmpl);
                }
            }
        if (buffered[0] == '\0') {
            lp->rxbsz = lp->txbsz = TMXR_MAXBUF;
            lp->txbfd = 0;
            }
        else {
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
            lp->txlogname = NULL;
            if (lp->txlog) {
                sim_close_logfile (&lp->txlogref);
                lp->txlog = NULL;
                }
            }
        if ((listen[0]) && (!datagram)) {
            if ((mp->lines == 1) && (mp->master))           /* single line mux can have either line specific OR mux listener but NOT both */
                return SCPE_ARG;
            sock = sim_master_sock (listen, &r);            /* make master socket */
            if (r)
                return SCPE_ARG;
            if (sock == INVALID_SOCKET)                     /* open error */
                return SCPE_OPENERR;
            _mux_detach_line (lp, TRUE, FALSE);
            sim_printf ("Line %d Listening on port %s\n", line, listen);
            lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
            strcpy (lp->port, listen);                       /* save port */
            lp->master = sock;                              /* save master socket */
            if (listennotelnet != mp->notelnet)
                lp->notelnet = listennotelnet;







|
|


|

|







2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
            lp->txlogname = NULL;
            if (lp->txlog) {
                sim_close_logfile (&lp->txlogref);
                lp->txlog = NULL;
                }
            }
        if ((listen[0]) && (!datagram)) {
            if ((mp->lines == 1) && (mp->master))
                return sim_messagef (SCPE_ARG, "Single Line MUX can have either line specific OR MUS listener but NOT both\n");
            sock = sim_master_sock (listen, &r);            /* make master socket */
            if (r)
                return sim_messagef (SCPE_ARG, "Invalid Listen Specification: %s\n", listen);
            if (sock == INVALID_SOCKET)                     /* open error */
                return sim_messagef (SCPE_OPENERR, "Can't listen on port: %s\n", listen);
            _mux_detach_line (lp, TRUE, FALSE);
            sim_printf ("Line %d Listening on port %s\n", line, listen);
            lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
            strcpy (lp->port, listen);                       /* save port */
            lp->master = sock;                              /* save master socket */
            if (listennotelnet != mp->notelnet)
                lp->notelnet = listennotelnet;
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626


2627
2628
2629
2630
2631
2632
2633
                lp->datagram = datagram;
                if (datagram) {
                    if (listen[0]) {
                        lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
                        strcpy (lp->port, listen);          /* save port */
                        }
                    else
                        return SCPE_ARG;
                    }
                sock = sim_connect_sock_ex (datagram ? listen : NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
                if (sock != INVALID_SOCKET) {
                    _mux_detach_line (lp, FALSE, TRUE);
                    lp->destination = (char *)malloc(1+strlen(hostport));
                    strcpy (lp->destination, hostport);
                    if (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR)) {
                        lp->connecting = sock;
                        lp->ipad = (char *)malloc (1 + strlen (lp->destination));
                        strcpy (lp->ipad, lp->destination);
                        }
                    else
                        sim_close_sock (sock);
                    lp->notelnet = notelnet;
                    tmxr_init_line (lp);                    /* init the line state */
                    }
                else
                    return SCPE_ARG;
                }
            }
        if (loopback) {
            tmxr_set_line_loopback (lp, loopback);
            sim_printf ("Line %d operating in loopback mode\n", line);
            }
        lp->modem_control = modem_control;


        r = SCPE_OK;
        }
    }
if (r == SCPE_OK)
    tmxr_add_to_open_list (mp);
return r;
}







|

















|







>
>







2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
                lp->datagram = datagram;
                if (datagram) {
                    if (listen[0]) {
                        lp->port = (char *)realloc (lp->port, 1 + strlen (listen));
                        strcpy (lp->port, listen);          /* save port */
                        }
                    else
                        return sim_messagef (SCPE_ARG, "Missing listen port for Datagram socket\n");
                    }
                sock = sim_connect_sock_ex (datagram ? listen : NULL, hostport, "localhost", NULL, (datagram ? SIM_SOCK_OPT_DATAGRAM : 0) | (packet ? SIM_SOCK_OPT_NODELAY : 0));
                if (sock != INVALID_SOCKET) {
                    _mux_detach_line (lp, FALSE, TRUE);
                    lp->destination = (char *)malloc(1+strlen(hostport));
                    strcpy (lp->destination, hostport);
                    if (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR)) {
                        lp->connecting = sock;
                        lp->ipad = (char *)malloc (1 + strlen (lp->destination));
                        strcpy (lp->ipad, lp->destination);
                        }
                    else
                        sim_close_sock (sock);
                    lp->notelnet = notelnet;
                    tmxr_init_line (lp);                    /* init the line state */
                    }
                else
                    return sim_messagef (SCPE_ARG, "Can't open %s socket on %s%s%s\n", datagram ? "Datagram" : "Stream", datagram ? listen : "", datagram ? "<->" : "", hostport);
                }
            }
        if (loopback) {
            tmxr_set_line_loopback (lp, loopback);
            sim_printf ("Line %d operating in loopback mode\n", line);
            }
        lp->modem_control = modem_control;
        if (speed[0] && (!datagram) && (!lp->serport))
            tmxr_set_line_speed (lp, speed);
        r = SCPE_OK;
        }
    }
if (r == SCPE_OK)
    tmxr_add_to_open_list (mp);
return r;
}
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
return SCPE_OK;
}


static TMXR **tmxr_open_devices = NULL;
static int tmxr_open_device_count = 0;

#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_t           sim_tmxr_poll_thread;          /* Polling Thread Id */
#if defined(_WIN32) || defined(VMS)
pthread_t           sim_tmxr_serial_poll_thread;   /* Serial Polling Thread Id */
pthread_cond_t      sim_tmxr_serial_startup_cond;
#endif
pthread_mutex_t     sim_tmxr_poll_lock;
pthread_cond_t      sim_tmxr_poll_cond;
pthread_cond_t      sim_tmxr_startup_cond;
int32               sim_tmxr_poll_count = 0;
t_bool              sim_tmxr_poll_running = FALSE;

static void *
_tmxr_poll(void *arg)
{
int sched_policy;
struct sched_param sched_priority;
struct timeval timeout;
int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT **units = NULL;
UNIT **activated = NULL;
SOCKET *sockets = NULL;
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_poll() - starting\n");

units = (UNIT **)calloc(FD_SETSIZE, sizeof(*units));
activated = (UNIT **)calloc(FD_SETSIZE, sizeof(*activated));
sockets = (SOCKET *)calloc(FD_SETSIZE, sizeof(*sockets));
timeout_usec = 1000000;







|














<
<











<
|
<







2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974


2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985

2986

2987
2988
2989
2990
2991
2992
2993
return SCPE_OK;
}


static TMXR **tmxr_open_devices = NULL;
static int tmxr_open_device_count = 0;

#if defined(SIM_ASYNCH_MUX)
pthread_t           sim_tmxr_poll_thread;          /* Polling Thread Id */
#if defined(_WIN32) || defined(VMS)
pthread_t           sim_tmxr_serial_poll_thread;   /* Serial Polling Thread Id */
pthread_cond_t      sim_tmxr_serial_startup_cond;
#endif
pthread_mutex_t     sim_tmxr_poll_lock;
pthread_cond_t      sim_tmxr_poll_cond;
pthread_cond_t      sim_tmxr_startup_cond;
int32               sim_tmxr_poll_count = 0;
t_bool              sim_tmxr_poll_running = FALSE;

static void *
_tmxr_poll(void *arg)
{


struct timeval timeout;
int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT **units = NULL;
UNIT **activated = NULL;
SOCKET *sockets = NULL;
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_poll() - starting\n");

units = (UNIT **)calloc(FD_SETSIZE, sizeof(*units));
activated = (UNIT **)calloc(FD_SETSIZE, sizeof(*activated));
sockets = (SOCKET *)calloc(FD_SETSIZE, sizeof(*sockets));
timeout_usec = 1000000;
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
return NULL;
}

#if defined(_WIN32)
static void *
_tmxr_serial_poll(void *arg)
{
int sched_policy;
struct sched_param sched_priority;
int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT **units = NULL;
UNIT **activated = NULL;
SERHANDLE *serports = NULL;
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - starting\n");

units = (UNIT **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*units));
activated = (UNIT **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*activated));
serports = (SERHANDLE *)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*serports));
timeout_usec = 1000000;







<
<










<
|
<







3184
3185
3186
3187
3188
3189
3190


3191
3192
3193
3194
3195
3196
3197
3198
3199
3200

3201

3202
3203
3204
3205
3206
3207
3208
return NULL;
}

#if defined(_WIN32)
static void *
_tmxr_serial_poll(void *arg)
{


int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT **units = NULL;
UNIT **activated = NULL;
SERHANDLE *serports = NULL;
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - starting\n");

units = (UNIT **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*units));
activated = (UNIT **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*activated));
serports = (SERHANDLE *)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*serports));
timeout_usec = 1000000;
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
pthread_cond_t      sim_serial_line_startup_cond;


static void *
_tmxr_serial_line_poll(void *arg)
{
TMLN *lp = (TMLN *)arg;
int sched_policy;
struct sched_param sched_priority;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT *uptr = (lp->uptr ? lp->uptr : lp->mp->uptr);
DEVICE *d = find_dev_from_unit(uptr);
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_line_poll() - starting\n");

pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_serial_line_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_enabled) {
    int i, j;







<
<








<
|
<







3316
3317
3318
3319
3320
3321
3322


3323
3324
3325
3326
3327
3328
3329
3330

3331

3332
3333
3334
3335
3336
3337
3338
pthread_cond_t      sim_serial_line_startup_cond;


static void *
_tmxr_serial_line_poll(void *arg)
{
TMLN *lp = (TMLN *)arg;


DEVICE *dptr = tmxr_open_devices[0]->dptr;
UNIT *uptr = (lp->uptr ? lp->uptr : lp->mp->uptr);
DEVICE *d = find_dev_from_unit(uptr);
int wait_count = 0;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */

sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);


sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_line_poll() - starting\n");

pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_serial_line_startup_cond);   /* Signal we're ready to go */
while (sim_asynch_enabled) {
    int i, j;
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193

return NULL;
}

static void *
_tmxr_serial_poll(void *arg)
{
int sched_policy;
struct sched_param sched_priority;
int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
TMLN **lines = NULL;
pthread_t *threads = NULL;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */
pthread_getschedparam (pthread_self(), &sched_policy, &sched_priority);
++sched_priority.sched_priority;
pthread_setschedparam (pthread_self(), sched_policy, &sched_priority);

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - starting\n");

lines = (TMLN **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*lines));
threads = (pthread_t *)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*threads));
pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_tmxr_serial_startup_cond);   /* Signal we're ready to go */







<
<








<
<
<







3394
3395
3396
3397
3398
3399
3400


3401
3402
3403
3404
3405
3406
3407
3408



3409
3410
3411
3412
3413
3414
3415

return NULL;
}

static void *
_tmxr_serial_poll(void *arg)
{


int timeout_usec;
DEVICE *dptr = tmxr_open_devices[0]->dptr;
TMLN **lines = NULL;
pthread_t *threads = NULL;

/* Boost Priority for this I/O thread vs the CPU instruction execution 
   thread which, in general, won't be readily yielding the processor when 
   this thread needs to run */




sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - starting\n");

lines = (TMLN **)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*lines));
threads = (pthread_t *)calloc(MAXIMUM_WAIT_OBJECTS, sizeof(*threads));
pthread_mutex_lock (&sim_tmxr_poll_lock);
pthread_cond_signal (&sim_tmxr_serial_startup_cond);   /* Signal we're ready to go */
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - exiting\n");

return NULL;
}
#endif /* VMS */

#endif /* defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX) */

t_stat tmxr_start_poll (void)
{
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
if ((tmxr_open_device_count > 0) && 
    sim_asynch_enabled           && 
    sim_is_running               && 
    !sim_tmxr_poll_running) {
    pthread_attr_t attr;








|



|







3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469

sim_debug (TMXR_DBG_ASY, dptr, "_tmxr_serial_poll() - exiting\n");

return NULL;
}
#endif /* VMS */

#endif /* defined(SIM_ASYNCH_MUX) */

t_stat tmxr_start_poll (void)
{
#if defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
if ((tmxr_open_device_count > 0) && 
    sim_asynch_enabled           && 
    sim_is_running               && 
    !sim_tmxr_poll_running) {
    pthread_attr_t attr;

3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
pthread_mutex_unlock (&sim_tmxr_poll_lock);
#endif
return SCPE_OK;
}

t_stat tmxr_stop_poll (void)
{
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
if (sim_tmxr_poll_running) {
    pthread_cond_signal (&sim_tmxr_poll_cond);
    pthread_mutex_unlock (&sim_tmxr_poll_lock);
    pthread_join (sim_tmxr_poll_thread, NULL);
    sim_tmxr_poll_running = FALSE;
    /* Transitioning from asynch mode so kick all polling units onto the event queue */







|







3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
pthread_mutex_unlock (&sim_tmxr_poll_lock);
#endif
return SCPE_OK;
}

t_stat tmxr_stop_poll (void)
{
#if defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
if (sim_tmxr_poll_running) {
    pthread_cond_signal (&sim_tmxr_poll_cond);
    pthread_mutex_unlock (&sim_tmxr_poll_lock);
    pthread_join (sim_tmxr_poll_thread, NULL);
    sim_tmxr_poll_running = FALSE;
    /* Transitioning from asynch mode so kick all polling units onto the event queue */
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
}

static void tmxr_add_to_open_list (TMXR* mux)
{
int i;
t_bool found = FALSE;

#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
#endif
for (i=0; i<tmxr_open_device_count; ++i)
    if (tmxr_open_devices[i] == mux) {
        found = TRUE;
        break;
        }
if (!found) {
    tmxr_open_devices = (TMXR **)realloc(tmxr_open_devices, (tmxr_open_device_count+1)*sizeof(*tmxr_open_devices));
    tmxr_open_devices[tmxr_open_device_count++] = mux;
    for (i=0; i<mux->lines; i++)
        if (0 == mux->ldsc[i].send.delay)
            mux->ldsc[i].send.delay = SEND_DEFAULT_DELAY;
    }
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_mutex_unlock (&sim_tmxr_poll_lock);
if ((tmxr_open_device_count == 1) && (sim_asynch_enabled))
    tmxr_start_poll ();
#endif
}

static void _tmxr_remove_from_open_list (TMXR* mux)
{
int i, j;

#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
tmxr_stop_poll ();
pthread_mutex_lock (&sim_tmxr_poll_lock);
#endif
for (i=0; i<tmxr_open_device_count; ++i)
    if (tmxr_open_devices[i] == mux) {
        for (j=i+1; j<tmxr_open_device_count; ++j)
            tmxr_open_devices[j-1] = tmxr_open_devices[j];
        --tmxr_open_device_count;
        break;
        }
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
pthread_mutex_unlock (&sim_tmxr_poll_lock);
#endif
}

static t_stat _tmxr_locate_line_send_expect (const char *cptr, SEND **snd, EXPECT **exp)
{
char gbuf[CBUFSIZE];







|














|










|










|







3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
}

static void tmxr_add_to_open_list (TMXR* mux)
{
int i;
t_bool found = FALSE;

#if defined(SIM_ASYNCH_MUX)
pthread_mutex_lock (&sim_tmxr_poll_lock);
#endif
for (i=0; i<tmxr_open_device_count; ++i)
    if (tmxr_open_devices[i] == mux) {
        found = TRUE;
        break;
        }
if (!found) {
    tmxr_open_devices = (TMXR **)realloc(tmxr_open_devices, (tmxr_open_device_count+1)*sizeof(*tmxr_open_devices));
    tmxr_open_devices[tmxr_open_device_count++] = mux;
    for (i=0; i<mux->lines; i++)
        if (0 == mux->ldsc[i].send.delay)
            mux->ldsc[i].send.delay = SEND_DEFAULT_DELAY;
    }
#if defined(SIM_ASYNCH_MUX)
pthread_mutex_unlock (&sim_tmxr_poll_lock);
if ((tmxr_open_device_count == 1) && (sim_asynch_enabled))
    tmxr_start_poll ();
#endif
}

static void _tmxr_remove_from_open_list (TMXR* mux)
{
int i, j;

#if defined(SIM_ASYNCH_MUX)
tmxr_stop_poll ();
pthread_mutex_lock (&sim_tmxr_poll_lock);
#endif
for (i=0; i<tmxr_open_device_count; ++i)
    if (tmxr_open_devices[i] == mux) {
        for (j=i+1; j<tmxr_open_device_count; ++j)
            tmxr_open_devices[j-1] = tmxr_open_devices[j];
        --tmxr_open_device_count;
        break;
        }
#if defined(SIM_ASYNCH_MUX)
pthread_mutex_unlock (&sim_tmxr_poll_lock);
#endif
}

static t_stat _tmxr_locate_line_send_expect (const char *cptr, SEND **snd, EXPECT **exp)
{
char gbuf[CBUFSIZE];
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403

3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
#endif
return SCPE_OK;
}


/* Attach unit to master socket */

t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, char *cptr, t_bool async)
{
t_stat r;
int32 i;

r = tmxr_open_master (mp, cptr);                        /* open master socket */
if (r != SCPE_OK)                                       /* error? */
    return r;
mp->uptr = uptr;                                        /* save unit for polling */
uptr->filename = tmxr_mux_attach_string (uptr->filename, mp);/* save */
uptr->flags = uptr->flags | UNIT_ATT;                   /* no more errors */

if ((mp->lines > 1) ||
    ((mp->master == 0) &&
     (mp->ldsc[0].connecting == 0) &&
     (mp->ldsc[0].serport == 0)))
    uptr->dynflags = uptr->dynflags | UNIT_ATTMULT;     /* allow multiple attach commands */

#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
if (!async || (uptr->flags & TMUF_NOASYNCH))            /* if asynch disabled */
    uptr->dynflags |= TMUF_NOASYNCH;                    /* tag as no asynch */
#else
uptr->dynflags |= TMUF_NOASYNCH;                        /* tag as no asynch */
#endif

if (mp->dptr == NULL)                                   /* has device been set? */







|










>






|







3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
#endif
return SCPE_OK;
}


/* Attach unit to master socket */

t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, CONST char *cptr, t_bool async)
{
t_stat r;
int32 i;

r = tmxr_open_master (mp, cptr);                        /* open master socket */
if (r != SCPE_OK)                                       /* error? */
    return r;
mp->uptr = uptr;                                        /* save unit for polling */
uptr->filename = tmxr_mux_attach_string (uptr->filename, mp);/* save */
uptr->flags = uptr->flags | UNIT_ATT;                   /* no more errors */
uptr->tmxr = (void *)mp;
if ((mp->lines > 1) ||
    ((mp->master == 0) &&
     (mp->ldsc[0].connecting == 0) &&
     (mp->ldsc[0].serport == 0)))
    uptr->dynflags = uptr->dynflags | UNIT_ATTMULT;     /* allow multiple attach commands */

#if defined(SIM_ASYNCH_MUX)
if (!async || (uptr->flags & TMUF_NOASYNCH))            /* if asynch disabled */
    uptr->dynflags |= TMUF_NOASYNCH;                    /* tag as no asynch */
#else
uptr->dynflags |= TMUF_NOASYNCH;                        /* tag as no asynch */
#endif

if (mp->dptr == NULL)                                   /* has device been set? */
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
t_stat tmxr_shutdown (void)
{
if (tmxr_open_device_count)
    return SCPE_IERR;
return SCPE_OK;
}

t_stat tmxr_show_open_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc)
{
int i, j;

if (0 == tmxr_open_device_count)
    fprintf(st, "No Attached Multiplexer Devices\n");
else {
    for (i=0; i<tmxr_open_device_count; ++i) {







|







3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
t_stat tmxr_shutdown (void)
{
if (tmxr_open_device_count)
    return SCPE_IERR;
return SCPE_OK;
}

t_stat tmxr_show_open_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc)
{
int i, j;

if (0 == tmxr_open_device_count)
    fprintf(st, "No Attached Multiplexer Devices\n");
else {
    for (i=0; i<tmxr_open_device_count; ++i) {
3471
3472
3473
3474
3475
3476
3477








3478



3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492






3493
3494
3495
3496
3497
3498
3499
            fprintf(st, ", Buffered=%d", mp->buffered);
        attach = tmxr_mux_attach_string (NULL, mp);
        if (attach)
            fprintf(st, ",\n    attached to %s, ", attach);
        free (attach);
        tmxr_show_summ(st, NULL, 0, mp);
        fprintf(st, ", sessions=%d", mp->sessions);








        fprintf(st, "\n");



        for (j = 0; j < mp->lines; j++) {
            lp = mp->ldsc + j;
            if (mp->lines > 1) {
                if (lp->dptr && (mp->dptr != lp->dptr))
                    fprintf (st, "Device: %s ", sim_dname(lp->dptr));
                fprintf (st, "Line: %d", j);
                if (mp->notelnet != lp->notelnet)
                    fprintf (st, " - %stelnet", lp->notelnet ? "no" : "");
                if (lp->uptr && (lp->uptr != lp->mp->uptr))
                    fprintf (st, " - Unit: %s", sim_uname (lp->uptr));
                if (mp->modem_control != lp->modem_control)
                    fprintf(st, ", ModemControl=%s", lp->modem_control ? "enabled" : "disabled");
                if (lp->loopback)
                    fprintf(st, ", Loopback");






                fprintf (st, "\n");
                }
            if ((!lp->sock) && (!lp->connecting) && (!lp->serport) && (!lp->master)) {
                if (lp->modem_control)
                    tmxr_fconns (st, lp, -1);
                continue;
                }







>
>
>
>
>
>
>
>

>
>
>














>
>
>
>
>
>







3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
            fprintf(st, ", Buffered=%d", mp->buffered);
        attach = tmxr_mux_attach_string (NULL, mp);
        if (attach)
            fprintf(st, ",\n    attached to %s, ", attach);
        free (attach);
        tmxr_show_summ(st, NULL, 0, mp);
        fprintf(st, ", sessions=%d", mp->sessions);
        if (mp->lines == 1) {
            if (mp->ldsc->rxbps) {
                fprintf(st, ", Speed=%d", mp->ldsc->rxbps);
                if (mp->ldsc->rxbpsfactor != TMXR_RX_BPS_UNIT_SCALE)
                    fprintf(st, "*%.0f", mp->ldsc->rxbpsfactor/TMXR_RX_BPS_UNIT_SCALE);
                fprintf(st, " bps");
                }
            }
        fprintf(st, "\n");
        if (mp->ring_start_time) {
            fprintf (st, "    incoming Connection from: %s ringing for %d milliseconds\n", mp->ring_ipad, sim_os_msec () - mp->ring_start_time);
            }
        for (j = 0; j < mp->lines; j++) {
            lp = mp->ldsc + j;
            if (mp->lines > 1) {
                if (lp->dptr && (mp->dptr != lp->dptr))
                    fprintf (st, "Device: %s ", sim_dname(lp->dptr));
                fprintf (st, "Line: %d", j);
                if (mp->notelnet != lp->notelnet)
                    fprintf (st, " - %stelnet", lp->notelnet ? "no" : "");
                if (lp->uptr && (lp->uptr != lp->mp->uptr))
                    fprintf (st, " - Unit: %s", sim_uname (lp->uptr));
                if (mp->modem_control != lp->modem_control)
                    fprintf(st, ", ModemControl=%s", lp->modem_control ? "enabled" : "disabled");
                if (lp->loopback)
                    fprintf(st, ", Loopback");
                if (lp->rxbps) {
                    fprintf(st, ", Speed=%d", lp->rxbps);
                    if (lp->rxbpsfactor != TMXR_RX_BPS_UNIT_SCALE)
                        fprintf(st, "*%.0f", lp->rxbpsfactor/TMXR_RX_BPS_UNIT_SCALE);
                    fprintf(st, " bps");
                    }
                fprintf (st, "\n");
                }
            if ((!lp->sock) && (!lp->connecting) && (!lp->serport) && (!lp->master)) {
                if (lp->modem_control)
                    tmxr_fconns (st, lp, -1);
                continue;
                }
3560
3561
3562
3563
3564
3565
3566







3567
3568
3569
3570
3571
3572
3573
    }

if (mp->master)
    sim_close_sock (mp->master);                        /* close master socket */
mp->master = 0;
free (mp->port);
mp->port = NULL;







_tmxr_remove_from_open_list (mp);
return SCPE_OK;
}


/* Detach unit from master socket and close all active network connections 
   and/or serial ports.







>
>
>
>
>
>
>







3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
    }

if (mp->master)
    sim_close_sock (mp->master);                        /* close master socket */
mp->master = 0;
free (mp->port);
mp->port = NULL;
if (mp->ring_sock != INVALID_SOCKET) {
    sim_close_sock (mp->ring_sock);
    mp->ring_sock = INVALID_SOCKET;
    free (mp->ring_ipad);
    mp->ring_ipad = NULL;
    mp->ring_start_time = 0;
    }
_tmxr_remove_from_open_list (mp);
return SCPE_OK;
}


/* Detach unit from master socket and close all active network connections 
   and/or serial ports.
3581
3582
3583
3584
3585
3586
3587

3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603


3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627














3628
3629


3630
3631
3632










3633
3634



3635
3636
3637
3638
3639
3640
3641


























3642
3643
3644






3645
3646
3647
3648
3649
3650
3651
int32 i;

if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;
tmxr_close_master (mp);                                 /* close master socket */
free (uptr->filename);                                  /* free setup string */
uptr->filename = NULL;

mp->last_poll_time = 0;
for (i=0; i < mp->lines; i++) {
    UNIT *uptr = mp->ldsc[i].uptr ? mp->ldsc[i].uptr : mp->uptr;
    UNIT *o_uptr = mp->ldsc[i].o_uptr ? mp->ldsc[i].o_uptr : mp->uptr;

    uptr->dynflags &= ~UNIT_TM_POLL;                    /* no polling */
    o_uptr->dynflags &= ~UNIT_TM_POLL;                  /* no polling */
    }
uptr->flags &= ~(UNIT_ATT);                             /* not attached */
uptr->dynflags &= ~(UNIT_TM_POLL|TMUF_NOASYNCH);        /* no polling, not asynch disabled  */
return SCPE_OK;
}


t_stat tmxr_activate (UNIT *uptr, int32 interval)
{


#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return _sim_activate (uptr, interval);
    }
return SCPE_OK;
#else
return _sim_activate (uptr, interval);
#endif
}

t_stat tmxr_activate_after (UNIT *uptr, int32 usecs_walltime)
{
#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return _sim_activate_after (uptr, usecs_walltime);
    }
return SCPE_OK;
#else
return _sim_activate_after (uptr, usecs_walltime);
#endif
}















t_stat tmxr_clock_coschedule (UNIT *uptr, int32 interval)
{


return tmxr_clock_coschedule_tmr (uptr, 0, interval);
}











t_stat tmxr_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 interval)
{



#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return sim_clock_coschedule (uptr, tmr, interval);
    }
return SCPE_OK;
#else


























return sim_clock_coschedule_tmr (uptr, tmr, interval);
#endif
}







/* Generic Multiplexer attach help */

t_stat tmxr_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
TMXR *mux = (TMXR *)dptr->help_ctx;
t_bool single_line = FALSE;               /* default to Multi-Line help */







>
















>
>
|










|

|










>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
|


>
>
>
>
>
>
>
>
>
>
|

>
>
>
|


|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|


>
>
>
>
>
>







3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
int32 i;

if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;
tmxr_close_master (mp);                                 /* close master socket */
free (uptr->filename);                                  /* free setup string */
uptr->filename = NULL;
uptr->tmxr = NULL;
mp->last_poll_time = 0;
for (i=0; i < mp->lines; i++) {
    UNIT *uptr = mp->ldsc[i].uptr ? mp->ldsc[i].uptr : mp->uptr;
    UNIT *o_uptr = mp->ldsc[i].o_uptr ? mp->ldsc[i].o_uptr : mp->uptr;

    uptr->dynflags &= ~UNIT_TM_POLL;                    /* no polling */
    o_uptr->dynflags &= ~UNIT_TM_POLL;                  /* no polling */
    }
uptr->flags &= ~(UNIT_ATT);                             /* not attached */
uptr->dynflags &= ~(UNIT_TM_POLL|TMUF_NOASYNCH);        /* no polling, not asynch disabled  */
return SCPE_OK;
}


t_stat tmxr_activate (UNIT *uptr, int32 interval)
{
if (uptr->dynflags & UNIT_TMR_UNIT)
    return sim_timer_activate (uptr, interval);
#if defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return _sim_activate (uptr, interval);
    }
return SCPE_OK;
#else
return _sim_activate (uptr, interval);
#endif
}

t_stat tmxr_activate_after (UNIT *uptr, uint32 usecs_walltime)
{
#if defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return _sim_activate_after (uptr, usecs_walltime);
    }
return SCPE_OK;
#else
return _sim_activate_after (uptr, usecs_walltime);
#endif
}

t_stat tmxr_activate_after_abs (UNIT *uptr, uint32 usecs_walltime)
{
#if defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return _sim_activate_after_abs (uptr, usecs_walltime);
    }
return SCPE_OK;
#else
return _sim_activate_after_abs (uptr, usecs_walltime);
#endif
}


t_stat tmxr_clock_coschedule (UNIT *uptr, int32 interval)
{
int32 ticks = (interval + (sim_rtcn_tick_size (0)/2))/sim_rtcn_tick_size (0);/* Convert to ticks */

return tmxr_clock_coschedule_tmr (uptr, 0, ticks);
}

t_stat tmxr_clock_coschedule_abs (UNIT *uptr, int32 interval)
{
int32 ticks = (interval + (sim_rtcn_tick_size (0)/2))/sim_rtcn_tick_size (0);/* Convert to ticks */

sim_cancel (uptr);
return tmxr_clock_coschedule_tmr (uptr, 0, ticks);
}

#define MIN(a,b) (((a) < (b)) ? (a) : (b))

t_stat tmxr_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks)
{
TMXR *mp = (TMXR *)uptr->tmxr;
int32 interval = ticks * sim_rtcn_tick_size (tmr);

#if defined(SIM_ASYNCH_MUX)
if ((!(uptr->dynflags & UNIT_TM_POLL)) || 
    (!sim_asynch_enabled)) {
    return sim_clock_coschedule (uptr, tmr, ticks);
    }
return SCPE_OK;
#else
if (mp) {
    int32 i, soon = interval;
    double sim_gtime_now = sim_gtime ();

    for (i = 0; i < mp->lines; i++) {
        TMLN *lp = &mp->ldsc[i];

        if (tmxr_rqln_bare (lp, FALSE)) {
            int32 due;

            if (lp->rxbps)
                if (lp->rxnexttime > sim_gtime_now)
                    due = (int32)(lp->rxnexttime - sim_gtime_now);
                else
                    due = sim_processing_event ? 1 : 0;     /* avoid potential infinite loop if called from service routine */
            else
                due = (int32)((uptr->wait * sim_timer_inst_per_sec ())/TMXR_RX_BPS_UNIT_SCALE);
            soon = MIN(soon, due);
            }
        }
    if (soon != interval) {
        sim_debug (TIMER_DBG_MUX, &sim_timer_dev, "scheduling %s after %d instructions\n", sim_uname (uptr), soon);
        return _sim_activate (uptr, soon);
        }
    }
sim_debug (TIMER_DBG_MUX, &sim_timer_dev, "coscheduling %s after interval %d ticks\n", sim_uname (uptr), ticks);
return sim_clock_coschedule_tmr (uptr, tmr, ticks);
#endif
}

t_stat tmxr_clock_coschedule_tmr_abs (UNIT *uptr, int32 tmr, int32 ticks)
{
sim_cancel (uptr);
return tmxr_clock_coschedule_tmr (uptr, tmr, ticks);
}

/* Generic Multiplexer attach help */

t_stat tmxr_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
TMXR *mux = (TMXR *)dptr->help_ctx;
t_bool single_line = FALSE;               /* default to Multi-Line help */
3727
3728
3729
3730
3731
3732
3733
































3734
3735
3736
3737
3738
3739
3740
else {
    fprintf (st, "   sim> ATTACH %s Line=n,Connect=ser0\n\n", dptr->name);
    fprintf (st, "or equivalently:\n\n");
    fprintf (st, "   sim> ATTACH %s Line=n,Connect=COM1\n\n", dptr->name);
    if (mux)
        fprintf (st, "Valid line numbers are from 0 thru %d\n\n", mux->lines-1);
    }
































fprintf (st, "An optional serial port configuration string may be present after the port\n");
fprintf (st, "name.  If present, it must be separated from the port name with a semicolon\n");
fprintf (st, "and has this form:\n\n");
fprintf (st, "   <rate>-<charsize><parity><stopbits>\n\n");
fprintf (st, "where:\n");
fprintf (st, "   rate     = communication rate in bits per second\n");
fprintf (st, "   charsize = character size in bits (5-8, including optional parity)\n");







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
else {
    fprintf (st, "   sim> ATTACH %s Line=n,Connect=ser0\n\n", dptr->name);
    fprintf (st, "or equivalently:\n\n");
    fprintf (st, "   sim> ATTACH %s Line=n,Connect=COM1\n\n", dptr->name);
    if (mux)
        fprintf (st, "Valid line numbers are from 0 thru %d\n\n", mux->lines-1);
    }
if (single_line) {          /* Single Line Multiplexer */
    fprintf (st, "The input data rate for the %s device can be controlled by\n", dptr->name);
    fprintf (st, "specifying SPEED=nnn{*fac} on the the ATTACH command.\n");
    }
else {
    fprintf (st, "The input data rate for all lines or a particular line of a the %s\n", dptr->name);
    fprintf (st, "device can be controlled by specifying SPEED=nnn{*fac} on the ATTACH command.\n");
    }
fprintf (st, "SPEED values can be any one of:\n\n");
fprintf (st, "    0 50 75 110 134 150 300 600 1200 1800 2000 2400\n");
fprintf (st, "    3600 4800 7200 9600 19200 38400 57600 76800 115200\n\n");
fprintf (st, "A SPEED value of 0 causes input data to be delivered to the simulated\n");
fprintf (st, "port as fast as it arrives.\n\n");
fprintf (st, "If a simulated multiplexor devices can programmatically set a serial\n");
fprintf (st, "port line speed, the programmatically specified speed will take precidence\n");
fprintf (st, "over any input speed specified on an attach command.\n");
fprintf (st, "Some simulated systems run very much faster than the original system\n");
fprintf (st, "which is being simulated.  To accommodate this, the speed specified may\n");
fprintf (st, "include a factor which will increase the input data delivery rate by\n");
fprintf (st, "the specified factor.  A factor is specified with a speed value of the\n");
fprintf (st, "form \"speed*factor\".  Factor values can range from 1 thru 32.\n");
fprintf (st, "Example:\n\n");
fprintf (st, "   sim> ATTACH %s 1234,SPEED=2400\n", dptr->name);
fprintf (st, "   sim> ATTACH %s 1234,SPEED=9600*8\n", dptr->name);
if (!single_line)
    fprintf (st, "   sim> ATTACH %s Line=2,SPEED=2400\n", dptr->name);
fprintf (st, "\n");
fprintf (st, "The SPEED parameter only influences the rate at which data is deliverd\n");
fprintf (st, "into the simulated multiplexor port.  Output data rates are unaffected\n");
fprintf (st, "If an attach command specifies a speed multiply factor, that value will\n");
fprintf (st, "persist independent of any programatic action by the simulated system to\n");
fprintf (st, "change the port speed.\n\n");
fprintf (st, "An optional serial port configuration string may be present after the port\n");
fprintf (st, "name.  If present, it must be separated from the port name with a semicolon\n");
fprintf (st, "and has this form:\n\n");
fprintf (st, "   <rate>-<charsize><parity><stopbits>\n\n");
fprintf (st, "where:\n");
fprintf (st, "   rate     = communication rate in bits per second\n");
fprintf (st, "   charsize = character size in bits (5-8, including optional parity)\n");
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
    free (buf);
return;
}


/* Print connections - used only in named SHOW command */

void tmxr_fconns (FILE *st, TMLN *lp, int32 ln)
{
int32 hr, mn, sc;
uint32 ctime;

if (ln >= 0)
    fprintf (st, "line %d: ", ln);








|







4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
    free (buf);
return;
}


/* Print connections - used only in named SHOW command */

void tmxr_fconns (FILE *st, const TMLN *lp, int32 ln)
{
int32 hr, mn, sc;
uint32 ctime;

if (ln >= 0)
    fprintf (st, "line %d: ", ln);

3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
    fprintf (st, " Logging to %s\n", lp->txlogname);
return;
}


/* Print statistics - used only in named SHOW command */

void tmxr_fstats (FILE *st, TMLN *lp, int32 ln)
{
static const char *enab = "on";
static const char *dsab = "off";

if (ln >= 0)
    fprintf (st, "Line %d:", ln);
if ((!lp->sock) && (!lp->connecting) && (!lp->serport))







|







4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
    fprintf (st, " Logging to %s\n", lp->txlogname);
return;
}


/* Print statistics - used only in named SHOW command */

void tmxr_fstats (FILE *st, const TMLN *lp, int32 ln)
{
static const char *enab = "on";
static const char *dsab = "off";

if (ln >= 0)
    fprintf (st, "Line %d:", ln);
if ((!lp->sock) && (!lp->connecting) && (!lp->serport))
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
   connection will be closed.

   Implementation notes:

    1. This function is usually called as an MTAB processing routine.
*/

t_stat tmxr_dscln (UNIT *uptr, int32 val, char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;
t_stat status;

if (val)                                                        /* explicit line? */
    uptr = NULL;                                                /* indicate to get routine */







|







4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
   connection will be closed.

   Implementation notes:

    1. This function is usually called as an MTAB processing routine.
*/

t_stat tmxr_dscln (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;
t_stat status;

if (val)                                                        /* explicit line? */
    uptr = NULL;                                                /* indicate to get routine */
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082

return SCPE_OK;
}


/* Enable logging for line */

t_stat tmxr_set_log (UNIT *uptr, int32 val, char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;

if (cptr == NULL)                                       /* no file name? */
    return SCPE_2FARG;
lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */







|







4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425

return SCPE_OK;
}


/* Enable logging for line */

t_stat tmxr_set_log (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;

if (cptr == NULL)                                       /* no file name? */
    return SCPE_2FARG;
lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119

4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
    lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return SCPE_OK;
}


/* Disable logging for line */

t_stat tmxr_set_nolog (UNIT *uptr, int32 val, char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;

if (cptr)                                               /* no arguments */
    return SCPE_2MARG;
lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */
if (lp == NULL)
    return SCPE_IERR;
if (lp->txlog) {                                        /* logging? */
    sim_close_logfile (&lp->txlogref);                  /* close log */
    free (lp->txlogname);                               /* free namebuf */
    lp->txlog = NULL;
    lp->txlogname = NULL;
    }

lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return SCPE_OK;
}


/* Show logging status for line */

t_stat tmxr_show_log (FILE *st, UNIT *uptr, int32 val, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;

lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */
if (lp == NULL)
    return SCPE_IERR;
if (lp->txlog)
    fprintf (st, "logging to %s", lp->txlogname);







|















>
|






|

|







4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
    lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return SCPE_OK;
}


/* Disable logging for line */

t_stat tmxr_set_nolog (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;
TMLN *lp;

if (cptr)                                               /* no arguments */
    return SCPE_2MARG;
lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */
if (lp == NULL)
    return SCPE_IERR;
if (lp->txlog) {                                        /* logging? */
    sim_close_logfile (&lp->txlogref);                  /* close log */
    free (lp->txlogname);                               /* free namebuf */
    lp->txlog = NULL;
    lp->txlogname = NULL;
    }
if (mp->uptr)
    lp->mp->uptr->filename = tmxr_mux_attach_string (lp->mp->uptr->filename, lp->mp);
return SCPE_OK;
}


/* Show logging status for line */

t_stat tmxr_show_log (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const TMXR *mp = (const TMXR *) desc;
TMLN *lp;

lp = tmxr_find_ldsc (uptr, val, mp);                    /* find line desc */
if (lp == NULL)
    return SCPE_IERR;
if (lp->txlog)
    fprintf (st, "logging to %s", lp->txlogname);
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172

4173

4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197


4198
4199
4200

4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
   array are set to the order specified by the command string.  All values are
   populated, first with those explicitly specified in the command string, and
   then in ascending sequence with those not specified.

   If an error occurs, the original line order is not disturbed.
*/

t_stat tmxr_set_lnorder (UNIT *uptr, int32 val, char *cptr, void *desc)
{
TMXR *mp = (TMXR *) desc;

char *tptr;

t_addr low, high, max = (t_addr) mp->lines - 1;
int32 *list;
t_bool *set;
uint32 line, idx = 0;
t_stat result = SCPE_OK;

if (mp->lnorder == NULL)                                /* line connection order undefined? */
    return SCPE_NXPAR;                                  /* "Non-existent parameter" error */

else if ((cptr == NULL) || (*cptr == '\0'))             /* line range not supplied? */
    return SCPE_MISVAL;                                 /* "Missing value" error */

list = (int32 *) calloc (mp->lines, sizeof (int32));    /* allocate new line order array */

if (list == NULL)                                       /* allocation failed? */
    return SCPE_MEM;                                    /* report it */

set = (t_bool *) calloc (mp->lines, sizeof (t_bool));   /* allocate line set tracking array */

if (set == NULL) {                                      /* allocation failed? */
    free (list);                                        /* free successful list allocation */
    return SCPE_MEM;                                    /* report it */
    }



tptr = cptr + strlen (cptr);                            /* append a semicolon */
*tptr++ = ';';                                          /*   to the command string */
*tptr = '\0';                                           /*   to make parsing easier for get_range */


while (*cptr) {                                         /* parse command string */
    cptr = (char *)get_range (NULL, cptr, &low, &high, 10, max, ';');/* get a line range */

    if (cptr == NULL) {                                 /* parsing error? */
        result = SCPE_ARG;                              /* "Invalid argument" error */
        break;
        }

    else if ((low > max) || (high > max)) {             /* line out of range? */







|


>

>









|














>
>
|


>


|







4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
   array are set to the order specified by the command string.  All values are
   populated, first with those explicitly specified in the command string, and
   then in ascending sequence with those not specified.

   If an error occurs, the original line order is not disturbed.
*/

t_stat tmxr_set_lnorder (UNIT *uptr, int32 val, CONST char *carg, void *desc)
{
TMXR *mp = (TMXR *) desc;
char *tbuf;
char *tptr;
CONST char *cptr;
t_addr low, high, max = (t_addr) mp->lines - 1;
int32 *list;
t_bool *set;
uint32 line, idx = 0;
t_stat result = SCPE_OK;

if (mp->lnorder == NULL)                                /* line connection order undefined? */
    return SCPE_NXPAR;                                  /* "Non-existent parameter" error */

else if ((carg == NULL) || (*carg == '\0'))             /* line range not supplied? */
    return SCPE_MISVAL;                                 /* "Missing value" error */

list = (int32 *) calloc (mp->lines, sizeof (int32));    /* allocate new line order array */

if (list == NULL)                                       /* allocation failed? */
    return SCPE_MEM;                                    /* report it */

set = (t_bool *) calloc (mp->lines, sizeof (t_bool));   /* allocate line set tracking array */

if (set == NULL) {                                      /* allocation failed? */
    free (list);                                        /* free successful list allocation */
    return SCPE_MEM;                                    /* report it */
    }

tbuf = (char *) calloc (strlen(carg)+2, sizeof(*carg));
strcpy (tbuf, carg);
tptr = tbuf + strlen (tbuf);                            /* append a semicolon */
*tptr++ = ';';                                          /*   to the command string */
*tptr = '\0';                                           /*   to make parsing easier for get_range */
cptr = tbuf;

while (*cptr) {                                         /* parse command string */
    cptr = get_range (NULL, cptr, &low, &high, 10, max, ';');/* get a line range */

    if (cptr == NULL) {                                 /* parsing error? */
        result = SCPE_ARG;                              /* "Invalid argument" error */
        break;
        }

    else if ((low > max) || (high > max)) {             /* line out of range? */
4236
4237
4238
4239
4240
4241
4242

4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
                }

    memcpy (mp->lnorder, list, mp->lines * sizeof (int32)); /* copy working array to connection array */
    }

free (list);                                            /* free list allocation */
free (set);                                             /* free set allocation */


return result;
}


/* Show line connection order.

   Parameters:
    - st   = stream on which output is to be written
    - uptr = (not used)
    - val  = (not used)
    - desc = pointer to multiplexer's TMXR structure

   If a connection order array is not defined in the multiplexer descriptor, the
   command is rejected.  If the first value of the connection order array is set
   to -1, then the connection order is sequential.  Otherwise, the line values
   in the array are printed as a semicolon-separated list.  Ranges are printed
   where possible to shorten the output.
*/

t_stat tmxr_show_lnorder (FILE *st, UNIT *uptr, int32 val, void *desc)
{
int32 i, j, low, last;
TMXR *mp = (TMXR *) desc;
int32 *iptr = mp->lnorder;
t_bool first = TRUE;

if (iptr == NULL)                                       /* connection order undefined? */
    return SCPE_NXPAR;                                  /* "Non-existent parameter" error */

if (*iptr < 0)                                          /* sequential order indicated? */







>




















|


|







4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
                }

    memcpy (mp->lnorder, list, mp->lines * sizeof (int32)); /* copy working array to connection array */
    }

free (list);                                            /* free list allocation */
free (set);                                             /* free set allocation */
free (tbuf);                                            /* free arg copy with ; */

return result;
}


/* Show line connection order.

   Parameters:
    - st   = stream on which output is to be written
    - uptr = (not used)
    - val  = (not used)
    - desc = pointer to multiplexer's TMXR structure

   If a connection order array is not defined in the multiplexer descriptor, the
   command is rejected.  If the first value of the connection order array is set
   to -1, then the connection order is sequential.  Otherwise, the line values
   in the array are printed as a semicolon-separated list.  Ranges are printed
   where possible to shorten the output.
*/

t_stat tmxr_show_lnorder (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
int32 i, j, low, last;
const TMXR *mp = (const TMXR *) desc;
int32 *iptr = mp->lnorder;
t_bool first = TRUE;

if (iptr == NULL)                                       /* connection order undefined? */
    return SCPE_NXPAR;                                  /* "Non-existent parameter" error */

if (*iptr < 0)                                          /* sequential order indicated? */
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
    fputc ('\n', st);

return SCPE_OK;
}

/* Show summary processor */

t_stat tmxr_show_summ (FILE *st, UNIT *uptr, int32 val, void *desc)
{
TMXR *mp = (TMXR *) desc;
int32 i, t;

if (mp == NULL)
    return SCPE_IERR;
for (i = t = 0; i < mp->lines; i++)
    if ((mp->ldsc[i].sock != 0) || (mp->ldsc[i].serport != 0))
        t = t + 1;
if (mp->lines > 1)
    fprintf (st, "%d current connection%s", t, (t != 1) ? "s" : "");
else
    fprintf (st, "%s", (t == 1) ? "connected" : "disconnected");
return SCPE_OK;
}

/* Show conn/stat processor */

t_stat tmxr_show_cstat (FILE *st, UNIT *uptr, int32 val, void *desc)
{
TMXR *mp = (TMXR *) desc;
int32 i, any;

if (mp == NULL)
    return SCPE_IERR;
for (i = any = 0; i < mp->lines; i++) {
    if ((mp->ldsc[i].sock != 0) || 
        (mp->ldsc[i].serport != 0) || mp->ldsc[i].modem_control) {







|

|
















|

|







4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
    fputc ('\n', st);

return SCPE_OK;
}

/* Show summary processor */

t_stat tmxr_show_summ (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const TMXR *mp = (const TMXR *) desc;
int32 i, t;

if (mp == NULL)
    return SCPE_IERR;
for (i = t = 0; i < mp->lines; i++)
    if ((mp->ldsc[i].sock != 0) || (mp->ldsc[i].serport != 0))
        t = t + 1;
if (mp->lines > 1)
    fprintf (st, "%d current connection%s", t, (t != 1) ? "s" : "");
else
    fprintf (st, "%s", (t == 1) ? "connected" : "disconnected");
return SCPE_OK;
}

/* Show conn/stat processor */

t_stat tmxr_show_cstat (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const TMXR *mp = (const TMXR *) desc;
int32 i, any;

if (mp == NULL)
    return SCPE_IERR;
for (i = any = 0; i < mp->lines; i++) {
    if ((mp->ldsc[i].sock != 0) || 
        (mp->ldsc[i].serport != 0) || mp->ldsc[i].modem_control) {
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
if (any == 0)
    fprintf (st, (mp->lines == 1? "disconnected\n": "all disconnected\n"));
return SCPE_OK;
}

/* Show number of lines */

t_stat tmxr_show_lines (FILE *st, UNIT *uptr, int32 val, void *desc)
{
TMXR *mp = (TMXR *) desc;

if (mp == NULL)
    return SCPE_IERR;
fprintf (st, "lines=%d", mp->lines);
return SCPE_OK;
}








|

|







4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
if (any == 0)
    fprintf (st, (mp->lines == 1? "disconnected\n": "all disconnected\n"));
return SCPE_OK;
}

/* Show number of lines */

t_stat tmxr_show_lines (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
const TMXR *mp = (const TMXR *) desc;

if (mp == NULL)
    return SCPE_IERR;
fprintf (st, "lines=%d", mp->lines);
return SCPE_OK;
}

Changes to src/sim_tmxr.h.
42
43
44
45
46
47
48




49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73
   30-Dec-01    RMS     Renamed tmxr_fstatus, added tmxr_fstats
   20-Oct-01    RMS     Removed tmxr_getchar, formalized buffer guard,
                        added tmxr_rqln, tmxr_tqln
*/

#ifndef SIM_TMXR_H_
#define SIM_TMXR_H_    0





#ifndef SIMH_SERHANDLE_DEFINED
#define SIMH_SERHANDLE_DEFINED 0
#if defined (_WIN32)                            /* Windows definitions */
typedef void *SERHANDLE;
#else                                           /* all other platforms */
typedef int SERHANDLE;
#endif
#endif

#include "sim_sock.h"

#define TMXR_V_VALID    15
#define TMXR_VALID      (1 << TMXR_V_VALID)
#define TMXR_MAXBUF     256                             /* buffer size */
#define TMXR_GUARD      12                              /* buffer guard */

#define TMXR_DTR_DROP_TIME 500                          /* milliseconds to drop DTR for 'pseudo' modem control */

#define TMXR_DEFAULT_CONNECT_POLL_INTERVAL 1            /* seconds between connection polls */

#define TMXR_DBG_XMT    0x0010000                        /* Debug Transmit Data */
#define TMXR_DBG_RCV    0x0020000                        /* Debug Received Data */
#define TMXR_DBG_RET    0x0040000                        /* Debug Returned Received Data */
#define TMXR_DBG_MDM    0x0080000                        /* Debug Modem Signals */
#define TMXR_DBG_CON    0x0100000                        /* Debug Connection Activities */







>
>
>
>



<
|
<
<
<







<


>







42
43
44
45
46
47
48
49
50
51
52
53
54
55

56



57
58
59
60
61
62
63

64
65
66
67
68
69
70
71
72
73
   30-Dec-01    RMS     Renamed tmxr_fstatus, added tmxr_fstats
   20-Oct-01    RMS     Removed tmxr_getchar, formalized buffer guard,
                        added tmxr_rqln, tmxr_tqln
*/

#ifndef SIM_TMXR_H_
#define SIM_TMXR_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

#ifndef SIMH_SERHANDLE_DEFINED
#define SIMH_SERHANDLE_DEFINED 0

typedef struct SERPORT *SERHANDLE;



#endif

#include "sim_sock.h"

#define TMXR_V_VALID    15
#define TMXR_VALID      (1 << TMXR_V_VALID)
#define TMXR_MAXBUF     256                             /* buffer size */


#define TMXR_DTR_DROP_TIME 500                          /* milliseconds to drop DTR for 'pseudo' modem control */
#define TMXR_MODEM_RING_TIME 3                          /* seconds to wait for DTR for incoming connections */
#define TMXR_DEFAULT_CONNECT_POLL_INTERVAL 1            /* seconds between connection polls */

#define TMXR_DBG_XMT    0x0010000                        /* Debug Transmit Data */
#define TMXR_DBG_RCV    0x0020000                        /* Debug Received Data */
#define TMXR_DBG_RET    0x0040000                        /* Debug Returned Received Data */
#define TMXR_DBG_MDM    0x0080000                        /* Debug Modem Signals */
#define TMXR_DBG_CON    0x0100000                        /* Debug Connection Activities */
92
93
94
95
96
97
98
























99
100
101
102
103
104
105
/* Unit flags */

#define TMUF_V_NOASYNCH   (UNIT_V_UF + 12)              /* Asynch Disabled unit */
#define TMUF_NOASYNCH     (1u << TMUF_V_NOASYNCH)       /* This flag can be defined */
                                                        /* statically in a unit's flag field */
                                                        /* This will disable the unit from */
                                                        /* supporting asynchronmous mux behaviors */

























typedef struct tmln TMLN;
typedef struct tmxr TMXR;
struct loopbuf {
    int32               bpr;                          /* xmt buf remove */
    int32               bpi;                          /* xmt buf insert */
    int32               size;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* Unit flags */

#define TMUF_V_NOASYNCH   (UNIT_V_UF + 12)              /* Asynch Disabled unit */
#define TMUF_NOASYNCH     (1u << TMUF_V_NOASYNCH)       /* This flag can be defined */
                                                        /* statically in a unit's flag field */
                                                        /* This will disable the unit from */
                                                        /* supporting asynchronmous mux behaviors */
/* Receive line speed limits */

#define TMLN_SPD_50_BPS     200000 /* usec per character */
#define TMLN_SPD_75_BPS     133333 /* usec per character */
#define TMLN_SPD_110_BPS     90909 /* usec per character */
#define TMLN_SPD_134_BPS     74626 /* usec per character */
#define TMLN_SPD_150_BPS     66666 /* usec per character */
#define TMLN_SPD_300_BPS     33333 /* usec per character */
#define TMLN_SPD_600_BPS     16666 /* usec per character */
#define TMLN_SPD_1200_BPS     8333 /* usec per character */
#define TMLN_SPD_1800_BPS     5555 /* usec per character */
#define TMLN_SPD_2000_BPS     5000 /* usec per character */
#define TMLN_SPD_2400_BPS     4166 /* usec per character */
#define TMLN_SPD_3600_BPS     2777 /* usec per character */
#define TMLN_SPD_4800_BPS     2083 /* usec per character */
#define TMLN_SPD_7200_BPS     1388 /* usec per character */
#define TMLN_SPD_9600_BPS     1041 /* usec per character */
#define TMLN_SPD_19200_BPS     520 /* usec per character */
#define TMLN_SPD_38400_BPS     260 /* usec per character */
#define TMLN_SPD_57600_BPS     173 /* usec per character */
#define TMLN_SPD_76800_BPS     130 /* usec per character */
#define TMLN_SPD_115200_BPS     86 /* usec per character */



typedef struct tmln TMLN;
typedef struct tmxr TMXR;
struct loopbuf {
    int32               bpr;                          /* xmt buf remove */
    int32               bpi;                          /* xmt buf insert */
    int32               size;
138
139
140
141
142
143
144








145
146
147
148
149
150
151
    char                *txlogname;                     /* xmt log file name */
    char                *rxb;                           /* rcv buffer */
    char                *rbr;                           /* rcv break */
    char                *txb;                           /* xmt buffer */
    uint8               *rxpb;                          /* rcv packet buffer */
    uint32              rxpbsize;                       /* rcv packet buffer size */
    uint32              rxpboffset;                     /* rcv packet buffer offset */








    uint8               *txpb;                          /* xmt packet buffer */
    uint32              txpbsize;                       /* xmt packet buffer size */
    uint32              txppsize;                       /* xmt packet packet size */
    uint32              txppoffset;                     /* xmt packet buffer offset */
    TMXR                *mp;                            /* back pointer to mux */
    char                *serconfig;                     /* line config */
    SERHANDLE           serport;                        /* serial port handle */







>
>
>
>
>
>
>
>







162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    char                *txlogname;                     /* xmt log file name */
    char                *rxb;                           /* rcv buffer */
    char                *rbr;                           /* rcv break */
    char                *txb;                           /* xmt buffer */
    uint8               *rxpb;                          /* rcv packet buffer */
    uint32              rxpbsize;                       /* rcv packet buffer size */
    uint32              rxpboffset;                     /* rcv packet buffer offset */
    uint32              rxbps;                          /* rcv bps speed (0 - unlimited) */
    double              rxbpsfactor;                    /* receive speed factor (scaled to usecs) */
#define TMXR_RX_BPS_UNIT_SCALE 1000000.0
    uint32              rxdelta;                        /* rcv inter character min time (usecs) */
    double              rxnexttime;                     /* min time for next receive character */
    uint32              txbps;                          /* xmt bps speed (0 - unlimited) */
    uint32              txdelta;                        /* xmt inter character min time (usecs) */
    double              txnexttime;                     /* min time for next transmit character */
    uint8               *txpb;                          /* xmt packet buffer */
    uint32              txpbsize;                       /* xmt packet buffer size */
    uint32              txppsize;                       /* xmt packet packet size */
    uint32              txppoffset;                     /* xmt packet buffer offset */
    TMXR                *mp;                            /* back pointer to mux */
    char                *serconfig;                     /* line config */
    SERHANDLE           serport;                        /* serial port handle */
178
179
180
181
182
183
184



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

246

247

248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263




264
265



266
267
268

269

270

271
272
273
274
275

276
277
    UNIT                *uptr;                          /* polling unit (connection) */
    char                logfiletmpl[FILENAME_MAX];      /* template logfile name */
    int32               txcount;                        /* count of transmit bytes */
    int32               buffered;                       /* Buffered Line Behavior and Buffer Size Flag */
    int32               sessions;                       /* count of tcp connections received */
    uint32              poll_interval;                  /* frequency of connection polls (seconds) */
    uint32              last_poll_time;                 /* time of last connection poll */



    t_bool              notelnet;                       /* default telnet capability for incoming connections */
    t_bool              modem_control;                  /* multiplexer supports modem control behaviors */
    t_bool              packet;                         /* Lines are packet oriented */
    t_bool              datagram;                       /* Lines use datagram packet transport */
    };

int32 tmxr_poll_conn (TMXR *mp);
t_stat tmxr_reset_ln (TMLN *lp);
t_stat tmxr_detach_ln (TMLN *lp);
int32 tmxr_input_pending_ln (TMLN *lp);
int32 tmxr_getc_ln (TMLN *lp);
t_stat tmxr_get_packet_ln (TMLN *lp, const uint8 **pbuf, size_t *psize);
t_stat tmxr_get_packet_ln_ex (TMLN *lp, const uint8 **pbuf, size_t *psize, uint8 frame_byte);
void tmxr_poll_rx (TMXR *mp);
t_stat tmxr_putc_ln (TMLN *lp, int32 chr);
t_stat tmxr_put_packet_ln (TMLN *lp, const uint8 *buf, size_t size);
t_stat tmxr_put_packet_ln_ex (TMLN *lp, const uint8 *buf, size_t size, uint8 frame_byte);
void tmxr_poll_tx (TMXR *mp);
int32 tmxr_send_buffered_data (TMLN *lp);
t_stat tmxr_open_master (TMXR *mp, char *cptr);
t_stat tmxr_close_master (TMXR *mp);
t_stat tmxr_connection_poll_interval (TMXR *mp, uint32 seconds);
t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, char *cptr, t_bool async);
t_stat tmxr_detach (TMXR *mp, UNIT *uptr);
t_stat tmxr_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
char *tmxr_line_attach_string(TMLN *lp);
t_stat tmxr_set_modem_control_passthru (TMXR *mp);
t_stat tmxr_clear_modem_control_passthru (TMXR *mp);
t_stat tmxr_set_get_modem_bits (TMLN *lp, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits);
t_stat tmxr_set_line_loopback (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_loopback (TMLN *lp);
t_stat tmxr_set_line_halfduplex (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_halfduplex (TMLN *lp);

t_stat tmxr_set_config_line (TMLN *lp, const char *config);
t_stat tmxr_set_line_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_line_output_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_console_units (UNIT *rxuptr, UNIT *txuptr);
t_stat tmxr_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw);
t_stat tmxr_dep (t_value val, t_addr addr, UNIT *uptr, int32 sw);
void tmxr_msg (SOCKET sock, const char *msg);
void tmxr_linemsg (TMLN *lp, const char *msg);
void tmxr_linemsgf (TMLN *lp, const char *fmt, ...);
void tmxr_linemsgvf (TMLN *lp, const char *fmt, va_list args);
void tmxr_fconns (FILE *st, TMLN *lp, int32 ln);
void tmxr_fstats (FILE *st, TMLN *lp, int32 ln);
t_stat tmxr_set_log (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat tmxr_set_nolog (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat tmxr_show_log (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat tmxr_dscln (UNIT *uptr, int32 val, char *cptr, void *desc);
int32 tmxr_rqln (TMLN *lp);
int32 tmxr_tqln (TMLN *lp);
int32 tmxr_tpqln (TMLN *lp);
t_bool tmxr_tpbusyln (TMLN *lp);
t_stat tmxr_set_lnorder (UNIT *uptr, int32 val, char *cptr, void *desc);
t_stat tmxr_show_lnorder (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat tmxr_show_summ (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat tmxr_show_cstat (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat tmxr_show_lines (FILE *st, UNIT *uptr, int32 val, void *desc);
t_stat tmxr_show_open_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, char* desc);
t_stat tmxr_activate (UNIT *uptr, int32 interval);
t_stat tmxr_activate_after (UNIT *uptr, int32 usecs_walltime);

t_stat tmxr_clock_coschedule (UNIT *uptr, int32 interval);

t_stat tmxr_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 interval);

t_stat tmxr_change_async (void);
t_stat tmxr_locate_line_send (const char *dev_line, SEND **snd);
t_stat tmxr_locate_line_expect (const char *dev_line, EXPECT **exp);
t_stat tmxr_startup (void);
t_stat tmxr_shutdown (void);
t_stat tmxr_start_poll (void);
t_stat tmxr_stop_poll (void);
void _tmxr_debug (uint32 dbits, TMLN *lp, const char *msg, char *buf, int bufsize);
#define tmxr_debug(dbits, lp, msg, buf, bufsize) if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) _tmxr_debug (dbits, lp, msg, buf, bufsize); else (void)0
#define tmxr_debug_msg(dbits, lp, msg) if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) sim_debug (dbits, (lp)->mp->dptr, msg); else (void)0
#define tmxr_debug_return(lp, val) if (sim_deb && (val) && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_RET & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_RET, (lp)->mp->dptr, "Ln%d: 0x%x\n", (int)((lp)-(lp)->mp->ldsc), val); else (void)0
#define tmxr_debug_trace(mp, msg) if (sim_deb && (mp)->dptr && (TMXR_DBG_TRC & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, mp->dptr, "%s\n", (msg)); else (void)0
#define tmxr_debug_trace_line(lp, msg) if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_TRC & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); else (void)0
#define tmxr_debug_connect(mp, msg) if (sim_deb && (mp)->dptr && (TMXR_DBG_CON & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_CON, mp->dptr, "%s\n", (msg)); else (void)0
#define tmxr_debug_connect_line(lp, msg) if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_CON & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_CON, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); else (void)0





#if defined(SIM_ASYNCH_IO) && defined(SIM_ASYNCH_MUX)
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, TRUE)



#if (!defined(NOT_MUX_USING_CODE))
#define sim_activate tmxr_activate
#define sim_activate_after tmxr_activate_after

#define sim_clock_coschedule tmxr_clock_coschedule 

#define sim_clock_coschedule_tmr tmxr_clock_coschedule_tmr

#endif
#else
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, FALSE)
#endif



#endif /* _SIM_TMXR_H_ */







>
>
>



















|


|










>
|









|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
>

>
|
>








|
|
|
|
|
|
|

>
>
>
>
|

>
>
>



>

>

>

|
|
|
|
>


210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    UNIT                *uptr;                          /* polling unit (connection) */
    char                logfiletmpl[FILENAME_MAX];      /* template logfile name */
    int32               txcount;                        /* count of transmit bytes */
    int32               buffered;                       /* Buffered Line Behavior and Buffer Size Flag */
    int32               sessions;                       /* count of tcp connections received */
    uint32              poll_interval;                  /* frequency of connection polls (seconds) */
    uint32              last_poll_time;                 /* time of last connection poll */
    uint32              ring_start_time;                /* time ring signal was raised */
    char                *ring_ipad;                     /* incoming connection address awaiting DTR */
    SOCKET              ring_sock;                      /* incoming connection socket awaiting DTR */
    t_bool              notelnet;                       /* default telnet capability for incoming connections */
    t_bool              modem_control;                  /* multiplexer supports modem control behaviors */
    t_bool              packet;                         /* Lines are packet oriented */
    t_bool              datagram;                       /* Lines use datagram packet transport */
    };

int32 tmxr_poll_conn (TMXR *mp);
t_stat tmxr_reset_ln (TMLN *lp);
t_stat tmxr_detach_ln (TMLN *lp);
int32 tmxr_input_pending_ln (TMLN *lp);
int32 tmxr_getc_ln (TMLN *lp);
t_stat tmxr_get_packet_ln (TMLN *lp, const uint8 **pbuf, size_t *psize);
t_stat tmxr_get_packet_ln_ex (TMLN *lp, const uint8 **pbuf, size_t *psize, uint8 frame_byte);
void tmxr_poll_rx (TMXR *mp);
t_stat tmxr_putc_ln (TMLN *lp, int32 chr);
t_stat tmxr_put_packet_ln (TMLN *lp, const uint8 *buf, size_t size);
t_stat tmxr_put_packet_ln_ex (TMLN *lp, const uint8 *buf, size_t size, uint8 frame_byte);
void tmxr_poll_tx (TMXR *mp);
int32 tmxr_send_buffered_data (TMLN *lp);
t_stat tmxr_open_master (TMXR *mp, CONST char *cptr);
t_stat tmxr_close_master (TMXR *mp);
t_stat tmxr_connection_poll_interval (TMXR *mp, uint32 seconds);
t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, CONST char *cptr, t_bool async);
t_stat tmxr_detach (TMXR *mp, UNIT *uptr);
t_stat tmxr_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
char *tmxr_line_attach_string(TMLN *lp);
t_stat tmxr_set_modem_control_passthru (TMXR *mp);
t_stat tmxr_clear_modem_control_passthru (TMXR *mp);
t_stat tmxr_set_get_modem_bits (TMLN *lp, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits);
t_stat tmxr_set_line_loopback (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_loopback (TMLN *lp);
t_stat tmxr_set_line_halfduplex (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_halfduplex (TMLN *lp);
t_stat tmxr_set_line_speed (TMLN *lp, CONST char *speed);
t_stat tmxr_set_config_line (TMLN *lp, CONST char *config);
t_stat tmxr_set_line_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_line_output_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_console_units (UNIT *rxuptr, UNIT *txuptr);
t_stat tmxr_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw);
t_stat tmxr_dep (t_value val, t_addr addr, UNIT *uptr, int32 sw);
void tmxr_msg (SOCKET sock, const char *msg);
void tmxr_linemsg (TMLN *lp, const char *msg);
void tmxr_linemsgf (TMLN *lp, const char *fmt, ...);
void tmxr_linemsgvf (TMLN *lp, const char *fmt, va_list args);
void tmxr_fconns (FILE *st, const TMLN *lp, int32 ln);
void tmxr_fstats (FILE *st, const TMLN *lp, int32 ln);
t_stat tmxr_set_log (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_set_nolog (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_show_log (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_dscln (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
int32 tmxr_rqln (const TMLN *lp);
int32 tmxr_tqln (const TMLN *lp);
int32 tmxr_tpqln (const TMLN *lp);
t_bool tmxr_tpbusyln (const TMLN *lp);
t_stat tmxr_set_lnorder (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_show_lnorder (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_summ (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_cstat (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_lines (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_open_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc);
t_stat tmxr_activate (UNIT *uptr, int32 interval);
t_stat tmxr_activate_after (UNIT *uptr, uint32 usecs_walltime);
t_stat tmxr_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat tmxr_clock_coschedule (UNIT *uptr, int32 interval);
t_stat tmxr_clock_coschedule_abs (UNIT *uptr, int32 interval);
t_stat tmxr_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks);
t_stat tmxr_clock_coschedule_tmr_abs (UNIT *uptr, int32 tmr, int32 ticks);
t_stat tmxr_change_async (void);
t_stat tmxr_locate_line_send (const char *dev_line, SEND **snd);
t_stat tmxr_locate_line_expect (const char *dev_line, EXPECT **exp);
t_stat tmxr_startup (void);
t_stat tmxr_shutdown (void);
t_stat tmxr_start_poll (void);
t_stat tmxr_stop_poll (void);
void _tmxr_debug (uint32 dbits, TMLN *lp, const char *msg, char *buf, int bufsize);
#define tmxr_debug(dbits, lp, msg, buf, bufsize) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) _tmxr_debug (dbits, lp, msg, buf, bufsize); } while (0)
#define tmxr_debug_msg(dbits, lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) sim_debug (dbits, (lp)->mp->dptr, "%s", msg); } while (0)
#define tmxr_debug_return(lp, val) do {if (sim_deb && (val) && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_RET & (lp)->mp->dptr->dctrl)) { if ((lp)->rxbps) sim_debug (TMXR_DBG_RET, (lp)->mp->dptr, "Ln%d: 0x%x - Next after: %.0f\n", (int)((lp)-(lp)->mp->ldsc), val, (lp)->rxnexttime); else sim_debug (TMXR_DBG_RET, (lp)->mp->dptr, "Ln%d: 0x%x\n", (int)((lp)-(lp)->mp->ldsc), val); } } while (0)
#define tmxr_debug_trace(mp, msg) do {if (sim_deb && (mp)->dptr && (TMXR_DBG_TRC & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, mp->dptr, "%s\n", (msg)); } while (0)
#define tmxr_debug_trace_line(lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_TRC & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); } while (0)
#define tmxr_debug_connect(mp, msg) do {if (sim_deb && (mp)->dptr && (TMXR_DBG_CON & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_CON, mp->dptr, "%s\n", (msg)); } while (0)
#define tmxr_debug_connect_line(lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_CON & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_CON, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); } while (0)

#if defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_IO)
#undef SIM_ASYNCH_MUX
#endif /* defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_IO) */

#if defined(SIM_ASYNCH_MUX)
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, TRUE)
#else
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, FALSE)
#endif
#if (!defined(NOT_MUX_USING_CODE))
#define sim_activate tmxr_activate
#define sim_activate_after tmxr_activate_after
#define sim_activate_after_abs tmxr_activate_after_abs
#define sim_clock_coschedule tmxr_clock_coschedule 
#define sim_clock_coschedule_abs tmxr_clock_coschedule_abs
#define sim_clock_coschedule_tmr tmxr_clock_coschedule_tmr
#define sim_clock_coschedule_tmr_abs tmxr_clock_coschedule_tmr_abs
#endif


#ifdef  __cplusplus
}
#endif

#endif /* _SIM_TMXR_H_ */
Changes to tools/mkrel.
1

2




#!/bin/bash

fossil ci --tag release --tag v$(date +%Y%m%d)





>
|
>
>
>
>
1
2
3
4
5
6
7
#!/bin/bash
tag=v$(date +%Y%m%d)
fossil ci --tag $tag &&
	cd ../release &&
	fossil merge $tag &&
	make -j11 &&
	fossil ci