PiDP-8/I Software

Check-in [c331a1d356]
Log In

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

Overview
Comment:Updated SIMH to tip-of-master
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: c331a1d35668ff5368da6ff188a735d09e33bb7c6abd0514ff6f409eadad8b22
User & Date: tangent 2020-04-20 00:53:33
References
2021-02-01
17:13 Ticket [7ae7a73744] LOAD_ADD + EXAM not working status still Verified with 3 other changes artifact: 641de36ffd user: tangent
Context
2020-04-20
01:01
Portability fix for lack of "file attributes" command in Jim Tcl, needed by fixup step at end of auto.def, where *.in scripts get handled, losing the +x bit set in Fossil. check-in: 78bb5a4cca user: tangent tags: trunk
00:53
Updated SIMH to tip-of-master check-in: c331a1d356 user: tangent tags: trunk
2020-04-19
23:47
Updated Autosetup to tip-of-master. ("0.6.9+") check-in: 32f74149a0 user: tangent tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to ChangeLog.md.

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
# PiDP-8/I Changes

<a id="202004xx"></a>
## Version 2020.04.xx

*   Raspberry Pi 4 support.

*   [Configurable screen manager][rmsm], allowing either tmux or
    "none" as an alternative to GNU screen.  Initial work on this
    feature done by Ryan Finnie.

*   Added udev rules to allow mounting media from disks on USB
    floppy drives.  (Thanks to Ryan Finnie for this feature.)




























*   The build system now detects the availability of Python 3 and
    prefers it if available.

*   Updated external dependencies Autosetup and SIMH.

*   Assorted portability and documentation improvements.

[rmsm]: https://tangentsoft.com/pidp8i/doc/trunk/README.md#rc-screen-manager


<a id="20190425"></a>
## Version 2019.04.25 — The "OS/8 V3F and os8-run" release














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




|

|







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
# PiDP-8/I Changes

<a id="202004xx"></a>
## Version 2020.04.xx

*   Raspberry Pi 4 support.

*   [Configurable screen manager][rmsm], allowing either tmux or
    "none" as an alternative to GNU screen.  Initial work on this
    feature done by Ryan Finnie.

*   Added udev rules to allow mounting media from disks on USB
    floppy drives.  (Thanks to Ryan Finnie for this feature.)

*   Updated SIMH.  The primary user-visible changes from the perspective
    of a PiDP-8/I user are:

    *   Better IPS rate calibration for the PDP-8 simulator when
        throttling.  The simulator now does a precalibration pass to
        achieve a good initial guess at the host's IPS rate rather
        than drop sharply into a calibrated level some seconds past
        the simulator startup time, as in the prior release.

    *   Improvements to SCP, the command shell / script interpreter:

        *   Add the `RENAME/MOVE/MV`, `MKDIR`, and `RMDIR` commands.

        *   The `SAVE` command can now overwrite existing files.

        *   Several improvements to power-of-2 unit handling in command
            output and parameter input.

        *   Regular expressions in SIMH `EXPECT` commands now use
            PCRE syntax if available instead of the POSIX regex
            library.

    *   Many improvements to tape device handling.  (Nothing PDP-8
        specific, just generic SIMH improvements.)

    *   Portability and documentation improvements.

*   The build system now detects the availability of Python 3 and
    prefers it if available.

*   Updated Autosetup to v0.6.9+.  Allows it to work under Tcl 8.7.

*   Portability and documentation improvements.

[rmsm]: https://tangentsoft.com/pidp8i/doc/trunk/README.md#rc-screen-manager


<a id="20190425"></a>
## Version 2019.04.25 — The "OS/8 V3F and os8-run" release

Changes to Makefile.in.

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
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization from those authors.
########################################################################

# Git commit ID and time of the latest version of the SIMH 4 project on
# GitHub that has been merged into this source base.
SGCID=4e0450cff96830c5aced36928a4427adfc5314f8
SGCTM=2019-04-18T20:03:17-07:00

# C build flags for the PDP-8 simulator and its PiDP-8/I extensions.
SIM_CFLAGS := @CFLAGS@ @PI_CFLAGS@ @BUILDMODE@ \
	-Wno-unused-result -Wno-parentheses \
	-DUSE_READER_THREAD -DHAVE_DLOPEN=$(subst .,,@SH_SOEXT@) -DPIDP8I \
	-DSIM_ASYNCH_IO -DHAVE_REGEX_H -DHAVE_GLOB \
	-DSIM_GIT_COMMIT_ID=$(SGCID) -DSIM_GIT_COMMIT_TIME=$(SGCTM) \

	-D_GNU_SOURCE \
	-U__STRICT_ANSI__ \
	-I @srcdir@/src/SIMH -I @srcdir@/src/pidp8i -I src -I src/SIMH -I src/pidp8i









PIDP8I_CFLAGS = $(SIM_CFLAGS)
SIMH_CFLAGS = $(SIM_CFLAGS)
SIMH_PDP8_CFLAGS = $(SIM_CFLAGS)

# Greatly stripped-down build options for the cc8 cross-compiler
# primarily because it's K&R C.  Building under SIM_CFLAGS spews
# pages of warnings.  The only thing we share is whether to build







|
|





|

>



>
>
>
>
>
>
>
>
>







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
# shall not be used in advertising or otherwise to promote the sale,
# use or other dealings in this Software without prior written
# authorization from those authors.
########################################################################

# Git commit ID and time of the latest version of the SIMH 4 project on
# GitHub that has been merged into this source base.
SGCID=cabd3784bc7e33d63906602e33a5d01b60c1dee1
SGCTM=2020-04-17T18:20:27-07:00

# C build flags for the PDP-8 simulator and its PiDP-8/I extensions.
SIM_CFLAGS := @CFLAGS@ @PI_CFLAGS@ @BUILDMODE@ \
	-Wno-unused-result -Wno-parentheses \
	-DUSE_READER_THREAD -DHAVE_DLOPEN=$(subst .,,@SH_SOEXT@) -DPIDP8I \
	-DSIM_ASYNCH_IO -DHAVE_GLOB \
	-DSIM_GIT_COMMIT_ID=$(SGCID) -DSIM_GIT_COMMIT_TIME=$(SGCTM) \
	-DSIM_BUILD_TOOL='autosetup+gmake' \
	-D_GNU_SOURCE \
	-U__STRICT_ANSI__ \
	-I @srcdir@/src/SIMH -I @srcdir@/src/pidp8i -I src -I src/SIMH -I src/pidp8i
ifneq "@HAVE_PCRE_H@" ""
SIM_CFLAGS += -DHAVE_PCRE_H
SIM_LFLAGS := -lpcre
else
SIM_CFLAGS += -DHAVE_REGEX_H
endif
ifneq "@HAVE_PCREPOSIX_H@" ""
SIM_CFLAGS += -DHAVE_PCREPOSIX_H
endif
PIDP8I_CFLAGS = $(SIM_CFLAGS)
SIMH_CFLAGS = $(SIM_CFLAGS)
SIMH_PDP8_CFLAGS = $(SIM_CFLAGS)

# Greatly stripped-down build options for the cc8 cross-compiler
# primarily because it's K&R C.  Building under SIM_CFLAGS spews
# pages of warnings.  The only thing we share is whether to build
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
obj/cc8/os8/%.c: @srcdir@/src/cc8/examples/%.c
	sed '/^#include/d' $< > $@

$(BUILDDIRS):
	mkdir -p $@

$(PIDP8I_SIM): $(SIM_OBJS) obj/pidp8i/gpio-@LED_DRIVER_MODULE@ls.o
	$(CC) -o $@ @PI_LFLAGS@ $^ $(LIBS) @PI_LIBS@
	ln -f bin/pidp8i-sim bin/pdp8

bin/cc8: $(CC8_OBJS)
	$(CC) -o $@ $^ $(LIBS)

bin/d8tape: $(D8TAPE_OBJS)
	$(CC) -o $@ $^







|







710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
obj/cc8/os8/%.c: @srcdir@/src/cc8/examples/%.c
	sed '/^#include/d' $< > $@

$(BUILDDIRS):
	mkdir -p $@

$(PIDP8I_SIM): $(SIM_OBJS) obj/pidp8i/gpio-@LED_DRIVER_MODULE@ls.o
	$(CC) -o $@ @PI_LFLAGS@ $^ $(LIBS) $(SIM_LFLAGS) @PI_LIBS@
	ln -f bin/pidp8i-sim bin/pdp8

bin/cc8: $(CC8_OBJS)
	$(CC) -o $@ $^ $(LIBS)

bin/d8tape: $(D8TAPE_OBJS)
	$(CC) -o $@ $^

Changes to auto.def.

337
338
339
340
341
342
343

344
345
346
347
348
349
350
    define LED_DRIVER_MODULE i
    define ILS_MODE 1
}

# Check for headers, functions, etc. whose absence we can work around
cc-check-decls __progname
cc-check-includes time.h

cc-check-function-in-lib clock_gettime rt
cc-check-functions clock_nanosleep nanosleep usleep
cc-check-functions sched_yield
cc-with {-includes signal.h} {
    cc-check-types sighandler_t sig_t
}








>







337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
    define LED_DRIVER_MODULE i
    define ILS_MODE 1
}

# Check for headers, functions, etc. whose absence we can work around
cc-check-decls __progname
cc-check-includes time.h
cc-check-includes pcre.h pcreposix.h
cc-check-function-in-lib clock_gettime rt
cc-check-functions clock_nanosleep nanosleep usleep
cc-check-functions sched_yield
cc-with {-includes signal.h} {
    cc-check-types sighandler_t sig_t
}

Changes to src/SIMH/PDP8/pdp8_cpu.c.

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
saved_DF = DF & 070000;
saved_LAC = LAC & 017777;
saved_MQ = MQ & 07777;
pcq_r->qptr = pcq_p;                                    /* update pc q ptr */
return reason;
}                                                       /* end sim_instr */
















/* Reset routine */

t_stat cpu_reset (DEVICE *dptr)
{
saved_LAC = 0;
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) */








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











>
|
>
>







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
saved_DF = DF & 070000;
saved_LAC = LAC & 017777;
saved_MQ = MQ & 07777;
pcq_r->qptr = pcq_p;                                    /* update pc q ptr */
return reason;
}                                                       /* end sim_instr */

/*
 * This sequence of instructions is a mix that hopefully
 * represents a resonable instruction set that is a close 
 * estimate to the normal calibrated result.
 */

static const char *pdp8_clock_precalibrate_commands[] = {
    "106 100"
    "-m 100 MQL MQA"
    "-m 101 ISZ 112",
    "-m 102 JMP I 106",
    "-m 103 JMP I 106",
    "PC 100",
    NULL};

/* Reset routine */

t_stat cpu_reset (DEVICE *dptr)
{
saved_LAC = 0;
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_clock_precalibrate_commands = pdp8_clock_precalibrate_commands;
sim_vm_initial_ips = 10 * SIM_INITIAL_IPS;
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) */

Changes to src/SIMH/PDP8/pdp8_ct.c.

325
326
327
328
329
330
331
332

333
334
335
336
337
338
339
340
            else old_ust = 0;                           /* defang next */
            }
        if ((old_ust ^ uptr->UST) == (UST_REV|UST_GAP)) { /* rev in gap? */
            if (DEBUG_PRS (ct_dev)) fprintf (sim_deb,
                ">>CT skip gap: op=%o, old_sta = %o, pos=%d\n",
                fnc, uptr->UST, uptr->pos);
            if (uptr->UST)                              /* skip file gap */
                sim_tape_rdrecr (uptr, ct_xb, &t, CT_MAXFR);

            else sim_tape_rdrecf (uptr, ct_xb, &t, CT_MAXFR);
            }
        }
    else uptr->UST = 0;
    ct_bptr = 0;                                        /* init buffer */
    ct_blnt = 0;
    uptr->FNC = fnc;                                    /* save function */
    sim_activate (uptr, ct_stime);                      /* schedule op */







|
>
|







325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            else old_ust = 0;                           /* defang next */
            }
        if ((old_ust ^ uptr->UST) == (UST_REV|UST_GAP)) { /* rev in gap? */
            if (DEBUG_PRS (ct_dev)) fprintf (sim_deb,
                ">>CT skip gap: op=%o, old_sta = %o, pos=%d\n",
                fnc, uptr->UST, uptr->pos);
            if (uptr->UST)                              /* skip file gap */
                (void)sim_tape_rdrecr (uptr, ct_xb, &t, CT_MAXFR);
            else
                (void)sim_tape_rdrecf (uptr, ct_xb, &t, CT_MAXFR);
            }
        }
    else uptr->UST = 0;
    ct_bptr = 0;                                        /* init buffer */
    ct_blnt = 0;
    uptr->FNC = fnc;                                    /* save function */
    sim_activate (uptr, ct_stime);                      /* schedule op */

Changes to src/SIMH/PDP8/pdp8_mt.c.

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            mt_sta = mt_sta | STA_ILL | STA_ERR;        /* illegal op error */
            mt_set_done ();                             /* set done */
            mt_updcsta (uptr);                          /* update status */
            return 0;
            }
        uptr->USTAT = uptr->USTAT & STA_WLK;            /* clear status */
        if (f == FN_UNLOAD) {                           /* unload? */
            detach_unit (uptr);                         /* set offline */
            uptr->USTAT = STA_REW | STA_REM;            /* rewinding, off */
            mt_set_done ();                             /* set done */
            }
        else if (f == FN_REWIND) {                      /* rewind */
            uptr->USTAT = uptr->USTAT | STA_REW;        /* rewinding */
            mt_set_done ();                             /* set done */
            }







|







271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            mt_sta = mt_sta | STA_ILL | STA_ERR;        /* illegal op error */
            mt_set_done ();                             /* set done */
            mt_updcsta (uptr);                          /* update status */
            return 0;
            }
        uptr->USTAT = uptr->USTAT & STA_WLK;            /* clear status */
        if (f == FN_UNLOAD) {                           /* unload? */
            sim_tape_detach (uptr);                     /* set offline */
            uptr->USTAT = STA_REW | STA_REM;            /* rewinding, off */
            mt_set_done ();                             /* set done */
            }
        else if (f == FN_REWIND) {                      /* rewind */
            uptr->USTAT = uptr->USTAT | STA_REW;        /* rewinding */
            mt_set_done ();                             /* set done */
            }

Changes to src/SIMH/scp.c.

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#define SCH_G           2
#define SCH_L           3
#define SCH_EE          4
#define SCH_NE          5
#define SCH_GE          6
#define SCH_LE          7

#define MAX_DO_NEST_LVL 20                              /* DO cmd nesting level */
#define SRBSIZ          1024                            /* save/restore buffer */
#define SIM_BRK_INILNT  4096                            /* bpt tbl length */
#define SIM_BRK_ALLTYP  0xFFFFFFFB
#define UPDATE_SIM_TIME                                         \
    if (1) {                                                    \
        int32 _x;                                               \
        AIO_LOCK;                                               \







|







297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#define SCH_G           2
#define SCH_L           3
#define SCH_EE          4
#define SCH_NE          5
#define SCH_GE          6
#define SCH_LE          7

#define MAX_DO_NEST_LVL 20                              /* DO cmd nesting level limit */
#define SRBSIZ          1024                            /* save/restore buffer */
#define SIM_BRK_INILNT  4096                            /* bpt tbl length */
#define SIM_BRK_ALLTYP  0xFFFFFFFB
#define UPDATE_SIM_TIME                                         \
    if (1) {                                                    \
        int32 _x;                                               \
        AIO_LOCK;                                               \
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
if (AIO_QUEUE_VAL != QUEUE_LIST_END) {  /* List !Empty */
    UNIT *q, *uptr;
    int32 a_event_time;
    do {                                /* Grab current queue */
        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_scp_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)







|







416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
if (AIO_QUEUE_VAL != QUEUE_LIST_END) {  /* List !Empty */
    UNIT *q, *uptr;
    int32 a_event_time;
    do {                                /* Grab current queue */
        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_scp_dev, "Migrating Asynch event for %s after %d %s\n", sim_uname(q), q->a_event_time, sim_vm_interval_units);
        ++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)
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
AIO_IUNLOCK;
return migrated;
}

void sim_aio_activate (ACTIVATE_API caller, UNIT *uptr, int32 event_time)
{
AIO_ILOCK;
sim_debug (SIM_DBG_AIO_QUEUE, &sim_scp_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));
    }
AIO_IUNLOCK;
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);







|















|




















>
>
>
>









>

















>
>







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
AIO_IUNLOCK;
return migrated;
}

void sim_aio_activate (ACTIVATE_API caller, UNIT *uptr, int32 event_time)
{
AIO_ILOCK;
sim_debug (SIM_DBG_AIO_QUEUE, &sim_scp_dev, "Queueing Asynch event for %s after %d %s\n", sim_uname(uptr), event_time, sim_vm_interval_units);
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));
    }
AIO_IUNLOCK;
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 %s\n", sim_uname(uptr), event_time, sim_vm_interval_units);
    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;
const char *sim_vm_release;
const char *sim_vm_release_message;
const char **sim_clock_precalibrate_commands = 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 set_unit_append (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 show_do (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr);
t_stat show_runlimit (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);
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
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 flush_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);
static const char *_get_dbg_verb (uint32 dbits, DEVICE* dptr, UNIT *uptr);
static t_stat sim_library_unit_tests (void);
static t_stat _sim_debug_flush (void);

/* Global data */


DEVICE *sim_dflt_dev = NULL;
UNIT *sim_clock_queue = QUEUE_LIST_END;
int32 sim_interval = 0;


int32 sim_switches = 0;
int32 sim_switch_number = 0;
FILE *sim_ofile = NULL;
TMLN *sim_oline = NULL;
MEMFILE *sim_mfile = NULL;
SCHTAB *sim_schrptr = FALSE;
SCHTAB *sim_schaptr = FALSE;







>












>


|




>



>
>







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
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 runlimit_svc (UNIT *ptr);
t_stat expect_svc (UNIT *ptr);
t_stat flush_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 set_runlimit (int32 flag, CONST char *cptr);
t_stat sim_set_asynch (int32 flag, CONST char *cptr);
static const char *_get_dbg_verb (uint32 dbits, DEVICE* dptr, UNIT *uptr);
static t_stat sim_sanity_check_register_declarations (void);
static t_stat _sim_debug_flush (void);

/* Global data */

const char *sim_prog_name = NULL;                       /* pointer to the executable name */
DEVICE *sim_dflt_dev = NULL;
UNIT *sim_clock_queue = QUEUE_LIST_END;
int32 sim_interval = 0;
const char *sim_vm_interval_units = "instructions";     /* Simulator can change to "cycles" as needed */
const char *sim_vm_step_unit = "instruction";           /* Simulator can change */
int32 sim_switches = 0;
int32 sim_switch_number = 0;
FILE *sim_ofile = NULL;
TMLN *sim_oline = NULL;
MEMFILE *sim_mfile = NULL;
SCHTAB *sim_schrptr = FALSE;
SCHTAB *sim_schaptr = FALSE;
622
623
624
625
626
627
628






629
630
631
632
633
634
635
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;






char *sim_sub_instr = NULL;         /* Copy of pre-substitution buffer contents */
char *sim_sub_instr_buf = NULL;     /* Buffer address that substitutions were saved in */
size_t sim_sub_instr_size = 0;      /* substitution buffer size */
size_t *sim_sub_instr_off = NULL;   /* offsets in substitution buffer where original data started */
static double sim_time;
static uint32 sim_rtime;
static int32 noqueue_time;







>
>
>
>
>
>







634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
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;
int32 sim_runlimit = 0;
int32 sim_runlimit_initial = 0;
double sim_runlimit_d = 0.0;
double sim_runlimit_d_initial = 0.0;
int32 sim_runlimit_switches = 0;
t_bool sim_runlimit_enabled = FALSE;
char *sim_sub_instr = NULL;         /* Copy of pre-substitution buffer contents */
char *sim_sub_instr_buf = NULL;     /* Buffer address that substitutions were saved in */
size_t sim_sub_instr_size = 0;      /* substitution buffer size */
size_t *sim_sub_instr_off = NULL;   /* offsets in substitution buffer where original data started */
static double sim_time;
static uint32 sim_rtime;
static int32 noqueue_time;
687
688
689
690
691
692
693

























694
695
696
697
698
699
700
DEVICE sim_step_dev = {
    "INT-STEP", &sim_step_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_step_description};


























static const char *sim_int_expect_description (DEVICE *dptr)
{
return "Expect facility";
}

#define FLUSH_INTERVAL 30*1000000           /* Flush I/O buffers every 30 seconds */







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







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
DEVICE sim_step_dev = {
    "INT-STEP", &sim_step_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_step_description};

static const char *sim_int_runlimit_description (DEVICE *dptr)
{
return "Run time limit facility";
}

static t_stat sim_int_runlimit_reset (DEVICE *dptr)
{
if (sim_runlimit_enabled) {
    if (sim_runlimit_switches & SWMASK ('T'))
        return sim_activate_after_d (dptr->units, sim_runlimit_d);
    else
        return sim_activate (dptr->units, sim_runlimit);
    }
return SCPE_OK;
}

static UNIT sim_runlimit_unit = { UDATA (&runlimit_svc, UNIT_IDLE, 0) };
DEVICE sim_runlimit_dev = {
    "INT-RUNLIMIT", &sim_runlimit_unit, NULL, NULL, 
    1, 0, 0, 0, 0, 0, 
    NULL, NULL, &sim_int_runlimit_reset, NULL, NULL, NULL, 
    NULL, DEV_NOSAVE, 0, 
    NULL, NULL, NULL, NULL, NULL, NULL,
    sim_int_runlimit_description};

static const char *sim_int_expect_description (DEVICE *dptr)
{
return "Expect facility";
}

#define FLUSH_INTERVAL 30*1000000           /* Flush I/O buffers every 30 seconds */
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
const char save_ver35[] = "V3.5";
const char save_ver32[] = "V3.2";
const char save_ver30[] = "V3.0";
const struct scp_error {
    const char *code;
    const char *message;
    } scp_errors[1+SCPE_MAX_ERR-SCPE_BASE] =
        {{"NXM",     "Address space exceeded"},
         {"UNATT",   "Unit not attached"},
         {"IOERR",   "I/O error"},
         {"CSUM",    "Checksum error"},
         {"FMT",     "Format error"},
         {"NOATT",   "Unit not attachable"},
         {"OPENERR", "File open error"},
         {"MEM",     "Memory exhausted"},
         {"ARG",     "Invalid argument"},
         {"STEP",    "Step expired"},
         {"UNK",     "Unknown command"},
         {"RO",      "Read only argument"},
         {"INCOMP",  "Command not completed"},
         {"STOP",    "Simulation stopped"},
         {"EXIT",    "Goodbye"},
         {"TTIERR",  "Console input I/O error"},
         {"TTOERR",  "Console output I/O error"},
         {"EOF",     "End of file"},
         {"REL",     "Relocation error"},
         {"NOPARAM", "No settable parameters"},
         {"ALATT",   "Unit already attached"},
         {"TIMER",   "Hardware timer error"},
         {"SIGERR",  "Signal handler setup error"},
         {"TTYERR",  "Console terminal setup error"},
         {"SUB",     "Subscript out of range"},
         {"NOFNC",   "Command not allowed"},
         {"UDIS",    "Unit disabled"},
         {"NORO",    "Read only operation not allowed"},
         {"INVSW",   "Invalid switch"},
         {"MISVAL",  "Missing value"},
         {"2FARG",   "Too few arguments"},
         {"2MARG",   "Too many arguments"},
         {"NXDEV",   "Non-existent device"},
         {"NXUN",    "Non-existent unit"},
         {"NXREG",   "Non-existent register"},
         {"NXPAR",   "Non-existent parameter"},
         {"NEST",    "Nested DO command limit exceeded"},
         {"IERR",    "Internal error"},
         {"MTRLNT",  "Invalid magtape record length"},
         {"LOST",    "Console Telnet connection lost"},
         {"TTMO",    "Console Telnet connection timed out"},
         {"STALL",   "Console Telnet output stall"},
         {"AFAIL",   "Assertion failed"},
         {"INVREM",  "Invalid remote console command"},
         {"EXPECT",  "Expect matched"},
         {"AMBREG",  "Ambiguous register name"},
         {"REMOTE",  "remote console command"},
         {"INVEXPR", "invalid expression"},
         {"SIGTERM", "SIGTERM received"},



    };

const size_t size_map[] = { sizeof (int8),
    sizeof (int8), sizeof (int16), sizeof (int32), sizeof (int32)
#if defined (USE_INT64)
    , sizeof (t_int64), sizeof (t_int64), sizeof (t_int64), sizeof (t_int64)
#endif







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







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
const char save_ver35[] = "V3.5";
const char save_ver32[] = "V3.2";
const char save_ver30[] = "V3.0";
const struct scp_error {
    const char *code;
    const char *message;
    } scp_errors[1+SCPE_MAX_ERR-SCPE_BASE] =
        {{"NXM",       "Address space exceeded"},
         {"UNATT",     "Unit not attached"},
         {"IOERR",     "I/O error"},
         {"CSUM",      "Checksum error"},
         {"FMT",       "Format error"},
         {"NOATT",     "Unit not attachable"},
         {"OPENERR",   "File open error"},
         {"MEM",       "Memory exhausted"},
         {"ARG",       "Invalid argument"},
         {"STEP",      "Step expired"},
         {"UNK",       "Unknown command"},
         {"RO",        "Read only argument"},
         {"INCOMP",    "Command not completed"},
         {"STOP",      "Simulation stopped"},
         {"EXIT",      "Goodbye"},
         {"TTIERR",    "Console input I/O error"},
         {"TTOERR",    "Console output I/O error"},
         {"EOF",       "End of file"},
         {"REL",       "Relocation error"},
         {"NOPARAM",   "No settable parameters"},
         {"ALATT",     "Unit already attached"},
         {"TIMER",     "Hardware timer error"},
         {"SIGERR",    "Signal handler setup error"},
         {"TTYERR",    "Console terminal setup error"},
         {"SUB",       "Subscript out of range"},
         {"NOFNC",     "Command not allowed"},
         {"UDIS",      "Unit disabled"},
         {"NORO",      "Read only operation not allowed"},
         {"INVSW",     "Invalid switch"},
         {"MISVAL",    "Missing value"},
         {"2FARG",     "Too few arguments"},
         {"2MARG",     "Too many arguments"},
         {"NXDEV",     "Non-existent device"},
         {"NXUN",      "Non-existent unit"},
         {"NXREG",     "Non-existent register"},
         {"NXPAR",     "Non-existent parameter"},
         {"NEST",      "Nested DO command limit exceeded"},
         {"IERR",      "Internal error"},
         {"MTRLNT",    "Invalid magtape record length"},
         {"LOST",      "Console Telnet connection lost"},
         {"TTMO",      "Console Telnet connection timed out"},
         {"STALL",     "Console Telnet output stall"},
         {"AFAIL",     "Assertion failed"},
         {"INVREM",    "Invalid remote console command"},
         {"EXPECT",    "Expect matched"},
         {"AMBREG",    "Ambiguous register name"},
         {"REMOTE",    "remote console command"},
         {"INVEXPR",   "invalid expression"},
         {"SIGTERM",   "SIGTERM received"},
         {"FSSIZE",    "File System size larger than disk size"},
         {"RUNTIME",   "Run time limit exhausted"},
         {"INCOMPDSK", "Incompatible Disk Container"},
    };

const size_t size_map[] = { sizeof (int8),
    sizeof (int8), sizeof (int16), sizeof (int32), sizeof (int32)
#if defined (USE_INT64)
    , sizeof (t_int64), sizeof (t_int64), sizeof (t_int64), sizeof (t_int64)
#endif
821
822
823
824
825
826
827


828
829
830
831
832
833
834
835
    0x1FFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFF,
    0x7FFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFF,
    0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF,
    0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF
#endif
    };



static const char simh_help[] =
       /***************** 80 character line width template *************************/
      "1Commands\n"
#define HLP_RESET       "*Commands Resetting Devices"
       /***************** 80 character line width template *************************/
      "2Resetting Devices\n"
      " The RESET command (abbreviation RE) resets a device or the entire simulator\n"
      " to a predefined condition.  If switch -p is specified, the device is reset\n"







>
>
|







867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
    0x1FFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFF,
    0x7FFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFF,
    0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF,
    0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF
#endif
    };

static char *simh_help = ""; /* First invocation of HELP command appends the help pieces */

static const char simh_help1[] =
       /***************** 80 character line width template *************************/
      "1Commands\n"
#define HLP_RESET       "*Commands Resetting Devices"
       /***************** 80 character line width template *************************/
      "2Resetting Devices\n"
      " The RESET command (abbreviation RE) resets a device or the entire simulator\n"
      " to a predefined condition.  If switch -p is specified, the device is reset\n"
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
#define HLP_CONTINUE    "*Commands Running_A_Simulated_Program CONTINUE"
      "3CONTINUE\n"
      " The CONT command (abbreviated CO) does not reset devices and resumes\n"
      " execution at the current PC.\n"
#define HLP_STEP        "*Commands Running_A_Simulated_Program STEP"
      "3STEP\n"
      " The STEP command (abbreviated S) resumes execution at the current PC for\n"
      " the number of instructions given by its argument.  If no argument is\n"
      " supplied, one instruction is executed.\n"
      "4Switches\n"
      " If the STEP command is invoked with the -T switch, the step command will\n"
      " cause execution to run for microseconds rather than instructions.\n"
#define HLP_NEXT        "*Commands Running_A_Simulated_Program NEXT"
      "3NEXT\n"
      " The NEXT command (abbreviated N) resumes execution at the current PC for\n"
      " one instruction, attempting to execute through a subroutine calls.\n"
      " If the next instruction to be executed is not a subroutine call,\n"
      " one instruction is executed.\n"
#define HLP_BOOT        "*Commands Running_A_Simulated_Program BOOT"







|
|


|







1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#define HLP_CONTINUE    "*Commands Running_A_Simulated_Program CONTINUE"
      "3CONTINUE\n"
      " The CONT command (abbreviated CO) does not reset devices and resumes\n"
      " execution at the current PC.\n"
#define HLP_STEP        "*Commands Running_A_Simulated_Program STEP"
      "3STEP\n"
      " The STEP command (abbreviated S) resumes execution at the current PC for\n"
      " the number of %Is given by its argument.  If no argument is\n"
      " supplied, one %I is executed.\n"
      "4Switches\n"
      " If the STEP command is invoked with the -T switch, the step command will\n"
      " cause execution to run for microseconds rather than %I.\n"
#define HLP_NEXT        "*Commands Running_A_Simulated_Program NEXT"
      "3NEXT\n"
      " The NEXT command (abbreviated N) resumes execution at the current PC for\n"
      " one instruction, attempting to execute through a subroutine calls.\n"
      " If the next instruction to be executed is not a subroutine call,\n"
      " one instruction is executed.\n"
#define HLP_BOOT        "*Commands Running_A_Simulated_Program BOOT"
1097
1098
1099
1100
1101
1102
1103



















1104
1105
1106
1107
1108
1109
1110
#define HLP_DEBUG       "*Commands Stopping_The_Simulator User_Specified_Stop_Conditions DEBUG"
#define HLP_NODEBUG     "*Commands Stopping_The_Simulator User_Specified_Stop_Conditions DEBUG"
      "4Debug\n"
      " The DEBUG snd NODEBUG commands are aliases for the \"SET DEBUG\" and\n"
      " \"SET NODEBUG\" commands.  Additionally, support is provided that is\n"
      " equivalent to the \"SET <dev> DEBUG=opt1{;opt2}\" and\n"
      " \"SET <dev> NODEBUG=opt1{;opt2}\" commands.\n\n"



















       /***************** 80 character line width template *************************/
      "2Connecting and Disconnecting Devices\n"
      " 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"







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







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
#define HLP_DEBUG       "*Commands Stopping_The_Simulator User_Specified_Stop_Conditions DEBUG"
#define HLP_NODEBUG     "*Commands Stopping_The_Simulator User_Specified_Stop_Conditions DEBUG"
      "4Debug\n"
      " The DEBUG snd NODEBUG commands are aliases for the \"SET DEBUG\" and\n"
      " \"SET NODEBUG\" commands.  Additionally, support is provided that is\n"
      " equivalent to the \"SET <dev> DEBUG=opt1{;opt2}\" and\n"
      " \"SET <dev> NODEBUG=opt1{;opt2}\" commands.\n\n"
#define HLP_RUNLIMIT      "*Commands Stopping_The_Simulator User_Specified_Stop_Conditions RUNLIMIT"
      "4RUNLIMIT\n"
      " A simulator user may want to limit the maximum execution time that a\n"
      " simulator may run for.  This might be appropriate to limit a runaway\n"
      " diagnostic which didn't achieve explicit success or failure within\n"
      " some user specified time.  The RUNLIMIT command provides ways to\n"
      " limit execution.\n\n"
      "++RUNLIMIT n {%C|MICROSECONDS|SECONDS|MINUTES|HOURS}\n"
      "++NORUNLIMIT\n\n"
      "  Equivalently:\n\n"
      "++SET RUNLIMIT n {CYCLES|MICROSECONDS|SECONDS|MINUTES|HOURS}\n"
      "++SET NORUNLIMIT\n\n"
      " The run limit state can be examined with:\n\n"
      "++SHOW RUNLIMIT\n\n"
      " If the units of the run limit are not specified, the default units are\n"
      " %C.  Once an execution run limit has beenn reached, any subsequent\n"
      " GO, RUN, CONTINUE, STEP or BOOT commands will cause the simulator to\n"
      " exit.  A previously defined RUNLIMIT can be cleared with the NORUNLIMIT\n"
      " command or the establishment of a new run limit.\n"
       /***************** 80 character line width template *************************/
      "2Connecting and Disconnecting Devices\n"
      " 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"
1123
1124
1125
1126
1127
1128
1129





1130
1131
1132
1133
1134
1135
1136
      "5-r\n"
      " If the -r switch is specified, or the file is write protected, ATTACH tries\n"
      " to open the file read only.  If the file does not exist, or the unit does\n"
      " not support read only operation, an error occurs.  Input-only devices, such\n"
      " as paper-tape readers, and devices with write lock switches, such as disks\n"
      " and tapes, support read only operation; other devices do not.  If a file is\n"
      " attached read only, its contents can be examined but not modified.\n"





      "5-q\n"
      " If the -q switch is specified when creating a new file (-n) or opening one\n"
      " read only (-r), any messages announcing these facts will be suppressed.\n"
      "5-f\n"
      " For simulated magnetic tapes, the ATTACH command can specify the format of\n"
      " the attached tape image file:\n\n"
      "++ATTACH -f <tape_unit> <format> <filename>\n\n"







>
>
>
>
>







1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
      "5-r\n"
      " If the -r switch is specified, or the file is write protected, ATTACH tries\n"
      " to open the file read only.  If the file does not exist, or the unit does\n"
      " not support read only operation, an error occurs.  Input-only devices, such\n"
      " as paper-tape readers, and devices with write lock switches, such as disks\n"
      " and tapes, support read only operation; other devices do not.  If a file is\n"
      " attached read only, its contents can be examined but not modified.\n"
      "5-a\n"
      " If the -a switch is specified, and the device being attached is a\n"
      " sequential output only device (like a line printer, paper tape punch,\n"
      " etc.), the file being attached will be opened in append mode thus adding\n"
      " to any existing file data beyond what may have already been there.\n"
      "5-q\n"
      " If the -q switch is specified when creating a new file (-n) or opening one\n"
      " read only (-r), any messages announcing these facts will be suppressed.\n"
      "5-f\n"
      " For simulated magnetic tapes, the ATTACH command can specify the format of\n"
      " the attached tape image file:\n\n"
      "++ATTACH -f <tape_unit> <format> <filename>\n\n"
1208
1209
1210
1211
1212
1213
1214

















1215
1216
1217
1218
1219
1220
1221
      "2Copying Files\n"
#define HLP_COPY        "*Commands Copying_Files COPY"
      "3COPY\n"
      "++COPY sfile dfile          copies a file\n"
#define HLP_CP          "*Commands Copying_Files CP"
      "3CP\n"
      "++CP sfile dfile            copies a file\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=value       specify console drop to simh character\n"







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







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
      "2Copying Files\n"
#define HLP_COPY        "*Commands Copying_Files COPY"
      "3COPY\n"
      "++COPY sfile dfile          copies a file\n"
#define HLP_CP          "*Commands Copying_Files CP"
      "3CP\n"
      "++CP sfile dfile            copies a file\n"
      "2Renaming Files\n"
#define HLP_RENAME      "*Commands Renaming_Files RENAME"
      "3RENAME\n"
      "++RENAME origname newname   renames a file\n"
#define HLP_MOVE        "*Commands Renaming_Files MOVE"
      "3MOVE\n"
      "++MOVE origname newname     renames a file\n"
      "+or\n"
      "++MV   origname newname     renames a file\n"
      "2Creating Directories\n"
#define HLP_MKDIR       "*Commands Creating_Directories MKDIR"
      "3MKDIR\n"
      "++MKDIR path                creates a directory\n"
      "2Deleting Directories\n"
#define HLP_RMDIR       "*Commands Deleting_Directories RMDIR"
      "3RMDIR\n"
      "++RMDIR path                deleting a directory\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=value       specify console drop to simh character\n"
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
       /***************** 80 character line width template *************************/
      "3Debug\n"
      "+SET DEBUG debug_file        specify the debug destination\n"
      "++++++++                     (STDOUT,STDERR,LOG or filename)\n"
      "+SET NODEBUG                 disables any currently active debug output\n"
      "4Switches\n"
      " Debug message output contains a timestamp which indicates the number of\n"
      " simulated instructions which have been executed prior to the debug event.\n\n"
      " Debug message output can be enhanced to contain additional, potentially\n"
      " useful information.\n"
      "5-T\n"
      " The -T switch causes debug output to contain a time of day displayed\n"
      " as hh:mm:ss.msec.\n"
      "5-A\n"
      " The -A switch causes debug output to contain a time of day displayed\n"







|







1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
       /***************** 80 character line width template *************************/
      "3Debug\n"
      "+SET DEBUG debug_file        specify the debug destination\n"
      "++++++++                     (STDOUT,STDERR,LOG or filename)\n"
      "+SET NODEBUG                 disables any currently active debug output\n"
      "4Switches\n"
      " Debug message output contains a timestamp which indicates the number of\n"
      " simulated %C which have been executed prior to the debug event.\n\n"
      " Debug message output can be enhanced to contain additional, potentially\n"
      " useful information.\n"
      "5-T\n"
      " The -T switch causes debug output to contain a time of day displayed\n"
      " as hh:mm:ss.msec.\n"
      "5-A\n"
      " The -A switch causes debug output to contain a time of day displayed\n"
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
      "+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"
      " Simulator instruction execution rate can be controlled by specifying\n"
      " one of the following throttle commands:\n\n"
      "+SET THROTTLE xM             execute x million instructions per second\n"
      "+SET THROTTLE xK             execute x thousand instructions per second\n"
      "+SET THROTTLE x%%             occupy x percent of the host capacity\n"
      "++++++++executing instructions\n"
      "+SET THROTTLE x/t            sleep for t milliseconds after executing x\n"
      "++++++++instructions\n\n"
      "+SET NOTHROTTLE              set simulation rate to maximum\n\n"
      " Throttling is only available on host systems that implement a precision\n"
      " real-time delay function.\n\n"
      " xM, xK and x%% modes require the simulator to execute sufficient\n"
      " instructions to actually calibrate the desired execution rate relative\n"
      " to wall clock time.  Very short running programs may complete before\n"
      " calibration completes and therefore before the simulated execution rate\n"
      " can match the desired rate.\n\n"
      " The SET NOTHROTTLE command turns off throttling.  The SHOW THROTTLE\n"
      " command shows the current settings for throttling and the calibration\n"
      " results\n\n"
      " Some simulators implement a different form of host CPU resource management\n"







|
|



|




|







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
      "+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"
      " Simulator instruction execution rate can be controlled by specifying\n"
      " one of the following throttle commands:\n\n"
      "+SET THROTTLE xM             execute x million %C per second\n"
      "+SET THROTTLE xK             execute x thousand %C per second\n"
      "+SET THROTTLE x%%             occupy x percent of the host capacity\n"
      "++++++++executing instructions\n"
      "+SET THROTTLE x/t            sleep for t milliseconds after executing x\n"
      "++++++++%C\n\n"
      "+SET NOTHROTTLE              set simulation rate to maximum\n\n"
      " Throttling is only available on host systems that implement a precision\n"
      " real-time delay function.\n\n"
      " xM, xK and x%% modes require the simulator to execute sufficient\n"
      " %C to actually calibrate the desired execution rate relative\n"
      " to wall clock time.  Very short running programs may complete before\n"
      " calibration completes and therefore before the simulated execution rate\n"
      " can match the desired rate.\n\n"
      " The SET NOTHROTTLE command turns off throttling.  The SHOW THROTTLE\n"
      " command shows the current settings for throttling and the calibration\n"
      " results\n\n"
      " Some simulators implement a different form of host CPU resource management\n"
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
      "+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"
      "+SET CLOCK calib=ALWAYS      specify calibration independent of idle\n"
      "+SET CLOCK stop=n            stop execution after n instructions\n\n"
      " The SET CLOCK STOP command allows execution to have a bound when\n"
      " execution starts with a BOOT, NEXT or CONTINUE command.\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 Environment"







|







1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
      "+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"
      "+SET CLOCK calib=ALWAYS      specify calibration independent of idle\n"
      "+SET CLOCK stop=n            stop execution after n %C\n\n"
      " The SET CLOCK STOP command allows execution to have a bound when\n"
      " execution starts with a BOOT, NEXT or CONTINUE command.\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 Environment"
1453
1454
1455
1456
1457
1458
1459
1460

1461
1462
1463
1464
1465
1466
1467
1468
      "+SET <dev> DEBUG{=arg}       set device debug flags\n"
      "+SET <dev> NODEBUG={arg}     clear device debug flags\n"
      "+SET <dev> arg{,arg...}      set device parameters (see show modifiers)\n"
      "+SET <unit> ENABLED          enable unit\n"
      "+SET <unit> DISABLED         disable unit\n"
      "+SET <unit> arg{,arg...}     set unit parameters (see show modifiers)\n"
      "+HELP <dev> SET              displays the device specific set commands\n"
      "++++++++                     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"







|
>
|







1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
      "+SET <dev> DEBUG{=arg}       set device debug flags\n"
      "+SET <dev> NODEBUG={arg}     clear device debug flags\n"
      "+SET <dev> arg{,arg...}      set device parameters (see show modifiers)\n"
      "+SET <unit> ENABLED          enable unit\n"
      "+SET <unit> DISABLED         disable unit\n"
      "+SET <unit> arg{,arg...}     set unit parameters (see show modifiers)\n"
      "+HELP <dev> SET              displays the device specific set commands\n"
      "++++++++                     available\n";
static const char simh_help2[] =
      /***************** 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"
1488
1489
1490
1491
1492
1493
1494


1495
1496
1497
1498
1499
1500
1501
      "+sh{ow} multiplexer {dev}    show open multiplexer device info\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"
#define HLP_SHOW_QUEUE          "*Commands SHOW"
#define HLP_SHOW_TIME           "*Commands SHOW"







>
>







1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
      "+sh{ow} multiplexer {dev}    show open multiplexer device info\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"
      "+sh{ow} do                   show do nesting state\n"
      "+sh{ow} runlimit             show execution limit states\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"
#define HLP_SHOW_QUEUE          "*Commands SHOW"
#define HLP_SHOW_TIME           "*Commands SHOW"
1513
1514
1515
1516
1517
1518
1519


1520
1521
1522
1523
1524
1525
1526
#define HLP_SHOW_ASYNCH         "*Commands SHOW"
#define HLP_SHOW_ETHERNET       "*Commands SHOW"
#define HLP_SHOW_SERIAL         "*Commands SHOW"
#define HLP_SHOW_MULTIPLEXER    "*Commands SHOW"
#define HLP_SHOW_VIDEO          "*Commands SHOW"
#define HLP_SHOW_CLOCKS         "*Commands SHOW"
#define HLP_SHOW_ON             "*Commands SHOW"


#define HLP_SHOW_SEND           "*Commands SHOW"
#define HLP_SHOW_EXPECT         "*Commands SHOW"
#define HLP_HELP                "*Commands HELP"
       /***************** 80 character line width template *************************/
      "2HELP\n"
      "+h{elp}                      type this message\n"
      "+h{elp} <command>            type help for command\n" 







>
>







1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
#define HLP_SHOW_ASYNCH         "*Commands SHOW"
#define HLP_SHOW_ETHERNET       "*Commands SHOW"
#define HLP_SHOW_SERIAL         "*Commands SHOW"
#define HLP_SHOW_MULTIPLEXER    "*Commands SHOW"
#define HLP_SHOW_VIDEO          "*Commands SHOW"
#define HLP_SHOW_CLOCKS         "*Commands SHOW"
#define HLP_SHOW_ON             "*Commands SHOW"
#define HLP_SHOW_DO             "*Commands SHOW"
#define HLP_SHOW_RUNLIMIT       "*Commands SHOW"
#define HLP_SHOW_SEND           "*Commands SHOW"
#define HLP_SHOW_EXPECT         "*Commands SHOW"
#define HLP_HELP                "*Commands HELP"
       /***************** 80 character line width template *************************/
      "2HELP\n"
      "+h{elp}                      type this message\n"
      "+h{elp} <command>            type help for command\n" 
1665
1666
1667
1668
1669
1670
1671


1672
1673
1674
1675
1676
1677
1678
      " and have their values be expanded to full paths and/or into pieces.\n"
      " Parsing and expansion of file names.\n\n"
      "++%%~I%%     - expands the value of %%I%% removing any surrounding quotes (\")\n"
      "++%%~fI%%    - expands the value of %%I%% to a fully qualified path name\n"
      "++%%~pI%%    - expands the value of %%I%% to a path only\n"
      "++%%~nI%%    - expands the value of %%I%% to a file name only\n"
      "++%%~xI%%    - expands the value of %%I%% to a file extension only\n\n"


      " The modifiers can be combined to get compound results:\n\n"
      "++%%~pnI%%   - expands the value of %%I%% to a path and name only\n"
      "++%%~nxI%%   - expands the value of %%I%% to a file name and extension only\n\n"
      " In the above example above %%I%% can be replaced by other\n"
      " environment variables or numeric parameters to a DO command\n"
      " invokation.\n"
      " Examples:\n\n"







>
>







1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
      " and have their values be expanded to full paths and/or into pieces.\n"
      " Parsing and expansion of file names.\n\n"
      "++%%~I%%     - expands the value of %%I%% removing any surrounding quotes (\")\n"
      "++%%~fI%%    - expands the value of %%I%% to a fully qualified path name\n"
      "++%%~pI%%    - expands the value of %%I%% to a path only\n"
      "++%%~nI%%    - expands the value of %%I%% to a file name only\n"
      "++%%~xI%%    - expands the value of %%I%% to a file extension only\n\n"
      "++%%~tI%%    - expands the value of %%I%% to date/time of file\n\n"
      "++%%~zI%%    - expands the value of %%I%% to size of file\n\n"
      " The modifiers can be combined to get compound results:\n\n"
      "++%%~pnI%%   - expands the value of %%I%% to a path and name only\n"
      "++%%~nxI%%   - expands the value of %%I%% to a file name and extension only\n\n"
      " In the above example above %%I%% can be replaced by other\n"
      " environment variables or numeric parameters to a DO command\n"
      " invokation.\n"
      " Examples:\n\n"
1693
1694
1695
1696
1697
1698
1699




1700
1701
1702
1703
1704
1705
1706
      " GOTO command:\n\n"
      "++GOTO <label>\n\n"
      " Labels are lines in a command file which the first non whitespace\n"
      " character is a \":\".  The target of a goto is the first matching label\n"
      " in the current do command file which is encountered.  Since labels\n"
      " don't do anything else besides being the targets of goto's, they could\n"
      " also be used to provide comments in do command files.\n\n"




      "4Examples\n\n"
      "++:: This is a comment\n"
      "++echo Some Message to Output\n"
      "++:Target\n"
      "++:: This is a comment\n"
      "++GOTO Target\n\n"
#define HLP_RETURN      "*Commands Executing_Command_Files RETURN"







>
>
>
>







1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
      " GOTO command:\n\n"
      "++GOTO <label>\n\n"
      " Labels are lines in a command file which the first non whitespace\n"
      " character is a \":\".  The target of a goto is the first matching label\n"
      " in the current do command file which is encountered.  Since labels\n"
      " don't do anything else besides being the targets of goto's, they could\n"
      " also be used to provide comments in do command files.\n\n"
      "++GOTO :EOF\n\n"
      " The target label of :EOF is explicitly defined to mean the end of the\n"
      " DO command file.  This will cause the execution to return from the current\n"
      " command file.\n\n"
      "4Examples\n\n"
      "++:: This is a comment\n"
      "++echo Some Message to Output\n"
      "++:Target\n"
      "++:: This is a comment\n"
      "++GOTO Target\n\n"
#define HLP_RETURN      "*Commands Executing_Command_Files RETURN"
1803
1804
1805
1806
1807
1808
1809


1810
1811
1812
1813
1814
1815
1816
      " Console Telnet output stall\n"
      "5 AFAIL\n"
      " Assertion failed\n"
      "5 INVREM\n"
      " Invalid remote console command\n"
      "5 AMBREG\n"
      " Ambiguous register\n"


#define HLP_SHIFT       "*Commands Executing_Command_Files SHIFT"
      "3SHIFT\n"
      "++shift                    shift the command file's positional parameters\n"
#define HLP_CALL        "*Commands Executing_Command_Files CALL"
      "3CALL\n"
      "++call                     transfer control to a labeled subroutine\n"
      "                         a command file.\n"







>
>







1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
      " Console Telnet output stall\n"
      "5 AFAIL\n"
      " Assertion failed\n"
      "5 INVREM\n"
      " Invalid remote console command\n"
      "5 AMBREG\n"
      " Ambiguous register\n"
      "5 RUNTIME\n"
      " Run time limit exhausted\n"
#define HLP_SHIFT       "*Commands Executing_Command_Files SHIFT"
      "3SHIFT\n"
      "++shift                    shift the command file's positional parameters\n"
#define HLP_CALL        "*Commands Executing_Command_Files CALL"
      "3CALL\n"
      "++call                     transfer control to a labeled subroutine\n"
      "                         a command file.\n"
1978
1979
1980
1981
1982
1983
1984


1985
1986
1987
1988
1989
1990
1991
1992
1993
1994


1995
1996
1997
1998
1999
2000
2001
      " between characters being sent.  The delay parameter can be set by\n"
      " itself with:\n\n"
      "++SEND DELAY=n\n\n"
      " which will set the default delay value for subsequent SEND commands\n"
      " which don't specify an explicit DELAY parameter along with a string\n"
      " If a SEND command is processed and no DELAY value has been specified,\n"
      " the default value of the delay parameter is 1000.\n"


       /***************** 80 character line width template *************************/
      "4After\n"
      " Specifies an integer (>=0) representing a minimal number of instructions\n"
      " which must execute before the first character in the string is sent.\n"
      " The after parameter value can be set by itself with:\n\n"
      "++SEND AFTER=n\n\n"
      " which will set the default after value for subsequent SEND commands\n"
      " which don't specify an explicit AFTER parameter along with a string\n"
      " If a SEND command is processed and no AFTER value has been specified,\n"
      " the default value of the delay parameter is the DELAY parameter value.\n"


      "4Escaping String Data\n"
      " The following character escapes are explicitly supported:\n"
      "++\\r  Sends the ASCII Carriage Return character (Decimal value 13)\n"
      "++\\n  Sends the ASCII Linefeed character (Decimal value 10)\n"
      "++\\f  Sends the ASCII Formfeed character (Decimal value 12)\n"
      "++\\t  Sends the ASCII Horizontal Tab character (Decimal value 9)\n"
      "++\\v  Sends the ASCII Vertical Tab character (Decimal value 11)\n"







>
>


|







>
>







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
      " between characters being sent.  The delay parameter can be set by\n"
      " itself with:\n\n"
      "++SEND DELAY=n\n\n"
      " which will set the default delay value for subsequent SEND commands\n"
      " which don't specify an explicit DELAY parameter along with a string\n"
      " If a SEND command is processed and no DELAY value has been specified,\n"
      " the default value of the delay parameter is 1000.\n"
      " The value n can be specified with a suffix of k or m which indicates\n"
      " a multiplier of 1000 or 1000000 respectively\n"
       /***************** 80 character line width template *************************/
      "4After\n"
      " Specifies an integer (>=0) representing a minimal number of %C\n"
      " which must execute before the first character in the string is sent.\n"
      " The after parameter value can be set by itself with:\n\n"
      "++SEND AFTER=n\n\n"
      " which will set the default after value for subsequent SEND commands\n"
      " which don't specify an explicit AFTER parameter along with a string\n"
      " If a SEND command is processed and no AFTER value has been specified,\n"
      " the default value of the delay parameter is the DELAY parameter value.\n"
      " The value n can be specified with a suffix of k or m which indicates\n"
      " a multiplier of 1000 or 1000000 respectively\n"
      "4Escaping String Data\n"
      " The following character escapes are explicitly supported:\n"
      "++\\r  Sends the ASCII Carriage Return character (Decimal value 13)\n"
      "++\\n  Sends the ASCII Linefeed character (Decimal value 10)\n"
      "++\\f  Sends the ASCII Formfeed character (Decimal value 12)\n"
      "++\\t  Sends the ASCII Horizontal Tab character (Decimal value 9)\n"
      "++\\v  Sends the ASCII Vertical Tab character (Decimal value 11)\n"
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
      "++\\n{n{n}} where each n is an octal digit (0-7)\n"
      " and hext character values of the form:\n"
      "++\\xh{h} where each h is a hex digit (0-9A-Fa-f)\n"
      "4Switches\n"
      " Switches can be used to influence the behavior of SEND commands\n\n"
      "5-t\n"
      " The -t switch indicates that the Delay and After values are in\n"
      " 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\n"
      "++EXPECT {dev:line} {[count]} {HALTAFTER=n,}\"<string>\" {actioncommand {; actioncommand}...}\n\n"







|







2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
      "++\\n{n{n}} where each n is an octal digit (0-7)\n"
      " and hext character values of the form:\n"
      "++\\xh{h} where each h is a hex digit (0-9A-Fa-f)\n"
      "4Switches\n"
      " Switches can be used to influence the behavior of SEND commands\n\n"
      "5-t\n"
      " The -t switch indicates that the Delay and After values are in\n"
      " units of microseconds rather than %C.\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\n"
      "++EXPECT {dev:line} {[count]} {HALTAFTER=n,}\"<string>\" {actioncommand {; actioncommand}...}\n\n"
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
      " 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"
      " to match other expect rules which may already be defined.\n"
      " Data which is output prior to the definition of an expect rule is not\n"
      " eligible to be matched against.\n\n"
      " The NOEXPECT command removes a previously defined EXPECT command for the\n"
      " console or a specific multiplexer line.\n\n"


      " The SHOW EXPECT command displays all of the pending EXPECT state for\n"
      " the console or a specific multiplexer line.\n"
       /***************** 80 character line width template *************************/
      "4Switches\n"
      " Switches can be used to influence the behavior of EXPECT rules\n\n"
      "5-p\n"
      " EXPECT rules default to be one shot activities.  That is a rule is\n"
      " automatically removed when it matches unless it is designated as a\n"
      " persistent rule by using a -p switch when the rule is defined.\n"
      "5-c\n"
      " If an expect rule is defined with the -c switch, it will cause all\n"
      " pending expect rules on the current device to be cleared when the rule\n"
      " matches data in the device output stream.\n"
      "5-r\n"
      " If an expect rule is defined with the -r switch, the string is interpreted\n"
      " as a regular expression applied to the output data stream.  This regular\n"
      " expression may contain parentheses delimited sub-groups.\n\n"
       /***************** 80 character line width template *************************/
#if defined (HAVE_PCREPOSIX_H)
      " The syntax of the regular expressions available are those supported by\n"
      " the Perl Compatible Regular Expression package (aka PCRE).  As the name\n"
      " implies, the syntax is generally the same as Perl regular expressions.\n"
      " See http://perldoc.perl.org/perlre.html for more details\n"
#elif defined (HAVE_REGEX_H)
      " The syntax of the regular expressions available are those supported by\n"
      " your local system's Regular Expression library using the Extended POSIX\n"
      " Regular Expressiona\n"
#else
      " Regular expression support is not currently available on your environment.\n"
      " This simulator could use regular expression support provided by the\n"
      " Perl Compatible Regular Expression (PCRE) package if it was available\n"
      " when you simulator was compiled.\n"
#endif
      "5-i\n"
      " If a regular expression expect rule is defined with the -i switch,\n"
      " character matching for that expression will be case independent.\n"
      " The -i switch is only valid for regular expression expect rules.\n"
      "5-t\n"
      " The -t switch indicates that the value specified by the HaltAfter\n"
      " parameter are in units of microseconds rather than instructions.\n"
      "4Determining Which Output Matched\n"
      " When an expect rule matches data in the output stream, the rule which\n"
      " matched is recorded in the environment variable _EXPECT_MATCH_PATTERN.\n"
      " If the expect rule was a regular expression rule, then the environment\n"
      " variable _EXPECT_MATCH_GROUP_0 is set to the whole string which matched\n"
      " and if the match pattern had any parentheses delimited sub-groups, the\n"
      " environment variables _EXPECT_MATCH_GROUP_1 thru _EXPECT_MATCH_GROUP_n\n"







|
>
>


















|




<
<
<
<












|







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
      " 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"
      " to match other expect rules which may already be defined.\n"
      " Data which is output prior to the definition of an expect rule is not\n"
      " eligible to be matched against.\n\n"
      " The NOEXPECT command removes a previously defined EXPECT command for the\n"
      " console or a specific multiplexer line.  A NOEXPECT command, without a\n"
      " specific mention of a particular EXPECT match string, will remove all\n"
      " currently defined EXPECT match rules.\n\n"
      " The SHOW EXPECT command displays all of the pending EXPECT state for\n"
      " the console or a specific multiplexer line.\n"
       /***************** 80 character line width template *************************/
      "4Switches\n"
      " Switches can be used to influence the behavior of EXPECT rules\n\n"
      "5-p\n"
      " EXPECT rules default to be one shot activities.  That is a rule is\n"
      " automatically removed when it matches unless it is designated as a\n"
      " persistent rule by using a -p switch when the rule is defined.\n"
      "5-c\n"
      " If an expect rule is defined with the -c switch, it will cause all\n"
      " pending expect rules on the current device to be cleared when the rule\n"
      " matches data in the device output stream.\n"
      "5-r\n"
      " If an expect rule is defined with the -r switch, the string is interpreted\n"
      " as a regular expression applied to the output data stream.  This regular\n"
      " expression may contain parentheses delimited sub-groups.\n\n"
       /***************** 80 character line width template *************************/
#if defined (HAVE_PCRE_H)
      " The syntax of the regular expressions available are those supported by\n"
      " the Perl Compatible Regular Expression package (aka PCRE).  As the name\n"
      " implies, the syntax is generally the same as Perl regular expressions.\n"
      " See http://perldoc.perl.org/perlre.html for more details\n"




#else
      " Regular expression support is not currently available on your environment.\n"
      " This simulator could use regular expression support provided by the\n"
      " Perl Compatible Regular Expression (PCRE) package if it was available\n"
      " when you simulator was compiled.\n"
#endif
      "5-i\n"
      " If a regular expression expect rule is defined with the -i switch,\n"
      " character matching for that expression will be case independent.\n"
      " The -i switch is only valid for regular expression expect rules.\n"
      "5-t\n"
      " The -t switch indicates that the value specified by the HaltAfter\n"
      " parameter are in units of microseconds rather than %C.\n"
      "4Determining Which Output Matched\n"
      " When an expect rule matches data in the output stream, the rule which\n"
      " matched is recorded in the environment variable _EXPECT_MATCH_PATTERN.\n"
      " If the expect rule was a regular expression rule, then the environment\n"
      " variable _EXPECT_MATCH_GROUP_0 is set to the whole string which matched\n"
      " and if the match pattern had any parentheses delimited sub-groups, the\n"
      " environment variables _EXPECT_MATCH_GROUP_1 thru _EXPECT_MATCH_GROUP_n\n"
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
      "++\\?  Expect the ASCII Question Mark character (Decimal value 63)\n"
      "++\\e  Expect the ASCII Escape character (Decimal value 27)\n"
      " as well as octal character values of the form:\n"
      "++\\n{n{n}} where each n is an octal digit (0-7)\n"
      " and hext character values of the form:\n"
      "++\\xh{h} where each h is a hex digit (0-9A-Fa-f)\n"
      "4HaltAfter\n"
      " Specifies the number of instructions which should be executed before\n"
      " simulator instruction execution should stop.  The default is to stop\n"
      " executing instructions immediately (i.e. HALTAFTER=0).\n"
      " The default HaltAfter delay, once set, persists for all expect behaviors\n"
      " for that device.\n"
      " The default HaltAfter parameter value can be set by itself with:\n\n"
      "++EXPECT HALTAFTER=n\n\n"
      " A unique HaltAfter value can be specified with each expect matching rule\n"
      " which if it is not specified then the default value will be used.\n"
      " To avoid potentially unpredictable system hehavior that will happen\n"
      " if multiple expect rules are in effect and a haltafter value is large\n"
      " enough for more than one expect rule to match before an earlier haltafter\n"
      " delay has expired, only a single EXPECT rule can be defined if a non-zero\n"
      " HaltAfter parameter has been set.\n"


      /***************** 80 character line width template *************************/
#define HLP_SLEEP       "*Commands Executing_Command_Files Pausing_Command_Execution"
      "3Pausing Command Execution\n"
      " A simulator command file may wait for a specific period of time with the\n\n"
      "++SLEEP NUMBER[SUFFIX]...\n\n"
      " Pause for NUMBER seconds.  SUFFIX may be 's' for seconds (the default),\n"
      " 'm' for minutes, 'h' for hours or 'd' for days.  NUMBER may be an\n"







|













>
>







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
      "++\\?  Expect the ASCII Question Mark character (Decimal value 63)\n"
      "++\\e  Expect the ASCII Escape character (Decimal value 27)\n"
      " as well as octal character values of the form:\n"
      "++\\n{n{n}} where each n is an octal digit (0-7)\n"
      " and hext character values of the form:\n"
      "++\\xh{h} where each h is a hex digit (0-9A-Fa-f)\n"
      "4HaltAfter\n"
      " Specifies the number of %C which should be executed before\n"
      " simulator instruction execution should stop.  The default is to stop\n"
      " executing instructions immediately (i.e. HALTAFTER=0).\n"
      " The default HaltAfter delay, once set, persists for all expect behaviors\n"
      " for that device.\n"
      " The default HaltAfter parameter value can be set by itself with:\n\n"
      "++EXPECT HALTAFTER=n\n\n"
      " A unique HaltAfter value can be specified with each expect matching rule\n"
      " which if it is not specified then the default value will be used.\n"
      " To avoid potentially unpredictable system hehavior that will happen\n"
      " if multiple expect rules are in effect and a haltafter value is large\n"
      " enough for more than one expect rule to match before an earlier haltafter\n"
      " delay has expired, only a single EXPECT rule can be defined if a non-zero\n"
      " HaltAfter parameter has been set.\n"
      " The value n can be specified with a suffix of k or m which indicates\n"
      " a multiplier of 1000 or 1000000 respectively\n"
      /***************** 80 character line width template *************************/
#define HLP_SLEEP       "*Commands Executing_Command_Files Pausing_Command_Execution"
      "3Pausing Command Execution\n"
      " A simulator command file may wait for a specific period of time with the\n\n"
      "++SLEEP NUMBER[SUFFIX]...\n\n"
      " Pause for NUMBER seconds.  SUFFIX may be 's' for seconds (the default),\n"
      " 'm' for minutes, 'h' for hours or 'd' for days.  NUMBER may be an\n"
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
      "++EXIT {status}        exit with optional status\n\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"
      " launch the host operating system's command shell.\n"
      " The exit status from the command which was executed is set as the command\n"
      " completion status for the ! command.  This may influence any enabled ON\n"
      " condition traps\n";























static CTAB cmd_table[] = {
    { "RESET",      &reset_cmd,     0,          HLP_RESET,      NULL, NULL },
    { "EXAMINE",    &exdep_cmd,     EX_E,       HLP_EXAMINE,    NULL, NULL },
    { "IEXAMINE",   &exdep_cmd,     EX_E+EX_I,  HLP_IEXAMINE,   NULL, NULL },
    { "DEPOSIT",    &exdep_cmd,     EX_D,       HLP_DEPOSIT,    NULL, NULL },







|















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







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
      "++EXIT {status}        exit with optional status\n\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"
      " launch the host operating system's command shell.\n"
      " The exit status from the command which was executed is set as the command\n"
      " completion status for the ! command.  This may influence any enabled ON\n"
      " condition traps\n"
#define HLP_TESTLIB     "*Commands Testing_Device_Libraries"
      "2Testing Device Libraries\n"
      " A simulator developer may need to invoke the simh internal device library\n"
      " test routines that exercise the various libraries used by different devices.\n\n"
      " There are library test routines for devices which use:\n\n"
      "++sim_disk  - Disk devices\n"
      "++sim_tape  - Tape devices\n"
      "++sim_ether - Ethernet devices\n"
      "++sim_card  - Card Reader/Punch Devices\n"
      "++sim_tmxr  - Terminal Multiplexor Devices\n\n"
      " The TESTLIB command by itself will invoke library tests for all devices in the\n"
      " current simulator.\n\n"
      " The library tests for a specific device can be invoked by specifying the device\n"
      " name as an argument to the TESTLIB command:\n\n"
      "++TESTLIB {device}           test a specific or all devices\n\n"
       /***************** 80 character line width template *************************/
      "3Switches\n"
      " Switches can be used to influence the behavior of the TESTLIB command\n\n"
      "4-d\n"
      " Many tests are capable of producing various amounts of debug output\n"
      " during their execution.  The -d switch enables that output\n";


static CTAB cmd_table[] = {
    { "RESET",      &reset_cmd,     0,          HLP_RESET,      NULL, NULL },
    { "EXAMINE",    &exdep_cmd,     EX_E,       HLP_EXAMINE,    NULL, NULL },
    { "IEXAMINE",   &exdep_cmd,     EX_E+EX_I,  HLP_IEXAMINE,   NULL, NULL },
    { "DEPOSIT",    &exdep_cmd,     EX_D,       HLP_DEPOSIT,    NULL, NULL },
2356
2357
2358
2359
2360
2361
2362





2363
2364
2365
2366
2367
2368
2369
    { "LS",         &dir_cmd,       0,          HLP_LS,         NULL, NULL },
    { "TYPE",       &type_cmd,      0,          HLP_TYPE,       NULL, NULL },
    { "CAT",        &type_cmd,      0,          HLP_CAT,        NULL, NULL },
    { "DELETE",     &delete_cmd,    0,          HLP_DELETE,     NULL, NULL },
    { "RM",         &delete_cmd,    0,          HLP_RM,         NULL, NULL },
    { "COPY",       &copy_cmd,      0,          HLP_COPY,       NULL, NULL },
    { "CP",         &copy_cmd,      0,          HLP_CP,         NULL, NULL },





    { "SET",        &set_cmd,       0,          HLP_SET,        NULL, NULL },
    { "SHOW",       &show_cmd,      0,          HLP_SHOW,       NULL, NULL },
    { "DO",         &do_cmd,        1,          HLP_DO,         NULL, NULL },
    { "GOTO",       &goto_cmd,      1,          HLP_GOTO,       NULL, NULL },
    { "RETURN",     &return_cmd,    0,          HLP_RETURN,     NULL, NULL },
    { "SHIFT",      &shift_cmd,     0,          HLP_SHIFT,      NULL, NULL },
    { "CALL",       &call_cmd,      0,          HLP_CALL,       NULL, NULL },







>
>
>
>
>







2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
    { "LS",         &dir_cmd,       0,          HLP_LS,         NULL, NULL },
    { "TYPE",       &type_cmd,      0,          HLP_TYPE,       NULL, NULL },
    { "CAT",        &type_cmd,      0,          HLP_CAT,        NULL, NULL },
    { "DELETE",     &delete_cmd,    0,          HLP_DELETE,     NULL, NULL },
    { "RM",         &delete_cmd,    0,          HLP_RM,         NULL, NULL },
    { "COPY",       &copy_cmd,      0,          HLP_COPY,       NULL, NULL },
    { "CP",         &copy_cmd,      0,          HLP_CP,         NULL, NULL },
    { "RENAME",     &rename_cmd,    0,          HLP_RENAME,     NULL, NULL },
    { "MOVE",       &rename_cmd,    0,          HLP_MOVE,       NULL, NULL },
    { "MV",         &rename_cmd,    0,          HLP_MOVE,       NULL, NULL },
    { "MKDIR",      &mkdir_cmd,     0,          HLP_MKDIR,      NULL, NULL },
    { "RMDIR",      &rmdir_cmd,     0,          HLP_RMDIR,      NULL, NULL },
    { "SET",        &set_cmd,       0,          HLP_SET,        NULL, NULL },
    { "SHOW",       &show_cmd,      0,          HLP_SHOW,       NULL, NULL },
    { "DO",         &do_cmd,        1,          HLP_DO,         NULL, NULL },
    { "GOTO",       &goto_cmd,      1,          HLP_GOTO,       NULL, NULL },
    { "RETURN",     &return_cmd,    0,          HLP_RETURN,     NULL, NULL },
    { "SHIFT",      &shift_cmd,     0,          HLP_SHIFT,      NULL, NULL },
    { "CALL",       &call_cmd,      0,          HLP_CALL,       NULL, NULL },
2381
2382
2383
2384
2385
2386
2387



2388
2389
2390
2391
2392
2393
2394
    { "NOEXPECT",   &expect_cmd,    0,          HLP_EXPECT,     NULL, NULL },
    { "SLEEP",      &sleep_cmd,     0,          HLP_SLEEP,      NULL, NULL },
    { "!",          &spawn_cmd,     0,          HLP_SPAWN,      NULL, NULL },
    { "HELP",       &help_cmd,      0,          HLP_HELP,       NULL, NULL },
#if defined(USE_SIM_VIDEO)
    { "SCREENSHOT", &screenshot_cmd,0,          HLP_SCREENSHOT, NULL, NULL },
#endif



    { NULL,         NULL,           0,          NULL,           NULL, NULL }
    };

static CTAB set_glob_tab[] = {
    { "CONSOLE",    &sim_set_console,           0, HLP_SET_CONSOLE },
    { "REMOTE",     &sim_set_remote_console,    0, HLP_SET_REMOTE },
    { "BREAK",      &brk_cmd,              SSH_ST, HLP_SET_BREAK },







>
>
>







2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
    { "NOEXPECT",   &expect_cmd,    0,          HLP_EXPECT,     NULL, NULL },
    { "SLEEP",      &sleep_cmd,     0,          HLP_SLEEP,      NULL, NULL },
    { "!",          &spawn_cmd,     0,          HLP_SPAWN,      NULL, NULL },
    { "HELP",       &help_cmd,      0,          HLP_HELP,       NULL, NULL },
#if defined(USE_SIM_VIDEO)
    { "SCREENSHOT", &screenshot_cmd,0,          HLP_SCREENSHOT, NULL, NULL },
#endif
    { "RUNLIMIT",   &runlimit_cmd,  1,          HLP_RUNLIMIT,   NULL, NULL },
    { "NORUNLIMIT", &runlimit_cmd,  0,          HLP_RUNLIMIT,   NULL, NULL },
    { "TESTLIB",    &test_lib_cmd,  0,          HLP_TESTLIB,    NULL, NULL },
    { NULL,         NULL,           0,          NULL,           NULL, NULL }
    };

static CTAB set_glob_tab[] = {
    { "CONSOLE",    &sim_set_console,           0, HLP_SET_CONSOLE },
    { "REMOTE",     &sim_set_remote_console,    0, HLP_SET_REMOTE },
    { "BREAK",      &brk_cmd,              SSH_ST, HLP_SET_BREAK },
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
    { "NOVERIFY",   &set_verify,                0, HLP_SET_VERIFY },
    { "NOVERBOSE",  &set_verify,                0, HLP_SET_VERIFY },
    { "MESSAGE",    &set_message,               1, HLP_SET_MESSAGE },
    { "NOMESSAGE",  &set_message,               0, HLP_SET_MESSAGE },
    { "QUIET",      &set_quiet,                 1, HLP_SET_QUIET },
    { "NOQUIET",    &set_quiet,                 0, HLP_SET_QUIET },
    { "PROMPT",     &set_prompt,                0, HLP_SET_PROMPT },


    { NULL,         NULL,                       0 }
    };

static C1TAB set_dev_tab[] = {
    { "OCTAL",      &set_dev_radix,     8 },
    { "DECIMAL",    &set_dev_radix,     10 },
    { "HEX",        &set_dev_radix,     16 },
    { "BINARY",     &set_dev_radix,     2 },
    { "ENABLED",    &set_dev_enbdis,    1 },
    { "DISABLED",   &set_dev_enbdis,    0 },
    { "DEBUG",      &set_dev_debug,     1 },
    { "NODEBUG",    &set_dev_debug,     0 },


    { NULL,         NULL,               0 }
    };

static C1TAB set_unit_tab[] = {
    { "ENABLED",    &set_unit_enbdis,   1 },
    { "DISABLED",   &set_unit_enbdis,   0 },
    { "DEBUG",      &set_dev_debug,     2+1 },
    { "NODEBUG",    &set_dev_debug,     2+0 },


    { NULL,         NULL,               0 }
    };

static SHTAB show_glob_tab[] = {
    { "CONFIGURATION",  &show_config,               0, HLP_SHOW_CONFIG },
    { "DEVICES",        &show_config,               1, HLP_SHOW_DEVICES },
    { "FEATURES",       &show_config,               2, HLP_SHOW_FEATURES },







>
>












>
>








>
>







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
    { "NOVERIFY",   &set_verify,                0, HLP_SET_VERIFY },
    { "NOVERBOSE",  &set_verify,                0, HLP_SET_VERIFY },
    { "MESSAGE",    &set_message,               1, HLP_SET_MESSAGE },
    { "NOMESSAGE",  &set_message,               0, HLP_SET_MESSAGE },
    { "QUIET",      &set_quiet,                 1, HLP_SET_QUIET },
    { "NOQUIET",    &set_quiet,                 0, HLP_SET_QUIET },
    { "PROMPT",     &set_prompt,                0, HLP_SET_PROMPT },
    { "RUNLIMIT",   &set_runlimit,              1, HLP_RUNLIMIT },
    { "NORUNLIMIT", &set_runlimit,              0, HLP_RUNLIMIT },
    { NULL,         NULL,                       0 }
    };

static C1TAB set_dev_tab[] = {
    { "OCTAL",      &set_dev_radix,     8 },
    { "DECIMAL",    &set_dev_radix,     10 },
    { "HEX",        &set_dev_radix,     16 },
    { "BINARY",     &set_dev_radix,     2 },
    { "ENABLED",    &set_dev_enbdis,    1 },
    { "DISABLED",   &set_dev_enbdis,    0 },
    { "DEBUG",      &set_dev_debug,     1 },
    { "NODEBUG",    &set_dev_debug,     0 },
    { "APPEND",     &set_unit_append,   0 },
    { "EOF",        &set_unit_append,   0 },
    { NULL,         NULL,               0 }
    };

static C1TAB set_unit_tab[] = {
    { "ENABLED",    &set_unit_enbdis,   1 },
    { "DISABLED",   &set_unit_enbdis,   0 },
    { "DEBUG",      &set_dev_debug,     2+1 },
    { "NODEBUG",    &set_dev_debug,     2+0 },
    { "APPEND",     &set_unit_append,   0 },
    { "EOF",        &set_unit_append,   0 },
    { NULL,         NULL,               0 }
    };

static SHTAB show_glob_tab[] = {
    { "CONFIGURATION",  &show_config,               0, HLP_SHOW_CONFIG },
    { "DEVICES",        &show_config,               1, HLP_SHOW_DEVICES },
    { "FEATURES",       &show_config,               2, HLP_SHOW_FEATURES },
2465
2466
2467
2468
2469
2470
2471
2472


2473
2474
2475
2476
2477
2478
2479
    { "MUX",            &tmxr_show_open_devices,    0, HLP_SHOW_MULTIPLEXER },
#if defined(USE_SIM_VIDEO)
    { "VIDEO",          &vid_show,                  0, HLP_SHOW_VIDEO },
#endif
    { "CLOCKS",         &sim_show_timers,           0, HLP_SHOW_CLOCKS },
    { "SEND",           &sim_show_send,             0, HLP_SHOW_SEND },
    { "EXPECT",         &sim_show_expect,           0, HLP_SHOW_EXPECT },
    { "ON",             &show_on,                   0, HLP_SHOW_ON },


    { NULL,             NULL,                       0 }
    };

static SHTAB show_dev_tab[] = {
    { "RADIX",      &show_dev_radix,            0 },
    { "DEBUG",      &show_dev_debug,            0 },
    { "MODIFIERS",  &show_dev_modifiers,        0 },







|
>
>







2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
    { "MUX",            &tmxr_show_open_devices,    0, HLP_SHOW_MULTIPLEXER },
#if defined(USE_SIM_VIDEO)
    { "VIDEO",          &vid_show,                  0, HLP_SHOW_VIDEO },
#endif
    { "CLOCKS",         &sim_show_timers,           0, HLP_SHOW_CLOCKS },
    { "SEND",           &sim_show_send,             0, HLP_SHOW_SEND },
    { "EXPECT",         &sim_show_expect,           0, HLP_SHOW_EXPECT },
    { "ON",             &show_on,                  -1, HLP_SHOW_ON },
    { "DO",             &show_do,                   0, HLP_SHOW_DO },
    { "RUNLIMIT",       &show_runlimit,             0, HLP_SHOW_RUNLIMIT },
    { NULL,             NULL,                       0 }
    };

static SHTAB show_dev_tab[] = {
    { "RADIX",      &show_dev_radix,            0 },
    { "DEBUG",      &show_dev_debug,            0 },
    { "MODIFIERS",  &show_dev_modifiers,        0 },
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
int unsetenv(const char *envname)
{
setenv(envname, "", 1);
return 0;
}
#endif

t_stat process_stdin_commands (t_stat stat, char *argv[]);

/* Main command loop */

int main (int argc, char *argv[])
{
char cbuf[4*CBUFSIZE], *cptr, *cptr2;
char nbuf[PATH_MAX + 7];
char **targv = NULL;
int32 i, sw;
t_bool lookswitch;

t_stat stat = SCPE_OK;

#if defined (__MWERKS__) && defined (macintosh)
argc = ccommand (&argv);
#endif

/* Make sure that argv has at least 10 elements and that it ends in a NULL pointer */
targv = (char **)calloc (1+MAX(10, argc), sizeof(*targv));
for (i=0; i<argc; i++)
    targv[i] = argv[i];
argv = targv;
set_prompt (0, "sim>");                                 /* start with set standard prompt */
*cbuf = 0;                                              /* init arg buffer */
sim_switches = 0;                                       /* init switches */
lookswitch = TRUE;
stdnul = fopen(NULL_DEVICE,"wb");










for (i = 1; i < argc; i++) {                            /* loop thru args */
    if (argv[i] == NULL)                                /* paranoia */
        continue;
    if ((*argv[i] == '-') && lookswitch) {              /* switch? */
        if (get_switches (argv[i], &sw, NULL) == SW_ERROR) {
            fprintf (stderr, "Invalid switch %s\n", argv[i]);
            free (targv);







|










>
















>
>
>
>
>
>
>
>
>
>







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
2703
int unsetenv(const char *envname)
{
setenv(envname, "", 1);
return 0;
}
#endif

t_stat process_stdin_commands (t_stat stat, char *argv[], t_bool do_called);

/* Main command loop */

int main (int argc, char *argv[])
{
char cbuf[4*CBUFSIZE], *cptr, *cptr2;
char nbuf[PATH_MAX + 7];
char **targv = NULL;
int32 i, sw;
t_bool lookswitch;
t_bool register_check = FALSE;
t_stat stat = SCPE_OK;

#if defined (__MWERKS__) && defined (macintosh)
argc = ccommand (&argv);
#endif

/* Make sure that argv has at least 10 elements and that it ends in a NULL pointer */
targv = (char **)calloc (1+MAX(10, argc), sizeof(*targv));
for (i=0; i<argc; i++)
    targv[i] = argv[i];
argv = targv;
set_prompt (0, "sim>");                                 /* start with set standard prompt */
*cbuf = 0;                                              /* init arg buffer */
sim_switches = 0;                                       /* init switches */
lookswitch = TRUE;
stdnul = fopen(NULL_DEVICE,"wb");
sim_prog_name = argv [0];                               /* save a pointer to the program name */
if (argc > 1) {                                         /* Check for special argument to invoke register test */
    if (sim_strcasecmp (argv[1], "RegisterSanityCheck") == 0) {
        register_check = TRUE;
        --argc;                                         /* Remove special argument to avoid confusion later */
        for (i = 1; i < argc; i++)
            argv[i] = argv[i+1];
        argv[i+1] = NULL;
        }
    }
for (i = 1; i < argc; i++) {                            /* loop thru args */
    if (argv[i] == NULL)                                /* paranoia */
        continue;
    if ((*argv[i] == '-') && lookswitch) {              /* switch? */
        if (get_switches (argv[i], &sw, NULL) == SW_ERROR) {
            fprintf (stderr, "Invalid switch %s\n", argv[i]);
            free (targv);
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
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
2654
2655
2656
2657
2658
            }
        if (*cbuf)                                      /* concat args */
            strlcat (cbuf, " ", sizeof (cbuf)); 
        sprintf(&cbuf[strlen(cbuf)], "%s%s%s", strchr(argv[i], ' ') ? "\"" : "", argv[i], strchr(argv[i], ' ') ? "\"" : "");
        lookswitch = FALSE;                             /* no more switches */
        }
    }                                                   /* end for */
sim_quiet = sim_switches & SWMASK ('Q');                /* -q means quiet */
sim_on_inherit = sim_switches & SWMASK ('O');           /* -o means inherit on state */


sim_init_sock ();                                       /* init socket capabilities */
AIO_INIT;                                               /* init Asynch I/O */
if (sim_vm_init != NULL)                                /* call once only */
    (*sim_vm_init)();
sim_finit ();                                           /* init fio package */
setenv ("SIM_NAME", sim_name, 1);                       /* Publish simulator name */
stop_cpu = FALSE;
sim_interval = 0;
sim_time = sim_rtime = 0;
noqueue_time = 0;
sim_clock_queue = QUEUE_LIST_END;
sim_is_running = FALSE;
sim_log = NULL;
if (sim_emax <= 0)
    sim_emax = 1;
if (sim_timer_init ()) {
    fprintf (stderr, "Fatal timer initialization error\n");
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
sim_register_internal_device (&sim_scp_dev);
sim_register_internal_device (&sim_expect_dev);
sim_register_internal_device (&sim_step_dev);
sim_register_internal_device (&sim_flush_dev);

if ((stat = sim_ttinit ()) != SCPE_OK) {
    fprintf (stderr, "Fatal terminal initialization error\n%s\n",
        sim_error_text (stat));
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
if ((sim_eval = (t_value *) calloc (sim_emax, sizeof (t_value))) == NULL) {
    fprintf (stderr, "Unable to allocate examine buffer\n");
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    };
if (sim_dflt_dev == NULL)                               /* if no default */
    sim_dflt_dev = sim_devices[0];
if ((stat = reset_all_p (0)) != SCPE_OK) {
    fprintf (stderr, "Fatal simulator initialization error\n%s\n",
        sim_error_text (stat));
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
if ((stat = sim_brk_init ()) != SCPE_OK) {
    fprintf (stderr, "Fatal breakpoint table initialization error\n%s\n",
        sim_error_text (stat));
    read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
signal (SIGINT, int_handler);
if (!sim_quiet) {
    printf ("\n");
    show_version (stdout, NULL, NULL, 0, NULL);
    }
show_version (stdnul, NULL, NULL, 1, NULL);             /* Quietly set SIM_OSTYPE */
#if defined (HAVE_PCREPOSIX_H)
setenv ("SIM_REGEX_TYPE", "PCREPOSIX", 1);              /* Publish regex type */
#elif defined (HAVE_REGEX_H)
setenv ("SIM_REGEX_TYPE", "REGEX", 1);                  /* Publish regex type */
#endif
if (*argv[0]) {                                         /* sim name arg? */
    char *np;                                           /* "path.ini" */

    strlcpy (nbuf, argv[0], PATH_MAX + 2);              /* 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 */
    setenv ("SIM_BIN_PATH", argv[0], 1);

#ifdef PIDP8I
    if (strstr (argv[0], "pidp8i-sim") == 0) use_pidp8i_extensions = 0;
    else if (start_pidp8i_gpio_thread (0) != 0) exit (EXIT_FAILURE);
#endif
    }























































































sim_argv = argv;




cptr = getenv("HOME");
if (cptr == NULL) {
    cptr = getenv("HOMEPATH");
    cptr2 = getenv("HOMEDRIVE");
    }
else
    cptr2 = NULL;







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















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

>
>
>
>







2713
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
2759
2760
2761
2762
2763
2764
2765
2766
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
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
            }
        if (*cbuf)                                      /* concat args */
            strlcat (cbuf, " ", sizeof (cbuf)); 
        sprintf(&cbuf[strlen(cbuf)], "%s%s%s", strchr(argv[i], ' ') ? "\"" : "", argv[i], strchr(argv[i], ' ') ? "\"" : "");
        lookswitch = FALSE;                             /* no more switches */
        }
    }                                                   /* end for */

































































if (*argv[0]) {                                         /* sim name arg? */
    char *np;                                           /* "path.ini" */

    strlcpy (nbuf, argv[0], PATH_MAX + 2);              /* 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 */
    setenv ("SIM_BIN_PATH", argv[0], 1);

#ifdef PIDP8I
    if (strstr (argv[0], "pidp8i-sim") == 0) use_pidp8i_extensions = 0;
    else if (start_pidp8i_gpio_thread (0) != 0) exit (EXIT_FAILURE);
#endif
    }

sim_quiet = sim_switches & SWMASK ('Q');                /* -q means quiet */
sim_on_inherit = sim_switches & SWMASK ('O');           /* -o means inherit on state */

sim_init_sock ();                                       /* init socket capabilities */
AIO_INIT;                                               /* init Asynch I/O */
if (sim_vm_init != NULL)                                /* call once only */
    (*sim_vm_init)();
sim_finit ();                                           /* init fio package */
setenv ("SIM_NAME", sim_name, 1);                       /* Publish simulator name */
stop_cpu = FALSE;
sim_interval = 0;
sim_time = sim_rtime = 0;
noqueue_time = 0;
sim_clock_queue = QUEUE_LIST_END;
sim_is_running = FALSE;
sim_log = NULL;
if (sim_emax <= 0)
    sim_emax = 1;
if (sim_timer_init ()) {
    fprintf (stderr, "Fatal timer initialization error\n");
    if (sim_ttisatty())
        read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
sim_register_internal_device (&sim_scp_dev);
sim_register_internal_device (&sim_expect_dev);
sim_register_internal_device (&sim_step_dev);
sim_register_internal_device (&sim_flush_dev);
sim_register_internal_device (&sim_runlimit_dev);

if ((stat = sim_ttinit ()) != SCPE_OK) {
    fprintf (stderr, "Fatal terminal initialization error\n%s\n",
        sim_error_text (stat));
    if (sim_ttisatty())
        read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
if ((sim_eval = (t_value *) calloc (sim_emax, sizeof (t_value))) == NULL) {
    fprintf (stderr, "Unable to allocate examine buffer\n");
    if (sim_ttisatty())
        read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    };
if (sim_dflt_dev == NULL)                               /* if no default */
    sim_dflt_dev = sim_devices[0];
if ((stat = reset_all_p (0)) != SCPE_OK) {
    fprintf (stderr, "Fatal simulator initialization error\n%s\n",
        sim_error_text (stat));
    if (sim_ttisatty())
        read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
if (register_check) {
    /* This test is explicitly run after the above reset_all_p() so that any devices 
       which dynamically manipulate their register lists have already done that. */
    sim_printf (" Running internal register sanity checks on %s simulator.\n", sim_name);
    if ((stat = sim_sanity_check_register_declarations ()) != SCPE_OK) {
        sim_printf ("Simulator device register sanity check error\n");
        if (sim_ttisatty())
            read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
        return EXIT_FAILURE;
        }
    sim_printf ("*** Good Registers in %s simulator.\n", sim_name);
    if (argc < 2)                                   /* No remaining command arguments? */
        return EXIT_SUCCESS;                        /* then we're done */
    }
if ((stat = sim_brk_init ()) != SCPE_OK) {
    fprintf (stderr, "Fatal breakpoint table initialization error\n%s\n",
        sim_error_text (stat));
    if (sim_ttisatty())
        read_line_p ("Hit Return to exit: ", cbuf, sizeof (cbuf) - 1, stdin);
    return EXIT_FAILURE;
    }
/* always check for register definition problems */
sim_sanity_check_register_declarations ();

signal (SIGINT, int_handler);
if (!sim_quiet) {
    printf ("\n");
    show_version (stdout, NULL, NULL, 0, NULL);
    }
sim_timer_precalibrate_execution_rate ();
show_version (stdnul, NULL, NULL, 1, NULL);             /* Quietly set SIM_OSTYPE */
#if defined (HAVE_PCRE_H)
setenv ("SIM_REGEX_TYPE", "PCRE", 1);                   /* Publish regex type */
#endif
sim_argv = argv;

if (sim_switches & SWMASK ('T'))                        /* Command Line -T switch */
    stat = test_lib_cmd (0, "ALL");                     /* run library unit tests */

cptr = getenv("HOME");
if (cptr == NULL) {
    cptr = getenv("HOMEPATH");
    cptr2 = getenv("HOMEDRIVE");
    }
else
    cptr2 = NULL;
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
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
2759
2760
2761
2762
2763
2764
2765
2766
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
            stat = do_cmd (-1, np) & ~SCPE_NOMESSAGE;   /* proc default cmd file */
            }
        }
    }
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)             /* didn't exist/can't open? */
    stat = SCPE_OK;

if (sim_switches & SWMASK ('T'))                       /* Command Line -T switch */
    stat = sim_library_unit_tests ();                   /* run library unit tests */

if (SCPE_BARE_STATUS(stat) != SCPE_EXIT)
    process_stdin_commands (SCPE_BARE_STATUS(stat), argv);

detach_all (0, TRUE);                                   /* close files */
sim_set_deboff (0, NULL);                               /* close debug */
sim_set_logoff (0, NULL);                               /* close log */
sim_set_notelnet (0, NULL);                             /* close Telnet */
vid_close ();                                           /* close video */
sim_ttclose ();                                         /* close console */
AIO_CLEANUP;                                            /* Asynch I/O */
sim_cleanup_sock ();                                    /* cleanup sockets */
fclose (stdnul);                                        /* close bit bucket file handle */
free (targv);                                           /* release any argv copy that was made */

#ifdef PIDP8I
if (use_pidp8i_extensions) stop_pidp8i_gpio_thread ();
#endif

return sim_exit_status;
}

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 */
    if (stop_cpu) {                                     /* SIGINT happened? */
        stop_cpu = FALSE;
        if ((!sim_ttisatty()) || 
            sigterm_received) {
            stat = SCPE_EXIT;
            break;
            }
        if (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION])
            sim_brk_setact (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]);
        }
#ifdef PIDP8I
    if (cptr = build_pidp8i_scp_cmd (cbuf, sizeof (cbuf)))
        printf ("Running '%s'...\n", cptr);
    else
#endif
    if ((cptr = sim_brk_getact (cbuf, sizeof(cbuf)))) { /* pending action? */

        if (sim_do_echo)
            printf ("%s+ %s\n", sim_prompt, cptr);      /* echo */
        sim_cptr_is_action[sim_do_depth] = TRUE;
        }
    else {
        if (sim_vm_read != NULL) {                      /* sim routine? */
            printf ("%s", sim_prompt);                  /* prompt */
            cptr = (*sim_vm_read) (cbuf, sizeof(cbuf), stdin);
            }
        else
            cptr = read_line_p (sim_prompt, cbuf, sizeof(cbuf), stdin);/* read with prompt*/

        sim_cptr_is_action[sim_do_depth] = FALSE;
        }
    if (cptr == NULL) {                                 /* EOF? or SIGINT? */
        if (sim_ttisatty()) {
            printf ("\n");
            continue;                                   /* ignore tty EOF */
            }
        else
            break;                                      /* otherwise exit */
        }
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    sim_cmd_echoed = TRUE;
    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);


    if (!sim_cptr_is_action[sim_do_depth]) {
        sim_if_cmd_last[sim_do_depth] = sim_if_cmd[sim_do_depth];
        sim_if_result_last[sim_do_depth] = sim_if_result[sim_do_depth];
        sim_if_result[sim_do_depth] = sim_if_cmd[sim_do_depth] = FALSE;
        }
    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)
{







<
<
<

|



















|




|














|



|
>











>


















>
>





<
<
|
>
>

>
















>
>
>
>
>
>
>
>







2863
2864
2865
2866
2867
2868
2869



2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
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
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
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
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
            stat = do_cmd (-1, np) & ~SCPE_NOMESSAGE;   /* proc default cmd file */
            }
        }
    }
if (SCPE_BARE_STATUS(stat) == SCPE_OPENERR)             /* didn't exist/can't open? */
    stat = SCPE_OK;




if (SCPE_BARE_STATUS(stat) != SCPE_EXIT)
    process_stdin_commands (SCPE_BARE_STATUS(stat), argv, FALSE);

detach_all (0, TRUE);                                   /* close files */
sim_set_deboff (0, NULL);                               /* close debug */
sim_set_logoff (0, NULL);                               /* close log */
sim_set_notelnet (0, NULL);                             /* close Telnet */
vid_close ();                                           /* close video */
sim_ttclose ();                                         /* close console */
AIO_CLEANUP;                                            /* Asynch I/O */
sim_cleanup_sock ();                                    /* cleanup sockets */
fclose (stdnul);                                        /* close bit bucket file handle */
free (targv);                                           /* release any argv copy that was made */

#ifdef PIDP8I
if (use_pidp8i_extensions) stop_pidp8i_gpio_thread ();
#endif

return sim_exit_status;
}

t_stat process_stdin_commands (t_stat stat, char *argv[], t_bool do_called)
{
char cbuf[4*CBUFSIZE], gbuf[CBUFSIZE];
CONST char *cptr;
t_stat stat_nomessage;
CTAB *cmdp = NULL;

stat = SCPE_BARE_STATUS(stat);                          /* remove possible flag */
while (stat != SCPE_EXIT) {                             /* in case exit */
    if (stop_cpu) {                                     /* SIGINT happened? */
        stop_cpu = FALSE;
        if ((!sim_ttisatty()) || 
            sigterm_received) {
            stat = SCPE_EXIT;
            break;
            }
        if (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION])
            sim_brk_setact (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]);
        }
#ifdef PIDP8I
    if (sim_do_ocptr[sim_do_depth] = cptr = build_pidp8i_scp_cmd (cbuf, sizeof (cbuf)))
        printf ("Running '%s'...\n", cptr);
    else
#endif
    sim_do_ocptr[sim_do_depth] = cptr = sim_brk_getact (cbuf, sizeof(cbuf)); /* get bkpt action */
    if (sim_do_ocptr[sim_do_depth]) {                   /* pending action? */
        if (sim_do_echo)
            printf ("%s+ %s\n", sim_prompt, cptr);      /* echo */
        sim_cptr_is_action[sim_do_depth] = TRUE;
        }
    else {
        if (sim_vm_read != NULL) {                      /* sim routine? */
            printf ("%s", sim_prompt);                  /* prompt */
            cptr = (*sim_vm_read) (cbuf, sizeof(cbuf), stdin);
            }
        else
            cptr = read_line_p (sim_prompt, cbuf, sizeof(cbuf), stdin);/* read with prompt*/
        sim_do_ocptr[sim_do_depth] = cptr;
        sim_cptr_is_action[sim_do_depth] = FALSE;
        }
    if (cptr == NULL) {                                 /* EOF? or SIGINT? */
        if (sim_ttisatty()) {
            printf ("\n");
            continue;                                   /* ignore tty EOF */
            }
        else
            break;                                      /* otherwise exit */
        }
    if (*cptr == 0)                                     /* ignore blank */
        continue;
    sim_cmd_echoed = TRUE;
    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 (!sim_cptr_is_action[sim_do_depth]) {
        sim_if_cmd_last[sim_do_depth] = sim_if_cmd[sim_do_depth];
        sim_if_result_last[sim_do_depth] = sim_if_result[sim_do_depth];
        sim_if_result[sim_do_depth] = sim_if_cmd[sim_do_depth] = FALSE;
        }


    if ((cmdp = find_cmd (gbuf))) {                     /* lookup command */
        if (do_called && (cmdp->action == &return_cmd)) /* RETURN command? */
            break;
        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 */
if (do_called && cmdp && 
    (cmdp->action == &return_cmd) && (0 != *cptr)) {    /* return command with argument? */
    sim_string_to_stat (cptr, &stat);
    sim_last_cmd_stat = stat;                           /* save explicit status as command error status */
    if (sim_switches & SWMASK ('Q'))
        stat |= SCPE_NOMESSAGE;                         /* suppress error message display (in caller) if requested */
    return stat;                                        /* return with explicit return status */
    }
return stat;
}

/* Set prompt routine */

t_stat set_prompt (int32 flag, CONST char *cptr)
{
2888
2889
2890
2891
2892
2893
2894

2895
2896
2897
2898
2899
2900
2901
2902
    }
fprintf (st, "Help is available for devices\n\n");
fprintf (st, "   HELP dev\n");
fprintf (st, "   HELP dev SET\n");
fprintf (st, "   HELP dev SHOW\n");
fprintf (st, "   HELP dev REGISTERS\n\n");
fprintf (st, "Help is available for the following commands:\n\n    ");

qsort (hlp_cmdp, cmd_cnt, sizeof(*hlp_cmdp), _cmd_name_compare);
line_offset = 4;
for (i=0; i<cmd_cnt; ++i) {
    fputs (hlp_cmdp[i]->name, st);
    line_offset += 5 + max_cmdname_size;
    if (line_offset + max_cmdname_size > 79) {
        line_offset = 4;
        fprintf (st, "\n    ");







>
|







3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
    }
fprintf (st, "Help is available for devices\n\n");
fprintf (st, "   HELP dev\n");
fprintf (st, "   HELP dev SET\n");
fprintf (st, "   HELP dev SHOW\n");
fprintf (st, "   HELP dev REGISTERS\n\n");
fprintf (st, "Help is available for the following commands:\n\n    ");
if (hlp_cmdp)
    qsort (hlp_cmdp, cmd_cnt, sizeof(*hlp_cmdp), _cmd_name_compare);
line_offset = 4;
for (i=0; i<cmd_cnt; ++i) {
    fputs (hlp_cmdp[i]->name, st);
    line_offset += 5 + max_cmdname_size;
    if (line_offset + max_cmdname_size > 79) {
        line_offset = 4;
        fprintf (st, "\n    ");
3020
3021
3022
3023
3024
3025
3026


3027
3028



3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
void fprint_set_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
MTAB *mptr;
DEBTAB *dep;
t_bool found = FALSE;
t_bool deb_desc_available = FALSE;
char buf[CBUFSIZE], header[CBUFSIZE];



sprintf (header, "\n%s device SET commands:\n\n", dptr->name);



if (dptr->modifiers) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        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







>
>


>
>
>




|







3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
void fprint_set_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
MTAB *mptr;
DEBTAB *dep;
t_bool found = FALSE;
t_bool deb_desc_available = FALSE;
char buf[CBUFSIZE], header[CBUFSIZE];
uint32 enabled_units = dptr->numunits;
uint32 unit;

sprintf (header, "\n%s device SET commands:\n\n", dptr->name);
for (unit=0; unit < dptr->numunits; unit++)
    if (dptr->units[unit].flags & UNIT_DIS)
        --enabled_units;
if (dptr->modifiers) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        if (!MODMASK(mptr,MTAB_VDV) && MODMASK(mptr,MTAB_VUN) && (dptr->numunits != 1))
            continue;                                       /* skip unit only extended modifiers */
        if ((enabled_units != 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
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
        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));
        sprintf (buf, "set %sn DISABLE", sim_dname (dptr));
        fprintf (st,  "%-30s\tDisables unit %sn\n", buf, sim_dname (dptr));
        }







|







3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
        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) && (enabled_units != 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));
        sprintf (buf, "set %sn DISABLE", sim_dname (dptr));
        fprintf (st,  "%-30s\tDisables unit %sn\n", buf, sim_dname (dptr));
        }
3109
3110
3111
3112
3113
3114
3115










3116
3117
3118
3119
3120
3121
3122
3123
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
            fprint_header (st, &found, header);
            sprintf (buf, "set %s%s %s%s", sim_dname (dptr), (dptr->numunits > 1) ? "n" : "0", 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, '=')) ? ((strlen (buf) > 30) ? "" : mptr->help) : (mptr->help ? mptr->help : ""));
            if ((strchr (mptr->mstring, '=')) && (strlen (buf) > 30))
                fprintf (st,  "%-30s\t%s\n", "", mptr->help);
            }
        }










    }
if (deb_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 (!found && !silent)
    fprintf (st, "No SET help is available for the %s device\n", dptr->name);
}

void fprint_set_help (FILE *st, DEVICE *dptr)
    {
    fprint_set_help_ex (st, dptr, TRUE);
    }

void fprint_show_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
MTAB *mptr;
t_bool found = FALSE;
char buf[CBUFSIZE], header[CBUFSIZE];



sprintf (header, "\n%s device SHOW commands:\n\n", dptr->name);



if (dptr->modifiers) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        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->disp) || (!mptr->pstring) || !(*mptr->pstring))
            continue;
        fprint_header (st, &found, header);
        sprintf (buf, "show %s %s%s", sim_dname (dptr), mptr->pstring, MODMASK(mptr,MTAB_SHP) ? "=arg" : "");
        fprintf (st, "%-30s\t%s\n", buf, mptr->help ? mptr->help : "");
        }
    }
if ((dptr->flags & DEV_DEBUG) || (dptr->debflags)) {
    fprint_header (st, &found, header);
    sprintf (buf, "show %s DEBUG", sim_dname (dptr));
    fprintf (st, "%-30s\tDisplays debugging status for device %s\n", buf, sim_dname (dptr));
    }
if ((dptr->modifiers) && (dptr->units) && (dptr->numunits != 1)) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        if ((!MODMASK(mptr,MTAB_VUN)) && MODMASK(mptr,MTAB_XTD))
            continue;                                           /* skip device only modifiers */
        if ((!mptr->disp) || (!mptr->pstring))
            continue;
        fprint_header (st, &found, header);
        sprintf (buf, "show %s%s %s%s", sim_dname (dptr), (dptr->numunits > 1) ? "n" : "0", mptr->pstring, MODMASK(mptr,MTAB_SHP) ? "=arg" : "");







>
>
>
>
>
>
>
>
>
>




















>
>


>
>
>




|




|








|







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
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
            fprint_header (st, &found, header);
            sprintf (buf, "set %s%s %s%s", sim_dname (dptr), (dptr->numunits > 1) ? "n" : "0", 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, '=')) ? ((strlen (buf) > 30) ? "" : mptr->help) : (mptr->help ? mptr->help : ""));
            if ((strchr (mptr->mstring, '=')) && (strlen (buf) > 30))
                fprintf (st,  "%-30s\t%s\n", "", mptr->help);
            }
        }
    }
if (enabled_units) {
    for (unit=0; unit < dptr->numunits; unit++)
        if ((!(dptr->units[unit].flags & UNIT_DIS)) &&
            (dptr->units[unit].flags & UNIT_SEQ) && 
            (!(dptr->units[unit].flags & UNIT_MUSTBUF))) {
            sprintf (buf, "set %s%s APPEND", sim_uname (&dptr->units[unit]), (enabled_units > 1) ? "n" : "");
            fprintf (st,  "%-30s\tSets %s%s position to EOF\n", buf, sim_uname (&dptr->units[unit]), (enabled_units > 1) ? "n" : "");
            break;
            }
    }
if (deb_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 (!found && !silent)
    fprintf (st, "No SET help is available for the %s device\n", dptr->name);
}

void fprint_set_help (FILE *st, DEVICE *dptr)
    {
    fprint_set_help_ex (st, dptr, TRUE);
    }

void fprint_show_help_ex (FILE *st, DEVICE *dptr, t_bool silent)
{
MTAB *mptr;
t_bool found = FALSE;
char buf[CBUFSIZE], header[CBUFSIZE];
uint32 enabled_units = dptr->numunits;
uint32 unit;

sprintf (header, "\n%s device SHOW commands:\n\n", dptr->name);
for (unit=0; unit < dptr->numunits; unit++)
    if (dptr->units[unit].flags & UNIT_DIS)
        --enabled_units;
if (dptr->modifiers) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        if (!MODMASK(mptr,MTAB_VDV) && MODMASK(mptr,MTAB_VUN) && (dptr->numunits != 1))
            continue;                                       /* skip unit only extended modifiers */
        if ((enabled_units != 1) && !(mptr->mask & MTAB_XTD))
            continue;                                       /* skip unit only simple modifiers */
        if ((!mptr->disp) || (!mptr->pstring) || !(*mptr->pstring))
            continue;
        fprint_header (st, &found, header);
        sprintf (buf, "show %s %s%s", sim_dname (dptr), mptr->pstring, MODMASK(mptr,MTAB_SHP) ? "{=arg}" : "");
        fprintf (st, "%-30s\t%s\n", buf, mptr->help ? mptr->help : "");
        }
    }
if ((dptr->flags & DEV_DEBUG) || (dptr->debflags)) {
    fprint_header (st, &found, header);
    sprintf (buf, "show %s DEBUG", sim_dname (dptr));
    fprintf (st, "%-30s\tDisplays debugging status for device %s\n", buf, sim_dname (dptr));
    }
if ((dptr->modifiers) && (dptr->units) && (enabled_units != 1)) {
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++) {
        if ((!MODMASK(mptr,MTAB_VUN)) && MODMASK(mptr,MTAB_XTD))
            continue;                                           /* skip device only modifiers */
        if ((!mptr->disp) || (!mptr->pstring))
            continue;
        fprint_header (st, &found, header);
        sprintf (buf, "show %s%s %s%s", sim_dname (dptr), (dptr->numunits > 1) ? "n" : "0", mptr->pstring, MODMASK(mptr,MTAB_SHP) ? "=arg" : "");
3289
3290
3291
3292
3293
3294
3295

3296
3297






3298
3299
3300
3301
3302
3303
3304
t_stat help_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE], gbuf2[CBUFSIZE];
CTAB *cmdp;
DEVICE *dptr;
UNIT *uptr;
t_stat r;

t_bool explicit_device = FALSE;







GET_SWITCHES (cptr);                                    /* get switches */
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;
if (*cptr) {
    cptr = get_glyph (cptr, gbuf, 0);

    if (0 == strcmp (gbuf, "DEVICE")) {







>


>
>
>
>
>
>







3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
t_stat help_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE], gbuf2[CBUFSIZE];
CTAB *cmdp;
DEVICE *dptr;
UNIT *uptr;
t_stat r;
static t_bool help_initialized = FALSE;
t_bool explicit_device = FALSE;

if (!help_initialized) {
    simh_help = (char *)malloc (1 + strlen (simh_help1) + strlen (simh_help2));
    strcpy (simh_help, simh_help1);
    strcat (simh_help, simh_help2);
    help_initialized = TRUE;
    }
GET_SWITCHES (cptr);                                    /* get switches */
if (sim_switches & SWMASK ('F'))
    flag = flag | SCP_HELP_FLAT;
if (*cptr) {
    cptr = get_glyph (cptr, gbuf, 0);

    if (0 == strcmp (gbuf, "DEVICE")) {
3396
3397
3398
3399
3400
3401
3402


3403

3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425

3426
3427
3428
3429
3430
3431
3432
                                    cmdp->name, cmdpa->name, cmdpa->help);
                        break;
                        }
                if (cmdpa->name == NULL)                /* not found? */
                    sim_printf ("No help available for the %s command\n", cmdp->name);
                }
            }


        }

    else {
        if (dptr->flags & DEV_DISABLE)
            sim_printf ("Device %s is currently disabled\n", dptr->name);
        r = help_dev_help (stdout, dptr, uptr, flag, cptr);
        if (sim_log)
            help_dev_help (sim_log, dptr, uptr, flag | SCP_HELP_FLAT, cptr);
        return r;
        }
    }
else {
    fprint_help (stdout);
    if (sim_log)
        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)
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = "SPAWN/INPUT=SYS$COMMAND:";







>
>
|
>

|




















>







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
                                    cmdp->name, cmdpa->name, cmdpa->help);
                        break;
                        }
                if (cmdpa->name == NULL)                /* not found? */
                    sim_printf ("No help available for the %s command\n", cmdp->name);
                }
            }
        else {
            sim_printf ("No such command or device %s\n", gbuf);
            }
        }
    else {
        if (dptr->flags & DEV_DIS)
            sim_printf ("Device %s is currently disabled\n", dptr->name);
        r = help_dev_help (stdout, dptr, uptr, flag, cptr);
        if (sim_log)
            help_dev_help (sim_log, dptr, uptr, flag | SCP_HELP_FLAT, cptr);
        return r;
        }
    }
else {
    fprint_help (stdout);
    if (sim_log)
        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)
if ((cptr == NULL) || (strlen (cptr) == 0))
    cptr = "SPAWN/INPUT=SYS$COMMAND:";
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
}

/* 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
}







|







3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
}

/* Screenshot command */

t_stat screenshot_cmd (int32 flag, CONST char *cptr)
{
if ((cptr == NULL) || (strlen (cptr) == 0))
    return sim_messagef (SCPE_ARG, "Missing screen shot filename\n");
#if defined (USE_SIM_VIDEO)
return vid_screenshot (cptr);
#else
sim_printf ("No video device\n");
return SCPE_UNK|SCPE_NOMESSAGE;
#endif
}
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
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;







|

|







|







3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
t_stat do_cmd (int32 flag, CONST char *fcptr)
{
return do_cmd_label (flag, fcptr, NULL);
}

static char *do_position(void)
{
static char cbuf[4*CBUFSIZE];

snprintf (cbuf, sizeof (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 = NULL;
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;
3586
3587
3588
3589
3590
3591
3592

3593
3594
3595
3596
3597
3598
3599
3600
        if (*c)                                         /* term at quote/spc */
            *c++ = 0;
        }
    }                                                   /* end for */

if (do_arg [0] == NULL)                                 /* need at least 1 */
    return SCPE_2FARG;

if ((fpin = fopen (do_arg[0], "r")) == NULL) {          /* file failed to open? */
    strlcpy (cbuf, do_arg[0], sizeof (cbuf));           /* try again with .sim extension */
    strlcat (cbuf, ".sim", sizeof (cbuf));
    if ((fpin = fopen (cbuf, "r")) == NULL) {           /* failed a second time? */
        if (flag == 0)                                  /* cmd line file? */
             fprintf (stderr, "Can't open file %s\n", do_arg[0]);
        return SCPE_OPENERR;                            /* return failure */
        }







>
|







3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
        if (*c)                                         /* term at quote/spc */
            *c++ = 0;
        }
    }                                                   /* end for */

if (do_arg [0] == NULL)                                 /* need at least 1 */
    return SCPE_2FARG;
if ((strcasecmp (do_arg[0], "<stdin>") != 0) &&
    ((fpin = fopen (do_arg[0], "r")) == NULL)) {        /* file failed to open? */
    strlcpy (cbuf, do_arg[0], sizeof (cbuf));           /* try again with .sim extension */
    strlcat (cbuf, ".sim", sizeof (cbuf));
    if ((fpin = fopen (cbuf, "r")) == NULL) {           /* failed a second time? */
        if (flag == 0)                                  /* cmd line file? */
             fprintf (stderr, "Can't open file %s\n", do_arg[0]);
        return SCPE_OPENERR;                            /* return failure */
        }
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
3656
3657
    }

sim_debug (SIM_DBG_DO, &sim_scp_dev, "do_cmd_label(%d, flag=%d, '%s', '%s')\n", sim_do_depth, flag, fcptr, label ? label : "");
if (NULL == (c = sim_filepath_parts (cbuf, "f"))) {
    stat = SCPE_MEM;
    goto Cleanup_Return;
    }
strlcpy( sim_do_filename[sim_do_depth], c, 
         sizeof (sim_do_filename[sim_do_depth]));       /* stash away full path of do file name for possible use by 'call' command */
free (c);
sim_do_label[sim_do_depth] = label;                     /* stash away do label for possible use in messages */
sim_goto_line[sim_do_depth] = 0;
if (label) {
    sim_gotofile = fpin;
    sim_do_echo = echo;
    stat = goto_cmd (0, label);
    if (stat != SCPE_OK) {
        strcpy(cbuf, "RETURN SCPE_ARG");
        cptr = get_glyph (cbuf, gbuf, 0);               /* get command glyph */
        cmdp = find_cmd (gbuf);                         /* return the errorStage things to the stat will be returned */
        goto Cleanup_Return;
        }
    }
if (errabort)                                           /* -e flag? */
    set_on (1, NULL);                                   /* equivalent to ON ERROR RETURN */






do {
    if (stop_cpu) {                                     /* SIGINT? */
        if (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]) {
            stop_cpu = FALSE;
            sim_brk_setact (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]);/* Use specified action */
            }







|

















>
>
>
>
>







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
    }

sim_debug (SIM_DBG_DO, &sim_scp_dev, "do_cmd_label(%d, flag=%d, '%s', '%s')\n", sim_do_depth, flag, fcptr, label ? label : "");
if (NULL == (c = sim_filepath_parts (cbuf, "f"))) {
    stat = SCPE_MEM;
    goto Cleanup_Return;
    }
strlcpy( sim_do_filename[sim_do_depth], strcasecmp (cbuf, "<stdin>") ? c : cbuf, 
         sizeof (sim_do_filename[sim_do_depth]));       /* stash away full path of do file name for possible use by 'call' command */
free (c);
sim_do_label[sim_do_depth] = label;                     /* stash away do label for possible use in messages */
sim_goto_line[sim_do_depth] = 0;
if (label) {
    sim_gotofile = fpin;
    sim_do_echo = echo;
    stat = goto_cmd (0, label);
    if (stat != SCPE_OK) {
        strcpy(cbuf, "RETURN SCPE_ARG");
        cptr = get_glyph (cbuf, gbuf, 0);               /* get command glyph */
        cmdp = find_cmd (gbuf);                         /* return the errorStage things to the stat will be returned */
        goto Cleanup_Return;
        }
    }
if (errabort)                                           /* -e flag? */
    set_on (1, NULL);                                   /* equivalent to ON ERROR RETURN */

if (strcasecmp (do_arg[0], "<stdin>") == 0) {
    stat = process_stdin_commands (SCPE_OK, do_arg, TRUE);
    goto Cleanup_Return;
    }

do {
    if (stop_cpu) {                                     /* SIGINT? */
        if (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]) {
            stop_cpu = FALSE;
            sim_brk_setact (sim_on_actions[sim_do_depth][ON_SIGINT_ACTION]);/* Use specified action */
            }
3759
3760
3761
3762
3763
3764
3765

3766
3767
3768
3769
3770
3771
3772
3773
        else
            sim_brk_setact (sim_on_actions[sim_do_depth][0]);
        }
    if (sim_vm_post != NULL)
        (*sim_vm_post) (TRUE);
    } while (staying);
Cleanup_Return:

fclose (fpin);                                          /* close file */
sim_gotofile = NULL;
if (flag >= 0) {
    sim_do_echo = saved_sim_do_echo;                    /* restore echo state we entered with */
    sim_show_message = saved_sim_show_message;          /* restore message display state we entered with */
    sim_on_inherit = saved_sim_on_inherit;              /* restore ON inheritance state we entered with */
    sim_quiet = saved_sim_quiet;                        /* restore quiet mode we entered with */
    }







>
|







3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
        else
            sim_brk_setact (sim_on_actions[sim_do_depth][0]);
        }
    if (sim_vm_post != NULL)
        (*sim_vm_post) (TRUE);
    } while (staying);
Cleanup_Return:
if (fpin)
    fclose (fpin);                                      /* close file */
sim_gotofile = NULL;
if (flag >= 0) {
    sim_do_echo = saved_sim_do_echo;                    /* restore echo state we entered with */
    sim_show_message = saved_sim_show_message;          /* restore message display state we entered with */
    sim_on_inherit = saved_sim_on_inherit;              /* restore ON inheritance state we entered with */
    sim_quiet = saved_sim_quiet;                        /* restore quiet mode we entered with */
    }
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239

        if (*ip == '%') {
            ap = NULL;
            ++ip;
            if (*ip == '~') {
                expand_it = TRUE;
                ++ip;
                for (i=0; (i < (sizeof (parts) - 1)) && (strchr ("fpnx", *ip)); i++, ip++) {
                    parts[i] = *ip;
                    parts[i + 1] = '\0';
                    }
                }
            if ((*ip >= '0') && (*ip <= ('9'))) {       /* %n = sub */
                ap = do_arg[*ip - '0'];
                for (i=0; i<*ip - '0'; ++i)           /* make sure we're not past the list end */







|







4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468

        if (*ip == '%') {
            ap = NULL;
            ++ip;
            if (*ip == '~') {
                expand_it = TRUE;
                ++ip;
                for (i=0; (i < (sizeof (parts) - 1)) && (strchr ("fpnxtz", *ip)); i++, ip++) {
                    parts[i] = *ip;
                    parts[i + 1] = '\0';
                    }
                }
            if ((*ip >= '0') && (*ip <= ('9'))) {       /* %n = sub */
                ap = do_arg[*ip - '0'];
                for (i=0; i<*ip - '0'; ++i)           /* make sure we're not past the list end */
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
dev_name = tmxr_send_line_name (snd);
if (!flag)
    return sim_send_clear (snd);
delay = get_default_env_parameter (dev_name, "SIM_SEND_DELAY", SEND_DEFAULT_DELAY);
after = get_default_env_parameter (dev_name, "SIM_SEND_AFTER", delay);
while (*cptr) {
    if ((!strncmp(gbuf, "DELAY=", 6)) && (gbuf[6])) {
        delay = (uint32)get_uint (&gbuf[6], 10, 10000000, &r);
        if (r != SCPE_OK)
            return sim_messagef (SCPE_ARG, "Invalid Delay Value\n");
        cptr = tptr;
        tptr = get_glyph (cptr, gbuf, ',');
        delay_set = TRUE;
        if (!after_set)
            after = delay;
        continue;
        }
    if ((!strncmp(gbuf, "AFTER=", 6)) && (gbuf[6])) {
        after = (uint32)get_uint (&gbuf[6], 10, 10000000, &r);
        if (r != SCPE_OK)
            return sim_messagef (SCPE_ARG, "Invalid After Value\n");
        cptr = tptr;
        tptr = get_glyph (cptr, gbuf, ',');
        after_set = TRUE;
        continue;
        }
    if ((*cptr == '"') || (*cptr == '\''))
        break;







|

|








|

|







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
dev_name = tmxr_send_line_name (snd);
if (!flag)
    return sim_send_clear (snd);
delay = get_default_env_parameter (dev_name, "SIM_SEND_DELAY", SEND_DEFAULT_DELAY);
after = get_default_env_parameter (dev_name, "SIM_SEND_AFTER", delay);
while (*cptr) {
    if ((!strncmp(gbuf, "DELAY=", 6)) && (gbuf[6])) {
        delay = (uint32)get_uint (&gbuf[6], 10, 2000000000, &r);
        if (r != SCPE_OK)
            return sim_messagef (SCPE_ARG, "Invalid Delay Value: %s\n", &gbuf[6]);
        cptr = tptr;
        tptr = get_glyph (cptr, gbuf, ',');
        delay_set = TRUE;
        if (!after_set)
            after = delay;
        continue;
        }
    if ((!strncmp(gbuf, "AFTER=", 6)) && (gbuf[6])) {
        after = (uint32)get_uint (&gbuf[6], 10, 2000000000, &r);
        if (r != SCPE_OK)
            return sim_messagef (SCPE_ARG, "Invalid After Value: %s\n", &gbuf[6]);
        cptr = tptr;
        tptr = get_glyph (cptr, gbuf, ',');
        after_set = TRUE;
        continue;
        }
    if ((*cptr == '"') || (*cptr == '\''))
        break;
4906
4907
4908
4909
4910
4911
4912


4913

4914
4915
4916
4917
4918
4919







4920
4921
4922
4923
4924
4925
4926
{
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])                                   /* unspecified goto target */
    return sim_messagef (SCPE_ARG, "Missing goto target\n");
fpos = ftell(sim_gotofile);                             /* Save start position */
if (fpos < 0)
    return sim_messagef (SCPE_IERR, "goto ftell error: %s\n", strerror (errno));







rewind(sim_gotofile);                                   /* start search for label */
sim_goto_line[sim_do_depth] = 0;                        /* reset line number */
sim_do_echo = 0;                                        /* Don't echo while searching for label */
while (1) {
    cptr = read_line (cbuf, sizeof(cbuf), sim_gotofile);/* get cmd line */
    if (cptr == NULL) break;                            /* exit on eof */
    sim_goto_line[sim_do_depth] += 1;                   /* record line number */







>
>
|
>






>
>
>
>
>
>
>







5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
{
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) || 
    (0 == strcasecmp (sim_do_filename[sim_do_depth], "<stdin>")))
    return SCPE_UNK;                                    /* only valid inside of do_cmd */

get_glyph (fcptr, gbuf1, 0);
if ('\0' == gbuf1[0])                                   /* unspecified goto target */
    return sim_messagef (SCPE_ARG, "Missing goto target\n");
fpos = ftell(sim_gotofile);                             /* Save start position */
if (fpos < 0)
    return sim_messagef (SCPE_IERR, "goto ftell error: %s\n", strerror (errno));
if (strcasecmp(":EOF", gbuf1) == 0) {
    if (fseek (sim_gotofile, 0, SEEK_END))
        return sim_messagef (SCPE_IERR, "goto seek error: %s\n", strerror (errno));
    sim_brk_clract ();                                  /* goto defangs current actions */
    sim_do_echo = saved_do_echo;                        /* restore echo mode */
    return SCPE_OK;
    }
rewind(sim_gotofile);                                   /* start search for label */
sim_goto_line[sim_do_depth] = 0;                        /* reset line number */
sim_do_echo = 0;                                        /* Don't echo while searching for label */
while (1) {
    cptr = read_line (cbuf, sizeof(cbuf), sim_gotofile);/* get cmd line */
    if (cptr == NULL) break;                            /* exit on eof */
    sim_goto_line[sim_do_depth] += 1;                   /* record line number */
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
/* 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 */







|







5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
/* 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 sim_messagef (SCPE_UNK, "Invalid Command\n"); /* 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 */
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
/* 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)







|





|







5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
/* 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[2*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 */
snprintf (cbuf, sizeof (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)
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
                        }
                    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 */
            else {                                      /* old style */
                if (cvptr)                              /* = value? */
                    return SCPE_ARG;







<
<
<
<
<







5564
5565
5566
5567
5568
5569
5570





5571
5572
5573
5574
5575
5576
5577
                        }
                    r = mptr->valid (uptr, mptr->match, cvptr, mptr->desc);
                    if (r != SCPE_OK)
                        return r;
                    }
                else if (!mptr->desc)                   /* value desc? */
                    break;





                else if (cvptr)                         /* = value? */
                    return SCPE_ARG;
                else *((int32 *) mptr->desc) = mptr->match;
                }                                       /* end if xtd */
            else {                                      /* old style */
                if (cvptr)                              /* = value? */
                    return SCPE_ARG;
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
    }
else {
    if (dptr->flags & DEV_DIS)                          /* already dsb? ok */
        return SCPE_OK;
    for (i = 0; i < dptr->numunits; i++) {              /* check units */
        up = (dptr->units) + i;                         /* att or active? */
        if ((up->flags & UNIT_ATT) || sim_is_active (up))
            return SCPE_NOFNC;                          /* can't do it */
        }
    dptr->flags = dptr->flags | DEV_DIS;                /* disable */
    }
if (dptr->reset)                                        /* reset device */
    return dptr->reset (dptr);
else return SCPE_OK;
}







|







5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
    }
else {
    if (dptr->flags & DEV_DIS)                          /* already dsb? ok */
        return SCPE_OK;
    for (i = 0; i < dptr->numunits; i++) {              /* check units */
        up = (dptr->units) + i;                         /* att or active? */
        if ((up->flags & UNIT_ATT) || sim_is_active (up))
            return sim_messagef (SCPE_NOFNC, "%s has attached or busy units\n", sim_dname (dptr));                          /* can't do it */
        }
    dptr->flags = dptr->flags | DEV_DIS;                /* disable */
    }
if (dptr->reset)                                        /* reset device */
    return dptr->reset (dptr);
else return SCPE_OK;
}
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
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/unit debug enabled/disabled routine */








|







5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
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 sim_messagef (SCPE_NOFNC, "%s is attached or busy\n", sim_uname (uptr));
    uptr->flags = uptr->flags | UNIT_DIS;               /* disable */
    }
return SCPE_OK;
}

/* Set device/unit debug enabled/disabled routine */

5496
5497
5498
5499
5500
5501
5502



















5503
5504
5505
5506
5507
5508
5509
            }
        }                                               /* end for */
    if (dep->mask == 0)                                 /* no match? */
        r = sim_messagef (SCPE_ARG, "Invalid DEBUG option '%s' for %s device\n", gbuf, dptr->name);
    }                                                   /* end while */
return r;
}




















/* Show command */

t_stat show_cmd (int32 flag, CONST char *cptr)
{
t_stat r;








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







5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
            }
        }                                               /* end for */
    if (dep->mask == 0)                                 /* no match? */
        r = sim_messagef (SCPE_ARG, "Invalid DEBUG option '%s' for %s device\n", gbuf, dptr->name);
    }                                                   /* end while */
return r;
}

/* Set sequential unit position to EOF */

t_stat set_unit_append (DEVICE *dptr, UNIT *uptr, int32 flags, CONST char *cptr)
{
if (!(uptr->flags & UNIT_SEQ))
    return sim_messagef (SCPE_NOFNC, "%s is not a sequential device.\n", sim_uname (uptr));
if (uptr->flags & UNIT_BUF)
    return sim_messagef (SCPE_NOFNC, "Can't append to a buffered device %s.\n", sim_uname (uptr));
if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;

if (0 == sim_fseek (uptr->fileref, 0, SEEK_END)) {
    uptr->pos = (t_addr)sim_ftell (uptr->fileref);      /* Position at end of file */
    return SCPE_OK;
    }

return sim_messagef (SCPE_IERR, "%s Can't seek to end of file: %s - %s\n", sim_uname (uptr), uptr->filename, strerror (errno));
}

/* Show command */

t_stat show_cmd (int32 flag, CONST char *cptr)
{
t_stat r;

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
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621

5622
5623
5624
5625

5626
5627
5628
5629
5630
5631
5632
    uptr = dptr->units;                                 /* first unit */
    shtb = show_dev_tab;                                /* global table */
    lvl = MTAB_VDV;                                     /* device match */
    GET_SWITCHES (cptr);                                /* get more switches */
    }
else if ((dptr = find_unit (gbuf, &uptr))) {            /* unit match? */
    if (uptr == NULL)                                   /* invalid unit */
        return SCPE_NXUN;
    if (uptr->flags & UNIT_DIS)                         /* disabled? */
        return SCPE_UDIS;
    shtb = show_unit_tab;                               /* global table */
    lvl = MTAB_VUN;                                     /* unit match */
    GET_SWITCHES (cptr);                                /* get more switches */
    }
else if ((shptr = find_shtab (show_glob_tab, gbuf))) {  /* global? */
    GET_SWITCHES (cptr);                                /* get more switches */
    return shptr->action (ofile, NULL, NULL, shptr->arg, cptr);
    }
else {
    if (sim_dflt_dev->modifiers) {
        if ((cvptr = strchr (gbuf, '=')))               /* = value? */
            *cvptr++ = 0;
        for (mptr = sim_dflt_dev->modifiers; mptr->mask != 0; mptr++) {
            if ((((mptr->mask & MTAB_VDV) == MTAB_VDV) &&
                 (mptr->pstring && (MATCH_CMD (gbuf, mptr->pstring) == 0))) ||
                (!(mptr->mask & MTAB_VDV) && (mptr->mstring && (MATCH_CMD (gbuf, mptr->mstring) == 0)))) {
                dptr = sim_dflt_dev;
                lvl = MTAB_VDV;                         /* device match */
                cptr = svptr;
                while (sim_isspace(*cptr))
                    ++cptr;
                break;
                }
            }
        }
    if (!dptr) {
        if ((shptr = find_shtab (show_dev_tab, gbuf)))  /* global match? */
            return shptr->action (ofile, sim_dflt_dev, uptr, shptr->arg, cptr);
        else
            return SCPE_NXDEV;                          /* no match */
        }
    }

if (*cptr == 0) {                                       /* now eol? */
    return (lvl == MTAB_VDV)?
        show_device (ofile, dptr, 0):
        show_unit (ofile, dptr, uptr, -1);
    }
GET_SWITCHES (cptr);                                    /* get more switches */

while (*cptr != 0) {                                    /* do all mods */
    cptr = get_glyph (cptr, gbuf, ',');                 /* get modifier */
    if ((cvptr = strchr (gbuf, '=')))                   /* = value? */
        *cvptr++ = 0;
    for (mptr = dptr->modifiers; mptr && (mptr->mask != 0); mptr++) {
        if (((mptr->mask & MTAB_XTD)?                   /* right level? */
            ((mptr->mask & lvl) == lvl): (MTAB_VUN & lvl)) &&
            ((mptr->disp && mptr->pstring &&            /* named disp? */
            (MATCH_CMD (gbuf, mptr->pstring) == 0))
 //           ||
 //           ((mptr->mask & MTAB_VAL) &&                 /* named value? */
 //           mptr->mstring &&
 //           (MATCH_CMD (gbuf, mptr->mstring) == 0)))
            )) {
            if (cvptr && !(mptr->mask & MTAB_SHP))
                return SCPE_ARG;
            show_one_mod (ofile, dptr, uptr, mptr, cvptr, 1);
            break;
            }                                           /* end if */
        }                                               /* end for */
    if (!mptr || (mptr->mask == 0)) {                   /* no match? */
        if (shtb && (shptr = find_shtab (shtb, gbuf))) {/* global match? */
            t_stat r;

            r = shptr->action (ofile, dptr, uptr, shptr->arg, cptr);
            if (r != SCPE_OK)
                return r;
            }

        else if (!dptr->modifiers)                      /* no modifiers? */
            return SCPE_NOPARAM;
        else
            return SCPE_NXPAR;

        }                                               /* end if */
    }                                                   /* end while */
return SCPE_OK;
}

SHTAB *find_shtab (SHTAB *tab, const char *gbuf)
{







|

|












|
















|



















<
<
<
<

|
|












>
|
|
|
|
>







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
5850
5851
5852
5853
5854
5855




5856
5857
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
    uptr = dptr->units;                                 /* first unit */
    shtb = show_dev_tab;                                /* global table */
    lvl = MTAB_VDV;                                     /* device match */
    GET_SWITCHES (cptr);                                /* get more switches */
    }
else if ((dptr = find_unit (gbuf, &uptr))) {            /* unit match? */
    if (uptr == NULL)                                   /* invalid unit */
        return sim_messagef (SCPE_NXUN, "Non-existent unit: %s\n", gbuf);
    if (uptr->flags & UNIT_DIS)                         /* disabled? */
        return sim_messagef (SCPE_UDIS, "Unit disabled: %s\n", gbuf);
    shtb = show_unit_tab;                               /* global table */
    lvl = MTAB_VUN;                                     /* unit match */
    GET_SWITCHES (cptr);                                /* get more switches */
    }
else if ((shptr = find_shtab (show_glob_tab, gbuf))) {  /* global? */
    GET_SWITCHES (cptr);                                /* get more switches */
    return shptr->action (ofile, NULL, NULL, shptr->arg, cptr);
    }
else {
    if (sim_dflt_dev->modifiers) {
        if ((cvptr = strchr (gbuf, '=')))               /* = value? */
            *cvptr++ = 0;
        for (mptr = sim_dflt_dev->modifiers; mptr && (mptr->mask != 0); mptr++) {
            if ((((mptr->mask & MTAB_VDV) == MTAB_VDV) &&
                 (mptr->pstring && (MATCH_CMD (gbuf, mptr->pstring) == 0))) ||
                (!(mptr->mask & MTAB_VDV) && (mptr->mstring && (MATCH_CMD (gbuf, mptr->mstring) == 0)))) {
                dptr = sim_dflt_dev;
                lvl = MTAB_VDV;                         /* device match */
                cptr = svptr;
                while (sim_isspace(*cptr))
                    ++cptr;
                break;
                }
            }
        }
    if (!dptr) {
        if ((shptr = find_shtab (show_dev_tab, gbuf)))  /* global match? */
            return shptr->action (ofile, sim_dflt_dev, uptr, shptr->arg, cptr);
        else
            return sim_messagef (SCPE_NXDEV, "Non-existent device: %s\n", gbuf);/* no match */
        }
    }

if (*cptr == 0) {                                       /* now eol? */
    return (lvl == MTAB_VDV)?
        show_device (ofile, dptr, 0):
        show_unit (ofile, dptr, uptr, -1);
    }
GET_SWITCHES (cptr);                                    /* get more switches */

while (*cptr != 0) {                                    /* do all mods */
    cptr = get_glyph (cptr, gbuf, ',');                 /* get modifier */
    if ((cvptr = strchr (gbuf, '=')))                   /* = value? */
        *cvptr++ = 0;
    for (mptr = dptr->modifiers; mptr && (mptr->mask != 0); mptr++) {
        if (((mptr->mask & MTAB_XTD)?                   /* right level? */
            ((mptr->mask & lvl) == lvl): (MTAB_VUN & lvl)) &&
            ((mptr->disp && mptr->pstring &&            /* named disp? */
            (MATCH_CMD (gbuf, mptr->pstring) == 0))




            )) {
            if (cvptr && !MODMASK(mptr,MTAB_SHP))
                return sim_messagef (SCPE_ARG, "Invalid Argument: %s=%s\n", gbuf, cvptr);
            show_one_mod (ofile, dptr, uptr, mptr, cvptr, 1);
            break;
            }                                           /* end if */
        }                                               /* end for */
    if (!mptr || (mptr->mask == 0)) {                   /* no match? */
        if (shtb && (shptr = find_shtab (shtb, gbuf))) {/* global match? */
            t_stat r;

            r = shptr->action (ofile, dptr, uptr, shptr->arg, cptr);
            if (r != SCPE_OK)
                return r;
            }
        else {
            if (!dptr->modifiers)                       /* no modifiers? */
                return sim_messagef (SCPE_NOPARAM, "%s device has no parameters\n", dptr->name);
            else
                return sim_messagef (SCPE_NXPAR, "Non-existent parameter: %s\n", gbuf);
            }
        }                                               /* end if */
    }                                                   /* end while */
return SCPE_OK;
}

SHTAB *find_shtab (SHTAB *tab, const char *gbuf)
{
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739

5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752


5753

5754

5755

5756
5757
5758
5759

5760
5761
5762







5763
5764
5765
5766
5767
5768
5769
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)
    psize = psize * 512;
if ((dptr->dwidth / dptr->aincr) > 8)
    width = "W";
else 
    width = "B";
if (psize < (kval * 10))


    scale = "";

else if (psize < (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));







|


>












|
>
>

>
|
>

>




>



>
>
>
>
>
>
>







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
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
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) + 12];
t_addr kval = (uptr->flags & UNIT_BINK)? 1024: 1000;
t_addr mval;
double remfrac;
t_addr psize = uptr->capac;
const char *scale, *width;

if (sim_switches & SWMASK ('B'))
    kval = 1024;
mval = kval * kval;
if (dptr->flags & DEV_SECTORS)
    psize = psize * 512;
if ((dptr->dwidth / dptr->aincr) > 8)
    width = "W";
else 
    width = "B";
if ((psize < (kval * 10)) &&
    (0 != (psize % kval))) {
    remfrac = 0.0;
    scale = "";
    }
else if ((psize < (mval * 10)) &&
         (0 != (psize % mval))){
    scale = "K";
    remfrac = ((double)(psize % kval))/kval;
    psize = psize / kval;
    }
else {
    scale = "M";
    remfrac = ((double)(psize % mval))/mval;
    psize = psize / mval;
    }
sprint_val (capac_buf, (t_value) psize, 10, T_ADDR_W, PV_LEFT);
if ((remfrac != 0.0) && (sim_switches & SWMASK ('R'))) {
    char *plast_char = &capac_buf[strlen (capac_buf) - 1];
    char save_char = *plast_char;

    sprintf (plast_char, "%0.3f", remfrac);
    *plast_char = save_char;
    }
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));
5784
5785
5786
5787
5788
5789
5790




5791
5792
5793
5794
5795
5796
5797
sprintf (vmaj_s, "%d", vmaj);
setenv ("SIM_MAJOR", vmaj_s, 1);
sprintf (vmin_s, "%d", vmin);
setenv ("SIM_MINOR", vmin_s, 1);
sprintf (vpat_s, "%d", vpat);
setenv ("SIM_PATCH", vpat_s, 1);
fprintf (st, "%s simulator V%d.%d-%d", sim_name, vmaj, vmin, vpat);




if (vdelt) {
    sprintf (vdelt_s, "%d", vdelt);
    setenv ("SIM_DELTA", vdelt_s, 1);
    fprintf (st, " delta %d", vdelt);
    }
#if defined (SIM_VERSION_MODE)
fprintf (st, " %s", SIM_VERSION_MODE);







>
>
>
>







6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
sprintf (vmaj_s, "%d", vmaj);
setenv ("SIM_MAJOR", vmaj_s, 1);
sprintf (vmin_s, "%d", vmin);
setenv ("SIM_MINOR", vmin_s, 1);
sprintf (vpat_s, "%d", vpat);
setenv ("SIM_PATCH", vpat_s, 1);
fprintf (st, "%s simulator V%d.%d-%d", sim_name, vmaj, vmin, vpat);
if (sim_vm_release != NULL) {                           /* if a release string is defined */
    setenv ("SIM_VM_RELEASE", sim_vm_release, 1);
    fprintf (st, " Release %s", sim_vm_release);        /*   then display it */
    }
if (vdelt) {
    sprintf (vdelt_s, "%d", vdelt);
    setenv ("SIM_DELTA", vdelt_s, 1);
    fprintf (st, " delta %d", vdelt);
    }
#if defined (SIM_VERSION_MODE)
fprintf (st, " %s", SIM_VERSION_MODE);
5875
5876
5877
5878
5879
5880
5881









5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894


5895
5896
5897
5898
5899
5900
5901
#define S_xstr(a) S_str(a)
#define S_str(a) #a
    fprintf (st, "\n        Simulator Compiled as %s%s%s on %s at %s %s", cpp, arch, build, __DATE__, __TIME__, S_xstr(SIM_BUILD_OS));
#undef S_str
#undef S_xstr
#endif
#endif









    fprintf (st, "\n        Memory Access: %s Endian", sim_end ? "Little" : "Big");
    fprintf (st, "\n        Memory Pointer Size: %d bits", (int)sizeof(dptr)*8);
    fprintf (st, "\n        %s", sim_toffset_64 ? "Large File (>2GB) support" : "No Large File support");
    fprintf (st, "\n        SDL Video support: %s", vid_version());
#if defined (HAVE_PCREPOSIX_H)
    fprintf (st, "\n        PCRE RegEx (Version %s) support for EXPECT commands", pcre_version());
#elif defined (HAVE_REGEX_H)
    fprintf (st, "\n        RegEx support for EXPECT commands");
#else
    fprintf (st, "\n        No RegEx support for EXPECT commands");
#endif
    fprintf (st, "\n        OS clock resolution: %dms", os_tick_size);
    fprintf (st, "\n        Time taken by msleep(1): %dms", os_ms_sleep_1);


#if defined(__VMS)
    if (1) {
        char *arch = 
#if defined(__ia64)
            "I64";
#elif defined(__ALPHA)
            "Alpha";







>
>
>
>
>
>
>
>
>




|

<
<





>
>







6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165


6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
#define S_xstr(a) S_str(a)
#define S_str(a) #a
    fprintf (st, "\n        Simulator Compiled as %s%s%s on %s at %s %s", cpp, arch, build, __DATE__, __TIME__, S_xstr(SIM_BUILD_OS));
#undef S_str
#undef S_xstr
#endif
#endif
#if defined (SIM_BUILD_TOOL)
#define S_xstr(a) S_str(a)
#define S_str(a) #a
    fprintf (st, "\n        Build Tool: %s", S_xstr(SIM_BUILD_TOOL));
#undef S_str
#undef S_xstr
#else
    fprintf (st, "\n        Build Tool: undefined (probably cmake)");
#endif
    fprintf (st, "\n        Memory Access: %s Endian", sim_end ? "Little" : "Big");
    fprintf (st, "\n        Memory Pointer Size: %d bits", (int)sizeof(dptr)*8);
    fprintf (st, "\n        %s", sim_toffset_64 ? "Large File (>2GB) support" : "No Large File support");
    fprintf (st, "\n        SDL Video support: %s", vid_version());
#if defined (HAVE_PCRE_H)
    fprintf (st, "\n        PCRE RegEx (Version %s) support for EXPECT commands", pcre_version());


#else
    fprintf (st, "\n        No RegEx support for EXPECT commands");
#endif
    fprintf (st, "\n        OS clock resolution: %dms", os_tick_size);
    fprintf (st, "\n        Time taken by msleep(1): %dms", os_ms_sleep_1);
    if (eth_version ())
        fprintf (st, "\n        Ethernet packet info: %s", eth_version());
#if defined(__VMS)
    if (1) {
        char *arch = 
#if defined(__ia64)
            "I64";
#elif defined(__ALPHA)
            "Alpha";
5978
5979
5980
5981
5982
5983
5984


5985
5986
5987
5988
5989
5990
5991
#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;







>
>







6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
#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");
if (sim_vm_release_message != NULL)                    /* if a release message string is defined */
    fprintf (st, "\n%s", sim_vm_release_message);      /*   then display it */
return SCPE_OK;
}

t_stat show_config (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
int32 i;
DEVICE *dptr;
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
return SCPE_OK;
}

t_stat show_queue (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
DEVICE *dptr;
UNIT *uptr;
int32 accum;
MEMFILE buf;

memset (&buf, 0, sizeof (buf));
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %s instructios/sec\n",
             sim_name, sim_time, sim_fmt_numeric (sim_timer_inst_per_sec ()));
else {
    const char *tim = "";
    double inst_per_sec = sim_timer_inst_per_sec ();

    fprintf (st, "%s event queue status, time = %.0f, executing %s instructions/sec\n",
             sim_name, sim_time, sim_fmt_numeric (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");
        if (inst_per_sec != 0.0)
            tim = sim_fmt_secs(((accum + uptr->time) / sim_timer_inst_per_sec ()) + (uptr->usecs_remaining / 1000000.0));
        if (uptr->usecs_remaining)
            fprintf (st, " at %d plus %.0f usecs%s%s%s%s\n", accum + uptr->time, uptr->usecs_remaining,
                                            (*tim) ? " (" : "", tim, (*tim) ? " total)" : "",
                                            (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");
        else
            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);
sim_mfile = &buf;
fprintf (st, "asynchronous pending event queue\n");







<






|
|




|
|
<















|

|



|


<







6307
6308
6309
6310
6311
6312
6313

6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327

6328
6329
6330
6331
6332
6333
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
return SCPE_OK;
}

t_stat show_queue (FILE *st, DEVICE *dnotused, UNIT *unotused, int32 flag, CONST char *cptr)
{
DEVICE *dptr;
UNIT *uptr;

MEMFILE buf;

memset (&buf, 0, sizeof (buf));
if (cptr && (*cptr != 0))
    return SCPE_2MARG;
if (sim_clock_queue == QUEUE_LIST_END)
    fprintf (st, "%s event queue empty, time = %.0f, executing %s %s/sec\n",
             sim_name, sim_time, sim_fmt_numeric (sim_timer_inst_per_sec ()), sim_vm_interval_units);
else {
    const char *tim = "";
    double inst_per_sec = sim_timer_inst_per_sec ();

    fprintf (st, "%s event queue status, time = %.0f, executing %s %s/sec\n",
             sim_name, sim_time, sim_fmt_numeric (inst_per_sec), sim_vm_interval_units);

    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");
        if (inst_per_sec != 0.0)
            tim = sim_fmt_secs(((_sim_activate_queue_time (uptr) - 1) / sim_timer_inst_per_sec ()) + (uptr->usecs_remaining / 1000000.0));
        if (uptr->usecs_remaining)
            fprintf (st, " at %d plus %.0f usecs%s%s%s%s\n", _sim_activate_queue_time (uptr) - 1, uptr->usecs_remaining,
                                            (*tim) ? " (" : "", tim, (*tim) ? " total)" : "",
                                            (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");
        else
            fprintf (st, " at %d%s%s%s%s\n", _sim_activate_queue_time (uptr) - 1, 
                                            (*tim) ? " (" : "", tim, (*tim) ? ")" : "",
                                            (uptr->flags & UNIT_IDLE) ? " (Idle capable)" : "");

        }
    }
sim_show_clock_queues (st, dnotused, unotused, flag, cptr);
#if defined (SIM_ASYNCH_IO)
pthread_mutex_lock (&sim_asynch_lock);
sim_mfile = &buf;
fprintf (st, "asynchronous pending event queue\n");
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
                (int32) (uptr - dptr->units));
            }
        else fprintf (st, "  Unknown");
        fprintf (st, " event delay %d\n", uptr->a_event_time);
        }
    }
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);
sim_mfile = NULL;
fprintf (st, "%*.*s", (int)buf.pos, (int)buf.pos, buf.buf);
free (buf.buf);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}







|







6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
                (int32) (uptr - dptr->units));
            }
        else fprintf (st, "  Unknown");
        fprintf (st, " event delay %d\n", uptr->a_event_time);
        }
    }
fprintf (st, "asynch latency: %d nanoseconds\n", sim_asynch_latency);
fprintf (st, "asynch instruction latency: %d %s\n", sim_asynch_inst_latency, sim_vm_interval_units);
pthread_mutex_unlock (&sim_asynch_lock);
sim_mfile = NULL;
fprintf (st, "%*.*s", (int)buf.pos, (int)buf.pos, buf.buf);
free (buf.buf);
#endif /* SIM_ASYNCH_IO */
return SCPE_OK;
}
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195

6196






6197
6198
6199
6200



6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214




































6215
6216
6217
6218
6219
6220
6221
    for (unit = 0; unit < dptr->numunits; unit++)
        show_dev_debug (st, dptr, &dptr->units[unit], 1, NULL);
    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);
    else
        fprintf(st, "On Processing for input commands");



    fprintf(st, " is %s\n", (sim_on_check[lvl]) ? "enabled" : "disabled");
    for (i=1; i<SCPE_BASE; ++i) {
        if (sim_on_actions[lvl][i])
            fprintf(st, "    on %6d    %s\n", i, sim_on_actions[lvl][i]); }
    for (i=SCPE_BASE; i<=SCPE_MAX_ERR; ++i) {
        if (sim_on_actions[lvl][i])
            fprintf(st, "    on %-6s    %s\n", scp_errors[i-SCPE_BASE].code, sim_on_actions[lvl][i]); }
    if (sim_on_actions[lvl][0])
        fprintf(st, "    on ERROR     %s\n", sim_on_actions[lvl][0]);
    if (sim_on_actions[lvl][ON_SIGINT_ACTION]) {
        fprintf(st, "CONTROL+C/SIGINT Handling:\n");
        fprintf(st, "    on CONTROL_C %s\n", sim_on_actions[lvl][ON_SIGINT_ACTION]);
        }
    fprintf(st, "\n");




































    }
if (sim_on_inherit)
    fprintf(st, "on state and actions are inherited by nested do commands and subroutines\n");
return SCPE_OK;
}

/* Show modifiers */







|






>
|
>
>
>
>
>
>




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







6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
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
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
    for (unit = 0; unit < dptr->numunits; unit++)
        show_dev_debug (st, dptr, &dptr->units[unit], 1, NULL);
    return SCPE_OK;
    }
else return SCPE_NOFNC;
}

/* Show On actions for one level (default current level) */

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? */
if (flag < 0)
    lvl = sim_do_depth;
else
    if (flag > sim_do_depth)
        return SCPE_ARG;
    else
        lvl = flag;
if (flag == -1) {
    if (lvl > 0)
        fprintf(st, "On Processing at Do Nest Level: %d", lvl);
    else
        fprintf(st, "On Processing for input commands");
    }
else
    fprintf(st, "On Processing");
fprintf(st, " is %s\n", (sim_on_check[lvl]) ? "enabled" : "disabled");
for (i=1; i<SCPE_BASE; ++i) {
    if (sim_on_actions[lvl][i])
        fprintf(st, "    on %6d    %s\n", i, sim_on_actions[lvl][i]); }
for (i=SCPE_BASE; i<=SCPE_MAX_ERR; ++i) {
    if (sim_on_actions[lvl][i])
        fprintf(st, "    on %-6s    %s\n", scp_errors[i-SCPE_BASE].code, sim_on_actions[lvl][i]); }
if (sim_on_actions[lvl][0])
    fprintf(st, "    on ERROR     %s\n", sim_on_actions[lvl][0]);
if (sim_on_actions[lvl][ON_SIGINT_ACTION]) {
    fprintf(st, "CONTROL+C/SIGINT Handling:\n");
    fprintf(st, "    on CONTROL_C %s\n", sim_on_actions[lvl][ON_SIGINT_ACTION]);
    }
fprintf(st, "\n");
if ((flag < 0) && sim_on_inherit)
    fprintf(st, "on state and actions are inherited by nested do commands and subroutines\n");
return SCPE_OK;
}

t_stat show_do (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
int32 lvl;

if (cptr && (*cptr != 0)) return SCPE_2MARG;            /* now eol? */
for (lvl=sim_do_depth; lvl >= 0; --lvl) {
    if (lvl > 0)
        fprintf(st, "Do Nest Level: %d\n", lvl);
    else {
        if (sim_do_filename[lvl][0])
            fprintf(st, "Initial Input ");
        else
            fprintf(st, "Console Input commands\n");
        }
    if (sim_do_filename[lvl][0]) {
        fprintf (st, "File: %s\n", sim_do_filename[lvl]);
        if (strcasecmp (sim_do_filename[lvl], "<stdin>"))
            fprintf (st, "Line: %d\n", sim_goto_line[lvl]);
        }
    if (sim_if_cmd[lvl])
        fprintf (st, "Processing IF command\n");
    if (sim_if_cmd_last[lvl])
        fprintf (st, "IF command last\n");
    if (sim_if_result[lvl])
        fprintf (st, "IF result\n");
    if (sim_if_result_last[lvl])
        fprintf (st, "IF result last\n");
    if (sim_cptr_is_action[lvl])
        fprintf (st, "Command is Action\n");
    fprintf (st, "Command is: %s\n", sim_do_ocptr[lvl]);
    show_on (st, dptr, uptr, lvl, cptr);
    }
if (sim_on_inherit)
    fprintf(st, "on state and actions are inherited by nested do commands and subroutines\n");
return SCPE_OK;
}

/* Show modifiers */
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
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 */








<



|
<
<
<
<
<
<
|







6587
6588
6589
6590
6591
6592
6593

6594
6595
6596
6597






6598
6599
6600
6601
6602
6603
6604
6605
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;


if (mptr->disp)
    r = mptr->disp (st, uptr, mptr->match, (CONST void *)(cptr? cptr: mptr->desc));
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 */

6579
6580
6581
6582
6583
6584
6585












































































6586
6587
6588
6589
6590
6591
6592
    return SCPE_2FARG;
cptr = get_glyph_quoted (cptr, copy_state.destname, 0);
stat = sim_dir_scan (sname, sim_copy_entry, &copy_state);
if ((stat == SCPE_OK) && (copy_state.count))
    return sim_messagef (SCPE_OK, "      %3d file(s) copied\n", copy_state.count);
return copy_state.stat;
}













































































/* Debug command */

t_stat debug_cmd (int32 flg, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *svptr;







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







6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
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
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
    return SCPE_2FARG;
cptr = get_glyph_quoted (cptr, copy_state.destname, 0);
stat = sim_dir_scan (sname, sim_copy_entry, &copy_state);
if ((stat == SCPE_OK) && (copy_state.count))
    return sim_messagef (SCPE_OK, "      %3d file(s) copied\n", copy_state.count);
return copy_state.stat;
}

t_stat rename_cmd (int32 flg, CONST char *cptr)
{
char sname[CBUFSIZE], dname[CBUFSIZE];

if ((!cptr) || (*cptr == 0))
    return SCPE_2FARG;
cptr = get_glyph_quoted (cptr, sname, 0);
if ((!cptr) || (*cptr == 0))
    return SCPE_2FARG;
cptr = get_glyph_quoted (cptr, dname, 0);
if (0 == rename (sname, dname))
    return SCPE_OK;
return sim_messagef (SCPE_ARG, "Can't rename '%s' to '%s': %s\n\n", sname, dname, strerror (errno));
}

t_stat mkdir_cmd (int32 flg, CONST char *cptr)
{
char path[CBUFSIZE];
char *c;
struct stat filestat;

GET_SWITCHES (cptr);                                    /* get switches */
if ((!cptr) || (*cptr == '\0'))
    return sim_messagef (SCPE_2FARG, "Must specify a directory path\n");
strlcpy (path, cptr, sizeof (path));
while ((c = strchr (path, '\\')))
    *c = '/';
if (path[strlen (path) - 1] == '/')     /* trim any trailing / from the path */
    path[strlen (path) - 1] = '\0';
while ((c = strstr (path, "//")))        
    memmove (c, c + 1, strlen (c + 1) + 1); /* clean out any empty directories // */
if ((!stat (path, &filestat)) && (filestat.st_mode & S_IFDIR))
    return sim_messagef (SCPE_OK, "directory %s already exists\n", path);
c = path;
while ((c = strchr (c, '/'))) {
    *c = '\0';
    if (!stat (path, &filestat)) {
        if (filestat.st_mode & S_IFDIR) {
            *c = '/';   /* restore / */
            ++c;
            continue;
            }
        return sim_messagef (SCPE_ARG, "%s is not a directory\n", path);
        }
    if (
#if defined(_WIN32)
        mkdir (path)
#else
        mkdir (path, 0777)
#endif
                          )
        return sim_messagef (SCPE_ARG, "Can't create directory: %s - %s\n", path, strerror (errno));
    *c = '/';   /* restore / */
    ++c;
    }
if (
#if defined(_WIN32)
    mkdir (path)
#else
    mkdir (path, 0777)
#endif
                      )
    return sim_messagef (SCPE_ARG, "Can't create directory: %s - %s\n", path, strerror (errno));
return SCPE_OK;
}

t_stat rmdir_cmd (int32 flg, CONST char *cptr)
{
GET_SWITCHES (cptr);                                    /* get switches */
if ((!cptr) || (*cptr == '\0'))
    return sim_messagef (SCPE_2FARG, "Must specify a directory\n");
if (rmdir (cptr))
    return sim_messagef (SCPE_ARG, "Can't remove directory: %s - %s\n", cptr, strerror (errno));
return SCPE_OK;
}

/* Debug command */

t_stat debug_cmd (int32 flg, CONST char *cptr)
{
char gbuf[CBUFSIZE];
CONST char *svptr;
6727
6728
6729
6730
6731
6732
6733





















































































































6734
6735
6736
6737
6738
6739
6740
dptr = find_dev (gbuf);                                 /* locate device */
if (dptr == NULL)                                       /* found it? */
    return SCPE_NXDEV;
if (dptr->reset != NULL)
    return dptr->reset (dptr);
else return SCPE_OK;
}






















































































































/* Reset devices start..end

   Inputs:
        start   =       number of starting device
   Outputs:
        status  =       error status







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







7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
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
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
7199
7200
7201
7202
7203
7204
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
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
dptr = find_dev (gbuf);                                 /* locate device */
if (dptr == NULL)                                       /* found it? */
    return SCPE_NXDEV;
if (dptr->reset != NULL)
    return dptr->reset (dptr);
else return SCPE_OK;
}

t_stat runlimit_cmd (int32 flag, CONST char *cptr)
{
char gbuf[CBUFSIZE];
int32 num;
t_stat r;
double usec_factor = 1.0;
const char *units = "";
char runlimit[32];

GET_SWITCHES (cptr);                                    /* get switches */
if (0 == flag) {
    if (*cptr)
        return sim_messagef (SCPE_ARG, "NORUNLIMIT expects no arguments: %s\n", cptr);
    sim_runlimit = 0;
    sim_runlimit_switches = 0;
    sim_runlimit_enabled = FALSE;
    sim_cancel (&sim_runlimit_unit);
    unsetenv ("SIM_RUNLIMIT");
    unsetenv ("SIM_RUNLIMIT_UNITS");
    return SCPE_OK;
    }

cptr = get_glyph (cptr, gbuf, 0);               /* get next glyph */
num = (int32) get_uint (gbuf, 10, INT_MAX, &r);
if ((r != SCPE_OK) || (num == 0))               /* error? */
    return sim_messagef (SCPE_ARG, "Invalid argument: %s\n", gbuf);
cptr = get_glyph (cptr, gbuf, 0);               /* get next glyph */
if ((gbuf[0] == '\0') ||
    (MATCH_CMD (gbuf, sim_vm_interval_units) == 0)) {
    sim_switches &= ~SWMASK ('T');
    units = sim_vm_interval_units;
    }
else {
    int i;
    struct {
        const char *name;
        double usec_factor;
        } time_units[] = {
            {"MICROSECONDS",             1.0},
            {"USECONDS",                 1.0},
            {"SECONDS",            1000000.0},
            {"MINUTES",         60*1000000.0},
            {"HOURS",        60*60*1000000.0},
            {NULL,                       0.0}};

    for (i=0; time_units[i].name; i++) {
        if (MATCH_CMD (gbuf, time_units[i].name) == 0) {
            sim_switches |= SWMASK ('T');
            usec_factor = time_units[i].usec_factor;
            units = time_units[i].name;
            break;
            }
        }
    if (time_units[i].name == NULL)
        return sim_messagef (SCPE_2MARG, "Too many arguments: %s %s\n", gbuf, cptr);
    }
if (*cptr)
    return sim_messagef (SCPE_2MARG, "Too many arguments: %s\n", cptr);
sim_runlimit_enabled = TRUE;
sim_cancel (&sim_runlimit_unit);
sim_runlimit_switches = sim_switches;
if (sim_runlimit_switches & SWMASK ('T')) {
    sim_runlimit_d_initial = sim_runlimit_d = num * usec_factor * sim_host_speed_factor ();
    if (sim_host_speed_factor () > 1.0)
        sim_messagef (SCPE_OK, "Slow host - adjusting RUNLIMIT from %d %s to %.1f %s\n", num, units, num * sim_host_speed_factor (), units);
    snprintf (runlimit, sizeof (runlimit), "%.f", num * sim_host_speed_factor ());
    setenv ("SIM_RUNLIMIT", runlimit, 1);
    setenv ("SIM_RUNLIMIT_UNITS", units, 1);
    return sim_activate_after_d (&sim_runlimit_unit, sim_runlimit_d);
    }
else {
    sim_runlimit_initial = sim_runlimit = num;
    snprintf (runlimit, sizeof (runlimit), "%d", num);
    setenv ("SIM_RUNLIMIT", runlimit, 1);
    setenv ("SIM_RUNLIMIT_UNITS", units, 1);
    return sim_activate (&sim_runlimit_unit, sim_runlimit);
    }
}

t_stat set_runlimit (int32 flag, CONST char *cptr)
{
return runlimit_cmd (flag, cptr);
}

t_stat show_runlimit (FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, CONST char *cptr)
{
if (sim_runlimit_enabled) {
    if (sim_runlimit_switches & SWMASK ('T')) {
        double inst_per_sec = sim_timer_inst_per_sec ();

        if (sim_runlimit_d_initial != sim_runlimit_d) {
            fprintf (st, "%s initially, ", sim_fmt_secs (sim_runlimit_d_initial / 1000000.0));
            if (sim_is_active (&sim_runlimit_unit))
                fprintf (st, "and %s remaining\n", sim_fmt_secs (sim_runlimit_d / 1000000.0));
            else
                fprintf (st, "expired now\n");
            }
        else
            fprintf (st, "%s\n", sim_fmt_secs (sim_runlimit_d_initial / 1000000.0));
        }
    else {
        if (sim_runlimit_initial != sim_runlimit) {
            fprintf (st, "%d %s initially, ", sim_runlimit_initial, sim_vm_interval_units);
            if (sim_is_active (&sim_runlimit_unit))
                fprintf (st, "and %d %s remaining\n", sim_activate_time (&sim_runlimit_unit), sim_vm_interval_units);
            else
                fprintf (st, "expired now\n");
            }
        else
            fprintf (st, "%d %s\n", sim_runlimit_initial, sim_vm_interval_units);
        }
    }
else
    fprintf (st, "Run Limit Disabled\n");
return SCPE_OK;
}

/* Reset devices start..end

   Inputs:
        start   =       number of starting device
   Outputs:
        status  =       error status
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    }
else {
    if (sim_switches & SWMASK ('N')) {                  /* new file only? */
        uptr->fileref = sim_fopen (cptr, "wb+");        /* open new file */
        if (uptr->fileref == NULL)                      /* open fail? */
            return attach_err (uptr, SCPE_OPENERR);     /* yes, error */
        sim_messagef (SCPE_OK, "%s: creating new file\n", sim_dname (dptr));
        }
    else {                                              /* normal */
        uptr->fileref = sim_fopen (cptr, "rb+");        /* open r/w */
        if (uptr->fileref == NULL) {                    /* open fail? */
#if defined(EPERM)
            if ((errno == EROFS) || (errno == EACCES) || (errno == EPERM)) {/* read only? */
#else







|







7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
    uptr->flags = uptr->flags | UNIT_RO;                /* set rd only */
    }
else {
    if (sim_switches & SWMASK ('N')) {                  /* new file only? */
        uptr->fileref = sim_fopen (cptr, "wb+");        /* open new file */
        if (uptr->fileref == NULL)                      /* open fail? */
            return attach_err (uptr, SCPE_OPENERR);     /* yes, error */
        sim_messagef (SCPE_OK, "%s: creating new file: %s\n", sim_dname (dptr), cptr);
        }
    else {                                              /* normal */
        uptr->fileref = sim_fopen (cptr, "rb+");        /* open r/w */
        if (uptr->fileref == NULL) {                    /* open fail? */
#if defined(EPERM)
            if ((errno == EROFS) || (errno == EACCES) || (errno == EPERM)) {/* read only? */
#else
7278
7279
7280
7281
7282
7283
7284

7285
7286

7287
7288
7289
7290
7291
7292
7293

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
gbuf[sizeof(gbuf)-1] = '\0';
strlcpy (gbuf, cptr, sizeof(gbuf));
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)
{







>
|
|
>







7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804

GET_SWITCHES (cptr);                                    /* get switches */
if (*cptr == 0)                                         /* must be more */
    return SCPE_2FARG;
gbuf[sizeof(gbuf)-1] = '\0';
strlcpy (gbuf, cptr, sizeof(gbuf));
sim_trim_endspc (gbuf);
if ((sfile = sim_fopen (gbuf, "r+b")) == NULL) {    /* try existing file */
    if ((sfile = sim_fopen (gbuf, "wb")) == NULL)   /* create new empty file */
        return SCPE_OPENERR;
    }
r = sim_save (sfile);
fclose (sfile);
return r;
}

t_stat sim_save (FILE *sfile)
{
7416
7417
7418
7419
7420
7421
7422







7423
7424
7425
7426
7427
7428
7429
            val = get_rval (rptr, j);                   /* get value */
            WRITE_I (val);                              /* store */
            }
        }
    fputc ('\n', sfile);                                /* end registers */
    }
fputc ('\n', sfile);                                    /* end devices */







return (ferror (sfile))? SCPE_IOERR: SCPE_OK;           /* error during save? */
}

/* Restore command

   re[store] filename           restore state from specified file
*/







>
>
>
>
>
>
>







7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
            val = get_rval (rptr, j);                   /* get value */
            WRITE_I (val);                              /* store */
            }
        }
    fputc ('\n', sfile);                                /* end registers */
    }
fputc ('\n', sfile);                                    /* end devices */
if (!ferror (sfile)) {
    t_offset pos = sim_ftell (sfile);                   /* get current position */

    if (pos < 0)                                        /* error? */
        return SCPE_IOERR;                              /* done! */
    sim_set_fsize (sfile, (t_addr)pos);                 /* truncate the save file */
    }
return (ferror (sfile))? SCPE_IOERR: SCPE_OK;           /* error during save? */
}

/* Restore command

   re[store] filename           restore state from specified file
*/
7847
7848
7849
7850
7851
7852
7853





7854
7855
7856
7857
7858
7859
7860
int32 sim_next = 0;
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) {







>
>
>
>
>







8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
int32 sim_next = 0;
int32 unitno;
t_value pcv, orig_pcv;
t_stat r;
DEVICE *dptr;
UNIT *uptr;

if (sim_runlimit_enabled &&                             /* If the run limit has been hit? */
    (!sim_is_active (&sim_runlimit_unit))) {
    sim_messagef (SCPE_RUNTIME, "Execution limit exceeded, can't proceed.  Exiting...\n");
    exit (SCPE_RUNTIME);                                /* Execution can't proceed */
    }
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) {
8064
8065
8066
8067
8068
8069
8070







8071
8072
8073
8074
8075
8076
8077
    if (sim_step)                                       /* set step timer */
        sim_activate (&sim_step_unit, sim_step);
    } while (1);

if ((SCPE_BARE_STATUS(r) == SCPE_STOP) &&
    sigterm_received)
    r = SCPE_SIGTERM;








if ((SCPE_BARE_STATUS(r) == SCPE_STOP) &&               /* WRU exit from sim_instr() */
    (sim_on_actions[sim_do_depth][SCPE_STOP] == NULL) &&/* without a handler for a STOP condition */
    (sim_on_actions[sim_do_depth][0] == NULL))
    sim_os_ms_sleep (sim_stop_sleep_ms);                /* wait a bit for SIGINT */
sim_is_running = FALSE;                                 /* flag idle */
sim_stop_timer_services ();                             /* disable wall clock timing */







>
>
>
>
>
>
>







8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
    if (sim_step)                                       /* set step timer */
        sim_activate (&sim_step_unit, sim_step);
    } while (1);

if ((SCPE_BARE_STATUS(r) == SCPE_STOP) &&
    sigterm_received)
    r = SCPE_SIGTERM;

if (sim_runlimit_enabled) {
    if (sim_runlimit_switches & SWMASK ('T'))
        sim_runlimit_d = sim_activate_time_usecs (&sim_runlimit_unit);
    else
        sim_runlimit = sim_activate_time (&sim_runlimit_unit) - 1;
    }

if ((SCPE_BARE_STATUS(r) == SCPE_STOP) &&               /* WRU exit from sim_instr() */
    (sim_on_actions[sim_do_depth][SCPE_STOP] == NULL) &&/* without a handler for a STOP condition */
    (sim_on_actions[sim_do_depth][0] == NULL))
    sim_os_ms_sleep (sim_stop_sleep_ms);                /* wait a bit for SIGINT */
sim_is_running = FALSE;                                 /* flag idle */
sim_stop_timer_services ();                             /* disable wall clock timing */
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125

8126
8127
8128
8129
8130
8131
8132

/* Common setup for RUN or BOOT */

t_stat sim_run_boot_prep (int32 flag)
{
t_stat r;

sim_interval = 0;                                       /* reset queue */
sim_time = sim_rtime = 0;
noqueue_time = 0;                                       /* reset queue */
while (sim_clock_queue != QUEUE_LIST_END)
    sim_cancel (sim_clock_queue);

noqueue_time = sim_interval = 0;
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");
        }







|
<
<


>







8644
8645
8646
8647
8648
8649
8650
8651


8652
8653
8654
8655
8656
8657
8658
8659
8660
8661

/* Common setup for RUN or BOOT */

t_stat sim_run_boot_prep (int32 flag)
{
t_stat r;

/* reset queue */


while (sim_clock_queue != QUEUE_LIST_END)
    sim_cancel (sim_clock_queue);
sim_time = sim_rtime = 0;
noqueue_time = sim_interval = 0;
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");
        }
8195
8196
8197
8198
8199
8200
8201








8202
8203
8204
8205
8206
8207
8208
/* Unit service for step timeout, originally scheduled by STEP n command
   Return step timeout SCP code, will cause simulation to stop */

t_stat step_svc (UNIT *uptr)
{
return SCPE_STEP;
}









/* Unit service to facilitate expect matching to stop simulation.
   Return expect SCP code, will cause simulation to stop */

t_stat expect_svc (UNIT *uptr)
{
return SCPE_EXPECT | (sim_do_echo ? 0 : SCPE_NOMESSAGE);







>
>
>
>
>
>
>
>







8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
/* Unit service for step timeout, originally scheduled by STEP n command
   Return step timeout SCP code, will cause simulation to stop */

t_stat step_svc (UNIT *uptr)
{
return SCPE_STEP;
}

/* Unit service for run for timeout, originally scheduled by RUNFOR n command
   Return runlimit timeout SCP code, will cause simulation to stop */

t_stat runlimit_svc (UNIT *uptr)
{
return SCPE_RUNTIME;
}

/* Unit service to facilitate expect matching to stop simulation.
   Return expect SCP code, will cause simulation to stop */

t_stat expect_svc (UNIT *uptr)
{
return SCPE_EXPECT | (sim_do_echo ? 0 : SCPE_NOMESSAGE);
8839
8840
8841
8842
8843
8844
8845
8846



8847
8848
8849
8850
8851
8852
8853
        fprintf (sim_log, "%s\n", cptr? cptr: "");
    if (cptr == NULL)                                   /* force exit */
        return 1;
    if (*cptr == 0)                                     /* success */
        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;







|
>
>
>







9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
        fprintf (sim_log, "%s\n", cptr? cptr: "");
    if (cptr == NULL)                                   /* force exit */
        return 1;
    if (*cptr == 0)                                     /* success */
        return dfltinc;
    }
if (uptr->flags & UNIT_RO)                              /* read only? */
    return sim_messagef (SCPE_RO, "%s is read only.\n"
                                  "%sse a writable device to change %s\n", 
                                  sim_uname (uptr), (uptr->flags & UNIT_ROABLE) ? "Attach Read/Write or u" : "U",
                                  uptr->filename ? uptr->filename : "it");
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;
9352
9353
9354
9355
9356
9357
9358










9359
9360
9361
9362
9363
9364
9365
9366

*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;
    }
return val;
}

/* get_range            range specification








>
>
>
>
>
>
>
>
>
>
|







9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916

*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 (sim_toupper (*tptr) == 'K') {
        val *= 1000;
        ++tptr;
        }
    else {
        if (sim_toupper (*tptr) == 'M') {
            val *= 1000000;
            ++tptr;
            }
        }
    if ((*tptr != 0) || (val > max))
        *status = SCPE_ARG;
    }
return val;
}

/* get_range            range specification

10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794

10795
10796
10797
10798
10799
10800
10801
        if (uptr->action != NULL)
            reason = uptr->action (uptr);
        else
            reason = SCPE_OK;
        }
    AIO_EVENT_COMPLETE(uptr, reason);
    bare_reason = SCPE_BARE_STATUS (reason);
    if ((bare_reason != SCPE_OK)     &&  /* Provide context for unexpected errors */
        (bare_reason >= SCPE_BASE)   &&
        (bare_reason != SCPE_EXPECT) &&
        (bare_reason != SCPE_REMOTE) &&
        (bare_reason != SCPE_MTRLNT) && 
        (bare_reason != SCPE_STOP)   && 
        (bare_reason != SCPE_STEP)   && 

        (bare_reason != SCPE_EXIT))
        sim_messagef (reason, "\nUnexpected internal error while processing event for %s which returned %d - %s\n", sim_uname (uptr), reason, sim_error_text (reason));
    } while ((reason == SCPE_OK) && 
             (sim_interval <= 0) && 
             (sim_clock_queue != QUEUE_LIST_END) &&
             (!stop_cpu));








|
|
|
|
|
|
|
>







11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
        if (uptr->action != NULL)
            reason = uptr->action (uptr);
        else
            reason = SCPE_OK;
        }
    AIO_EVENT_COMPLETE(uptr, reason);
    bare_reason = SCPE_BARE_STATUS (reason);
    if ((bare_reason != SCPE_OK)      && /* Provide context for unexpected errors */
        (bare_reason >= SCPE_BASE)    &&
        (bare_reason != SCPE_EXPECT)  &&
        (bare_reason != SCPE_REMOTE)  &&
        (bare_reason != SCPE_MTRLNT)  && 
        (bare_reason != SCPE_STOP)    && 
        (bare_reason != SCPE_STEP)    && 
        (bare_reason != SCPE_RUNTIME) && 
        (bare_reason != SCPE_EXIT))
        sim_messagef (reason, "\nUnexpected internal error while processing event for %s which returned %d - %s\n", sim_uname (uptr), reason, sim_error_text (reason));
    } while ((reason == SCPE_OK) && 
             (sim_interval <= 0) && 
             (sim_clock_queue != QUEUE_LIST_END) &&
             (!stop_cpu));

10993
10994
10995
10996
10997
10998
10999

11000
11001
11002
11003
11004
11005
11006
11007
if (nptr != QUEUE_LIST_END)
    nptr->time += (uptr->next) ? 0 : uptr->time;
if (!uptr->next)
    uptr->time = 0;
uptr->usecs_remaining = 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;







>
|







11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
if (nptr != QUEUE_LIST_END)
    nptr->time += (uptr->next) ? 0 : uptr->time;
if (!uptr->next)
    uptr->time = 0;
uptr->usecs_remaining = 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;
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050









11051
11052
11053
11054
11055
11056
11057

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        absolute activation time + 1, 0 if inactive
*/

int32 _sim_activate_time (UNIT *uptr)
{
UNIT *cptr;
int32 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 + (int32)((uptr->usecs_remaining * sim_timer_inst_per_sec ()) / 1000000.0);
    }
return 0;
}










int32 sim_activate_time (UNIT *uptr)
{
int32 accum;

AIO_VALIDATE(uptr);
accum = _sim_timer_activate_time (uptr);







|













|



>
>
>
>
>
>
>
>
>







11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618

   Inputs:
        uptr    =       pointer to unit
   Outputs:
        result =        absolute activation time + 1, 0 if inactive
*/

int32 _sim_activate_queue_time (UNIT *uptr)
{
UNIT *cptr;
int32 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;
}

int32 _sim_activate_time (UNIT *uptr)
{
int32 accum = _sim_activate_queue_time (uptr);

if (accum)
    return accum + (int32)((uptr->usecs_remaining * sim_timer_inst_per_sec ()) / 1000000.0);
return 0;
}

int32 sim_activate_time (UNIT *uptr)
{
int32 accum;

AIO_VALIDATE(uptr);
accum = _sim_timer_activate_time (uptr);
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
    cnt -= 1;
    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");
    cptr = tptr;
    after_set = TRUE;
    }
if ((*cptr != '\0') && (*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);








|

|







12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
    cnt -= 1;
    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, 2000000000, &r);
    if (r != SCPE_OK)
        return sim_messagef (SCPE_ARG, "Invalid Halt After Value: %s\n", &gbuf[10]);
    cptr = tptr;
    after_set = TRUE;
    }
if ((*cptr != '\0') && (*cptr != '"') && (*cptr != '\''))
    return sim_messagef (SCPE_ARG, "String must be quote delimited\n");
cptr = get_glyph_quoted (cptr, gbuf, 0);

11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
if (!ep)                                                /* not there? ok */
    return SCPE_OK;
free (ep->match);                                       /* deallocate match string */
free (ep->match_pattern);                               /* deallocate the display format match string */
free (ep->act);                                         /* deallocate action */
#if defined(USE_REGEX)
if (ep->switches & EXP_TYP_REGEX)
    regfree (&ep->regex);                               /* release compiled regex */
#endif
exp->size -= 1;                                         /* decrement count */
for (i=ep-exp->rules; i<exp->size; i++)                 /* shuffle up remaining rules */
    exp->rules[i] = exp->rules[i+1];
if (exp->size == 0) {                                   /* No rules left? */
    free (exp->rules);
    exp->rules = NULL;







|







12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
if (!ep)                                                /* not there? ok */
    return SCPE_OK;
free (ep->match);                                       /* deallocate match string */
free (ep->match_pattern);                               /* deallocate the display format match string */
free (ep->act);                                         /* deallocate action */
#if defined(USE_REGEX)
if (ep->switches & EXP_TYP_REGEX)
    pcre_free (ep->regex);                              /* release compiled regex */
#endif
exp->size -= 1;                                         /* decrement count */
for (i=ep-exp->rules; i<exp->size; i++)                 /* shuffle up remaining rules */
    exp->rules[i] = exp->rules[i+1];
if (exp->size == 0) {                                   /* No rules left? */
    free (exp->rules);
    exp->rules = NULL;
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843

for (i=0; i<exp->size; i++) {
    free (exp->rules[i].match);                         /* deallocate match string */
    free (exp->rules[i].match_pattern);                 /* deallocate display format match string */
    free (exp->rules[i].act);                           /* deallocate action */
#if defined(USE_REGEX)
    if (exp->rules[i].switches & EXP_TYP_REGEX)
        regfree (&exp->rules[i].regex);                               /* release compiled regex */
#endif
    }
free (exp->rules);
exp->rules = NULL;
exp->size = 0;
free (exp->buf);
exp->buf = NULL;







|







12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404

for (i=0; i<exp->size; i++) {
    free (exp->rules[i].match);                         /* deallocate match string */
    free (exp->rules[i].match_pattern);                 /* deallocate display format match string */
    free (exp->rules[i].act);                           /* deallocate action */
#if defined(USE_REGEX)
    if (exp->rules[i].switches & EXP_TYP_REGEX)
        pcre_free (exp->rules[i].regex);                /* release compiled regex */
#endif
    }
free (exp->rules);
exp->rules = NULL;
exp->size = 0;
free (exp->buf);
exp->buf = NULL;
11861
11862
11863
11864
11865
11866
11867
11868
11869

11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884

11885
11886
11887
11888
11889
11890
11891
11892
11893
    return SCPE_MEM;
if (switches & EXP_TYP_REGEX) {
#if !defined (USE_REGEX)
    free (match_buf);
    return sim_messagef (SCPE_ARG, "RegEx support not available\n");
    }
#else   /* USE_REGEX */
    int res;
    regex_t re;


    memset (&re, 0, sizeof(re));
    memcpy (match_buf, match+1, strlen(match)-2);       /* extract string without surrounding quotes */
    match_buf[strlen(match)-2] = '\0';
    res = regcomp (&re, (char *)match_buf, REG_EXTENDED | ((switches & EXP_TYP_REGEX_I) ? REG_ICASE : 0));
    if (res) {
        size_t err_size = regerror (res, &re, NULL, 0);
        char *err_buf = (char *)calloc (err_size+1, 1);

        regerror (res, &re, err_buf, err_size);
        sim_messagef (SCPE_ARG, "Regular Expression Error: %s\n", err_buf);
        free (err_buf);
        free (match_buf);
        return SCPE_ARG|SCPE_NOMESSAGE;
        }

    sim_debug (exp->dbit, exp->dptr, "Expect Regular Expression: \"%s\" has %d sub expressions\n", match_buf, (int)re.re_nsub);
    regfree (&re);
    }
#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");
        }







|
|
>

<


|
|
<
<
<
<
|
<



>
|
|







12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432

12433
12434
12435
12436




12437

12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
    return SCPE_MEM;
if (switches & EXP_TYP_REGEX) {
#if !defined (USE_REGEX)
    free (match_buf);
    return sim_messagef (SCPE_ARG, "RegEx support not available\n");
    }
#else   /* USE_REGEX */
    pcre *re;
    const char *errmsg;
    int erroffset, re_nsub;


    memcpy (match_buf, match+1, strlen(match)-2);       /* extract string without surrounding quotes */
    match_buf[strlen(match)-2] = '\0';
    re = pcre_compile ((char *)match_buf, (switches & EXP_TYP_REGEX_I) ? PCRE_CASELESS : 0, &errmsg, &erroffset, NULL);
    if (re == NULL) {




        sim_messagef (SCPE_ARG, "Regular Expression Error: %s\n", errmsg);

        free (match_buf);
        return SCPE_ARG|SCPE_NOMESSAGE;
        }
    (void)pcre_fullinfo(re, NULL, PCRE_INFO_CAPTURECOUNT, &re_nsub);
    sim_debug (exp->dbit, exp->dptr, "Expect Regular Expression: \"%s\" has %d sub expressions\n", match_buf, re_nsub);
    pcre_free (re);
    }
#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");
        }
11919
11920
11921
11922
11923
11924
11925



11926
11927
11928

11929
11930
11931
11932
11933
11934
11935
if ((match_buf == NULL) || (ep->match_pattern == NULL)) {
    sim_exp_clr_tab (exp, ep);                          /* clear it */
    free (match_buf);
    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);
    /* quoted string was validated above, this decode operation will always succeed */







>
>
>


|
>







12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
if ((match_buf == NULL) || (ep->match_pattern == NULL)) {
    sim_exp_clr_tab (exp, ep);                          /* clear it */
    free (match_buf);
    return SCPE_MEM;
    }
if (switches & EXP_TYP_REGEX) {
#if defined(USE_REGEX)
    const char *errmsg;
    int erroffset;

    memcpy (match_buf, match+1, strlen(match)-2);      /* extract string without surrounding quotes */
    match_buf[strlen(match)-2] = '\0';
    ep->regex = pcre_compile ((char *)match_buf, (switches & EXP_TYP_REGEX_I) ? PCRE_CASELESS : 0, &errmsg, &erroffset, NULL);
    (void)pcre_fullinfo(ep->regex, NULL, PCRE_INFO_CAPTURECOUNT, &ep->re_nsub);
#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);
    /* quoted string was validated above, this decode operation will always succeed */
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
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);
    if (default_haltafter)
        fprintf (st, "  Default HaltAfter: %u instructions\n", (unsigned)default_haltafter);
    free (bstr);
    }
if (exp->dptr && (exp->dbit & exp->dptr->dctrl))
    fprintf (st, "  Expect 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, NULL) : "");
fprintf (st, "  Match Rules:\n");
if (!*match)
    return sim_exp_showall (st, exp);







|







12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
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);
    if (default_haltafter)
        fprintf (st, "  Default HaltAfter: %u %s\n", (unsigned)default_haltafter, sim_vm_interval_units);
    free (bstr);
    }
if (exp->dptr && (exp->dbit & exp->dptr->dctrl))
    fprintf (st, "  Expect 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, NULL) : "");
fprintf (st, "  Match Rules:\n");
if (!*match)
    return sim_exp_showall (st, exp);
12056
12057
12058
12059
12060
12061
12062
12063

12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088

12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108

12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
if (exp->buf_data < exp->buf_size)
    ++exp->buf_data;                                    /* Record amount of data in buffer */

for (i=0; i < exp->size; i++) {
    ep = &exp->rules[i];
    if (ep->switches & EXP_TYP_REGEX) {
#if defined (USE_REGEX)
        regmatch_t *matches;

        char *cbuf = (char *)exp->buf;
        static size_t sim_exp_match_sub_count = 0;

        if (tstr)
            cbuf = tstr;
        else {
            if (strlen ((char *)exp->buf) != exp->buf_ins) { /* Nul characters in buffer? */
                size_t off;

                tstr = (char *)malloc (exp->buf_ins + 1);
                tstr[0] = '\0';
                for (off=0; off < exp->buf_ins; off += 1 + strlen ((char *)&exp->buf[off]))
                    strcpy (&tstr[strlen (tstr)], (char *)&exp->buf[off]);
                cbuf = tstr;
                }
            }
        ++regex_checks;
        matches = (regmatch_t *)calloc ((ep->regex.re_nsub + 1), sizeof(*matches));
        if (sim_deb && exp->dptr && (exp->dptr->dctrl & exp->dbit)) {
            char *estr = sim_encode_quoted_string (exp->buf, exp->buf_ins);
            sim_debug (exp->dbit, exp->dptr, "Checking String: %s\n", estr);
            sim_debug (exp->dbit, exp->dptr, "Against RegEx Match Rule: %s\n", ep->match_pattern);
            free (estr);
            }
        if (!regexec (&ep->regex, cbuf, ep->regex.re_nsub + 1, matches, REG_NOTBOL)) {

            size_t j;
            char *buf = (char *)malloc (1 + exp->buf_ins);

            for (j=0; j<ep->regex.re_nsub + 1; j++) {
                char env_name[32];

                sprintf (env_name, "_EXPECT_MATCH_GROUP_%d", (int)j);
                memcpy (buf, &cbuf[matches[j].rm_so], matches[j].rm_eo-matches[j].rm_so);
                buf[matches[j].rm_eo-matches[j].rm_so] = '\0';
                setenv (env_name, buf, 1);      /* Make the match and substrings available as environment variables */
                sim_debug (exp->dbit, exp->dptr, "%s=%s\n", env_name, buf);
                }
            for (; j<sim_exp_match_sub_count; j++) {
                char env_name[32];

                sprintf (env_name, "_EXPECT_MATCH_GROUP_%d", (int)j);
                setenv (env_name, "", 1);      /* Remove previous extra environment variables */
                }
            sim_exp_match_sub_count = ep->regex.re_nsub;
            free (matches);

            free (buf);
            break;
            }
        free (matches);
#endif
        }
    else {
        if (exp->buf_data < ep->size)                           /* Too little data to match yet? */
            continue;                                           /* Yes, Try next one. */
        if (exp->buf_ins < ep->size) {                          /* Match might stradle end of buffer */
            /* 







|
>

















|






|
>



|



|
|









|
|
>



|







12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
if (exp->buf_data < exp->buf_size)
    ++exp->buf_data;                                    /* Record amount of data in buffer */

for (i=0; i < exp->size; i++) {
    ep = &exp->rules[i];
    if (ep->switches & EXP_TYP_REGEX) {
#if defined (USE_REGEX)
        int *ovector = NULL;
        int rc;
        char *cbuf = (char *)exp->buf;
        static size_t sim_exp_match_sub_count = 0;

        if (tstr)
            cbuf = tstr;
        else {
            if (strlen ((char *)exp->buf) != exp->buf_ins) { /* Nul characters in buffer? */
                size_t off;

                tstr = (char *)malloc (exp->buf_ins + 1);
                tstr[0] = '\0';
                for (off=0; off < exp->buf_ins; off += 1 + strlen ((char *)&exp->buf[off]))
                    strcpy (&tstr[strlen (tstr)], (char *)&exp->buf[off]);
                cbuf = tstr;
                }
            }
        ++regex_checks;
        ovector = (int *)malloc (3 * (ep->re_nsub + 1) * sizeof (*ovector));
        if (sim_deb && exp->dptr && (exp->dptr->dctrl & exp->dbit)) {
            char *estr = sim_encode_quoted_string (exp->buf, exp->buf_ins);
            sim_debug (exp->dbit, exp->dptr, "Checking String: %s\n", estr);
            sim_debug (exp->dbit, exp->dptr, "Against RegEx Match Rule: %s\n", ep->match_pattern);
            free (estr);
            }
        rc = pcre_exec (ep->regex, NULL, cbuf, exp->buf_ins, 0, PCRE_NOTBOL, ovector, 3 * (ep->re_nsub + 1));
        if (rc >= 0) {
            size_t j;
            char *buf = (char *)malloc (1 + exp->buf_ins);

            for (j=0; j < (size_t)rc; j++) {
                char env_name[32];

                sprintf (env_name, "_EXPECT_MATCH_GROUP_%d", (int)j);
                memcpy (buf, &cbuf[ovector[2 * j]], ovector[2 * j + 1] - ovector[2 * j]);
                buf[ovector[2 * j + 1] - ovector[2 * j]] = '\0';
                setenv (env_name, buf, 1);      /* Make the match and substrings available as environment variables */
                sim_debug (exp->dbit, exp->dptr, "%s=%s\n", env_name, buf);
                }
            for (; j<sim_exp_match_sub_count; j++) {
                char env_name[32];

                sprintf (env_name, "_EXPECT_MATCH_GROUP_%d", (int)j);
                setenv (env_name, "", 1);      /* Remove previous extra environment variables */
                }
            sim_exp_match_sub_count = ep->re_nsub;
            free (ovector);
            ovector = NULL;
            free (buf);
            break;
            }
        free (ovector);
#endif
        }
    else {
        if (exp->buf_data < ep->size)                           /* Too little data to match yet? */
            continue;                                           /* Yes, Try next one. */
        if (exp->buf_ins < ep->size) {                          /* Match might stradle end of buffer */
            /* 
12230
12231
12232
12233
12234
12235
12236






12237
12238
12239
12240
12241
12242
12243
    snd->bufsize = snd->insoff+size;
    snd->buffer = (uint8 *)realloc(snd->buffer, snd->bufsize);
    }
memcpy(snd->buffer+snd->insoff, data, size);
snd->insoff += size;
snd->delay = (sim_switches & SWMASK ('T')) ? (uint32)((sim_timer_inst_per_sec()*delay)/1000000.0) : delay;
snd->after = (sim_switches & SWMASK ('T')) ? (uint32)((sim_timer_inst_per_sec()*after)/1000000.0) : after;






snd->next_time = sim_gtime() + snd->after;
return SCPE_OK;
}

/* Cancel Queued input data */
t_stat sim_send_clear (SEND *snd)
{







>
>
>
>
>
>







12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
    snd->bufsize = snd->insoff+size;
    snd->buffer = (uint8 *)realloc(snd->buffer, snd->bufsize);
    }
memcpy(snd->buffer+snd->insoff, data, size);
snd->insoff += size;
snd->delay = (sim_switches & SWMASK ('T')) ? (uint32)((sim_timer_inst_per_sec()*delay)/1000000.0) : delay;
snd->after = (sim_switches & SWMASK ('T')) ? (uint32)((sim_timer_inst_per_sec()*after)/1000000.0) : after;
if (sim_switches & SWMASK ('T'))
    sim_debug (snd->dbit, snd->dptr, "%d bytes queued for input. Delay %d usecs = %d insts, After %d usecs = %d insts\n", 
                                     (int)size, (int)delay, (int)snd->delay, (int)after, (int)snd->after);
else
    sim_debug (snd->dbit, snd->dptr, "%d bytes queued for input. Delay=%d, After=%d\n", 
                                     (int)size, (int)delay, (int)after);
snd->next_time = sim_gtime() + snd->after;
return SCPE_OK;
}

/* Cancel Queued input data */
t_stat sim_send_clear (SEND *snd)
{
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
    fprint_buffer_string (st, snd->buffer+snd->extoff, snd->insoff-snd->extoff);
    fprintf (st, "\n");
    }
else
    fprintf (st, "  No Pending Input Data\n");
if ((snd->next_time - sim_gtime()) > 0) {
    if (((snd->next_time - sim_gtime()) > (sim_timer_inst_per_sec()/1000000.0)) && ((sim_timer_inst_per_sec()/1000000.0) > 0.0))
        fprintf (st, "  Minimum of %d instructions (%d microseconds) before sending first character\n", (int)(snd->next_time - sim_gtime()),
                                                        (int)((snd->next_time - sim_gtime())/(sim_timer_inst_per_sec()/1000000.0)));
    else
        fprintf (st, "  Minimum of %d instructions before sending first character\n", (int)(snd->next_time - sim_gtime()));
    }
if ((snd->delay > (sim_timer_inst_per_sec()/1000000.0)) && ((sim_timer_inst_per_sec()/1000000.0) > 0.0))
    fprintf (st, "  Minimum of %d instructions (%d microseconds) between characters\n", (int)snd->delay, (int)(snd->delay/(sim_timer_inst_per_sec()/1000000.0)));
else
    fprintf (st, "  Minimum of %d instructions between characters\n", (int)snd->delay);
if (after)
    fprintf (st, "  Default delay before first character input is %u instructions\n", after);
if (delay)
    fprintf (st, "  Default delay between character input is %u instructions\n", after);
if (snd->dptr && (snd->dbit & snd->dptr->dctrl))
    fprintf (st, "  Send Debugging via: SET %s DEBUG%s%s\n", sim_dname(snd->dptr), snd->dptr->debflags ? "=" : "", snd->dptr->debflags ? _get_dbg_verb (snd->dbit, snd->dptr, NULL) : "");
return SCPE_OK;
}

/* Poll for Queued input data */








|


|


|

|

|

|







12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
    fprint_buffer_string (st, snd->buffer+snd->extoff, snd->insoff-snd->extoff);
    fprintf (st, "\n");
    }
else
    fprintf (st, "  No Pending Input Data\n");
if ((snd->next_time - sim_gtime()) > 0) {
    if (((snd->next_time - sim_gtime()) > (sim_timer_inst_per_sec()/1000000.0)) && ((sim_timer_inst_per_sec()/1000000.0) > 0.0))
        fprintf (st, "  Minimum of %d %s (%d microseconds) before sending first character\n", (int)(snd->next_time - sim_gtime()), sim_vm_interval_units,
                                                        (int)((snd->next_time - sim_gtime())/(sim_timer_inst_per_sec()/1000000.0)));
    else
        fprintf (st, "  Minimum of %d %s before sending first character\n", (int)(snd->next_time - sim_gtime()), sim_vm_interval_units);
    }
if ((snd->delay > (sim_timer_inst_per_sec()/1000000.0)) && ((sim_timer_inst_per_sec()/1000000.0) > 0.0))
    fprintf (st, "  Minimum of %d %s (%d microseconds) between characters\n", (int)snd->delay, sim_vm_interval_units, (int)(snd->delay/(sim_timer_inst_per_sec()/1000000.0)));
else
    fprintf (st, "  Minimum of %d %s between characters\n", (int)snd->delay, sim_vm_interval_units);
if (after)
    fprintf (st, "  Default delay before first character input is %u %s\n", after, sim_vm_interval_units);
if (delay)
    fprintf (st, "  Default delay between character input is %u %s\n", after, sim_vm_interval_units);
if (snd->dptr && (snd->dbit & snd->dptr->dctrl))
    fprintf (st, "  Send Debugging via: SET %s DEBUG%s%s\n", sim_dname(snd->dptr), snd->dptr->debflags ? "=" : "", snd->dptr->debflags ? _get_dbg_verb (snd->dbit, snd->dptr, NULL) : "");
return SCPE_OK;
}

/* Poll for Queued input data */

12854
12855
12856
12857
12858
12859
12860








12861
12862
12863
12864
12865
12866
12867
                    _sim_debug_write (&buf[j], i-j);
                    _sim_debug_write ("\r\n", 2);
                    }
                debug_unterm = 0;
                }
            j = i + 1;
            }








        }
    if (i > j) {
        if (!debug_unterm)                          /* print prefix when required */
            _sim_debug_write (debug_prefix, strlen (debug_prefix));
        _sim_debug_write (&buf[j], i-j);
        }








>
>
>
>
>
>
>
>







13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
                    _sim_debug_write (&buf[j], i-j);
                    _sim_debug_write ("\r\n", 2);
                    }
                debug_unterm = 0;
                }
            j = i + 1;
            }
        else {
            if (buf[i] == 0) {      /* Imbedded \0 character in formatted result? */
                fprintf (stderr, "sim_debug() formatted result: '%s'\r\n"
                                 "            has an imbedded \\0 character.\r\n"
                                 "DON'T DO THAT!\r\n", buf);
                abort();
                }
            }
        }
    if (i > j) {
        if (!debug_unterm)                          /* print prefix when required */
            _sim_debug_write (debug_prefix, strlen (debug_prefix));
        _sim_debug_write (&buf[j], i-j);
        }

13228
13229
13230
13231
13232
13233
13234






13235
13236
13237
13238
13239
13240
13241
                        case 'D':
                            if (dptr)
                                appendText (topic, dptr->name, strlen (dptr->name));
                            break;
                        case 'S':
                            appendText (topic, sim_name, strlen (sim_name));
                            break;






                        case '%':
                            appendText (topic, "%", 1);
                            break;
                        case '+':
                            appendText (topic, "+", 1);
                            break;
                        default:                    /* Check for vararg # */







>
>
>
>
>
>







13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
                        case 'D':
                            if (dptr)
                                appendText (topic, dptr->name, strlen (dptr->name));
                            break;
                        case 'S':
                            appendText (topic, sim_name, strlen (sim_name));
                            break;
                        case 'C':
                            appendText (topic, sim_vm_interval_units, strlen (sim_vm_interval_units));
                            break;
                        case 'I':
                            appendText (topic, sim_vm_step_unit, strlen (sim_vm_step_unit));
                            break;
                        case '%':
                            appendText (topic, "%", 1);
                            break;
                        case '+':
                            appendText (topic, "+", 1);
                            break;
                        default:                    /* Check for vararg # */
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
        }
    }
rewind (tmp);

/* Discard leading blank lines/redundant titles */

for (i =0; i < skiplines; i++)
    fgets (tbuf, sizeof (tbuf), tmp);

while (fgets (tbuf, sizeof (tbuf), tmp)) {
    if (tbuf[0] != '\n')
        fputs ("    ", st);
    fputs (tbuf, st);
    }
fclose (tmp);







|







14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
        }
    }
rewind (tmp);

/* Discard leading blank lines/redundant titles */

for (i =0; i < skiplines; i++)
    if (fgets (tbuf, sizeof (tbuf), tmp)) {};

while (fgets (tbuf, sizeof (tbuf), tmp)) {
    if (tbuf[0] != '\n')
        fputs ("    ", st);
    fputs (tbuf, st);
    }
fclose (tmp);
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555

13556
13557
13558
13559
13560
13561
13562

return SCPE_OK;
}

#define HLP_MATCH_AMBIGUOUS (~0u)
#define HLP_MATCH_WILDCARD  (~1U)
#define HLP_MATCH_NONE      0
static int matchHelpTopicName (TOPIC *topic, const char *token)
{
size_t i, match;
char cbuf[CBUFSIZE], *cptr;

if (!strcmp (token, "*"))
    return HLP_MATCH_WILDCARD;

match = 0;
for (i = 0; i < topic->kids; i++) {
    strcpy (cbuf,topic->children[i]->title +
            ((topic->children[i]->flags & HLP_MAGIC_TOPIC)? 1 : 0));

    cptr = cbuf;
    while (*cptr) {
        if (blankch (*cptr)) {
            *cptr++ = '_';
            } 
        else {
            *cptr = (char)sim_toupper (*cptr);







|









|
|
>







14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147

return SCPE_OK;
}

#define HLP_MATCH_AMBIGUOUS (~0u)
#define HLP_MATCH_WILDCARD  (~1U)
#define HLP_MATCH_NONE      0
static size_t matchHelpTopicName (TOPIC *topic, const char *token)
{
size_t i, match;
char cbuf[CBUFSIZE], *cptr;

if (!strcmp (token, "*"))
    return HLP_MATCH_WILDCARD;

match = 0;
for (i = 0; i < topic->kids; i++) {
    strlcpy (cbuf,topic->children[i]->title +
            ((topic->children[i]->flags & HLP_MAGIC_TOPIC)? 1 : 0),
            sizeof (cbuf));
    cptr = cbuf;
    while (*cptr) {
        if (blankch (*cptr)) {
            *cptr++ = '_';
            } 
        else {
            *cptr = (char)sim_toupper (*cptr);
13715
13716
13717
13718
13719
13720
13721
13722
13723

13724
13725
13726
13727
13728
13729
13730
    if (topic->kids) {
        size_t w = 0;
        char *p;
        char tbuf[CBUFSIZE];

        fprintf (st, "\n    Additional information available:\n\n");
        for (i = 0; i < topic->kids; i++) {
            strcpy (tbuf, topic->children[i]->title + 
                    ((topic->children[i]->flags & HLP_MAGIC_TOPIC)? 1 : 0));

            for (p = tbuf; *p; p++) {
                if (blankch (*p))
                    *p = '_';
                }
            w += 4 + topic->kidwid;
            if (w > 80) {
                w = 4 + topic->kidwid;







|
|
>







14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
    if (topic->kids) {
        size_t w = 0;
        char *p;
        char tbuf[CBUFSIZE];

        fprintf (st, "\n    Additional information available:\n\n");
        for (i = 0; i < topic->kids; i++) {
            strlcpy (tbuf, topic->children[i]->title + 
                    ((topic->children[i]->flags & HLP_MAGIC_TOPIC)? 1 : 0),
                    sizeof (tbuf));
            for (p = tbuf; *p; p++) {
                if (blankch (*p))
                    *p = '_';
                }
            w += 4 + topic->kidwid;
            if (w > 80) {
                w = 4 + topic->kidwid;
14316
14317
14318
14319
14320
14321
14322























14323

14324


14325
14326
14327
14328
14329
14330
14331
            else {
                if (*cptr == '0') {         /* Octal Number */
                    while (*cptr && strchr (OctalDigits, *cptr))
                        *buf++ = *cptr++;
                    *buf = '\0';
                    }
                else {                      /* Decimal Number */























                    while (isdigit (*cptr))

                        *buf++ = *cptr++;


                    *buf = '\0';
                    }
                }
            }
        if (sim_isalpha (*cptr)) {          /* Numbers can't be followed by alpha character */
            *stat = SCPE_INVEXPR;
            return cptr;







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







14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
            else {
                if (*cptr == '0') {         /* Octal Number */
                    while (*cptr && strchr (OctalDigits, *cptr))
                        *buf++ = *cptr++;
                    *buf = '\0';
                    }
                else {                      /* Decimal Number */
                    int digits = 0;
                    int commas = 0;
                    const char *cp = cptr;

                    /* Ignore commas in decimal numbers */
                    while (isdigit (*cp) || (*cp == ',')) {
                        if (*cp == ',')
                            ++commas;
                        else
                            ++digits;
                        ++cp;
                        }
                    if ((commas > 0) && (commas != (digits - 1)/3)) {
                        *stat = SCPE_INVEXPR;
                        return cptr;
                        }
                    while (commas--) {
                        cp -= 4;
                        if (*cp != ',') {
                            *stat = SCPE_INVEXPR;
                            return cptr;
                            }
                        }
                    while (isdigit (*cptr) || (*cptr == ',')) {
                        if (*cptr != ',')
                            *buf++ = *cptr;
                        ++cptr;
                        }
                    *buf = '\0';
                    }
                }
            }
        if (sim_isalpha (*cptr)) {          /* Numbers can't be followed by alpha character */
            *stat = SCPE_INVEXPR;
            return cptr;
14637
14638
14639
14640
14641
14642
14643
























































































































































































14644
14645
14646
14647
14648
14649
14650
14651
14652

14653
14654
14655

14656



14657
14658
14659
14660
14661
14662
14663

14664






14665



14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680



14681
14682
14683





14684
14685








14686
14687
14688
hi = sim_rand_seed / q;
lo = sim_rand_seed % q;
sim_rand_seed = a * lo - r * hi;
if (sim_rand_seed < 0)
    sim_rand_seed += RAND_MAX + 1;
return (sim_rand_seed - 1);
}

























































































































































































/*
 * Compiled in unit tests for the various device oriented library 
 * modules: sim_card, sim_disk, sim_tape, sim_ether, sim_tmxr, etc.
 */

static t_stat sim_library_unit_tests (void)
{
int i;

DEVICE *dptr;
int32 saved_switches = sim_switches & ~SWMASK ('T');
t_stat stat = SCPE_OK;





if (sim_switches & SWMASK ('D')) {
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F') | SWMASK ('T'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    t_stat tstat = SCPE_OK;








    sim_switches = saved_switches;



    switch (DEV_TYPE(dptr)) {
#if defined(USE_SIM_CARD)
        case DEV_CARD:
            tstat = sim_card_test (dptr);
            break;
#endif
        case DEV_DISK:
            tstat = sim_disk_test (dptr);
            break;
        case DEV_ETHER:
            tstat = sim_ether_test (dptr);
            break;
        case DEV_TAPE:
            tstat = sim_tape_test (dptr);
            break;



        default:
            break;
        }





    if (tstat != SCPE_OK)
        stat = tstat;








    }
return stat;
}







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






|


>



>

>
>
>







>

>
>
>
>
>
>

>
>
>
|

|
|
|

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

>
>
>
>
>
>
>
>



15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
hi = sim_rand_seed / q;
lo = sim_rand_seed % q;
sim_rand_seed = a * lo - r * hi;
if (sim_rand_seed < 0)
    sim_rand_seed += RAND_MAX + 1;
return (sim_rand_seed - 1);
}


typedef struct MFILE {
    char *buf;
    size_t pos;
    size_t size;
    } MFILE;

static int Mprintf (MFILE *f, const char* fmt, ...)
{
    va_list arglist;
    int len;

    while (f) {
        size_t buf_space = (f->size - f->pos);

        va_start (arglist, fmt);
#if defined(NO_vsnprintf)
        len = vsprintf (f->buf + f->pos, fmt, arglist);
#else                                                   /* !defined(NO_vsnprintf) */
        len = vsnprintf (f->buf + f->pos, buf_space, fmt, arglist);
#endif                                                  /* NO_vsnprintf */
        va_end (arglist);

        if ((len < 0) || (len >= (int)buf_space)) {
            f->size *= 2;
            buf_space = (f->size - f->pos);
            if ((int)buf_space < len + 2)
                f->size += len + 2;
            f->buf = (char *)realloc (f->buf, f->size + 1);
            if (f->buf == NULL)            /* out of memory */
                return -1;
            f->buf[f->size-1] = '\0';
            continue;
            }
        f->pos += len;
        break;
    }
return 0;
}

static MFILE *
MOpen ()
{
return (MFILE *)calloc (1, sizeof (MFILE));
}

void
MFlush (MFILE *f)
{
f->pos = 0;
}

static int
FMwrite (FILE *fout, MFILE *fdata)
{
int ret = fwrite (fdata->buf, 1, fdata->pos, fout);

MFlush (fdata);
return ret;
}

static void
MClose (MFILE *f)
{
free (f->buf);
free (f);
}

/*
 * This sanity check walks through the all of simulator's device registers
 * to verify that each contains a reasonable description of a method to 
 * access the devices simulator data and that description stays within the 
 * device state variables it is supposed to reference.
 */

static t_stat sim_sanity_check_register_declarations (void)
{
t_stat stat = SCPE_OK;
int i;
DEVICE *dptr;
MFILE *f = MOpen ();

for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    REG *rptr;

    for (rptr = dptr->registers; (rptr != NULL) && (rptr->name != NULL); rptr++) {
        uint32 bytes = 1;
        uint32 rsz = SZ_R(rptr);
        uint32 memsize = ((rptr->flags & REG_FIT) || (rptr->depth > 1)) ? rptr->depth * rsz : 4;
        DEVICE *udptr = NULL;
        t_bool Bad;

        while ((bytes << 3) < rptr->offset + rptr->width)
            bytes <<= 1;

        if (rptr->depth > 1)
            bytes = rptr->ele_size;

        if (rptr->flags & REG_UNIT) {
            DEVICE **d;

            for (d = sim_devices; *d != NULL; d++) {
                if (((UNIT *)rptr->loc >= (*d)->units) &&
                    ((UNIT *)rptr->loc < (*d)->units + (*d)->numunits)) {
                    udptr = *d;
                    break;
                    }
                }
            }
        if (((rptr->width + rptr->offset + CHAR_BIT - 1) / CHAR_BIT) >= sizeof(size_map) / sizeof(size_map[0])) {
            Bad = TRUE;
            rsz = 0;
            }
        else {
            Bad = FALSE;
            rsz = SZ_R(rptr);
            }

        if (sim_switches & SWMASK ('R'))            /* Debug output */
            sim_printf ("%5s:%-9.9s %s(rdx=%u, wd=%u, off=%u, dep=%u, strsz=%u, objsz=%u, elesz=%u, rsz=%u, %s %s%s%s membytes=%u)\n", dptr->name, rptr->name, rptr->macro, 
                        rptr->radix, rptr->width, rptr->offset, rptr->depth, (uint32)rptr->str_size, (uint32)rptr->obj_size, (uint32)rptr->ele_size, rsz, rptr->desc ? rptr->desc : "",
                        (rptr->flags & REG_FIT) ? "REG_FIT" : "", (rptr->flags & REG_VMIO) ? " REG_VMIO" : "", (rptr->flags & REG_STRUCT) ? " REG_STRUCT" : "",
                        memsize);

        MFlush (f);
        if (rptr->depth == 1) {
            if (rptr->offset)
                Mprintf (f, "%s %s:%s used the %s macro to describe a %u bit%s wide field at offset %u\n", sim_name, dptr->name, rptr->name, rptr->macro, rptr->width, (rptr->width == 1) ? "" : "s", rptr->offset);
            else
                Mprintf (f, "%s %s:%s used the %s macro to describe a %u bit wide field\n", sim_name, dptr->name, rptr->name, rptr->macro, rptr->width);
            }
        else
            Mprintf (f, "%s %s:%s used the %s macro to describe a %u bit%s wide and %u elements deep array\n", sim_name, dptr->name, rptr->name, rptr->macro, rptr->width, (rptr->width == 1) ? "" : "s", rptr->depth);
        if (rsz > sizeof (t_value)) {
            Bad = TRUE;
            Mprintf (f, "%u bits at offset %u is wider than the maximum allowed width of %u bits\n", rptr->width, rptr->offset, (uint32)(8 * sizeof(t_value)));
            }
        if ((rptr->obj_size != 0) && (rptr->ele_size != 0) && (rptr->depth != 0) && (rptr->macro != NULL)) {
            if (rptr->flags & REG_UNIT) {
                if (udptr == NULL) {
                    Bad = TRUE;
                    Mprintf (f, "\tthe indicated UNIT can't be found for this %u depth array\n", rptr->depth);
                    }
                else {
                    if (rptr->depth > udptr->numunits) {
                        Bad = TRUE;
                        Mprintf (f, "\tthe depth of the UNIT array exceeds the number of units on the %s device which is %u\n", dptr->name, udptr->numunits);
                        }
                    if (rptr->obj_size > sizeof (t_value)) {
                        Bad = TRUE;
                        Mprintf (f, "\t%u is larger than the size of the t_value type (%u)\n", (uint32)rptr->obj_size, (uint32)sizeof (t_value));
                        }
                    }
                }
            else {
                bytes *= rptr->depth;
                if (!Bad) 
                    if ((rsz * rptr->depth == rptr->obj_size)                                       ||
                        ((rptr->flags & REG_STRUCT) && (rsz <= rptr->obj_size))                     ||
                        ((rptr->depth == 1) && 
                         ((rptr->obj_size == sizeof (t_value)) || (rsz < rptr->obj_size)))          ||
                        ((rptr->depth != 1) && (bytes == rptr->obj_size))                           ||
                        ((rptr->depth != 1) && (rptr->offset == 0) && (rptr->width == 8) &&
                         ((rptr->depth == rptr->obj_size) || (rptr->depth == rptr->obj_size - 1)))  ||
                        ((rptr->depth != 1) && (rptr->offset == 0) && (rptr->obj_size == rptr->ele_size)))
                    continue;
                Bad = TRUE;
                Mprintf (f, "\ttherefore SAVE/RESTORE operations will affect %u byte%s of memory\n", bytes, (bytes != 1) ? "s" : "");
                Mprintf (f, "\twhile the variable lives in %u bytes of memory\n", (uint32)rptr->obj_size);
                }
            }
        else
            Mprintf (f, "\tthis register entry is not properly initialized\n");
        if (Bad) {
            FMwrite (stdout, f);
            stat = SCPE_IERR;
            }
        }
    }
MClose (f);
return stat;
}


/*
 * Compiled in unit tests for the various device oriented library 
 * modules: sim_card, sim_disk, sim_tape, sim_ether, sim_tmxr, etc.
 */

t_stat test_lib_cmd (int32 flag, CONST char *cptr)
{
int i;
int bad_regs = 0;
DEVICE *dptr;
int32 saved_switches = sim_switches & ~SWMASK ('T');
t_stat stat = SCPE_OK;
char gbuf[CBUFSIZE];

cptr = get_glyph (cptr, gbuf, 0);
if (gbuf[0] == '\0')
    strcpy (gbuf, "ALL");
if (sim_switches & SWMASK ('D')) {
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F') | SWMASK ('T'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }
for (i = 0; (dptr = sim_devices[i]) != NULL; i++) {
    t_stat tstat = SCPE_OK;
    t_bool was_disabled = ((dptr->flags & DEV_DIS) != 0);

    if ((strcmp (gbuf, "ALL") != 0) && (strcmp (gbuf, dptr->name) != 0))
        continue;
    if (DEV_TYPE(dptr) == 0) {
        sim_printf ("Skipping %s - non library device type\n", dptr->name);
        continue;                       /* skip unspecified devices */
        }
    sim_switches = saved_switches;
    if (was_disabled)
        tstat = set_dev_enbdis (dptr, NULL, 1, NULL);
    if (tstat == SCPE_OK) {
        switch (DEV_TYPE(dptr)) {
#if defined(USE_SIM_CARD)
            case DEV_CARD:
                tstat = sim_card_test (dptr);
                break;
#endif
            case DEV_DISK:
                tstat = sim_disk_test (dptr);
                break;
            case DEV_ETHER:
                tstat = sim_ether_test (dptr);
                break;
            case DEV_TAPE:
                tstat = sim_tape_test (dptr);
                break;
            case DEV_MUX:
                tstat = tmxr_sock_test (dptr);
                break;
            default:
                break;
            }
        if (was_disabled)
            set_dev_enbdis (dptr, NULL, 0, NULL);
        }
    else
        tstat = SCPE_OK;        /* can't enable, just skip device */
    if (tstat != SCPE_OK) {
        stat = tstat;
        sim_printf ("%s device tests returned: %d - %s\n", dptr->name, tstat, sim_error_text (tstat));
        if (sim_ttisatty()) {
            if (get_yn ("Continue with additional tests? [N]", SCPE_STOP) == SCPE_STOP)
                break;
            }
        else
            break;
        }
    }
return stat;
}

Changes to src/SIMH/scp.h.

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
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 delete_cmd (int32 flg, CONST char *cptr);
t_stat copy_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 sleep_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);
t_stat echof_cmd (int32 flag, CONST char *ptr);
t_stat debug_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)))







>
>
>


















>
>







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
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 delete_cmd (int32 flg, CONST char *cptr);
t_stat copy_cmd (int32 flg, CONST char *cptr);
t_stat rename_cmd (int32 flg, CONST char *cptr);
t_stat mkdir_cmd (int32 flg, CONST char *cptr);
t_stat rmdir_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 sleep_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);
t_stat echof_cmd (int32 flag, CONST char *ptr);
t_stat debug_cmd (int32 flag, CONST char *ptr);
t_stat runlimit_cmd (int32 flag, CONST char *ptr);
t_stat test_lib_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)))
134
135
136
137
138
139
140

141
142
143
144
145
146
147
t_stat _sim_activate_after (UNIT *uptr, double usecs_walltime);
t_stat sim_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat sim_activate_after_abs_d (UNIT *uptr, double usecs_walltime);
t_stat _sim_activate_after_abs (UNIT *uptr, double usecs_walltime);
t_stat sim_cancel (UNIT *uptr);
t_bool sim_is_active (UNIT *uptr);
int32 sim_activate_time (UNIT *uptr);

int32 _sim_activate_time (UNIT *uptr);
double sim_activate_time_usecs (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);







>







139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
t_stat _sim_activate_after (UNIT *uptr, double usecs_walltime);
t_stat sim_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat sim_activate_after_abs_d (UNIT *uptr, double usecs_walltime);
t_stat _sim_activate_after_abs (UNIT *uptr, double usecs_walltime);
t_stat sim_cancel (UNIT *uptr);
t_bool sim_is_active (UNIT *uptr);
int32 sim_activate_time (UNIT *uptr);
int32 _sim_activate_queue_time (UNIT *uptr);
int32 _sim_activate_time (UNIT *uptr);
double sim_activate_time_usecs (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);
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#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_device sim_debug
void sim_debug (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#define _sim_debug_unit sim_debug_unit
void sim_debug_unit (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug_unit (uint32 dbits, UNIT *uptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
void _sim_debug_device (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_device (dbits, dptr, __VA_ARGS__);} while (0)
#define sim_debug_unit(dbits, uptr, ...) do { if (sim_deb && uptr && (((uptr)->dctrl | (uptr)->dptr->dctrl) & (dbits))) _sim_debug_unit (dbits, uptr, __VA_ARGS__);} while (0)
#endif
void sim_flush_buffered_files (void);







|







330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#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_device sim_debug
void sim_debug (uint32 dbits, DEVICE* dptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#define _sim_debug_unit sim_debug_unit
void sim_debug_unit (uint32 dbits, UNIT* uptr, const char *fmt, ...) GCC_FMT_ATTR(3, 4);
#else
void _sim_debug_unit (uint32 dbits, UNIT *uptr, const char* fmt, ...) GCC_FMT_ATTR(3, 4);
void _sim_debug_device (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_device (dbits, dptr, __VA_ARGS__);} while (0)
#define sim_debug_unit(dbits, uptr, ...) do { if (sim_deb && uptr && (((uptr)->dctrl | (uptr)->dptr->dctrl) & (dbits))) _sim_debug_unit (dbits, uptr, __VA_ARGS__);} while (0)
#endif
void sim_flush_buffered_files (void);
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
extern t_value *sim_eval;
extern volatile t_bool 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[64];


extern DEVICE *sim_devices[];
extern REG *sim_PC;
extern const char *sim_stop_messages[SCPE_BASE];
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);






/* Core SCP libraries can potentially have unit test routines.
   These defines help implement consistent unit test functionality */

#define SIM_TEST_INIT                                           \
        int test_stat;                                          \
        const char *sim_test;                                   \







|
>










>
>














|









>
>
>
>
>







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
extern t_value *sim_eval;
extern volatile t_bool 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 const char *sim_prog_name;                       /* executable program name */
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[64];
extern const char *sim_vm_release;
extern const char *sim_vm_release_message;
extern DEVICE *sim_devices[];
extern REG *sim_PC;
extern const char *sim_stop_messages[SCPE_BASE];
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 */

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);
extern const char **sim_clock_precalibrate_commands;
extern int32 sim_vm_initial_ips;                        /* base estimate of simulated instructions per second */
extern const char *sim_vm_interval_units;               /* Simulator can change this - default "instructions" */
extern const char *sim_vm_step_unit;                    /* Simulator can change this - default "instruction" */


/* Core SCP libraries can potentially have unit test routines.
   These defines help implement consistent unit test functionality */

#define SIM_TEST_INIT                                           \
        int test_stat;                                          \
        const char *sim_test;                                   \

Changes to src/SIMH/sim_card.c.

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    0x212, 0xB00, 0xA80, 0xA40, 0xA20, 0xA10, 0xA08, 0xA04,     /* 140 - 177 */
   /*   h      i      j      k      l      m      n      o */
    0xA02, 0xA01, 0xD00, 0xC80, 0xC40, 0xC20, 0xC10, 0xC08,
   /*   p      q      r      s      t      u      v      w */
    0xC04, 0xC02, 0xC01, 0x680, 0x640, 0x620, 0x610, 0x608,
   /*   x      y      z      {      |      }      ~    del */
   /*                     T79     Y78   Y79     79         */
    0x604, 0x602, 0x601, 0x406, 0x806, 0x006, 0x005, 0xf000
};

/* Set for Burrough codes */
static const uint16          ascii_to_hol_029[128] = {
   /* Control                              */
    0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,    /*0-37*/
   /*Control*/







|







137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    0x212, 0xB00, 0xA80, 0xA40, 0xA20, 0xA10, 0xA08, 0xA04,     /* 140 - 177 */
   /*   h      i      j      k      l      m      n      o */
    0xA02, 0xA01, 0xD00, 0xC80, 0xC40, 0xC20, 0xC10, 0xC08,
   /*   p      q      r      s      t      u      v      w */
    0xC04, 0xC02, 0xC01, 0x680, 0x640, 0x620, 0x610, 0x608,
   /*   x      y      z      {      |      }      ~    del */
   /*                     T79     Y78   Y79     79         */
    0x604, 0x602, 0x601, 0x406, 0x806, 0x805, 0x005, 0xf000
};

/* Set for Burrough codes */
static const uint16          ascii_to_hol_029[128] = {
   /* Control                              */
    0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,0xf000,    /*0-37*/
   /*Control*/
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
        return 1;
    return 0;
}



struct _card_buffer {
   char                  buffer[8192+500];    /* Buffer data */
   int                   len;                 /* Amount of data in buffer */
   int                   size;                /* Size of last card read */
};

static int _cmpcard(const char *p, const char *s) {
   int  i;
   if (p[0] != '~')
        return 0;
   for(i = 0; i < 3; i++) {
        if (tolower(p[i+1]) != s[i])
           return 0;
   }







|




|







595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
        return 1;
    return 0;
}



struct _card_buffer {
   uint8                 buffer[8192+500];    /* Buffer data */
   int                   len;                 /* Amount of data in buffer */
   int                   size;                /* Size of last card read */
};

static int _cmpcard(const uint8 *p, const char *s) {
   int  i;
   if (p[0] != '~')
        return 0;
   for(i = 0; i < 3; i++) {
        if (tolower(p[i+1]) != s[i])
           return 0;
   }
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639

    sim_debug(DEBUG_CARD, dptr, "Read card ");
    if ((uptr->flags & UNIT_CARD_MODE) == MODE_AUTO) {
        mode = MODE_TEXT;   /* Default is text */

        /* Check buffer to see if binary card in it. */
        for (i = 0, temp = 0; i < 160 && i <buf->len; i+=2)
            temp |= buf->buffer[i];
        /* Check if every other char < 16 & full buffer */
        if ((temp & 0x0f) == 0 && i == 160)
            mode = MODE_BIN;        /* Probably binary */
        /* Check if maybe BCD or CBN */
        if (buf->buffer[0] & 0x80) {
            int     odd = 0;
            int     even = 0;







|







625
626
627
628
629
630
631
632
633
634
635
636
637
638
639

    sim_debug(DEBUG_CARD, dptr, "Read card ");
    if ((uptr->flags & UNIT_CARD_MODE) == MODE_AUTO) {
        mode = MODE_TEXT;   /* Default is text */

        /* Check buffer to see if binary card in it. */
        for (i = 0, temp = 0; i < 160 && i <buf->len; i+=2)
            temp |= (uint16)(buf->buffer[i] & 0xFF);
        /* Check if every other char < 16 & full buffer */
        if ((temp & 0x0f) == 0 && i == 160)
            mode = MODE_BIN;        /* Probably binary */
        /* Check if maybe BCD or CBN */
        if (buf->buffer[0] & 0x80) {
            int     odd = 0;
            int     even = 0;
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
        sim_debug(DEBUG_CARD, dptr, "bin\n");
        if (buf->len < 160) {
            (*image)[0] = CARD_ERR;
            return SCPE_OPENERR;
        }
        /* Move data to buffer */
        for (col = i = 0; i < 160;) {
            temp |= buf->buffer[i];
            (*image)[col] = (buf->buffer[i++] >> 4) & 0xF;
            (*image)[col++] |= ((uint16)buf->buffer[i++]) << 4;
        }
        /* Check if format error */
        if (temp & 0xF)
            (*image)[0]  |= CARD_ERR;

        break;

    case MODE_CBN:
        sim_debug(DEBUG_CARD, dptr, "cbn\n");
        /* Check if first character is a tape mark */
        if (((uint8)buf->buffer[0]) == 0217 &&
                   (buf->len == 1 || (((uint8)buf->buffer[1]) & 0200) != 0)) {
            i = 1;
            (*image)[0] |= CARD_EOF;
            break;
        }

        /* Clear record mark */
        buf->buffer[0] &= 0x7f;







|

|










|
|







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
        sim_debug(DEBUG_CARD, dptr, "bin\n");
        if (buf->len < 160) {
            (*image)[0] = CARD_ERR;
            return SCPE_OPENERR;
        }
        /* Move data to buffer */
        for (col = i = 0; i < 160;) {
            temp |= (uint16)(buf->buffer[i] & 0xff);
            (*image)[col] = (buf->buffer[i++] >> 4) & 0xF;
            (*image)[col++] |= ((uint16)buf->buffer[i++] & 0xff) << 4;
        }
        /* Check if format error */
        if (temp & 0xF)
            (*image)[0]  |= CARD_ERR;

        break;

    case MODE_CBN:
        sim_debug(DEBUG_CARD, dptr, "cbn\n");
        /* Check if first character is a tape mark */
        if (buf->buffer[0] == 0217 &&
                   (buf->len == 1 || (buf->buffer[1] & 0200) != 0)) {
            i = 1;
            (*image)[0] |= CARD_EOF;
            break;
        }

        /* Clear record mark */
        buf->buffer[0] &= 0x7f;
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
            i++;
        }
        break;

    case MODE_BCD:
        sim_debug(DEBUG_CARD, dptr, "bcd [");
        /* Check if first character is a tape mark */
        if (((uint8)buf->buffer[0]) == 0217 && (((uint8)buf->buffer[1]) & 0200) != 0) {
            i = 1;
            (*image)[0] |= CARD_EOF;
            break;
        }

        /* Clear record mark */
        buf->buffer[0] &= 0x7f;







|







840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
            i++;
        }
        break;

    case MODE_BCD:
        sim_debug(DEBUG_CARD, dptr, "bcd [");
        /* Check if first character is a tape mark */
        if (buf->buffer[0] == 0217 && (buf->buffer[1] & 0200) != 0) {
            i = 1;
            (*image)[0] |= CARD_EOF;
            break;
        }

        /* Clear record mark */
        buf->buffer[0] &= 0x7f;
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895

    case MODE_EBCDIC:
        sim_debug(DEBUG_CARD, dptr, "ebcdic\n");
        if (buf->len < 80)
            (*image)[0] |= CARD_ERR;
        /* Move data to buffer */
        for (i = 0; i < 80 && i < buf->len; i++) {
            temp = buf->buffer[i] & 0xFF;
            (*image)[i] = ebcdic_to_hol[temp];
        }
        break;

    }
    buf->size = i;
    return SCPE_OK;







|







881
882
883
884
885
886
887
888
889
890
891
892
893
894
895

    case MODE_EBCDIC:
        sim_debug(DEBUG_CARD, dptr, "ebcdic\n");
        if (buf->len < 80)
            (*image)[0] |= CARD_ERR;
        /* Move data to buffer */
        for (i = 0; i < 80 && i < buf->len; i++) {
            temp = (uint16)(buf->buffer[i]) & 0xFF;
            (*image)[i] = ebcdic_to_hol[temp];
        }
        break;

    }
    buf->size = i;
    return SCPE_OK;
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
                buf.len += l;
        }

        /* Allocate space for some more cards if needed */
        if (data->hopper_cards >= data->hopper_size) {
            data->hopper_size += DECK_SIZE;
            data->images = (uint16 (*)[1][80])realloc(data->images,
                       data->hopper_size * sizeof(*(data->images)));
            memset(&data->images[data->hopper_cards], 0,
                       (data->hopper_size - data->hopper_cards) *
                             sizeof(*(data->images)));
        }

        /* Process one card */
        cards++;
        if (_sim_parse_card(uptr, dptr, &buf, &(*data->images)[data->hopper_cards])
                != SCPE_OK) {







|

|







927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
                buf.len += l;
        }

        /* Allocate space for some more cards if needed */
        if (data->hopper_cards >= data->hopper_size) {
            data->hopper_size += DECK_SIZE;
            data->images = (uint16 (*)[1][80])realloc(data->images,
                       (size_t)data->hopper_size * sizeof(*(data->images)));
            memset(&data->images[data->hopper_cards], 0,
                       (size_t)(data->hopper_size - data->hopper_cards) *
                             sizeof(*(data->images)));
        }

        /* Process one card */
        cards++;
        if (_sim_parse_card(uptr, dptr, &buf, &(*data->images)[data->hopper_cards])
                != SCPE_OK) {
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    /* If there is an error, free just read deck */
    if (r == SCPE_OK) {
       if (eof) {
          /* Allocate space for some more cards if needed */
          if (data->hopper_cards >= data->hopper_size) {
              data->hopper_size += DECK_SIZE;
              data->images = (uint16 (*)[1][80])realloc(data->images,
                         data->hopper_size * sizeof(*(data->images)));
              memset(&data->images[data->hopper_cards], 0,
                         (data->hopper_size - data->hopper_cards) *
                               sizeof(*(data->images)));
          }

          /* Create empty card */
          (*data->images)[data->hopper_cards][0] = CARD_EOF;
          data->hopper_cards++;
       }







|

|







957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    /* If there is an error, free just read deck */
    if (r == SCPE_OK) {
       if (eof) {
          /* Allocate space for some more cards if needed */
          if (data->hopper_cards >= data->hopper_size) {
              data->hopper_size += DECK_SIZE;
              data->images = (uint16 (*)[1][80])realloc(data->images,
                         (size_t)data->hopper_size * sizeof(*(data->images)));
              memset(&data->images[data->hopper_cards], 0,
                         (size_t)(data->hopper_size - data->hopper_cards) *
                               sizeof(*(data->images)));
          }

          /* Create empty card */
          (*data->images)[data->hopper_cards][0] = CARD_EOF;
          data->hopper_cards++;
       }
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
                     (eof)? "-E ": "", fmt, cptr);
                free(saved_filename);
            } else {
                uptr->filename = (char *)malloc (32 + strlen (cptr));
                sprintf (uptr->filename, "%s-F %s %s", (eof)?"-E ": "", fmt, cptr);
            }
            r = sim_messagef(SCPE_OK, "%s: %d card Deck Loaded from %s\n",
                       sim_uname(uptr), data->hopper_cards - previous_cards, cptr);
        } else {
            if (uptr->dynflags & UNIT_ATTMULT)
                uptr->flags |= UNIT_ATT;
            detach_unit(uptr);
            return r;
        }
    }







|







1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
                     (eof)? "-E ": "", fmt, cptr);
                free(saved_filename);
            } else {
                uptr->filename = (char *)malloc (32 + strlen (cptr));
                sprintf (uptr->filename, "%s-F %s %s", (eof)?"-E ": "", fmt, cptr);
            }
            r = sim_messagef(SCPE_OK, "%s: %d card Deck Loaded from %s\n",
                       sim_uname(uptr), (int)(data->hopper_cards - previous_cards), cptr);
        } else {
            if (uptr->dynflags & UNIT_ATTMULT)
                uptr->flags |= UNIT_ATT;
            detach_unit(uptr);
            return r;
        }
    }
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
SIM_TEST(attach_cmd (0, cmd));
sprintf (cmd, "%s -S File30.deck", dptr->name);
SIM_TEST(attach_cmd (0, cmd));
sprintf (cmd, "%s -S -E File40.deck", dptr->name);
SIM_TEST(attach_cmd (0, cmd));
sprintf (saved_filename, "%s %s", dptr->name, dptr->units->filename);
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", sim_card_output_hopper_count(dptr->units));
while (!sim_card_eof (dptr->units))
    SIM_TEST(sim_read_card (dptr->units, card_image));
sim_printf ("Input Hopper Count:  %d\n", sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", sim_card_output_hopper_count(dptr->units));
sim_printf ("Detaching %s\n", dptr->name);
SIM_TEST(detach_cmd (0, dptr->name));
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", sim_card_output_hopper_count(dptr->units));
sim_printf ("Attaching Saved Filenames: %s\n", saved_filename + strlen(dptr->name));
SIM_TEST(attach_cmd (0, saved_filename));
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", sim_card_output_hopper_count(dptr->units));
SIM_TEST(detach_cmd (0, dptr->name));
(void)remove ("file10.deck");
(void)remove ("file20.deck");
(void)remove ("file30.deck");
(void)remove ("file40.deck");
#endif /* defined(USE_SIM_CARD) && defined(SIM_CARD_API) */
return stat;







|
|


|
|



|
|



|
|







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
SIM_TEST(attach_cmd (0, cmd));
sprintf (cmd, "%s -S File30.deck", dptr->name);
SIM_TEST(attach_cmd (0, cmd));
sprintf (cmd, "%s -S -E File40.deck", dptr->name);
SIM_TEST(attach_cmd (0, cmd));
sprintf (saved_filename, "%s %s", dptr->name, dptr->units->filename);
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", (int)sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", (int)sim_card_output_hopper_count(dptr->units));
while (!sim_card_eof (dptr->units))
    SIM_TEST(sim_read_card (dptr->units, card_image));
sim_printf ("Input Hopper Count:  %d\n", (int)sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", (int)sim_card_output_hopper_count(dptr->units));
sim_printf ("Detaching %s\n", dptr->name);
SIM_TEST(detach_cmd (0, dptr->name));
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", (int)sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", (int)sim_card_output_hopper_count(dptr->units));
sim_printf ("Attaching Saved Filenames: %s\n", saved_filename + strlen(dptr->name));
SIM_TEST(attach_cmd (0, saved_filename));
show_cmd (0, dptr->name);
sim_printf ("Input Hopper Count:  %d\n", (int)sim_card_input_hopper_count(dptr->units));
sim_printf ("Output Hopper Count: %d\n", (int)sim_card_output_hopper_count(dptr->units));
SIM_TEST(detach_cmd (0, dptr->name));
(void)remove ("file10.deck");
(void)remove ("file20.deck");
(void)remove ("file30.deck");
(void)remove ("file40.deck");
#endif /* defined(USE_SIM_CARD) && defined(SIM_CARD_API) */
return stat;

Changes to src/SIMH/sim_console.c.

178
179
180
181
182
183
184







185
186
187
188
189
190
191
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







extern TMLN *sim_oline;                                 /* global output socket */

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) */








>
>
>
>
>
>
>







178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
t_bool sim_signaled_int_char                            /* WRU character detected by signal while running */
#if defined (_WIN32) || defined (_VMS) || defined (__CYGWIN__)
                             = FALSE;
#else
                             = TRUE;
#endif
uint32 sim_last_poll_kbd_time;                          /* time when sim_poll_kbd was called */
extern TMLN *sim_oline;                                 /* global output socket */

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) */

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
        if (show_con_tab[i].arg != -1)
            show_con_tab[i].action (st, dptr, uptr, show_con_tab[i].arg, cptr);
    return SCPE_OK;
    }
while (*cptr != 0) {
    cptr = get_glyph (cptr, gbuf, ',');                 /* get modifier */
    if ((shptr = find_shtab (show_con_tab, gbuf)))
        shptr->action (st, dptr, uptr, shptr->arg, cptr);
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

#define MAX_REMOTE_SESSIONS 40                          /* Arbitrary Session Limit */








|







433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
        if (show_con_tab[i].arg != -1)
            show_con_tab[i].action (st, dptr, uptr, show_con_tab[i].arg, cptr);
    return SCPE_OK;
    }
while (*cptr != 0) {
    cptr = get_glyph (cptr, gbuf, ',');                 /* get modifier */
    if ((shptr = find_shtab (show_con_tab, gbuf)))
        shptr->action (st, dptr, uptr, shptr->arg, NULL);
    else return SCPE_NOPARAM;
    }
return SCPE_OK;
}

#define MAX_REMOTE_SESSIONS 40                          /* Arbitrary Session Limit */

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        fprintf (st, "    is repeated every %s\n", sim_fmt_secs (rem->repeat_interval / 1000000.0));
        }
    if (rem->smp_reg_count) {
        uint32 reg;
        DEVICE *dptr = NULL;

        if (rem->smp_sample_dither_pct)
            fprintf (st, "Register Bit Sampling is occurring every %d cycles (dithered %d percent)\n", rem->smp_sample_interval, rem->smp_sample_dither_pct);
        else
            fprintf (st, "Register Bit Sampling is occurring every %d cycles\n", rem->smp_sample_interval);
        fprintf (st, " Registers being sampled are: ");
        for (reg = 0; reg < rem->smp_reg_count; reg++) {
            if (rem->smp_regs[reg].indirect)
                fprintf (st, " indirect ");
            if (dptr != rem->smp_regs[reg].dptr)
                fprintf (st, "%s ", rem->smp_regs[reg].dptr->name);
            if (rem->smp_regs[reg].reg->depth > 1)







|

|







635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
        fprintf (st, "    is repeated every %s\n", sim_fmt_secs (rem->repeat_interval / 1000000.0));
        }
    if (rem->smp_reg_count) {
        uint32 reg;
        DEVICE *dptr = NULL;

        if (rem->smp_sample_dither_pct)
            fprintf (st, "Register Bit Sampling is occurring every %d %s (dithered %d percent)\n", rem->smp_sample_interval, sim_vm_interval_units, rem->smp_sample_dither_pct);
        else
            fprintf (st, "Register Bit Sampling is occurring every %d %s\n", rem->smp_sample_interval, sim_vm_interval_units);
        fprintf (st, " Registers being sampled are: ");
        for (reg = 0; reg < rem->smp_reg_count; reg++) {
            if (rem->smp_regs[reg].indirect)
                fprintf (st, " indirect ");
            if (dptr != rem->smp_regs[reg].dptr)
                fprintf (st, "%s ", rem->smp_regs[reg].dptr->name);
            if (rem->smp_regs[reg].reg->depth > 1)
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
cptr = get_glyph_nc (cptr, gbuf, 0);                    /* get file name */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
sim_set_logoff (0, NULL);                               /* close cur log */
r = sim_open_logfile (gbuf, FALSE, &sim_log, &sim_log_ref); /* open log */
if (r != SCPE_OK)                                       /* error? */
    return r;
if (!sim_quiet)
    fprintf (stdout, "Logging to file \"%s\"\n", 
             sim_logfile_name (sim_log, sim_log_ref));
fprintf (sim_log, "Logging to file \"%s\"\n", 
             sim_logfile_name (sim_log, sim_log_ref));  /* start of log */
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)
    fprintf (stdout, "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;
}








|





>
|











|







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
cptr = get_glyph_nc (cptr, gbuf, 0);                    /* get file name */
if (*cptr != 0)                                         /* now eol? */
    return SCPE_2MARG;
sim_set_logoff (0, NULL);                               /* close cur log */
r = sim_open_logfile (gbuf, FALSE, &sim_log, &sim_log_ref); /* open log */
if (r != SCPE_OK)                                       /* error? */
    return r;
if ((!sim_quiet) && (!(sim_switches & SWMASK ('Q'))))
    fprintf (stdout, "Logging to file \"%s\"\n", 
             sim_logfile_name (sim_log, sim_log_ref));
fprintf (sim_log, "Logging to file \"%s\"\n", 
             sim_logfile_name (sim_log, sim_log_ref));  /* start of log */
time(&now);
if ((!sim_quiet) && (!(sim_switches & SWMASK ('Q'))))
    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) && (!(sim_switches & SWMASK ('Q'))))
    fprintf (stdout, "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;
}

2830
2831
2832
2833
2834
2835
2836

2837
2838
2839
2840
2841
2842
2843

/* 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 */
    if (sim_ttisatty ())







>







2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852

/* Poll for character */

t_stat sim_poll_kbd (void)
{
t_stat c;

sim_last_poll_kbd_time = sim_os_msec ();                    /* record when this poll happened */
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 */
    if (sim_ttisatty ())
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
}

static t_stat sim_os_putchar (int32 out)
{
char c;

c = out;
(void)write (1, &c, 1);
return SCPE_OK;
}

#endif

/* Decode a string.








|







4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
}

static t_stat sim_os_putchar (int32 out)
{
char c;

c = out;
if (write (1, &c, 1)) {};
return SCPE_OK;
}

#endif

/* Decode a string.

Changes to src/SIMH/sim_console.h.

123
124
125
126
127
128
129
130
131
132
133
134
135


136
137
138
139
140
141
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







|

|
|
|
|
>
>






123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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 */
extern t_bool sim_signaled_int_char;    /* WRU character detected by signal while running  */
extern uint32 sim_last_poll_kbd_time;   /* time when sim_poll_kbd was called */

#ifdef  __cplusplus
}
#endif

#endif

Changes to src/SIMH/sim_defs.h.

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#undef MEM_MAPPED                   /* avoid macro name collision */
#include <process.h>
#endif

#ifdef USE_REGEX
#undef USE_REGEX
#endif
#if defined(HAVE_PCREPOSIX_H)
#include <pcreposix.h>
#include <pcre.h>
#define USE_REGEX 1
#elif defined(HAVE_REGEX_H)
#include <regex.h>
#define USE_REGEX 1
#endif

#ifdef  __cplusplus
extern "C" {
#endif








|
<

<
<
<







142
143
144
145
146
147
148
149

150



151
152
153
154
155
156
157
#undef MEM_MAPPED                   /* avoid macro name collision */
#include <process.h>
#endif

#ifdef USE_REGEX
#undef USE_REGEX
#endif
#if defined(HAVE_PCRE_H)

#include <pcre.h>



#define USE_REGEX 1
#endif

#ifdef  __cplusplus
extern "C" {
#endif

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
#elif defined(__GNUC__)
#define SIM_INLINE inline
#define SIM_NOINLINE  __attribute__ ((noinline))
#else
#define SIM_INLINE 
#define SIM_NOINLINE
#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







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








|
|
|
>
>
>
|
|
|
>







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
#elif defined(__GNUC__)
#define SIM_INLINE inline
#define SIM_NOINLINE  __attribute__ ((noinline))
#else
#define SIM_INLINE 
#define SIM_NOINLINE
#endif

/* Packed structure support */

#ifdef _MSC_VER
# define PACKED_BEGIN __pragma( pack(push, 1) )
# define PACKED_END __pragma( pack(pop) )
#else
# define PACKED_BEGIN
#if defined(_WIN32)
# define PACKED_END __attribute__((gcc_struct, packed))
#else
# define PACKED_END __attribute__((packed))
#endif
#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   /* !defined(__GNUC__) && !defined(_MSC_VER)  */
#define WEAK
#endif  /* __GNUC__ */
#else   /* !defined(__cplusplus) */
#if defined(__GNUC__)
#define WEAK __attribute__((common))
#else   /* !defined(__GNUC__) */
#define WEAK
#endif  /* defined(__GNUC__) */
#endif  /* defined(__cplusplus) */

/* System independent definitions */

#define FLIP_SIZE       (1 << 16)                       /* flip buf size */
#if !defined (PATH_MAX)                                 /* usually in limits */
#define PATH_MAX        512
#endif
412
413
414
415
416
417
418



419
420
421
422
423
424
425
426
427
#define SCPE_AFAIL      (SCPE_BASE + 42)                /* assert failed */
#define SCPE_INVREM     (SCPE_BASE + 43)                /* invalid remote console command */
#define SCPE_EXPECT     (SCPE_BASE + 44)                /* expect matched */
#define SCPE_AMBREG     (SCPE_BASE + 45)                /* ambiguous register */
#define SCPE_REMOTE     (SCPE_BASE + 46)                /* remote console command */
#define SCPE_INVEXPR    (SCPE_BASE + 47)                /* invalid expression */
#define SCPE_SIGTERM    (SCPE_BASE + 48)                /* SIGTERM has been received */




#define SCPE_MAX_ERR    (SCPE_BASE + 48)                /* Maximum SCPE Error Value */
#define SCPE_KFLAG      0x10000000                      /* tti data flag */
#define SCPE_BREAK      0x20000000                      /* tti break flag */
#define SCPE_NOMESSAGE  0x40000000                      /* message display supression flag */
#define SCPE_BARE_STATUS(stat) ((stat) & ~(SCPE_NOMESSAGE|SCPE_KFLAG|SCPE_BREAK))

/* Print value format codes */








>
>
>

|







427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#define SCPE_AFAIL      (SCPE_BASE + 42)                /* assert failed */
#define SCPE_INVREM     (SCPE_BASE + 43)                /* invalid remote console command */
#define SCPE_EXPECT     (SCPE_BASE + 44)                /* expect matched */
#define SCPE_AMBREG     (SCPE_BASE + 45)                /* ambiguous register */
#define SCPE_REMOTE     (SCPE_BASE + 46)                /* remote console command */
#define SCPE_INVEXPR    (SCPE_BASE + 47)                /* invalid expression */
#define SCPE_SIGTERM    (SCPE_BASE + 48)                /* SIGTERM has been received */
#define SCPE_FSSIZE     (SCPE_BASE + 49)                /* File System size larger than disk size */
#define SCPE_RUNTIME    (SCPE_BASE + 50)                /* Run Time Limit Exhausted */
#define SCPE_INCOMPDSK  (SCPE_BASE + 51)                /* Incompatible Disk Container */

#define SCPE_MAX_ERR    (SCPE_BASE + 51)                /* Maximum SCPE Error Value */
#define SCPE_KFLAG      0x10000000                      /* tti data flag */
#define SCPE_BREAK      0x20000000                      /* tti break flag */
#define SCPE_NOMESSAGE  0x40000000                      /* message display supression flag */
#define SCPE_BARE_STATUS(stat) ((stat) & ~(SCPE_NOMESSAGE|SCPE_KFLAG|SCPE_BREAK))

/* Print value format codes */

644
645
646
647
648
649
650
651
652
653
654
655
656

657
658






659
660
661
662
663
664
665
#define UNIT_UFMASK     (((1u << UNIT_V_RSV) - 1) & ~((1u << UNIT_V_UF) - 1))
#define UNIT_RFLAGS     (UNIT_UFMASK|UNIT_DIS)          /* restored flags */

/* 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_TAPE_MRK   0000040         /* Tape Unit AWS Tapemark */

#define UNIT_V_DF_TAPE  7               /* 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 */







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







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
#define UNIT_UFMASK     (((1u << UNIT_V_RSV) - 1) & ~((1u << UNIT_V_UF) - 1))
#define UNIT_RFLAGS     (UNIT_UFMASK|UNIT_DIS)          /* restored flags */

/* 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       0000200         /* Unit registered as a calibrated timer */
#define UNIT_TAPE_MRK       0000400         /* Tape Unit Tapemark */
#define UNIT_TAPE_PNU       0001000         /* Tape Unit Position Not Updated */
#define UNIT_V_DF_TAPE      10              /* Bit offset for Tape Density reservation */
#define UNIT_S_DF_TAPE      3               /* Bits Reserved for Tape Density */
#define UNIT_V_TAPE_FMT     13              /* Bit offset for Tape Format */
#define UNIT_S_TAPE_FMT     4               /* Bits Reserved for Tape Format */
#define UNIT_M_TAPE_FMT     (((1 << UNIT_S_TAPE_FMT) - 1) << UNIT_V_TAPE_FMT)
#define UNIT_V_TAPE_ANSI    17              /* Bit offset for ANSI Tape Type */
#define UNIT_S_TAPE_ANSI    4               /* Bits Reserved for ANSI Tape Type */
#define UNIT_M_TAPE_ANSI    (((1 << UNIT_S_TAPE_ANSI) - 1) << UNIT_V_TAPE_ANSI)

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 */
674
675
676
677
678
679
680



681
682
683
684
685
686
687
    uint32              width;                          /* width */
    uint32              offset;                         /* starting bit */
    uint32              depth;                          /* save depth */
    const char          *desc;                          /* description */
    BITFIELD            *fields;                        /* bit fields */
    uint32              qptr;                           /* circ q ptr */
    size_t              str_size;                       /* structure size */



    /* NOTE: Flags MUST always be last since it is initialized outside of macro definitions */
    uint32              flags;                          /* flags */
    };

/* Register flags */

#define REG_FMT         00003                           /* see PV_x */







>
>
>







699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    uint32              width;                          /* width */
    uint32              offset;                         /* starting bit */
    uint32              depth;                          /* save depth */
    const char          *desc;                          /* description */
    BITFIELD            *fields;                        /* bit fields */
    uint32              qptr;                           /* circ q ptr */
    size_t              str_size;                       /* structure size */
    size_t              obj_size;                       /* sizeof(*loc) */
    size_t              ele_size;                       /* sizeof(**loc) or sizeof(*loc) if depth == 1 */
    const char          *macro;                         /* Initializer Macro Name */
    /* NOTE: Flags MUST always be last since it is initialized outside of macro definitions */
    uint32              flags;                          /* flags */
    };

/* Register flags */

#define REG_FMT         00003                           /* see PV_x */
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
    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 */
    };


/* mtab mask flag bits */
/* NOTE: MTAB_VALR and MTAB_VALO are only used to display help */
#define MTAB_XTD        (1u << UNIT_V_RSV)              /* ext entry flag */







|
|







765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
    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 */
                                                        /* pointer to something needed by */
                                                        /* the validation and/or display routines */
    const char          *help;                          /* help string */
    };


/* mtab mask flag bits */
/* NOTE: MTAB_VALR and MTAB_VALO are only used to display help */
#define MTAB_XTD        (1u << UNIT_V_RSV)              /* ext entry flag */
806
807
808
809
810
811
812
813

814
815
816
817
818
819
820
    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 {







|
>







834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
    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)
    pcre                *regex;                         /* compiled regular expression */
    int                 re_nsub;                        /* regular expression sub expression count */
#endif
    char                *act;                           /* action string */
    };

/* Expect Context */

struct EXPECT {
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
   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

/* Internal use ONLY (see below) Generic Register declaration for all fields */
#define _REGDATANF(nm,loc,rdx,wd,off,dep,desc,flds,qptr,siz) \
    nm, (loc), (rdx), (wd), (off), (dep), (desc), (flds), (qptr), (siz)

#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 internal macro will be provided that populates the new register structure */
#define REGDATA(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,qptr,siz),(fl)
#define REGDATAC(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,qptr,siz),(fl)
/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,NULL,NULL,0,0)
#define ORDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,desc,NULL,0,0)
#define ORDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,desc,flds,0,0)
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,NULL,NULL,0,0)
#define DRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,desc,NULL,0,0)
#define DRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,desc,flds,0,0)
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,NULL,NULL,0,0)
#define HRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,desc,NULL,0,0)
#define HRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,desc,flds,0,0)
/* Right Justified Binary Register Data */
#define BINRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,NULL,NULL,0,0)
#define BINRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,desc,NULL,0,0)
#define BINRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,desc,flds,0,0)
/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,NULL,NULL,0,0)
#define FLDATAD(nm,loc,pos,desc) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,desc,NULL,0,0)
#define FLDATADF(nm,loc,pos,desc,flds) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,desc,flds,0,0)
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,NULL,NULL,0,0)
#define GRDATAD(nm,loc,rdx,wd,pos,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,desc,NULL,0,0)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,desc,flds,0,0)
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF(#nm,loc,rdx,wd,0,dep,NULL,NULL,0,0)
#define BRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF(#nm,loc,rdx,wd,0,dep,desc,NULL,0,0)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) \







    _REGDATANF(#nm,loc,rdx,wd,0,dep,desc,flds,0,0)
/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,NULL,NULL,0,0),((fl) | REG_UNIT)
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,NULL,0,0),((fl) | REG_UNIT)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,0,0),((fl) | REG_UNIT)
/* Arrayed register whose data is part of an arbitrary structure */
#define STRDATA(nm,loc,rdx,wd,off,dep,siz,fl) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,NULL,NULL,0,siz),((fl) | REG_STRUCT)
#define STRDATAD(nm,loc,rdx,wd,off,dep,siz,fl,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,NULL,0,siz),((fl) | REG_STRUCT)
#define STRDATADF(nm,loc,rdx,wd,off,dep,siz,fl,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,0,siz),((fl) | REG_STRUCT)



#define BIT(nm)              {#nm, 0xffffffff, 1,  NULL, NULL}  /* Single Bit definition */
#define BITNC                {"",  0xffffffff, 1,  NULL, NULL}  /* Don't care Bit definition */
#define BITF(nm,sz)          {#nm, 0xffffffff, sz, NULL, NULL}  /* Bit Field definition */
#define BITNCF(sz)           {"",  0xffffffff, sz, NULL, NULL}  /* 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,NULL}  /* Bit Field definition with value->name map */
#else /* For non-STD-C compiler which can't stringify macro arguments with # */
/* 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) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,qptr,siz),(fl)
#define REGDATAC(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,qptr,siz),(fl)
/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),8,wd,0,1,NULL,NULL,0,0)
#define ORDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),8,wd,0,1,desc,NULL,0,0)
#define ORDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),8,wd,0,1,desc,flds,0,0)
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),10,wd,0,1,NULL,NULL,0,0)
#define DRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),10,wd,0,1,desc,NULL,0,0)
#define DRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),10,wd,0,1,desc,flds,0,0)
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),16,wd,0,1,NULL,NULL,0,0)
#define HRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),16,wd,0,1,desc,NULL,0,0)
#define HRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),16,wd,0,1,desc,flds,0,0)
/* Right Justified Binary Register Data */
#define BINRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),2,wd,0,1,NULL,NULL,0,0)
#define BINRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),2,wd,0,1,desc,NULL,0,0)
#define BINRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),2,wd,0,1,desc,flds,0,0)
/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) \
    _REGDATANF("nm",&(loc),2,1,pos,1,NULL,NULL,0,0)
#define FLDATAD(nm,loc,pos,desc) \
    _REGDATANF("nm",&(loc),2,1,pos,1,desc,NULL,0,0)
#define FLDATADF(nm,loc,pos,desc,flds) \
    _REGDATANF("nm",&(loc),2,1,pos,1,desc,flds,0,0)
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,NULL,NULL,0,0)
#define GRDATAD(nm,loc,rdx,wd,pos,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,desc,NULL,0,0)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,desc,flds,0,0)
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF("nm",loc,rdx,wd,0,dep,NULL,NULL,0,0)
#define BRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF("nm",loc,rdx,wd,0,dep,desc,NULL,0,0)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) \
    _REGDATANF("nm",loc,rdx,wd,0,dep,desc,flds,0,0)







/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,NULL,NULL,0,0),((fl) | REG_UNIT)
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,NULL,0,0),((fl) | REG_UNIT)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,0,0),((fl) | REG_UNIT)
/* Arrayed register whose data is part of an arbitrary structure */
#define STRDATA(nm,loc,rdx,wd,off,dep,siz,fl) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,NULL,NULL,0,siz),((fl) | REG_STRUCT)
#define STRDATAD(nm,loc,rdx,wd,off,dep,siz,fl,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,NULL,0,siz),((fl) | REG_STRUCT)
#define STRDATADF(nm,loc,rdx,wd,off,dep,siz,fl,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,0,siz),((fl) | REG_STRUCT)



#define BIT(nm)              {"nm", 0xffffffff, 1,  NULL, NULL} /* Single Bit definition */
#define BITNC                {"",   0xffffffff, 1,  NULL, NULL} /* Don't care Bit definition */
#define BITF(nm,sz)          {"nm", 0xffffffff, sz, NULL, NULL} /* Bit Field definition */
#define BITNCF(sz)           {"",   0xffffffff, sz, NULL, NULL} /* 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,NULL} /* Bit Field definition with value->name map */
#endif







|
|






|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

>
>
>
>
>
>
>
|


|

|

|


|

|

|
>
>
>











|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

|


|

|

|
>
>
>
>
>
>
>


|

|

|


|

|

|
>
>
>







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
   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

/* Internal use ONLY (see below) Generic Register declaration for all fields */
#define _REGDATANF(nm,loc,rdx,wd,off,dep,desc,flds,qptr,siz,elesiz,macro) \
    nm, (loc), (rdx), (wd), (off), (dep), (desc), (flds), (qptr), (siz), sizeof(*(loc)), (elesiz), #macro

#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 internal macro will be provided that populates the new register structure */
#define REGDATA(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,qptr,siz,sizeof((loc)),REGDATA),(fl)
#define REGDATAC(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,qptr,siz,sizeof((loc)),REGDATAC),(fl)
/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,NULL,NULL,0,0,sizeof((loc)),ORDATA)
#define ORDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,desc,NULL,0,0,sizeof((loc)),ORDATAD)
#define ORDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),8,wd,0,1,desc,flds,0,0,sizeof((loc)),ORDATADF)
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,NULL,NULL,0,0,sizeof((loc)),DRDATA)
#define DRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,desc,NULL,0,0,sizeof((loc)),DRDATAD)
#define DRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),10,wd,0,1,desc,flds,0,0,sizeof((loc)),DRDATADF)
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,NULL,NULL,0,0,sizeof((loc)),HRDATA)
#define HRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,desc,NULL,0,0,sizeof((loc)),HRDATAD)
#define HRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),16,wd,0,1,desc,flds,0,0,sizeof((loc)),HRDATADF)
/* Right Justified Binary Register Data */
#define BINRDATA(nm,loc,wd) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,NULL,NULL,0,0,sizeof((loc)),BINRDATA)
#define BINRDATAD(nm,loc,wd,desc) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,desc,NULL,0,0,sizeof((loc)),BINRDATAD)
#define BINRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF(#nm,&(loc),2,wd,0,1,desc,flds,0,0,sizeof((loc)),BINRDATADF)
/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,NULL,NULL,0,0,sizeof((loc)),FLDATA)
#define FLDATAD(nm,loc,pos,desc) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,desc,NULL,0,0,sizeof((loc)),FLDATAD)
#define FLDATADF(nm,loc,pos,desc,flds) \
    _REGDATANF(#nm,&(loc),2,1,pos,1,desc,flds,0,0,sizeof((loc)),FLDATADF)
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,NULL,NULL,0,0,sizeof((loc)),GRDATA)
#define GRDATAD(nm,loc,rdx,wd,pos,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,desc,NULL,0,0,sizeof((loc)),GRDATAD)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,pos,1,desc,flds,0,0,sizeof((loc)),GRDATADF)
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,NULL,NULL,0,0,sizeof(*(loc)),BRDATA)
#define BRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,desc,NULL,0,0,sizeof(*(loc)),BRDATAD)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,desc,flds,0,0,sizeof(*(loc)),BRDATADF)
/* Range of memory whose data is successive scalar values accessed like an array Register */
#define VBRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,NULL,NULL,0,0,sizeof(loc),VBRDATA)
#define VBRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,desc,NULL,0,0,sizeof(loc),VBRDATAD)
#define VBRDATADF(nm,loc,rdx,wd,dep,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,0,dep,desc,flds,0,0,sizeof(loc),VBRDATADF)
/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,NULL,NULL,0,0,sizeof((loc)),URDATA),((fl) | REG_UNIT)
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,NULL,0,0,sizeof((loc)),URDATAD),((fl) | REG_UNIT)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,0,0,sizeof((loc)),URDATADF),((fl) | REG_UNIT)
/* Arrayed register whose data is part of an arbitrary structure */
#define STRDATA(nm,loc,rdx,wd,off,dep,siz,fl) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,NULL,NULL,0,siz,sizeof((loc)),STRDATA),((fl) | REG_STRUCT)
#define STRDATAD(nm,loc,rdx,wd,off,dep,siz,fl,desc) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,NULL,0,siz,sizeof((loc)),STRDATAD),((fl) | REG_STRUCT)
#define STRDATADF(nm,loc,rdx,wd,off,dep,siz,fl,desc,flds) \
    _REGDATANF(#nm,&(loc),rdx,wd,off,dep,desc,flds,0,siz,sizeof((loc)),STRDATADF),((fl) | REG_STRUCT)
/* Hidden Blob of Data - Only used for SAVE/RESTORE */
#define SAVEDATA(nm,loc) \
    _REGDATANF(#nm,&(loc),0,8,0,1,NULL,NULL,0,sizeof(loc),sizeof(loc),SAVEDATA),(REG_HRO)
#define BIT(nm)              {#nm, 0xffffffff, 1,  NULL, NULL}  /* Single Bit definition */
#define BITNC                {"",  0xffffffff, 1,  NULL, NULL}  /* Don't care Bit definition */
#define BITF(nm,sz)          {#nm, 0xffffffff, sz, NULL, NULL}  /* Bit Field definition */
#define BITNCF(sz)           {"",  0xffffffff, sz, NULL, NULL}  /* 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,NULL}  /* Bit Field definition with value->name map */
#else /* For non-STD-C compiler which can't stringify macro arguments with # */
/* 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) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,qptr,siz,sizeof((loc)),REGDATA),(fl)
#define REGDATAC(nm,loc,rdx,wd,off,dep,desc,flds,fl,qptr,siz) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,qptr,siz,sizeof((loc)),REGDATAC),(fl)
/* Right Justified Octal Register Data */
#define ORDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),8,wd,0,1,NULL,NULL,0,0,sizeof((loc)),ORDATA)
#define ORDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),8,wd,0,1,desc,NULL,0,0,sizeof((loc)),ORDATAD)
#define ORDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),8,wd,0,1,desc,flds,0,0,sizeof((loc)),ORDATADF)
/* Right Justified Decimal Register Data */
#define DRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),10,wd,0,1,NULL,NULL,0,0,sizeof((loc)),DRDATA)
#define DRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),10,wd,0,1,desc,NULL,0,0,sizeof((loc)),DRDATAD)
#define DRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),10,wd,0,1,desc,flds,0,0,sizeof((loc)),DRDATADF)
/* Right Justified Hexadecimal Register Data */
#define HRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),16,wd,0,1,NULL,NULL,0,0,sizeof((loc)),HRDATA)
#define HRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),16,wd,0,1,desc,NULL,0,0,sizeof((loc)),HRDATAD)
#define HRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),16,wd,0,1,desc,flds,0,0,sizeof((loc)),HRDATADF)
/* Right Justified Binary Register Data */
#define BINRDATA(nm,loc,wd) \
    _REGDATANF("nm",&(loc),2,wd,0,1,NULL,NULL,0,0,sizeof((loc)),BINRDATA)
#define BINRDATAD(nm,loc,wd,desc) \
    _REGDATANF("nm",&(loc),2,wd,0,1,desc,NULL,0,0,sizeof((loc)),BINRDATAD)
#define BINRDATADF(nm,loc,wd,desc,flds) \
    _REGDATANF("nm",&(loc),2,wd,0,1,desc,flds,0,0,sizeof((loc)),BINRDATADF)
/* One-bit binary flag at an arbitrary offset in a 32-bit word Register */
#define FLDATA(nm,loc,pos) \
    _REGDATANF("nm",&(loc),2,1,pos,1,NULL,NULL,0,0,sizeof((loc)),FLDATA)
#define FLDATAD(nm,loc,pos,desc) \
    _REGDATANF("nm",&(loc),2,1,pos,1,desc,NULL,0,0,sizeof((loc)),FLDATAD)
#define FLDATADF(nm,loc,pos,desc,flds) \
    _REGDATANF("nm",&(loc),2,1,pos,1,desc,flds,0,0,sizeof((loc)),FLDATADF)
/* Arbitrary location and Radix Register */
#define GRDATA(nm,loc,rdx,wd,pos) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,NULL,NULL,0,0,sizeof((loc)),GRDATA)
#define GRDATAD(nm,loc,rdx,wd,pos,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,desc,NULL,0,0,sizeof((loc)),GRDATAD)
#define GRDATADF(nm,loc,rdx,wd,pos,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,pos,1,desc,flds,0,0,sizeof((loc)),GRDATADF)
/* Arrayed register whose data is kept in a standard C array Register */
#define BRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,NULL,NULL,0,0,sizeof(*(loc)),BRDATA)
#define BRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,desc,NULL,0,0,sizeof(*(loc)),BRDATAD)
#define BRDATADF(nm,loc,rdx,wd,dep,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,desc,flds,0,0,sizeof(*(loc)),BRDATADF)
/* Range of memory whose data is successive scalar values accessed like an array Register */
#define VBRDATA(nm,loc,rdx,wd,dep) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,NULL,NULL,0,0,sizeof(loc),VBRDATA)
#define VBRDATAD(nm,loc,rdx,wd,dep,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,desc,NULL,0,0,sizeof(loc),VBRDATAD)
#define VBRDATADF(nm,loc,rdx,wd,dep,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,0,dep,desc,flds,0,0,sizeof(loc),VBRDATADF)
/* Arrayed register whose data is part of the UNIT structure */
#define URDATA(nm,loc,rdx,wd,off,dep,fl) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,NULL,NULL,0,0,sizeof((loc)),URDATA),((fl) | REG_UNIT)
#define URDATAD(nm,loc,rdx,wd,off,dep,fl,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,NULL,0,0,sizeof((loc)),URDATAD),((fl) | REG_UNIT)
#define URDATADF(nm,loc,rdx,wd,off,dep,fl,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,0,0,sizeof((loc)),URDATADF),((fl) | REG_UNIT)
/* Arrayed register whose data is part of an arbitrary structure */
#define STRDATA(nm,loc,rdx,wd,off,dep,siz,fl) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,NULL,NULL,0,siz,sizeof((loc)),STRDATA),((fl) | REG_STRUCT)
#define STRDATAD(nm,loc,rdx,wd,off,dep,siz,fl,desc) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,NULL,0,siz,sizeof((loc)),STRDATAD),((fl) | REG_STRUCT)
#define STRDATADF(nm,loc,rdx,wd,off,dep,siz,fl,desc,flds) \
    _REGDATANF("nm",&(loc),rdx,wd,off,dep,desc,flds,0,siz,sizeof((loc)),STRDATADF),((fl) | REG_STRUCT)
/* Hidden Blob of Data - Only used for SAVE/RESTORE */
#define SAVEDATA(nm,loc) \
    _REGDATANF("nm",&(loc),0,8,0,1,NULL,NULL,0,sizeof(loc),sizeof(loc)),SAVEDATA),(REG_HRO)
#define BIT(nm)              {"nm", 0xffffffff, 1,  NULL, NULL} /* Single Bit definition */
#define BITNC                {"",   0xffffffff, 1,  NULL, NULL} /* Don't care Bit definition */
#define BITF(nm,sz)          {"nm", 0xffffffff, sz, NULL, NULL} /* Bit Field definition */
#define BITNCF(sz)           {"",   0xffffffff, sz, NULL, NULL} /* 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,NULL} /* Bit Field definition with value->name map */
#endif
1076
1077
1078
1079
1080
1081
1082




1083
1084
1085
1086
1087
1088
1089
1090
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







>
>
>
>
|







1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
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(thread_local)
#define AIO_TLS thread_local
#elif (__STDC_VERSION__ >= 201112) && !(defined(__STDC_NO_THREADS__))
#define AIO_TLS _Thread_local
#elif 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
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
#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"
#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);                      \







<





<
<







1215
1216
1217
1218
1219
1220
1221

1222
1223
1224
1225
1226


1227
1228
1229
1230
1231
1232
1233
#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"
#define AIO_INIT                                                  \
    do {                                                          \

      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;                          \


      } 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);                      \
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
#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"
#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);                      \







<











<
<







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
#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"
#define AIO_INIT                                                  \
    do {                                                          \

      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;                          \


      } 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);                      \
1247
1248
1249
1250
1251
1252
1253


1254


1255
1256
1257
1258
1259
1260
1261
      } 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 */







>
>
|
>
>







1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
      } 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) {                                             \
        if (sim_deb) {  /* only while debug do lock/unlock overhead */ \
          AIO_UNLOCK;                                                  \
          sim_debug (TIMER_DBG_IDLE, &sim_timer_dev, "waking due to event on %s after %d instructions\n", sim_uname(uptr), event_time);\
          AIO_LOCK;                                                    \
          }                                                            \
        pthread_cond_signal (&sim_asynch_wake);                        \
        }                                                              \
      AIO_UNLOCK;                                                      \
      sim_asynch_check = 0;                                            \
      return SCPE_OK;                                                  \
    } else (void)0
#endif /* USE_AIO_INTRINSICS */

Changes to src/SIMH/sim_disk.c.

29
30
31
32
33
34
35

36
37
38
39
40
41
42
   as well as OS-specific direct hardware access.

   25-Jan-11    MP      Initial Implemementation

Public routines:

   sim_disk_attach           attach disk unit

   sim_disk_detach           detach disk unit
   sim_disk_attach_help      help routine for attaching disks
   sim_disk_rdsect           read disk sectors
   sim_disk_rdsect_a         read disk sectors asynchronously
   sim_disk_wrsect           write disk sectors
   sim_disk_wrsect_a         write disk sectors asynchronously
   sim_disk_unload           unload or detach a disk as needed







>







29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
   as well as OS-specific direct hardware access.

   25-Jan-11    MP      Initial Implemementation

Public routines:

   sim_disk_attach           attach disk unit
   sim_disk_attach_ex        attach disk unit extended parameters
   sim_disk_detach           detach disk unit
   sim_disk_attach_help      help routine for attaching disks
   sim_disk_rdsect           read disk sectors
   sim_disk_rdsect_a         read disk sectors asynchronously
   sim_disk_wrsect           write disk sectors
   sim_disk_wrsect_a         write disk sectors asynchronously
   sim_disk_unload           unload or detach a disk as needed
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
#include "sim_ether.h"
#include <ctype.h>
#include <sys/stat.h>

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif



























































struct disk_context {

    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit */
    uint32              sector_size;        /* Disk Sector Size (of the pseudo disk) */
    uint32              capac_factor;       /* Units of Capacity (2 = word, 1 = byte) */
    uint32              xfer_element_size;  /* Disk Bus Transfer size (1 - byte, 2 - word, 4 - longword) */
    uint32              storage_sector_size;/* Sector size of the containing storage */

    uint32              removable;          /* Removable device flag */
    uint32              is_cdrom;           /* Host system CDROM Device */
    uint32              media_removed;      /* Media not available flag */
    uint32              auto_format;        /* Format determined dynamically */


#if defined _WIN32
    HANDLE              disk_handle;        /* OS specific Raw device handle */
#endif
#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;








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

>



|


>




>
>







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
#include "sim_ether.h"
#include <ctype.h>
#include <sys/stat.h>

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif

/* Newly created SIMH (and possibly RAW) disk containers       */
/* will have this data as the last 512 bytes of the container  */
/* It will not be considered part of the data in the container */
/* Previously existing containers will have this appended to   */
/* the end of the container if they are opened for write       */
struct simh_disk_footer {
    uint8       Signature[4];           /* must be 'simh' */
    uint8       CreatingSimulator[64];  /* name of simulator */
    uint8       DriveType[16];
    uint32      SectorSize;
    uint32      SectorCount;
    uint32      TransferElementSize;
    uint8       CreationTime[28];       /* Result of ctime() */
    uint8       FooterVersion;          /* Initially 0 */
    uint8       AccessFormat;           /* 1 - SIMH, 2 - RAW */
    uint8       Reserved[382];          /* Currently unused */
    uint32      Checksum;               /* CRC32 of the prior 508 bytes */
    };

/* OS Independent Disk Virtual Disk (VHD) I/O support */

#if (defined (VMS) && !(defined (__ALPHA) || defined (__ia64)))
#define DONT_DO_VHD_SUPPORT  /* VAX/VMS compilers don't have 64 bit integers */
#endif

#if defined(_WIN32) || defined (__ALPHA) || defined (__ia64) || defined (VMS)
#ifndef __BYTE_ORDER__
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#endif
#endif
#ifndef __BYTE_ORDER__
#define __BYTE_ORDER__ UNKNOWN
#endif
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static uint32
NtoHl(uint32 value)
{
uint8 *l = (uint8 *)&value;
return (uint32)l[3] | ((uint32)l[2]<<8) | ((uint32)l[1]<<16) | ((uint32)l[0]<<24);
}
#elif  __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
static uint32
NtoHl(uint32 value)
{
return value;
}
#else
static uint32
NtoHl(uint32 value)
{
uint8 *l = (uint8 *)&value;

if (sim_end)
    return l[3] | (l[2]<<8) | (l[1]<<16) | (l[0]<<24);
return value;
}
#endif

struct disk_context {
    t_offset            container_size;     /* Size of the data portion (of the pseudo disk) */
    DEVICE              *dptr;              /* Device for unit (access to debug flags) */
    uint32              dbit;               /* debugging bit */
    uint32              sector_size;        /* Disk Sector Size (of the pseudo disk) */
    uint32              capac_factor;       /* Units of Capacity (8 = quadword, 2 = word, 1 = byte) */
    uint32              xfer_element_size;  /* Disk Bus Transfer size (1 - byte, 2 - word, 4 - longword) */
    uint32              storage_sector_size;/* Sector size of the containing storage */

    uint32              removable;          /* Removable device flag */
    uint32              is_cdrom;           /* Host system CDROM Device */
    uint32              media_removed;      /* Media not available flag */
    uint32              auto_format;        /* Format determined dynamically */
    struct simh_disk_footer
                        *footer;
#if defined _WIN32
    HANDLE              disk_handle;        /* OS specific Raw device handle */
#endif
#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;
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
        struct disk_context *ctx =                              \
                      (struct disk_context *)uptr->disk_ctx;    \
                                                                \
        pthread_mutex_lock (&ctx->io_lock);                     \
                                                                \
        sim_debug_unit (ctx->dbit, uptr,                        \
      "sim_disk AIO_CALL(op=%d, unit=%d, lba=0x%X, sects=%d)\n",\
                op, (int)(uptr-ctx->dptr->units), _lba, _sects);\
                                                                \
        if (ctx->callback)                                      \
            abort(); /* horrible mistake, stop */               \
        ctx->io_dop = op;                                       \
        ctx->lba = _lba;                                        \
        ctx->buf = _buf;                                        \
        ctx->sects = _sects;                                    \







|







194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        struct disk_context *ctx =                              \
                      (struct disk_context *)uptr->disk_ctx;    \
                                                                \
        pthread_mutex_lock (&ctx->io_lock);                     \
                                                                \
        sim_debug_unit (ctx->dbit, uptr,                        \
      "sim_disk AIO_CALL(op=%d, unit=%d, lba=0x%X, sects=%d)\n",\
                op, (int)(uptr - ctx->dptr->units), _lba, _sects);\
                                                                \
        if (ctx->callback)                                      \
            abort(); /* horrible mistake, stop */               \
        ctx->io_dop = op;                                       \
        ctx->lba = _lba;                                        \
        ctx->buf = _buf;                                        \
        ctx->sects = _sects;                                    \
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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_unit (ctx->dbit, uptr, "_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);
    if (ctx->io_dop == DOP_DONE)
        break;







|







228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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_unit (ctx->dbit, uptr, "_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);
    if (ctx->io_dop == DOP_DONE)
        break;
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
    pthread_mutex_lock (&ctx->io_lock);
    ctx->io_dop = DOP_DONE;
    pthread_cond_signal (&ctx->io_done);
    sim_activate (uptr, ctx->asynch_io_latency);
    }
pthread_mutex_unlock (&ctx->io_lock);

sim_debug_unit (ctx->dbit, uptr, "_disk_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 asynchrconous thread.
  
   Since disk processing only handles a single I/O at a time to a
   particular disk device (due to using stdio for the SimH Disk format
   and stdio doesn't have an atomic seek+(read|write) operation),
   we have the opportunity to possibly detect improper attempts to
   issue multiple concurrent I/O requests. */
static void _disk_completion_dispatch (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
DISK_PCALLBACK callback = ctx->callback;

sim_debug_unit (ctx->dbit, uptr, "_disk_completion_dispatch(unit=%d, dop=%d, callback=%p)\n", (int)(uptr-ctx->dptr->units), ctx->io_dop, (void *)(ctx->callback));

if (ctx->io_dop != DOP_DONE)
    abort();                                            /* horribly wrong, stop */

if (ctx->callback && ctx->io_dop == DOP_DONE) {
    ctx->callback = NULL;
    callback (uptr, ctx->io_status);
    }
}

static t_bool _disk_is_active (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug_unit (ctx->dbit, uptr, "_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 t_bool _disk_cancel (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug_unit (ctx->dbit, uptr, "_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);
        }
    }







|




















|















|










|







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
    pthread_mutex_lock (&ctx->io_lock);
    ctx->io_dop = DOP_DONE;
    pthread_cond_signal (&ctx->io_done);
    sim_activate (uptr, ctx->asynch_io_latency);
    }
pthread_mutex_unlock (&ctx->io_lock);

sim_debug_unit (ctx->dbit, uptr, "_disk_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 asynchrconous thread.
  
   Since disk processing only handles a single I/O at a time to a
   particular disk device (due to using stdio for the SimH Disk format
   and stdio doesn't have an atomic seek+(read|write) operation),
   we have the opportunity to possibly detect improper attempts to
   issue multiple concurrent I/O requests. */
static void _disk_completion_dispatch (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
DISK_PCALLBACK callback = ctx->callback;

sim_debug_unit (ctx->dbit, uptr, "_disk_completion_dispatch(unit=%d, dop=%d, callback=%p)\n", (int)(uptr - ctx->dptr->units), ctx->io_dop, (void *)(ctx->callback));

if (ctx->io_dop != DOP_DONE)
    abort();                                            /* horribly wrong, stop */

if (ctx->callback && ctx->io_dop == DOP_DONE) {
    ctx->callback = NULL;
    callback (uptr, ctx->io_status);
    }
}

static t_bool _disk_is_active (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug_unit (ctx->dbit, uptr, "_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 t_bool _disk_cancel (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (ctx) {
    sim_debug_unit (ctx->dbit, uptr, "_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);
        }
    }
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
static FILE *sim_vhd_disk_open (const char *rawdevicename, const char *openmode);
static FILE *sim_vhd_disk_create (const char *szVHDPath, t_offset desiredsize);
static FILE *sim_vhd_disk_create_diff (const char *szVHDPath, const char *szParentVHDPath);
static FILE *sim_vhd_disk_merge (const char *szVHDPath, char **ParentVHD);
static int sim_vhd_disk_close (FILE *f);
static void sim_vhd_disk_flush (FILE *f);
static t_offset sim_vhd_disk_size (FILE *f);

static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);
static t_stat sim_vhd_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);
static t_stat sim_vhd_disk_clearerr (UNIT *uptr);
static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype);
static const char *sim_vhd_disk_get_dtype (FILE *f);
static t_stat sim_os_disk_implemented_raw (void);
static FILE *sim_os_disk_open_raw (const char *rawdevicename, const char *openmode);
static int sim_os_disk_close_raw (FILE *f);
static void sim_os_disk_flush_raw (FILE *f);
static t_offset sim_os_disk_size_raw (FILE *f);
static t_stat sim_os_disk_unload_raw (FILE *f);
static t_bool sim_os_disk_isavailable_raw (FILE *f);
static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);

static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom);
static char *HostPathToVhdPath (const char *szHostPath, char *szVhdPath, size_t VhdPathSize);
static char *VhdPathToHostPath (const char *szVhdPath, char *szHostPath, size_t HostPathSize);
static t_offset get_filesystem_size (UNIT *uptr);

struct sim_disk_fmt {
    const char          *name;                          /* name */
    int32               uflags;                         /* unit flags */
    int32               fmtval;                         /* Format type value */
    t_stat              (*impl_fnc)(void);              /* Implemented Test Function */
    };

static struct sim_disk_fmt fmts[] = {
    { "AUTO", 0, DKUF_F_AUTO, NULL},
    { "SIMH", 0, DKUF_F_STD,  NULL},
    { "RAW",  0, DKUF_F_RAW,  sim_os_disk_implemented_raw},
    { "VHD",  0, DKUF_F_VHD,  sim_vhd_disk_implemented},
    { NULL,   0, 0,           NULL}
    };

/* 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;
for (f = 0; fmts[f].name; f++) {
    if (fmts[f].name && (strcmp (cptr, fmts[f].name) == 0)) {
        if ((fmts[f].impl_fnc) && (fmts[f].impl_fnc() != SCPE_OK))
            return SCPE_NOFNC;
        uptr->flags = (uptr->flags & ~DKUF_FMT) |
            (fmts[f].fmtval << DKUF_V_FMT) | fmts[f].uflags;
        return SCPE_OK;
        }
    }
return sim_messagef (SCPE_ARG, "Unknown disk format: %s\n", cptr);
}

/* 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; fmts[i].name; 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)
{







>



|
|








>

>













|
|
|
|
|










|


|












|






|
>
|
|
>
>
>
|







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
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
static FILE *sim_vhd_disk_open (const char *rawdevicename, const char *openmode);
static FILE *sim_vhd_disk_create (const char *szVHDPath, t_offset desiredsize);
static FILE *sim_vhd_disk_create_diff (const char *szVHDPath, const char *szParentVHDPath);
static FILE *sim_vhd_disk_merge (const char *szVHDPath, char **ParentVHD);
static int sim_vhd_disk_close (FILE *f);
static void sim_vhd_disk_flush (FILE *f);
static t_offset sim_vhd_disk_size (FILE *f);
static t_stat sim_vhd_disk_info (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom);
static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);
static t_stat sim_vhd_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);
static t_stat sim_vhd_disk_clearerr (UNIT *uptr);
static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype, uint32 SectorSize, uint32 xfer_element_size);
static const char *sim_vhd_disk_get_dtype (FILE *f, uint32 *SectorSize, uint32 *xfer_element_size, char sim_name[64]);
static t_stat sim_os_disk_implemented_raw (void);
static FILE *sim_os_disk_open_raw (const char *rawdevicename, const char *openmode);
static int sim_os_disk_close_raw (FILE *f);
static void sim_os_disk_flush_raw (FILE *f);
static t_offset sim_os_disk_size_raw (FILE *f);
static t_stat sim_os_disk_unload_raw (FILE *f);
static t_bool sim_os_disk_isavailable_raw (FILE *f);
static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects);
static t_stat sim_os_disk_read (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *bytesread, uint32 bytes);
static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects);
static t_stat sim_os_disk_write (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *byteswritten, uint32 bytes);
static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom);
static char *HostPathToVhdPath (const char *szHostPath, char *szVhdPath, size_t VhdPathSize);
static char *VhdPathToHostPath (const char *szVhdPath, char *szHostPath, size_t HostPathSize);
static t_offset get_filesystem_size (UNIT *uptr);

struct sim_disk_fmt {
    const char          *name;                          /* name */
    int32               uflags;                         /* unit flags */
    int32               fmtval;                         /* Format type value */
    t_stat              (*impl_fnc)(void);              /* Implemented Test Function */
    };

static struct sim_disk_fmt fmts[] = {
    { "AUTO detect", 0, DKUF_F_AUTO, NULL},
    { "SIMH",        0, DKUF_F_STD,  NULL},
    { "RAW",         0, DKUF_F_RAW,  sim_os_disk_implemented_raw},
    { "VHD",         0, DKUF_F_VHD,  sim_vhd_disk_implemented},
    { NULL,          0, 0,           NULL}
    };

/* 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) || (*cptr == '\0'))
    return SCPE_ARG;
for (f = 0; fmts[f].name; f++) {
    if (fmts[f].name && (MATCH_CMD (cptr, fmts[f].name) == 0)) {
        if ((fmts[f].impl_fnc) && (fmts[f].impl_fnc() != SCPE_OK))
            return SCPE_NOFNC;
        uptr->flags = (uptr->flags & ~DKUF_FMT) |
            (fmts[f].fmtval << DKUF_V_FMT) | fmts[f].uflags;
        return SCPE_OK;
        }
    }
return sim_messagef (SCPE_ARG, "Unknown disk format: %s\n", cptr);
}

/* Show disk format */

static const char *sim_disk_fmt (UNIT *uptr)
{
int32 f = DK_GET_FMT (uptr);
size_t i;

for (i = 0; fmts[i].name; i++)
    if (fmts[i].fmtval == f) {
        return fmts[i].name;
        }
return "invalid";
}

t_stat sim_disk_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{
fprintf (st, "%s format", sim_disk_fmt (uptr));
return SCPE_OK;
}

/* Set disk capacity */

t_stat sim_disk_set_capac (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
            ctx->media_removed = 1;
        is_available = !ctx->media_removed;
        break;
    default:
        is_available = FALSE;
        break;
    }
sim_debug_unit (ctx->dbit, uptr, "sim_disk_isavailable(unit=%d)=%s\n", (int)(uptr-ctx->dptr->units), is_available ? "true" : "false");
return is_available;
}

t_bool sim_disk_isavailable_a (UNIT *uptr, DISK_PCALLBACK callback)
{
t_bool r = FALSE;
AIO_CALLSETUP







|







492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
            ctx->media_removed = 1;
        is_available = !ctx->media_removed;
        break;
    default:
        is_available = FALSE;
        break;
    }
sim_debug_unit (ctx->dbit, uptr, "sim_disk_isavailable(unit=%d)=%s\n", (int)(uptr - ctx->dptr->units), is_available ? "true" : "false");
return is_available;
}

t_bool sim_disk_isavailable_a (UNIT *uptr, DISK_PCALLBACK callback)
{
t_bool r = FALSE;
AIO_CALLSETUP
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
return (uptr->flags & DKUF_WRP)? TRUE: FALSE;
}

/* Get Disk size */

t_offset sim_disk_size (UNIT *uptr)
{

t_offset physical_size, filesystem_size;
t_bool saved_quiet = sim_quiet;

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* SIMH format */
        physical_size = sim_fsize_ex (uptr->fileref);
        break;
    case DKUF_F_VHD:                                    /* VHD format */
        physical_size = sim_vhd_disk_size (uptr->fileref);
        break;
    case DKUF_F_RAW:                                    /* Raw Physical Disk Access */
        physical_size = sim_os_disk_size_raw (uptr->fileref);
        break;
    default:
        return (t_offset)-1;
    }

sim_quiet = TRUE;
filesystem_size = get_filesystem_size (uptr);
sim_quiet = saved_quiet;
if ((filesystem_size == (t_offset)-1) ||
    (filesystem_size < physical_size))
    return physical_size;
return filesystem_size;







>



<
<
|
<
<
<
<
<
<
<
<
|
<
>







516
517
518
519
520
521
522
523
524
525
526


527








528

529
530
531
532
533
534
535
536
return (uptr->flags & DKUF_WRP)? TRUE: FALSE;
}

/* Get Disk size */

t_offset sim_disk_size (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_offset physical_size, filesystem_size;
t_bool saved_quiet = sim_quiet;



if ((uptr->flags & UNIT_ATT) == 0)








    return (t_offset)-1;

physical_size = ctx->container_size;
sim_quiet = TRUE;
filesystem_size = get_filesystem_size (uptr);
sim_quiet = saved_quiet;
if ((filesystem_size == (t_offset)-1) ||
    (filesystem_size < physical_size))
    return physical_size;
return filesystem_size;
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
char *msg = "Disk: can't operate asynchronously\r\n";
sim_printf ("%s", msg);
return SCPE_NOFNC;
#else
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
pthread_attr_t attr;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_set_async(unit=%d)\n", (int)(uptr-ctx->dptr->units));

ctx->asynch_io = sim_asynch_enabled;
ctx->asynch_io_latency = latency;
if (ctx->asynch_io) {
    pthread_mutex_init (&ctx->io_lock, NULL);
    pthread_cond_init (&ctx->io_cond, NULL);
    pthread_cond_init (&ctx->io_done, NULL);







|







544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
char *msg = "Disk: can't operate asynchronously\r\n";
sim_printf ("%s", msg);
return SCPE_NOFNC;
#else
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
pthread_attr_t attr;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_set_async(unit=%d)\n", (int)(uptr - ctx->dptr->units));

ctx->asynch_io = sim_asynch_enabled;
ctx->asynch_io_latency = latency;
if (ctx->asynch_io) {
    pthread_mutex_init (&ctx->io_lock, NULL);
    pthread_cond_init (&ctx->io_cond, NULL);
    pthread_cond_init (&ctx->io_done, NULL);
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
return SCPE_NOFNC;
#else
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

/* make sure device exists */
if (!ctx) return SCPE_UNATT;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_clr_async(unit=%d)\n", (int)(uptr-ctx->dptr->units));

if (ctx->asynch_io) {
    pthread_mutex_lock (&ctx->io_lock);
    ctx->asynch_io = 0;
    pthread_cond_signal (&ctx->io_cond);
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_join (ctx->io_thread, NULL);







|







581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
return SCPE_NOFNC;
#else
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

/* make sure device exists */
if (!ctx) return SCPE_UNATT;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_clr_async(unit=%d)\n", (int)(uptr - ctx->dptr->units));

if (ctx->asynch_io) {
    pthread_mutex_lock (&ctx->io_lock);
    ctx->asynch_io = 0;
    pthread_cond_signal (&ctx->io_cond);
    pthread_mutex_unlock (&ctx->io_lock);
    pthread_join (ctx->io_thread, NULL);
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
static t_stat _sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
t_offset da;
uint32 err, tbc;
size_t i;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "_sim_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);

da = ((t_offset)lba) * ctx->sector_size;
tbc = sects * ctx->sector_size;
if (sectsread)
    *sectsread = 0;



err = sim_fseeko (uptr->fileref, da, SEEK_SET);          /* set pos */
if (!err) {

    i = sim_fread (buf, ctx->xfer_element_size, tbc/ctx->xfer_element_size, uptr->fileref);
    if (i < tbc/ctx->xfer_element_size)                 /* fill */
        memset (&buf[i*ctx->xfer_element_size], 0, tbc-(i*ctx->xfer_element_size));



    err = ferror (uptr->fileref);
    if ((!err) && (sectsread))
        *sectsread = (t_seccnt)((i*ctx->xfer_element_size+ctx->sector_size-1)/ctx->sector_size);






    }
return err;
}

t_stat sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
t_stat r;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_seccnt sread = 0;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);

if ((sects == 1) &&                                     /* Single sector reads */
    (lba >= (uptr->capac*ctx->capac_factor)/(ctx->sector_size/((ctx->dptr->flags & DEV_SECTORS) ? 512 : 1)))) {/* beyond the end of the disk */
    memset (buf, '\0', ctx->sector_size);               /* are bad block management efforts - zero buffer */
    if (sectsread)
        *sectsread = 1;
    return SCPE_OK;                                     /* return success */
    }

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))))) {
    switch (DK_GET_FMT (uptr)) {                        /* case on format */
        case DKUF_F_STD:                                /* SIMH format */
            return _sim_disk_rdsect (uptr, lba, buf, sectsread, sects);

        case DKUF_F_VHD:                                /* VHD format */
            r = sim_vhd_disk_rdsect (uptr, lba, buf, &sread, sects);
            break;
        case DKUF_F_RAW:                                /* Raw Physical Disk Access */
            r = sim_os_disk_rdsect (uptr, lba, buf, &sread, sects);
            break;
        default:
            return SCPE_NOFNC;
        }
    if (sectsread)
        *sectsread = sread;

    if (r != SCPE_OK)
        return r;
    sim_buf_swap_data (buf, ctx->xfer_element_size, (sread * ctx->sector_size) / ctx->xfer_element_size);
    return r;
    }
else { /* Unaligned and/or partial sector transfers */
    uint8 *tbuf = (uint8*) malloc (sects*ctx->sector_size + 2*ctx->storage_sector_size);
    t_lba sspsts = ctx->storage_sector_size/ctx->sector_size; /* sim sectors in a storage sector */
    t_lba tlba = lba & ~(sspsts - 1);
    t_seccnt tsects = sects + (lba - tlba);

    tsects = (tsects + (sspsts - 1)) & ~(sspsts - 1);
    if (sectsread)
        *sectsread = 0;
    if (tbuf == NULL)
        return SCPE_MEM;
    switch (DK_GET_FMT (uptr)) {                        /* case on format */
        case DKUF_F_STD:                                /* SIMH format */
            r = _sim_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);
            break;
        case DKUF_F_VHD:                                /* VHD format */
            r = sim_vhd_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);
            if (r == SCPE_OK)
                sim_buf_swap_data (tbuf, ctx->xfer_element_size, (sread * ctx->sector_size) / ctx->xfer_element_size);
            break;
        case DKUF_F_RAW:                                /* Raw Physical Disk Access */
            r = sim_os_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);
            if (r == SCPE_OK)
                sim_buf_swap_data (tbuf, ctx->xfer_element_size, (sread * ctx->sector_size) / ctx->xfer_element_size);
            break;
        default:
            free (tbuf);
            return SCPE_NOFNC;
        }
    if (r == SCPE_OK) {
        memcpy (buf, tbuf + ((lba - tlba) * ctx->sector_size), sects * ctx->sector_size);
        if (sectsread) {
            *sectsread = sread - (lba - tlba);
            if (*sectsread > sects)
                *sectsread = sects;
            }
        }
    free (tbuf);
    return r;
    }
}

t_stat sim_disk_rdsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects, DISK_PCALLBACK callback)







|





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

|
<
>
>
>
>
>
>

|








|














|
>











>


<



|
|














<
<



<
<





|
|
|
|
|
|
<







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
700
701


702
703
704
705
706
707
708
709
710
711
712

713
714
715
716
717
718
719
static t_stat _sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
t_offset da;
uint32 err, tbc;
size_t i;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "_sim_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

da = ((t_offset)lba) * ctx->sector_size;
tbc = sects * ctx->sector_size;
if (sectsread)
    *sectsread = 0;
while (tbc) {
    size_t sectbytes;

    err = sim_fseeko (uptr->fileref, da, SEEK_SET);          /* set pos */
    if (err)
        return SCPE_IOERR;
    i = sim_fread (buf, 1, tbc, uptr->fileref);
    if (i < tbc)                 /* fill */
        memset (&buf[i], 0, tbc-i);
    if (sectsread)
        *sectsread += i / ctx->sector_size;
    sectbytes = (i / ctx->sector_size) * ctx->sector_size;
    err = ferror (uptr->fileref);
    if (err)

        return SCPE_IOERR;
    tbc -= sectbytes;
    if ((tbc == 0) || (i == 0))
        return SCPE_OK;
    da += sectbytes;
    buf += sectbytes;
    }
return SCPE_OK;
}

t_stat sim_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
t_stat r;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_seccnt sread = 0;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

if ((sects == 1) &&                                     /* Single sector reads */
    (lba >= (uptr->capac*ctx->capac_factor)/(ctx->sector_size/((ctx->dptr->flags & DEV_SECTORS) ? 512 : 1)))) {/* beyond the end of the disk */
    memset (buf, '\0', ctx->sector_size);               /* are bad block management efforts - zero buffer */
    if (sectsread)
        *sectsread = 1;
    return SCPE_OK;                                     /* return success */
    }

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))))) {
    switch (DK_GET_FMT (uptr)) {                        /* case on format */
        case DKUF_F_STD:                                /* SIMH format */
            r = _sim_disk_rdsect (uptr, lba, buf, &sread, sects);
            break;
        case DKUF_F_VHD:                                /* VHD format */
            r = sim_vhd_disk_rdsect (uptr, lba, buf, &sread, sects);
            break;
        case DKUF_F_RAW:                                /* Raw Physical Disk Access */
            r = sim_os_disk_rdsect (uptr, lba, buf, &sread, sects);
            break;
        default:
            return SCPE_NOFNC;
        }
    if (sectsread)
        *sectsread = sread;
    sim_buf_swap_data (buf, ctx->xfer_element_size, (sread * ctx->sector_size) / ctx->xfer_element_size);
    if (r != SCPE_OK)
        return r;

    return r;
    }
else { /* Unaligned and/or partial sector transfers */
    uint8 *tbuf = (uint8*) malloc (sects * ctx->sector_size + 2 * ctx->storage_sector_size);
    t_lba sspsts = ctx->storage_sector_size / ctx->sector_size; /* sim sectors in a storage sector */
    t_lba tlba = lba & ~(sspsts - 1);
    t_seccnt tsects = sects + (lba - tlba);

    tsects = (tsects + (sspsts - 1)) & ~(sspsts - 1);
    if (sectsread)
        *sectsread = 0;
    if (tbuf == NULL)
        return SCPE_MEM;
    switch (DK_GET_FMT (uptr)) {                        /* case on format */
        case DKUF_F_STD:                                /* SIMH format */
            r = _sim_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);
            break;
        case DKUF_F_VHD:                                /* VHD format */
            r = sim_vhd_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);


            break;
        case DKUF_F_RAW:                                /* Raw Physical Disk Access */
            r = sim_os_disk_rdsect (uptr, tlba, tbuf, &sread, tsects);


            break;
        default:
            free (tbuf);
            return SCPE_NOFNC;
        }
    sim_buf_swap_data (tbuf, ctx->xfer_element_size, (sread * ctx->sector_size) / ctx->xfer_element_size);
    memcpy (buf, tbuf + ((lba - tlba) * ctx->sector_size), sects * ctx->sector_size);
    if (sectsread) {
        *sectsread = sread - (lba - tlba);
        if (*sectsread > sects)
            *sectsread = sects;

        }
    free (tbuf);
    return r;
    }
}

t_stat sim_disk_rdsect_a (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects, DISK_PCALLBACK callback)
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
static t_stat _sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
t_offset da;
uint32 err, tbc;
size_t i;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "_sim_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);

da = ((t_offset)lba) * ctx->sector_size;
tbc = sects * ctx->sector_size;
if (sectswritten)
    *sectswritten = 0;
err = sim_fseeko (uptr->fileref, da, SEEK_SET);          /* set pos */
if (!err) {

    i = sim_fwrite (buf, ctx->xfer_element_size, tbc/ctx->xfer_element_size, uptr->fileref);


    err = ferror (uptr->fileref);
    if ((!err) && (sectswritten))
        *sectswritten = (t_seccnt)((i*ctx->xfer_element_size+ctx->sector_size-1)/ctx->sector_size);
    }

return err;
}

t_stat sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
uint32 f = DK_GET_FMT (uptr);
t_stat r;
uint8 *tbuf = NULL;

sim_debug_unit (ctx->dbit, uptr, "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;








|






|
>
|
>
>
|
|
<
<
>
|









|



|







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
static t_stat _sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
t_offset da;
uint32 err, tbc;
size_t i;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "_sim_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

da = ((t_offset)lba) * ctx->sector_size;
tbc = sects * ctx->sector_size;
if (sectswritten)
    *sectswritten = 0;
err = sim_fseeko (uptr->fileref, da, SEEK_SET);          /* set pos */
if (err)
    return SCPE_IOERR;
i = sim_fwrite (buf, ctx->xfer_element_size, tbc/ctx->xfer_element_size, uptr->fileref);
if (sectswritten)
    *sectswritten += (t_seccnt)((i * ctx->xfer_element_size + ctx->sector_size - 1)/ctx->sector_size);
err = ferror (uptr->fileref);
if (err)


    return SCPE_IOERR;
return SCPE_OK;
}

t_stat sim_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
uint32 f = DK_GET_FMT (uptr);
t_stat r;
uint8 *tbuf = NULL;

sim_debug_unit (ctx->dbit, uptr, "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) >= 32) ? 8 : ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (quadword: 8, 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;

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


static t_offset get_ods2_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
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 = 0;
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, 512 / ctx->sector_size, (uint8 *)&Home, NULL, sizeof (Home) / ctx->sector_size))

    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm2_w_checksum1)-((char *)&Home.hm2_l_homelbn))/2));
CheckSum2 = ODSChecksum (&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) * (512 / ctx->sector_size), 

                           (uint8 *)&Header, NULL, sizeof (Header) / ctx->sector_size))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&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)







|
<







>



<

|
|
>



















|
>
|







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


static t_offset get_ods2_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_offset temp_capac = (sim_toffset_64 ? (t_addr)0xFFFFFFFFu : (t_addr)0x7FFFFFFFu);  /* Make sure we can access the largest sector */

ODS2_HomeBlock Home;
ODS2_FileHeader Header;
ODS2_Retreval *Retr;
ODS2_SCB Scb;
uint16 CheckSum1, CheckSum2;
uint32 ScbLbn = 0;
t_offset ret_val = (t_offset)-1;
t_seccnt sects_read;

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

saved_capac = uptr->capac;
uptr->capac = (t_addr)temp_capac;
if ((sim_disk_rdsect (uptr, 512 / ctx->sector_size, (uint8 *)&Home, &sects_read, sizeof (Home) / ctx->sector_size)) ||
    (sects_read != (sizeof (Home) / ctx->sector_size)))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm2_w_checksum1)-((char *)&Home.hm2_l_homelbn))/2));
CheckSum2 = ODSChecksum (&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) * (512 / ctx->sector_size), 
                            (uint8 *)&Header, &sects_read, sizeof (Header) / ctx->sector_size)) || 
    (sects_read != (sizeof (Header) / ctx->sector_size)))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&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)
1164
1165
1166
1167
1168
1169
1170
1171

1172
1173
1174
1175
1176
1177
1178
        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 * (512 / ctx->sector_size), (uint8 *)&Scb, NULL, sizeof (Scb) / ctx->sector_size))

    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&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))







|
>







1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
        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 * (512 / ctx->sector_size), (uint8 *)&Scb, &sects_read, sizeof (Scb) / ctx->sector_size)) ||
    (sects_read != (sizeof (Scb) / ctx->sector_size)))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&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))
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
}

static t_offset get_ods1_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_offset temp_capac = 512 * (t_offset)0xFFFFFFFFu;  /* Make sure we can access the largest sector */
uint32 capac_factor;
ODS1_HomeBlock Home;
ODS1_FileHeader Header;
ODS1_Retreval *Retr;
uint8 scb_buf[512];
ODS1_SCB *Scb = (ODS1_SCB *)scb_buf;
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, 512 / ctx->sector_size, (uint8 *)&Home, NULL, sizeof (Home) / ctx->sector_size))

    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm1_w_checksum1)-((char *)&Home.hm1_w_ibmapsize))/2));
CheckSum2 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm1_w_checksum2)-((char *)&Home.hm1_w_ibmapsize))/2));
if ((Home.hm1_w_ibmapsize == 0) || 
    (Home.hm1_l_ibmaplbn == 0) || 
    (Home.hm1_w_maxfiles == 0) || 
    (Home.hm1_w_cluster != 1) || 
    ((Home.hm1_w_structlev != HM1_C_LEVEL1) && (Home.hm1_w_structlev != HM1_C_LEVEL2)) || 
    (Home.hm1_l_ibmaplbn == 0) || 
    (Home.hm1_w_checksum1 != CheckSum1) ||
    (Home.hm1_w_checksum2 != CheckSum2))
    goto Return_Cleanup;
if (sim_disk_rdsect (uptr, (((Home.hm1_l_ibmaplbn << 16) + ((Home.hm1_l_ibmaplbn >> 16) & 0xFFFF)) + Home.hm1_w_ibmapsize + 1) * (512 / ctx->sector_size),

                           (uint8 *)&Header, NULL, sizeof (Header) / ctx->sector_size))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Header, 255);
if (CheckSum1 != *(((uint16 *)&Header)+255)) /* Verify Checksum on BITMAP.SYS file header */
    goto Return_Cleanup;

Retr = (ODS1_Retreval *)(((uint16*)(&Header))+Header.fh1_b_mpoffset);
ScbLbn = (Retr->fm1_pointers[0].fm1_s_fm1def1.fm1_b_highlbn<<16)+Retr->fm1_pointers[0].fm1_s_fm1def1.fm1_w_lowlbn;
if (sim_disk_rdsect (uptr, ScbLbn * (512 / ctx->sector_size), (uint8 *)Scb, NULL, 512 / ctx->sector_size))

    goto Return_Cleanup;
if (Scb->scb_b_bitmapblks < 127)
    ret_val = (((t_offset)Scb->scb_r_blocks[Scb->scb_b_bitmapblks].scb_w_freeblks << 16) + Scb->scb_r_blocks[Scb->scb_b_bitmapblks].scb_w_freeptr) * 512;
else
    ret_val = (((t_offset)Scb->scb_r_blocks[0].scb_w_freeblks << 16) + Scb->scb_r_blocks[0].scb_w_freeptr) * 512;
if (!sim_quiet) {
    sim_printf ("%s%d: '%s' Contains an ODS1 File system\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
    sim_printf ("%s%d: Volume Name: %12.12s ", sim_dname (dptr), (int)(uptr-dptr->units), Home.hm1_t_volname);
    sim_printf ("Format: %12.12s ", Home.hm1_t_format);
    sim_printf ("Sectors In Volume: %u\n", (uint32)(ret_val / 512));
    }

Return_Cleanup:
uptr->capac = saved_capac;
return ret_val;
}

typedef struct ultrix_disklabel {







|
<








>



<

|
|
>












|
>
|







|
>





<
|
|
|
|
<







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
}

static t_offset get_ods1_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_addr temp_capac = (sim_toffset_64 ? (t_addr)0xFFFFFFFFu : (t_addr)0x7FFFFFFFu);  /* Make sure we can access the largest sector */

ODS1_HomeBlock Home;
ODS1_FileHeader Header;
ODS1_Retreval *Retr;
uint8 scb_buf[512];
ODS1_SCB *Scb = (ODS1_SCB *)scb_buf;
uint16 CheckSum1, CheckSum2;
uint32 ScbLbn;
t_offset ret_val = (t_offset)-1;
t_seccnt sects_read;

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

saved_capac = uptr->capac;
uptr->capac = temp_capac;
if ((sim_disk_rdsect (uptr, 512 / ctx->sector_size, (uint8 *)&Home, &sects_read, sizeof (Home) / ctx->sector_size)) ||
    (sects_read != (sizeof (Home) / ctx->sector_size)))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm1_w_checksum1)-((char *)&Home.hm1_w_ibmapsize))/2));
CheckSum2 = ODSChecksum (&Home, (uint16)((((char *)&Home.hm1_w_checksum2)-((char *)&Home.hm1_w_ibmapsize))/2));
if ((Home.hm1_w_ibmapsize == 0) || 
    (Home.hm1_l_ibmaplbn == 0) || 
    (Home.hm1_w_maxfiles == 0) || 
    (Home.hm1_w_cluster != 1) || 
    ((Home.hm1_w_structlev != HM1_C_LEVEL1) && (Home.hm1_w_structlev != HM1_C_LEVEL2)) || 
    (Home.hm1_l_ibmaplbn == 0) || 
    (Home.hm1_w_checksum1 != CheckSum1) ||
    (Home.hm1_w_checksum2 != CheckSum2))
    goto Return_Cleanup;
if ((sim_disk_rdsect (uptr, (((Home.hm1_l_ibmaplbn << 16) + ((Home.hm1_l_ibmaplbn >> 16) & 0xFFFF)) + Home.hm1_w_ibmapsize + 1) * (512 / ctx->sector_size),
                            (uint8 *)&Header, &sects_read, sizeof (Header) / ctx->sector_size)) ||
    (sects_read != (sizeof (Header) / ctx->sector_size)))
    goto Return_Cleanup;
CheckSum1 = ODSChecksum (&Header, 255);
if (CheckSum1 != *(((uint16 *)&Header)+255)) /* Verify Checksum on BITMAP.SYS file header */
    goto Return_Cleanup;

Retr = (ODS1_Retreval *)(((uint16*)(&Header))+Header.fh1_b_mpoffset);
ScbLbn = (Retr->fm1_pointers[0].fm1_s_fm1def1.fm1_b_highlbn<<16)+Retr->fm1_pointers[0].fm1_s_fm1def1.fm1_w_lowlbn;
if ((sim_disk_rdsect (uptr, ScbLbn * (512 / ctx->sector_size), (uint8 *)Scb, &sects_read, 512 / ctx->sector_size)) ||
    (sects_read != (512 / ctx->sector_size)))
    goto Return_Cleanup;
if (Scb->scb_b_bitmapblks < 127)
    ret_val = (((t_offset)Scb->scb_r_blocks[Scb->scb_b_bitmapblks].scb_w_freeblks << 16) + Scb->scb_r_blocks[Scb->scb_b_bitmapblks].scb_w_freeptr) * 512;
else
    ret_val = (((t_offset)Scb->scb_r_blocks[0].scb_w_freeblks << 16) + Scb->scb_r_blocks[0].scb_w_freeptr) * 512;

sim_messagef (SCPE_OK, "%s%d: '%s' Contains an ODS1 File system\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
sim_messagef (SCPE_OK, "%s%d: Volume Name: %12.12s ", sim_dname (dptr), (int)(uptr-dptr->units), Home.hm1_t_volname);
sim_messagef (SCPE_OK, "Format: %12.12s ", Home.hm1_t_format);
sim_messagef (SCPE_OK, "Sectors In Volume: %u\n", (uint32)(ret_val / 512));


Return_Cleanup:
uptr->capac = saved_capac;
return ret_val;
}

typedef struct ultrix_disklabel {
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
#define PT_VALID        1               /* Indicates if struct is valid */

static t_offset get_ultrix_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_offset temp_capac = 512 * (t_offset)0xFFFFFFFFu;  /* Make sure we can access the largest sector */
uint32 capac_factor;
uint8 sector_buf[512];
ultrix_disklabel *Label = (ultrix_disklabel *)(sector_buf + sizeof (sector_buf) - sizeof (ultrix_disklabel));
t_offset ret_val = (t_offset)-1;
int i;
uint32 max_lbn = 0, max_lbn_partnum = 0;


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, 31 * (512 / ctx->sector_size), sector_buf, NULL, 512 / ctx->sector_size))

    goto Return_Cleanup;

if ((Label->pt_magic != PT_MAGIC) || 
    (Label->pt_valid != PT_VALID))
    goto Return_Cleanup;

for (i = 0; i < 8; i++) {
    uint32 end_lbn = Label->pt_part[i].pi_blkoff + Label->pt_part[i].pi_nblocks;
    if (end_lbn > max_lbn) {
        max_lbn = end_lbn;
        max_lbn_partnum = i;
        }
    }
if (!sim_quiet) {
    sim_printf ("%s%d: '%s' Contains Ultrix partitions\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
    sim_printf ("Partition with highest sector: %c, Sectors On Disk: %u\n", 'a' + max_lbn_partnum, max_lbn);
    }
ret_val = ((t_offset)max_lbn) * 512;

Return_Cleanup:




















































































































































































































































































































































































































































































































































































































































































































uptr->capac = saved_capac;
return ret_val;
}

typedef t_offset (*FILESYSTEM_CHECK)(UNIT *uptr);

static t_offset get_filesystem_size (UNIT *uptr)
{
static FILESYSTEM_CHECK checks[] = {
    &get_ods2_filesystem_size,
    &get_ods1_filesystem_size,
    &get_ultrix_filesystem_size,






    NULL
    };
t_offset ret_val;
int i;

for (i = 0; checks[i] != NULL; i++) {
    ret_val = checks[i] (uptr);
    if (ret_val != (t_offset)-1)
        break;
    }
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, uint32 *is_cdrom) = NULL;
t_bool created = FALSE, copied = FALSE;
t_bool auto_format = FALSE;
t_offset container_size, filesystem_size, current_unit_size;


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;











if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    char gbuf[CBUFSIZE];
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    if ((sim_disk_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK) ||
        (DK_GET_FMT (uptr) == DKUF_F_AUTO))







|
<





>



<

|
|
>













<
|
|
<



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












>
>
>
>
>
>


|










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

>
>
>
>
>
>











>







>
>
>
>
>
>
>
>
>
>
>







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
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
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
#define PT_VALID        1               /* Indicates if struct is valid */

static t_offset get_ultrix_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_addr temp_capac = (sim_toffset_64 ? (t_addr)0xFFFFFFFFu : (t_addr)0x7FFFFFFFu);  /* Make sure we can access the largest sector */

uint8 sector_buf[512];
ultrix_disklabel *Label = (ultrix_disklabel *)(sector_buf + sizeof (sector_buf) - sizeof (ultrix_disklabel));
t_offset ret_val = (t_offset)-1;
int i;
uint32 max_lbn = 0, max_lbn_partnum = 0;
t_seccnt sects_read;

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

saved_capac = uptr->capac;
uptr->capac = temp_capac;
if ((sim_disk_rdsect (uptr, 31 * (512 / ctx->sector_size), sector_buf, &sects_read, 512 / ctx->sector_size)) ||
    (sects_read != (512 / ctx->sector_size)))
    goto Return_Cleanup;

if ((Label->pt_magic != PT_MAGIC) || 
    (Label->pt_valid != PT_VALID))
    goto Return_Cleanup;

for (i = 0; i < 8; i++) {
    uint32 end_lbn = Label->pt_part[i].pi_blkoff + Label->pt_part[i].pi_nblocks;
    if (end_lbn > max_lbn) {
        max_lbn = end_lbn;
        max_lbn_partnum = i;
        }
    }

sim_messagef (SCPE_OK, "%s%d: '%s' Contains Ultrix partitions\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
sim_messagef (SCPE_OK, "Partition with highest sector: %c, Sectors On Disk: %u\n", 'a' + max_lbn_partnum, max_lbn);

ret_val = ((t_offset)max_lbn) * 512;

Return_Cleanup:
uptr->capac = saved_capac;
return ret_val;
}

#pragma pack(push,1)
/*
 * The first logical block of device cluster 1 is either:
 *      1. MFD label entry (RSTS versions through 7.x)
 *      2. Disk Pack label (RSTS version 8.0 and later)
 */
typedef struct _RSTS_MFDLABEL {
    uint16  ml_ulnk;
    uint16  ml_mbm1;
    uint16  ml_reserved1;
    uint16  ml_reserved2;
    uint16  ml_pcs;
    uint16  ml_pstat;
    uint16  ml_packid[2];
    } RSTS_MFDLABEL;

typedef struct _RSTS_PACKLABEL {
    uint16  pk_mb01;
    uint16  pk_mbm1;
    uint16  pk_mdcn;
    uint16  pk_plvl;
#define PK_LVL0         0000
#define PK_LVL11        0401
#define PK_LVL12        0402
    uint16  pk_ppcs;
    uint16  pk_pstat;
#define PK_UC_NEW       0020000
    uint16  pk_packid[2];
    uint16  pk_tapgvn[2];
    uint16  pk_bckdat;
    uint16  pk_bcktim;
    } RSTS_PACKLABEL;

typedef union _RSTS_ROOT {
    RSTS_MFDLABEL  rt_mfd;
    RSTS_PACKLABEL rt_pack;
    uint8          rt_block[512];
    } RSTS_ROOT;

typedef struct _RSTS_MFDBLOCKETTE {
    uint16  mb_ulnk;
    uint16  mb_mbm1;
    uint16  mb_reserved1;
    uint16  mb_reserved2;
    uint16  mb_reserved3;
    uint16  mb_malnk;
    uint16  mb_lppn;
    uint16  mb_lid;
#define MB_ID           0051064
    } RSTS_MFDBLOCKETTE;
#define IS_VALID_RSTS_MFD(b) \
     ((((b)->mb_ulnk == 0) || ((b)->mb_ulnk == 1)) &&                         \
      ((b)->mb_mbm1 == 0177777) &&                                            \
      ((b)->mb_reserved1 == 0) &&                                             \
      ((b)->mb_reserved2 == 0) &&                                             \
      ((b)->mb_reserved3 == 0) &&                                             \
      ((b)->mb_lppn == 0177777) &&                                            \
      ((b)->mb_lid == MB_ID))

typedef struct _RSTS_GFDBLOCKETTE {
    uint16  gb_ulnk;
    uint16  gb_mbm1;
    uint16  gb_reserved1;
    uint16  gb_reserved2;
    uint16  gb_reserved3;
    uint16  gb_reserved4;
    uint16  gb_lppn;
    uint16  gb_lid;
#define GB_ID           0026264
    } RSTS_GFDBLOCKETTE;
#define IS_VALID_RSTS_GFD(b, g) \
     ((((b)->gb_ulnk == 0) || ((b)->gb_ulnk == 1)) &&                         \
      ((b)->gb_mbm1 == 0177777) &&                                            \
      ((b)->gb_reserved1 == 0) &&                                             \
      ((b)->gb_reserved2 == 0) &&                                             \
      ((b)->gb_reserved3 == 0) &&                                             \
      ((b)->gb_reserved4 == 0) &&                                             \
      ((b)->gb_lppn == (((g) << 8) | 0377)) &&                                \
      ((b)->gb_lid == GB_ID))

typedef struct _RSTS_UFDBLOCKETTE {
    uint16  ub_ulnk;
    uint16  ub_mbm1;
    uint16  ub_reserved1;
    uint16  ub_reserved2;
    uint16  ub_reserved3;
    uint16  ub_reserved4;
    uint16  ub_lppn;
    uint16  ub_lid;
#define UB_ID           0102064
    } RSTS_UFDBLOCKETTE;
#define IS_VALID_RSTS_UFD(b, g, u) \
     (((b)->ub_mbm1 == 0177777) &&                                            \
      ((b)->ub_reserved1 == 0) &&                                             \
      ((b)->ub_reserved2 == 0) &&                                             \
      ((b)->ub_reserved3 == 0) &&                                             \
      ((b)->ub_reserved4 == 0) &&                                             \
      ((b)->ub_lppn == (((g) << 8) | (u))) &&                                 \
      ((b)->ub_lid == UB_ID))

typedef struct _RSTS_UNAME {
    uint16  un_ulnk;
    uint16  un_unam;
    uint16  un_reserved1;
    uint16  un_reserved2;
    uint16  un_ustat;
    uint16  un_uacnt;
    uint16  un_uaa;
    uint16  un_uar;
    } RSTS_UNAME;

typedef struct _RSTS_FNAME {
    uint16  fn_ulnk;
    uint16  fn_unam[3];
    uint16  fn_ustat;
    uint16  fn_uacnt;
    uint16  fn_uaa;
    uint16  fn_uar;
    } RSTS_FNAME;

typedef struct _RSTS_ACNT {
    uint16  ac_ulnk;
    uint16  ac_udla;
    uint16  ac_usiz;
    uint16  ac_udc;
    uint16  ac_utc;
    uint16  ac_urts[2];
    uint16  ac_uclus;
    } RSTS_ACNT;

typedef struct _RSTS_RETR {
    uint16  rt_ulnk;
    uint16  rt_uent[7];
#define RT_ENTRIES      7
    } RSTS_RETR;

typedef struct _RSTS_DCMAP {
    uint16  dc_clus;
#define DC_MASK         0077777
    uint16  dc_map[7];
    }  RSTS_DCMAP;

/*
 * Directory link definitions
 */
#define DL_USE          0000001
#define DL_BAD          0000002
#define DL_CHE          0000004
#define DL_CLN          0000010
#define DL_ENO          0000760
#define DL_CLO          0007000
#define DL_BLO          0170000

#define DLSH_ENO         4
#define DLSH_CLO         9
#define DLSH_BLO        12

#define BLOCKETTE_SZ    (8 * sizeof(uint16))
#define MAP_OFFSET      (31 * BLOCKETTE_SZ)

#define SATT0           0073374
#define SATT1           0076400
#define SATT2           0075273

#pragma pack(pop)

typedef struct _rstsContext {
    UNIT        *uptr;
    int         dcshift;
    int         pcs;
    char        packid[8];
    t_seccnt    sects;
    RSTS_DCMAP  map;
} rstsContext;

static char rad50[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ$.%0123456789";

static void r50Asc(uint16 val, char *buf)
{
buf[2] = rad50[val % 050];
val /= 050;
buf[1] = rad50[val % 050];
buf[0] = rad50[val / 050];
}

static t_stat rstsValidateClusterSize(uint16 size, uint16 minSize)
{
int i;

/*
 * Check that the cluster size is a power of 2 and greater than or equal
 * to some location dependent value.
 */
if (size >= minSize)
    for (i = 0; i < 16; i++)
        if (size == (1 << i))
            return SCPE_OK;

return SCPE_IOERR;
}

static t_stat rstsReadBlock(rstsContext *context, uint16 cluster, uint16 block, void *buf)
{
t_lba blk = (cluster << context->dcshift) + block;
t_seccnt sects_read;

if ((sim_disk_rdsect(context->uptr, blk * context->sects, (uint8 *)buf, &sects_read, context->sects) == SCPE_OK) &&
    (sects_read == context->sects))
    return SCPE_OK;

return SCPE_IOERR;
}

static t_stat rstsReadBlockette(rstsContext *context, uint16 link, void *buf)
{
uint16 block = (link & DL_BLO) >> DLSH_BLO;
uint16 dcn = (link & DL_CLO) >> DLSH_CLO;
uint16 blockette = (link & DL_ENO) >> DLSH_ENO;
uint8 temp[512];

if ((dcn != 7) && (blockette != 31) &&
    (block <= (context->map.dc_clus & DC_MASK))) {
    if (rstsReadBlock(context, context->map.dc_map[dcn], block, temp) == SCPE_OK) {
        memcpy(buf, &temp[blockette * BLOCKETTE_SZ], BLOCKETTE_SZ);
        return SCPE_OK;
        }
    }
return SCPE_IOERR;
}

static t_stat rstsFind01UFD(rstsContext *context, uint16 *ufd, uint16 *level)
{
uint16 dcs = 1 << context->dcshift;
RSTS_ROOT root;
uint16 buf[256];

if (rstsReadBlock(context, 1, 0, &root) == SCPE_OK) {
    /*
     * First validate fields which are common to both the MFD label and
     * Pack label - we'll use Pack label offsets here.
     */
    if ((root.rt_pack.pk_mbm1 == 0177777) &&
        (rstsValidateClusterSize(root.rt_pack.pk_ppcs, dcs) == SCPE_OK)) {
        char ch, *tmp = &context->packid[1];
        uint16 mfd, gfd;

        context->pcs = root.rt_pack.pk_ppcs;

        r50Asc(root.rt_pack.pk_packid[0], &context->packid[0]);
        r50Asc(root.rt_pack.pk_packid[1], &context->packid[3]);
        context->packid[6] = '\0';

        /*
         * The Pack ID must consist of 1 - 6 alphanumeric characters
         * padded at the end with spaces.
         */
        if (!isalnum(context->packid[0]))
            return SCPE_IOERR;

        while ((ch = *tmp++) != 0) {
            if (!isalnum(ch)) {
                if (ch != ' ')
                    return SCPE_IOERR;

                while (*tmp)
                    if (*tmp++ != ' ')
                        return SCPE_IOERR;
                break;
                }
            }

        /*
         * Determine the pack revision level and, therefore, the path to
         * [0,1]satt.sys which will allow us to determine the size of the
         * pack used by RSTS.
         */
        if ((root.rt_pack.pk_pstat & PK_UC_NEW) == 0) {
            uint16 link = root.rt_mfd.ml_ulnk;
            RSTS_UNAME uname;

            /*
             * Old format used by RSTS up through V07.x
             */
            if (dcs > 16)
                return SCPE_IOERR;

            *level = PK_LVL0;

            memcpy(&context->map, &root.rt_block[MAP_OFFSET], BLOCKETTE_SZ);

            /*
             * Scan the MFD name entries looking for [0,1]. Note there will
             * always be at least 1 entry.
             */
            do {
                if (rstsReadBlockette(context, link, &uname) != SCPE_OK)
                    break;

                if (uname.un_unam == ((0 << 8) | 1)) {
                    *ufd = uname.un_uar;
                    return SCPE_OK;
                    }
                } while ((link = uname.un_ulnk) != 0);
            }
        else {
            /*
             * New format used by RSTS V08 and later
             */
            switch (root.rt_pack.pk_plvl) {
                case PK_LVL11:
                    if (dcs > 16)
                        return SCPE_IOERR;
                    break;

                case PK_LVL12:
                    if (dcs > 64)
                        return SCPE_IOERR;
                    break;

                default:
                    return SCPE_IOERR;
                }
            *level = root.rt_pack.pk_plvl;

            mfd = root.rt_pack.pk_mdcn;

            if (rstsReadBlock(context, mfd, 0, buf) == SCPE_OK) {
                if (IS_VALID_RSTS_MFD((RSTS_MFDBLOCKETTE *)buf)) {
                    if (rstsReadBlock(context, mfd, 1, buf) == SCPE_OK)
                        if ((gfd = buf[0]) != 0)
                            if (rstsReadBlock(context, gfd, 0, buf) == SCPE_OK)
                                if (IS_VALID_RSTS_GFD((RSTS_GFDBLOCKETTE *)buf, 0)) {
                                    if (rstsReadBlock(context, gfd, 1, buf) == SCPE_OK)
                                        if ((*ufd = buf[1]) != 0)
                                            return SCPE_OK;
                                    }
                    }
                }
            }
        }
    }
return SCPE_IOERR;
}

static t_stat rstsLoadAndScanSATT(rstsContext *context, uint16 uaa, uint16 uar, t_offset *result)
{
t_offset blocks = 0;
uint8 bitmap[8192];
int i, j;
RSTS_ACNT acnt;
RSTS_RETR retr;

if (uar != 0) {
    if (rstsReadBlockette(context, uaa, &acnt) == SCPE_OK) {
        uint16 blocks = acnt.ac_usiz;
        uint16 offset = 0;

        if ((rstsValidateClusterSize(acnt.ac_uclus, context->pcs) != SCPE_OK) ||
            (blocks > 16))
            return SCPE_IOERR;

        memset(bitmap, 0xFF, sizeof(bitmap));

        if (blocks != 0) {
            do {
                int i, j;
                uint16 fcl;

                if (rstsReadBlockette(context, uar, &retr) != SCPE_OK)
                    return SCPE_IOERR;

                for (i = 0; i < RT_ENTRIES; i++) {
                    if ((fcl = retr.rt_uent[i]) == 0)
                        goto scanBitmap;

                    for (j = 0; j < acnt.ac_uclus; j++) {
                        if ((blocks == 0) || (offset >= sizeof(bitmap)))
                            goto scanBitmap;

                        if (rstsReadBlock(context, fcl, j, &bitmap[offset]) != SCPE_OK)
                            return SCPE_IOERR;

                        offset += 512;
                        blocks--;
                        }
                    }
                } while ((uar = retr.rt_ulnk) != 0);

        scanBitmap:
            for (i = sizeof(bitmap) - 1; i != 0; i--)
                if (bitmap[i] != 0xFF) {
                    blocks = i * 8;
                    for (j = 7; j >= 0; j--)
                        if ((bitmap[i] & (1 << j)) == 0) {
                            blocks += j + 1;
                            goto scanDone;
                            }
                    }
        scanDone:
            *result = (t_offset)(blocks + 1) * context->pcs;
            return SCPE_OK;
            }
        }
    }
return SCPE_IOERR;
}

static t_offset get_rsts_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_addr temp_capac = (sim_toffset_64 ? (t_addr)0xFFFFFFFFu : (t_addr)0x7FFFFFFFu);  /* Make sure we can access the largest sector */
uint8 buf[512];
t_offset ret_val = (t_offset)-1;
rstsContext context;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return ret_val;
saved_capac = uptr->capac;
uptr->capac = temp_capac;

context.uptr = uptr;
context.sects = 512 / ctx->sector_size;

/*
 * Check all possible device cluster sizes
 */
for (context.dcshift = 0; context.dcshift < 8; context.dcshift++) {
    uint16 ufd, level;

    /*
     * We need to find [0,1]SATT.SYS to compute the actual size of the disk.
     * First find the DCN of the [0,1] UFD.
     */
    if (rstsFind01UFD(&context, &ufd, &level) == SCPE_OK) {
        if (rstsReadBlock(&context, ufd, 0, buf) == SCPE_OK) {
            if (IS_VALID_RSTS_UFD((RSTS_UFDBLOCKETTE *)buf, 0, 1)) {
                uint16 link = ((RSTS_UFDBLOCKETTE *)buf)->ub_ulnk;
                RSTS_FNAME fname;

                memcpy(&context.map, &buf[MAP_OFFSET], BLOCKETTE_SZ);

                /*
                 * Scan the UFD looking for SATT.SYS - the allocation bitmap
                 */
                do {
                    if (rstsReadBlockette(&context, link, &fname) != SCPE_OK)
                        break;

                    if ((fname.fn_unam[0] == SATT0) &&
                        (fname.fn_unam[1] == SATT1) &&
                        (fname.fn_unam[2] == SATT2)) {
                        if (rstsLoadAndScanSATT(&context, fname.fn_uaa, fname.fn_uar, &ret_val) == SCPE_OK) {
                            const char *fmt = "???";

                            ret_val *= 512;

                            switch (level) {
                                case PK_LVL0:
                                    fmt = "0.0";
                                    break;

                                case PK_LVL11:
                                    fmt = "1.1";
                                    break;

                                case PK_LVL12:
                                    fmt = "1.2";
                                    break;
                                }

                            sim_messagef(SCPE_OK, "%s%d: '%s' Contains a RSTS File system\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
                            sim_messagef(SCPE_OK, "%s%d: Pack ID: %6.6s ", sim_dname (dptr), (int)(uptr-dptr->units), context.packid);
                            sim_messagef(SCPE_OK, "Revision Level: %3s ", fmt);
                            sim_messagef(SCPE_OK, "Pack Clustersize: %d\n", context.pcs);
                            sim_messagef(SCPE_OK, "%s%d: Last Unallocated Sector In File System: %u\n", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)(ret_val / 512));
                            goto cleanup_done;
                            }
                        }
                    } while ((link = fname.fn_ulnk) != 0);
                }
            }
        }
    }
cleanup_done:
uptr->capac = saved_capac;
return ret_val;
}

#pragma pack(push,1)
typedef struct _RT11_HomeBlock {
    uint8   hb_b_bbtable[130];
    uint8   hb_b_unused1[2];
    uint8   hb_b_initrestore[38];
    uint8   hb_b_bup[18];
    uint8   hb_b_unused2[260];
    uint16  hb_w_reserved1;
    uint16  hb_w_reserved2;
    uint8   hb_b_unused3[14];
    uint16  hb_w_clustersize;
    uint16  hb_w_firstdir;
    uint16  hb_w_sysver;
#define HB_C_SYSVER_V3A 36521
#define HB_C_SYSVER_V04 36434
#define HB_C_SYSVER_V05 36435
    uint8   hb_b_volid[12];
    uint8   hb_b_owner[12];
    uint8   hb_b_sysid[12];
#define HB_C_SYSID      "DECRT11A    "
    uint8   hb_b_unused4[2];
    uint16  hb_w_checksum;
    } RT11_HomeBlock;

typedef struct _RT11_DirHeader {
    uint16  dh_w_count;
    uint16  dh_w_next;
    uint16  dh_w_highest;
#define DH_C_MAXSEG     31
    uint16  dh_w_extra;
    uint16  dh_w_start;
    } RT11_DirHeader;

typedef struct _RT11_DirEntry {
    uint16  de_w_status;
#define DE_C_PRE        0000020
#define DE_C_TENT       0000400
#define DE_C_EMPTY      0001000
#define DE_C_PERM       0002000
#define DE_C_EOS        0004000
#define DE_C_READ       0040000
#define DE_C_PROT       0100000
    uint16  de_w_fname1;
    uint16  de_w_fname2;
    uint16  de_w_ftype;
    uint16  de_w_length;
    uint16  de_w_jobchannel;
    uint16  de_w_creationdate;
    } RT11_DirEntry;
#pragma pack(pop)

#define RT11_MAXPARTITIONS      256             /* Max partitions supported */
#define RT11_HOME                 1             /* Home block # */

#define RT11_NOPART             0
#define RT11_SINGLEPART         1
#define RT11_MULTIPART          2

static int rt11_get_partition_type(RT11_HomeBlock *home, int part)
{
if (strncmp((char *)&home->hb_b_sysid, HB_C_SYSID, strlen(HB_C_SYSID)) == 0) {
    uint16 type = home->hb_w_sysver;

    if (part == 0) {
        if ((type == HB_C_SYSVER_V3A) || (type == HB_C_SYSVER_V04))
            return RT11_SINGLEPART;
        }

    if (type == HB_C_SYSVER_V05)
        return RT11_MULTIPART;
    }
return RT11_NOPART;
}

static t_offset get_rt11_filesystem_size (UNIT *uptr)
{
DEVICE *dptr;
t_addr saved_capac;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
t_addr temp_capac = (sim_toffset_64 ? (t_addr)0xFFFFFFFFu : (t_addr)0x7FFFFFFFu);  /* Make sure we can access the largest sector */
uint8 sector_buf[1024];
RT11_HomeBlock Home;
t_seccnt sects_read;
RT11_DirHeader *dir_hdr = (RT11_DirHeader *)sector_buf;
int partitions = 0;
int part;
uint32 base;
uint32 dir_sec;
uint16 dir_seg;
uint16 version = 0;
t_offset ret_val = (t_offset)-1;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
     return ret_val;
saved_capac = uptr->capac;
uptr->capac = temp_capac;

for (part = 0; part < RT11_MAXPARTITIONS; part++) {
    uint16 seg_highest;
    int type;

    base = part << 16;

    if (sim_disk_rdsect(uptr, (base + RT11_HOME) * (512 / ctx->sector_size), (uint8 *)&Home, &sects_read, 512 / ctx->sector_size) ||
        (sects_read != (512 / ctx->sector_size)))
        goto Return_Cleanup;

    type = rt11_get_partition_type(&Home, part);

    if (type != RT11_NOPART) {
        uint16 highest = 0;
        uint8 seg_seen[DH_C_MAXSEG + 1];

        memset(seg_seen, 0, sizeof(seg_seen));

        partitions++;

        dir_seg = 1;
        do {
            int offset = sizeof(RT11_DirHeader);
            int dir_size = sizeof(RT11_DirEntry);
            uint16 cur_blk;

            if (seg_seen[dir_seg]++ != 0)
                goto Next_Partition;

            dir_sec = Home.hb_w_firstdir + ((dir_seg - 1) * 2);

            if ((sim_disk_rdsect(uptr, (base + dir_sec) * (512 / ctx->sector_size), sector_buf, &sects_read, 1024 / ctx->sector_size)) ||
                (sects_read != (1024 / ctx->sector_size)))
                goto Return_Cleanup;

            if (dir_seg == 1) {
                seg_highest = dir_hdr->dh_w_highest;
                if (seg_highest > DH_C_MAXSEG)
                    goto Next_Partition;
                }
            dir_size += dir_hdr->dh_w_extra;
            cur_blk = dir_hdr->dh_w_start;

            while ((1024 - offset) >= dir_size) {
                RT11_DirEntry *dir_entry = (RT11_DirEntry *)&sector_buf[offset];

                if (dir_entry->de_w_status & DE_C_EOS)
                    break;

                /*
                 * Within each directory segment the bas address should never
                 * decrease.
                 */
                if (((cur_blk + dir_entry->de_w_length) & 0xFFFF) < cur_blk)
                    goto Next_Partition;

                cur_blk += dir_entry->de_w_length;
                offset += dir_size;
                }
            if (cur_blk > highest)
                highest = cur_blk;
            dir_seg = dir_hdr->dh_w_next;

            if (dir_seg > seg_highest)
                goto Next_Partition;
            } while (dir_seg != 0);

        ret_val = (t_offset)((base + highest) * (t_offset)512);
        version = Home.hb_w_sysver;

        if (type == RT11_SINGLEPART)
          break;
        }
Next_Partition:
    ;
    }

Return_Cleanup:
if (partitions) {
    const char *parttype;

    switch (version) {
        case HB_C_SYSVER_V3A:
            parttype = "V3A";
            break;

        case HB_C_SYSVER_V04:
            parttype = "V04";
            break;

        case HB_C_SYSVER_V05:
            parttype = "V05";
            break;

        default:
            parttype = "???";
            break;
        }
    sim_messagef (SCPE_OK, "%s%d: '%s' Contains RT11 partitions\n", sim_dname (dptr), (int)(uptr-dptr->units), uptr->filename);
    sim_messagef (SCPE_OK, "%d valid partition%s, Type: %s, Sectors On Disk: %u\n", partitions, partitions == 1 ? "" : "s", parttype, (uint32)(ret_val / 512));
    }
uptr->capac = saved_capac;
return ret_val;
}

typedef t_offset (*FILESYSTEM_CHECK)(UNIT *uptr);

static t_offset get_filesystem_size (UNIT *uptr)
{
static FILESYSTEM_CHECK checks[] = {
    &get_ods2_filesystem_size,
    &get_ods1_filesystem_size,
    &get_ultrix_filesystem_size,
    &get_rsts_filesystem_size,
    &get_rt11_filesystem_size,          /* This should be the last entry
                                           in the table to reduce the
                                           possibility of matching an RT-11
                                           container file stored in another
                                           filesystem */
    NULL
    };
t_offset ret_val = (t_offset)-1;
int i;

for (i = 0; checks[i] != NULL; i++) {
    ret_val = checks[i] (uptr);
    if (ret_val != (t_offset)-1)
        break;
    }
return ret_val;
}

static t_stat get_disk_footer (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
struct simh_disk_footer *f = (struct simh_disk_footer *)calloc (1, sizeof (*f));
t_offset container_size;
t_offset sim_fsize_ex (FILE *fptr);
uint32 bytesread;

if (f == NULL)
    return SCPE_MEM;
sim_debug_unit (ctx->dbit, uptr, "get_disk_footer(%s)\n", sim_uname (uptr));
switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* SIMH format */
        container_size = sim_fsize_ex (uptr->fileref);
        if ((container_size != (t_offset)-1) && (container_size > sizeof (*f)) &&
            (sim_fseeko (uptr->fileref, container_size - sizeof (*f), SEEK_SET) == 0) &&
            (sizeof (*f) == sim_fread (f, 1, sizeof (*f), uptr->fileref)))
            break;
        free (f);
        f = NULL;
        break;
    case DKUF_F_RAW:                                    /* RAW format */
        container_size = sim_os_disk_size_raw (uptr->fileref);
        if ((container_size != (t_offset)-1) && (container_size > sizeof (*f)) &&
            (sim_os_disk_read (uptr, container_size - sizeof (*f), (uint8 *)f, &bytesread, sizeof (*f)) == SCPE_OK) &&
            (bytesread == sizeof (*f)))
            break;
        free (f);
        f = NULL;
        break;
    case DKUF_F_VHD:                                    /* VHD format */
        /* Construct a pseudo simh disk footer*/
        memcpy (f->Signature, "simh", 4);
        strncpy ((char *)f->DriveType, sim_vhd_disk_get_dtype (uptr->fileref, &f->SectorSize, &f->TransferElementSize, (char *)f->CreatingSimulator), sizeof (f->DriveType) - 1);
        f->SectorSize = NtoHl (f->SectorSize);
        f->TransferElementSize = NtoHl (f->TransferElementSize);
        if ((f->SectorSize == 0) || (NtoHl (f->SectorSize) == 0x00020000)) {  /* Old or mangled format VHD footer */
            sim_vhd_disk_set_dtype (uptr->fileref, (char *)f->DriveType, ctx->sector_size, ctx->xfer_element_size);
            sim_vhd_disk_get_dtype (uptr->fileref, &f->SectorSize, &f->TransferElementSize, (char *)f->CreatingSimulator);
            f->SectorSize = NtoHl (f->SectorSize);
            f->TransferElementSize = NtoHl (f->TransferElementSize);
            }
        container_size = sim_vhd_disk_size (uptr->fileref);
        f->SectorCount = NtoHl ((uint32)(container_size / NtoHl (f->SectorSize)));
        container_size += sizeof (*f);      /* Adjust since it is removed below */
        f->AccessFormat = DKUF_F_VHD;
        strncpy ((char *)f->CreationTime, "\n", sizeof (f->CreationTime));
        f->Checksum = NtoHl (eth_crc32 (0, f, sizeof (*f) - sizeof (f->Checksum)));
        break;
    default:
        return SCPE_IERR;
    }
if (f) {
    if (f->Checksum != NtoHl (eth_crc32 (0, f, sizeof (*f) - sizeof (f->Checksum)))) {
        sim_debug_unit (ctx->dbit, uptr, "No footer found on %s format container: %s\n", sim_disk_fmt (uptr), uptr->filename);
        free (f);
        f = NULL;
        }
    else {
        ctx->footer = f;
        container_size -= sizeof (*f);
        sim_debug_unit (ctx->dbit, uptr, "Footer: %s - %s\n"
            "   Simulator:           %s\n"
            "   DriveType:           %s\n"
            "   SectorSize:          %u\n"
            "   SectorCount:         %u\n"
            "   TransferElementSize: %u\n"
            "   FooterVersion:       %u\n"
            "   AccessFormat:        %u\n"
            "   CreationTime:        %s",
            sim_uname (uptr), uptr->filename,
            f->CreatingSimulator, f->DriveType, NtoHl(f->SectorSize), NtoHl (f->SectorCount), 
            NtoHl (f->TransferElementSize), f->FooterVersion, f->AccessFormat, f->CreationTime);
        }
    }
sim_debug_unit (ctx->dbit, uptr, "Container Size: %u sectors %u bytes each\n", (uint32)(container_size/ctx->sector_size), ctx->sector_size);
ctx->container_size = container_size;
return SCPE_OK;
}

static t_stat store_disk_footer (UNIT *uptr, const char *dtype)
{
DEVICE *dptr;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
struct simh_disk_footer *f;
time_t now = time (NULL);
t_offset total_sectors;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
if (uptr->flags & UNIT_RO)
    return SCPE_RO;
f = (struct simh_disk_footer *)calloc (1, sizeof (*f));
f->AccessFormat = DK_GET_FMT (uptr);
total_sectors = (((t_offset)uptr->capac) * ctx->capac_factor * ((dptr->flags & DEV_SECTORS) ? 512 : 1)) / ctx->sector_size;
memcpy (f->Signature, "simh", 4);
strncpy ((char *)f->CreatingSimulator, sim_name, sizeof (f->CreatingSimulator) - 1);
strncpy ((char *)f->DriveType, dtype, sizeof (f->DriveType) - 1);
f->SectorSize = NtoHl (ctx->sector_size);
f->SectorCount = NtoHl ((uint32)total_sectors);
f->TransferElementSize = NtoHl (ctx->xfer_element_size);
strncpy ((char*)f->CreationTime, ctime (&now), sizeof (f->CreationTime) - 1);
f->Checksum = NtoHl (eth_crc32 (0, f, sizeof (*f) - sizeof (f->Checksum)));
free (ctx->footer);
ctx->footer = f;
switch (f->AccessFormat) {
    case DKUF_F_STD:                                    /* SIMH format */
        if (sim_fseeko ((FILE *)uptr->fileref, total_sectors * ctx->sector_size, SEEK_SET) == 0)
            sim_fwrite (f, sizeof (*f), 1, (FILE *)uptr->fileref);
        break;
    case DKUF_F_VHD:                                    /* VHD format */
        break;
    case DKUF_F_RAW:                                    /* Raw Physical Disk Access */
        sim_os_disk_write (uptr, total_sectors * ctx->sector_size, (uint8 *)f, NULL, sizeof (*f));
        break;
    default:
        break;
    }
return SCPE_OK;
}

t_stat sim_disk_attach (UNIT *uptr, const char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontchangecapac,
                        uint32 dbit, const char *dtype, uint32 pdp11tracksize, int completion_delay)
{
return sim_disk_attach_ex (uptr, cptr, sector_size, xfer_element_size, dontchangecapac, dbit, dtype, pdp11tracksize, completion_delay, NULL);
}

t_stat sim_disk_attach_ex (UNIT *uptr, const char *cptr, size_t sector_size, size_t xfer_element_size, t_bool dontchangecapac,
                           uint32 dbit, const char *dtype, uint32 pdp11tracksize, int completion_delay, const char **drivetypes)
{
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, uint32 *is_cdrom) = NULL;
t_bool created = FALSE, copied = FALSE;
t_bool auto_format = FALSE;
t_offset container_size, filesystem_size, current_unit_size;
size_t size_tmp;

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;
switch (xfer_element_size) {
    default:
        return sim_messagef (SCPE_ARG, "Unsupported transfer element size: %u\n", (uint32)xfer_element_size);
    case 1: case 2: case 4: case 8:
        break;
    }
size_tmp = 64;
while ((size_tmp != sector_size) && (size_tmp < 4096))
    size_tmp = size_tmp << 1;
if (sector_size != size_tmp)
    return sim_messagef (SCPE_ARG, "Invalid sector size: %u - must be a power of 2 between 64 and 4096\n", (uint32)sector_size);
if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    char gbuf[CBUFSIZE];
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    if ((sim_disk_set_fmt (uptr, 0, gbuf, NULL) != SCPE_OK) ||
        (DK_GET_FMT (uptr) == DKUF_F_AUTO))
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
    sim_switches = sim_switches & ~(SWMASK ('D'));
    cptr = get_glyph_nc (cptr, gbuf, 0);                /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    vhd = sim_vhd_disk_create_diff (gbuf, cptr);
    if (vhd) {
        sim_vhd_disk_close (vhd);
        return sim_disk_attach (uptr, gbuf, sector_size, xfer_element_size, dontautosize, dbit, dtype, pdp11tracksize, completion_delay);
        }
    return sim_messagef (SCPE_ARG, "Unable to create differencing VHD: %s\n", gbuf);
    }
if (sim_switches & SWMASK ('C')) {                      /* create vhd disk & copy contents? */
    char gbuf[CBUFSIZE];
    FILE *vhd;
    int saved_sim_switches = sim_switches;
    int32 saved_sim_quiet = sim_quiet;
    uint32 capac_factor;
    t_stat r;

    sim_switches = sim_switches & ~(SWMASK ('C'));
    cptr = get_glyph_nc (cptr, gbuf, 0);                /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    sim_switches |= SWMASK ('R') | SWMASK ('E');
    sim_quiet = TRUE;
    /* First open the source of the copy operation */
    r = sim_disk_attach (uptr, cptr, sector_size, xfer_element_size, dontautosize, dbit, dtype, pdp11tracksize, completion_delay);
    sim_quiet = saved_sim_quiet;
    if (r != SCPE_OK) {
        sim_switches = saved_sim_switches;
        return sim_messagef (r, "Can't open source VHD: %s\n", cptr);
        }
    sim_messagef (SCPE_OK, "%s%d: creating new virtual disk '%s'\n", sim_dname (dptr), (int)(uptr-dptr->units), gbuf);
    capac_factor = ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (word: 2, byte: 1) */
    vhd = sim_vhd_disk_create (gbuf, ((t_offset)uptr->capac)*capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1));
    if (!vhd) {
        return sim_messagef (r, "%s%d: can't create virtual disk '%s'\n", sim_dname (dptr), (int)(uptr-dptr->units), gbuf);
        }
    else {
        uint8 *copy_buf = (uint8*) malloc (1024*1024);
        t_lba lba;
        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 (!copy_buf) {
            sim_vhd_disk_close(vhd);
            (void)remove (gbuf);
            return SCPE_MEM;
            }

        for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects) {
            sim_messagef (SCPE_OK, "%s%d: Copied %dMB.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000), (int)((((float)lba)*100)/total_sectors));
            sects = sectors_per_buffer;
            if (lba + sects > total_sectors)
                sects = total_sectors - lba;
            r = sim_disk_rdsect (uptr, lba, copy_buf, NULL, sects);
            if (r == SCPE_OK) {
                uint32 saved_unit_flags = uptr->flags;
                FILE *save_unit_fileref = uptr->fileref;


                sim_disk_set_fmt (uptr, 0, "VHD", NULL);
                uptr->fileref = vhd;
                r = sim_disk_wrsect (uptr, lba, copy_buf, NULL, sects);
                uptr->fileref = save_unit_fileref;
                uptr->flags = saved_unit_flags;



                }
            }
        if (r == SCPE_OK)
            sim_messagef (SCPE_OK, "\n%s%d: Copied %dMB. Done.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)(((t_offset)lba*sector_size)/1000000));
        else
            sim_messagef (r, "\n%s%d: Error copying: %s.\n", sim_dname (dptr), (int)(uptr-dptr->units), sim_error_text (r));
        if ((r == SCPE_OK) && (sim_switches & SWMASK ('V'))) {
            uint8 *verify_buf = (uint8*) malloc (1024*1024);


            if (!verify_buf) {
                sim_vhd_disk_close(vhd);
                (void)remove (gbuf);
                free (copy_buf);
                return SCPE_MEM;
                }
            for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects) {
                sim_messagef (SCPE_OK, "%s%d: Verified %dMB.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000), (int)((((float)lba)*100)/total_sectors));
                sects = sectors_per_buffer;
                if (lba + sects > total_sectors)
                    sects = total_sectors - lba;
                r = sim_disk_rdsect (uptr, lba, copy_buf, NULL, sects);
                if (r == SCPE_OK) {
                    uint32 saved_unit_flags = uptr->flags;
                    FILE *save_unit_fileref = uptr->fileref;

                    sim_disk_set_fmt (uptr, 0, "VHD", NULL);
                    uptr->fileref = vhd;
                    r = sim_disk_rdsect (uptr, lba, verify_buf, NULL, sects);
                    uptr->fileref = save_unit_fileref;
                    uptr->flags = saved_unit_flags;
                    if (r == SCPE_OK) {

                        if (0 != memcmp (copy_buf, verify_buf, 1024*1024))
                            r = SCPE_IOERR;
                        }
                    }


                }
            if (!sim_quiet) {
                if (r == SCPE_OK)
                    sim_messagef (r, "\n%s%d: Verified %dMB. Done.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)(((t_offset)lba*sector_size)/1000000));
                else {
                    t_lba i;
                    uint32 save_dctrl = dptr->dctrl;
                    FILE *save_sim_deb = sim_deb;

                    for (i = 0; i < (1024*1024/sector_size); ++i)
                        if (0 != memcmp (copy_buf+i*sector_size, verify_buf+i*sector_size, sector_size))
                            break;
                    sim_printf ("\n%s%d: Verification Error on lbn %d.\n", sim_dname (dptr), (int)(uptr-dptr->units), lba+i);
                    dptr->dctrl = 0xFFFFFFFF;
                    sim_deb = stdout;
                    sim_disk_data_trace (uptr,   copy_buf+i*sector_size, lba+i, sector_size, "Expected", TRUE, 1);
                    sim_disk_data_trace (uptr, verify_buf+i*sector_size, lba+i, sector_size,    "Found", TRUE, 1);







|


















|



|


|










>






>
|
<



|
|


>



|


>
>
>



|




>







|
|



|






|



>
|



>
>



|





|







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
    sim_switches = sim_switches & ~(SWMASK ('D'));
    cptr = get_glyph_nc (cptr, gbuf, 0);                /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    vhd = sim_vhd_disk_create_diff (gbuf, cptr);
    if (vhd) {
        sim_vhd_disk_close (vhd);
        return sim_disk_attach (uptr, gbuf, sector_size, xfer_element_size, dontchangecapac, dbit, dtype, pdp11tracksize, completion_delay);
        }
    return sim_messagef (SCPE_ARG, "Unable to create differencing VHD: %s\n", gbuf);
    }
if (sim_switches & SWMASK ('C')) {                      /* create vhd disk & copy contents? */
    char gbuf[CBUFSIZE];
    FILE *vhd;
    int saved_sim_switches = sim_switches;
    int32 saved_sim_quiet = sim_quiet;
    uint32 capac_factor;
    t_stat r;

    sim_switches = sim_switches & ~(SWMASK ('C'));
    cptr = get_glyph_nc (cptr, gbuf, 0);                /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return SCPE_2FARG;
    sim_switches |= SWMASK ('R') | SWMASK ('E');
    sim_quiet = TRUE;
    /* First open the source of the copy operation */
    r = sim_disk_attach_ex (uptr, cptr, sector_size, xfer_element_size, dontchangecapac, dbit, dtype, pdp11tracksize, completion_delay, drivetypes);
    sim_quiet = saved_sim_quiet;
    if (r != SCPE_OK) {
        sim_switches = saved_sim_switches;
        return sim_messagef (r, "Can't open copy source: %s - %s\n", cptr, sim_error_text (r));
        }
    sim_messagef (SCPE_OK, "%s%d: creating new virtual disk '%s'\n", sim_dname (dptr), (int)(uptr-dptr->units), gbuf);
    capac_factor = ((dptr->dwidth / dptr->aincr) >= 32) ? 8 : ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (quadword: 8, word: 2, byte: 1) */
    vhd = sim_vhd_disk_create (gbuf, ((t_offset)uptr->capac)*capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1));
    if (!vhd) {
        return sim_messagef (r, "%s%d: can't create virtual disk '%s'\n", sim_dname (dptr), (int)(uptr-dptr->units), gbuf);
        }
    else {
        uint8 *copy_buf = (uint8*) malloc (1024*1024);
        t_lba lba;
        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;
        t_seccnt sects_read;

        if (!copy_buf) {
            sim_vhd_disk_close(vhd);
            (void)remove (gbuf);
            return SCPE_MEM;
            }
        sim_messagef (SCPE_OK, "Copying %u sectors each %u bytes in size\n", (uint32)total_sectors, (uint32)sector_size);
        for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects_read) {

            sects = sectors_per_buffer;
            if (lba + sects > total_sectors)
                sects = total_sectors - lba;
            r = sim_disk_rdsect (uptr, lba, copy_buf, &sects_read, sects);
            if ((r == SCPE_OK) && (sects_read > 0)) {
                uint32 saved_unit_flags = uptr->flags;
                FILE *save_unit_fileref = uptr->fileref;
                t_seccnt sects_written;

                sim_disk_set_fmt (uptr, 0, "VHD", NULL);
                uptr->fileref = vhd;
                r = sim_disk_wrsect (uptr, lba, copy_buf, &sects_written, sects_read);
                uptr->fileref = save_unit_fileref;
                uptr->flags = saved_unit_flags;
                if (sects_read != sects_written)
                    r = SCPE_IOERR;
                sim_messagef (SCPE_OK, "%s%d: Copied %u/%u sectors.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)(lba + sects_read), (uint32)total_sectors, (int)((((float)lba)*100)/total_sectors));
                }
            }
        if (r == SCPE_OK)
            sim_messagef (SCPE_OK, "\n%s%d: Copied %u sectors. Done.\n", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)total_sectors);
        else
            sim_messagef (r, "\n%s%d: Error copying: %s.\n", sim_dname (dptr), (int)(uptr-dptr->units), sim_error_text (r));
        if ((r == SCPE_OK) && (sim_switches & SWMASK ('V'))) {
            uint8 *verify_buf = (uint8*) malloc (1024*1024);
            t_seccnt sects_read, verify_read;

            if (!verify_buf) {
                sim_vhd_disk_close(vhd);
                (void)remove (gbuf);
                free (copy_buf);
                return SCPE_MEM;
                }
            for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects_read) {
                sim_messagef (SCPE_OK, "%s%d: Verified %u/%u sectors.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)lba, (uint32)total_sectors, (int)((((float)lba)*100)/total_sectors));
                sects = sectors_per_buffer;
                if (lba + sects > total_sectors)
                    sects = total_sectors - lba;
                r = sim_disk_rdsect (uptr, lba, copy_buf, &sects_read, sects);
                if (r == SCPE_OK) {
                    uint32 saved_unit_flags = uptr->flags;
                    FILE *save_unit_fileref = uptr->fileref;

                    sim_disk_set_fmt (uptr, 0, "VHD", NULL);
                    uptr->fileref = vhd;
                    r = sim_disk_rdsect (uptr, lba, verify_buf, &verify_read, sects_read);
                    uptr->fileref = save_unit_fileref;
                    uptr->flags = saved_unit_flags;
                    if (r == SCPE_OK) {
                        if ((sects_read != verify_read) || 
                            (0 != memcmp (copy_buf, verify_buf, verify_read*sector_size)))
                            r = SCPE_IOERR;
                        }
                    }
                if (r != SCPE_OK)
                    break;
                }
            if (!sim_quiet) {
                if (r == SCPE_OK)
                    sim_messagef (r, "\n%s%d: Verified %u sectors. Done.\n", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)total_sectors);
                else {
                    t_lba i;
                    uint32 save_dctrl = dptr->dctrl;
                    FILE *save_sim_deb = sim_deb;

                    for (i = 0; i < sects_read; ++i)
                        if (0 != memcmp (copy_buf+i*sector_size, verify_buf+i*sector_size, sector_size))
                            break;
                    sim_printf ("\n%s%d: Verification Error on lbn %d.\n", sim_dname (dptr), (int)(uptr-dptr->units), lba+i);
                    dptr->dctrl = 0xFFFFFFFF;
                    sim_deb = stdout;
                    sim_disk_data_trace (uptr,   copy_buf+i*sector_size, lba+i, sector_size, "Expected", TRUE, 1);
                    sim_disk_data_trace (uptr, verify_buf+i*sector_size, lba+i, sector_size,    "Found", TRUE, 1);
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
        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_AUTO:                                   /* SIMH format */
        auto_format = TRUE;
        if (NULL != (uptr->fileref = sim_vhd_disk_open (cptr, "rb"))) { /* Try VHD */
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);    /* set file format to VHD */
            sim_vhd_disk_close (uptr->fileref);         /* close vhd file*/
            uptr->fileref = NULL;
            open_function = sim_vhd_disk_open;
            size_function = sim_vhd_disk_size;

            break;
            }
        if (NULL != (uptr->fileref = sim_os_disk_open_raw (cptr, "rb"))) {
            sim_disk_set_fmt (uptr, 0, "RAW", NULL);    /* set file format to RAW */
            sim_os_disk_close_raw (uptr->fileref);      /* close raw file*/
            open_function = sim_os_disk_open_raw;
            size_function = sim_os_disk_size_raw;







|















>







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
        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, dontchangecapac, dbit, dtype, pdp11tracksize, completion_delay);
            free (Parent);
            return r;
            }
        return SCPE_ARG;
        }

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_AUTO:                                   /* SIMH format */
        auto_format = TRUE;
        if (NULL != (uptr->fileref = sim_vhd_disk_open (cptr, "rb"))) { /* Try VHD */
            sim_disk_set_fmt (uptr, 0, "VHD", NULL);    /* set file format to VHD */
            sim_vhd_disk_close (uptr->fileref);         /* close vhd file*/
            uptr->fileref = NULL;
            open_function = sim_vhd_disk_open;
            size_function = sim_vhd_disk_size;
            storage_function = sim_vhd_disk_info;
            break;
            }
        if (NULL != (uptr->fileref = sim_os_disk_open_raw (cptr, "rb"))) {
            sim_disk_set_fmt (uptr, 0, "RAW", NULL);    /* set file format to RAW */
            sim_os_disk_close_raw (uptr->fileref);      /* close raw file*/
            open_function = sim_os_disk_open_raw;
            size_function = sim_os_disk_size_raw;
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
        open_function = sim_fopen;
        size_function = sim_fsize_ex;
        break;
    case DKUF_F_VHD:                                    /* VHD format */
        open_function = sim_vhd_disk_open;
        create_function = sim_vhd_disk_create;
        size_function = sim_vhd_disk_size;

        break;
    case DKUF_F_RAW:                                    /* Raw Physical Disk Access */
        open_function = sim_os_disk_open_raw;
        size_function = sim_os_disk_size_raw;
        storage_function = sim_os_disk_info_raw;
        break;
    default:
        return SCPE_IERR;
    }
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char));/* alloc name buf */
uptr->disk_ctx = ctx = (struct disk_context *)calloc(1, sizeof(struct disk_context));
if ((uptr->filename == NULL) || (uptr->disk_ctx == NULL))
    return _err_return (uptr, SCPE_MEM);
strlcpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
ctx->sector_size = (uint32)sector_size;                 /* save sector_size */
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 */
ctx->media_removed = 0;                                 /* default present */
sim_debug_unit (ctx->dbit, uptr, "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 */







>















|




|







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
        open_function = sim_fopen;
        size_function = sim_fsize_ex;
        break;
    case DKUF_F_VHD:                                    /* VHD format */
        open_function = sim_vhd_disk_open;
        create_function = sim_vhd_disk_create;
        size_function = sim_vhd_disk_size;
        storage_function = sim_os_disk_info_raw;
        break;
    case DKUF_F_RAW:                                    /* Raw Physical Disk Access */
        open_function = sim_os_disk_open_raw;
        size_function = sim_os_disk_size_raw;
        storage_function = sim_os_disk_info_raw;
        break;
    default:
        return SCPE_IERR;
    }
uptr->filename = (char *) calloc (CBUFSIZE, sizeof (char));/* alloc name buf */
uptr->disk_ctx = ctx = (struct disk_context *)calloc(1, sizeof(struct disk_context));
if ((uptr->filename == NULL) || (uptr->disk_ctx == NULL))
    return _err_return (uptr, SCPE_MEM);
strlcpy (uptr->filename, cptr, CBUFSIZE);               /* save name */
ctx->sector_size = (uint32)sector_size;                 /* save sector_size */
ctx->capac_factor = ((dptr->dwidth / dptr->aincr) >= 32) ? 8 : ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* save capacity units (quadword: 8, 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 */
ctx->media_removed = 0;                                 /* default present */
sim_debug_unit (ctx->dbit, uptr, "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 */
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
            if (uptr->fileref == NULL)                  /* open fail? */
                return _err_return (uptr, SCPE_OPENERR);/* yes, error */
            sim_messagef (SCPE_OK, "%s%d: creating new file\n", sim_dname (dptr), (int)(uptr-dptr->units));
            created = TRUE;
            }
        }                                               /* end if null */
    }                                                   /* end else */
if (DK_GET_FMT (uptr) == DKUF_F_VHD) {



    if ((created) && dtype)





        sim_vhd_disk_set_dtype (uptr->fileref, dtype);
    if (dtype && strcmp (dtype, sim_vhd_disk_get_dtype (uptr->fileref))) {
        char cmd[32];




        sprintf (cmd, "%s%d %s", dptr->name, (int)(uptr-dptr->units), sim_vhd_disk_get_dtype (uptr->fileref));










        set_cmd (0, cmd);

        }
    }

uptr->flags = uptr->flags | UNIT_ATT;
uptr->pos = 0;

/* Get Device attributes if they are available */
if (storage_function)
    storage_function (uptr->fileref, &ctx->storage_sector_size, &ctx->removable, &ctx->is_cdrom);

if ((created) && (!copied)) {
    t_stat r = SCPE_OK;
    uint8 *secbuf = (uint8 *)calloc (128, ctx->sector_size);     /* alloc temp sector buf */

    /*
       On a newly created disk, we write a zero sector to the last and the
       first sectors.  This serves 3 purposes:
         1) it avoids strange allocation delays writing newly allocated
            storage at the end of the disk during simulator operation
         2) it allocates storage for the whole disk at creation time to
            avoid strange failures which may happen during simulator execution
            if the containing disk is full
         3) it leaves a Simh Format disk at the intended size so it may
            subsequently be autosized with the correct size.







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

>

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











|
|







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
            if (uptr->fileref == NULL)                  /* open fail? */
                return _err_return (uptr, SCPE_OPENERR);/* yes, error */
            sim_messagef (SCPE_OK, "%s%d: creating new file\n", sim_dname (dptr), (int)(uptr-dptr->units));
            created = TRUE;
            }
        }                                               /* end if null */
    }                                                   /* end else */
if ((DK_GET_FMT (uptr) == DKUF_F_VHD) || (ctx->footer)) {
    uint32 sector_size, xfer_element_size;
    char created_name[64];
    const char *container_dtype = ctx->footer ? (char *)ctx->footer->DriveType : sim_vhd_disk_get_dtype (uptr->fileref, &sector_size, &xfer_element_size, created_name);

    if (ctx->footer) {
        sector_size = NtoHl (ctx->footer->SectorSize);
        xfer_element_size = NtoHl (ctx->footer->TransferElementSize);
        }
    if ((DK_GET_FMT (uptr) == DKUF_F_VHD) && created && dtype)
        sim_vhd_disk_set_dtype (uptr->fileref, dtype, ctx->sector_size, ctx->xfer_element_size);
    if (dtype) {
        char cmd[32];
        t_stat r = SCPE_OK;

        if (((sector_size == 0) || (sector_size == ctx->sector_size)) &&
            ((xfer_element_size == 0) || (xfer_element_size == ctx->xfer_element_size))) {
            sprintf (cmd, "%s%d %s", dptr->name, (int)(uptr-dptr->units), sim_vhd_disk_get_dtype (uptr->fileref, NULL, NULL, NULL));
            r = set_cmd (0, cmd);
            if (r != SCPE_OK)
                r = sim_messagef (r, "Can't set %s%d to drive type %s\n", dptr->name, (int)(uptr-dptr->units), sim_vhd_disk_get_dtype (uptr->fileref, NULL, NULL, NULL));
            }
        else
            r = sim_messagef (SCPE_INCOMPDSK, "Disk created by the %s simulator is incompatible with the %s simulator\n", created_name, sim_name);
        if (r != SCPE_OK) {
            uptr->flags |= UNIT_ATT;
            sim_disk_detach (uptr);                         /* report error now */
            sprintf (cmd, "%s%d %s", dptr->name, (int)(uptr-dptr->units), dtype);/* restore original dtype */
            set_cmd (0, cmd);
            return r;
            }
        }
    }
uptr->flags |= UNIT_ATT;
uptr->pos = 0;

/* Get Device attributes if they are available */
if (storage_function)
    storage_function (uptr->fileref, &ctx->storage_sector_size, &ctx->removable, &ctx->is_cdrom);

if ((created) && (!copied)) {
    t_stat r = SCPE_OK;
    uint8 *secbuf = (uint8 *)calloc (128, ctx->sector_size);     /* alloc temp sector buf */

    /*
       On a newly created disk, we write zeros to the whole disk.
       This serves 3 purposes:
         1) it avoids strange allocation delays writing newly allocated
            storage at the end of the disk during simulator operation
         2) it allocates storage for the whole disk at creation time to
            avoid strange failures which may happen during simulator execution
            if the containing disk is full
         3) it leaves a Simh Format disk at the intended size so it may
            subsequently be autosized with the correct size.
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
    free (secbuf);
    if (r != SCPE_OK) {
        sim_disk_detach (uptr);                         /* report error now */
        (void)remove (cptr);                            /* remove the created 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 */
            (void)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 */
                (void)remove (cptr);                            /* remove the created file */
                return SCPE_OPENERR;

                }
            sim_messagef (SCPE_OK, "%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));
            }
        sim_messagef (SCPE_OK, "%s%d: Initialized To Sector Address %dMB.  100%% complete.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)((((float)lba)*sector_size)/1000000));
        free (init_buf);
        }
    if (pdp11tracksize)
        sim_disk_pdp11_bad_block (uptr, pdp11tracksize, sector_size/sizeof(uint16));
    }

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;







>
|

|
|








>

>
>








|
|



|
>

|

|





<



|



>






|



|

>
>
|







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
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
    free (secbuf);
    if (r != SCPE_OK) {
        sim_disk_detach (uptr);                         /* report error now */
        (void)remove (cptr);                            /* remove the created file */
        return SCPE_OPENERR;
        }
    if (sim_switches & SWMASK ('I')) {                  /* Initialize To Sector Address */
        size_t init_buf_size = 1024*1024;
        uint8 *init_buf = (uint8*) malloc (init_buf_size);
        t_lba lba, sect;
        uint32 capac_factor = ((dptr->dwidth / dptr->aincr) >= 32) ? 8 : ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (quadword: 8, word: 2, byte: 1) */
        t_seccnt sectors_per_buffer = (t_seccnt)((init_buf_size)/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 */
            (void)remove (cptr);
            return SCPE_MEM;
            }
        sim_messagef (SCPE_OK, "Initializing %u sectors each %u bytes in size with the sector address\n", (uint32)total_sectors, (uint32)sector_size);
        for (lba = 0; (lba < total_sectors) && (r == SCPE_OK); lba += sects) {
            t_seccnt sects_written;

            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, &sects_written, sects);
            if ((r != SCPE_OK) || (sects != sects_written)) {
                free (init_buf);
                sim_disk_detach (uptr);                         /* report error now */
                (void)remove (cptr);                            /* remove the created file */
                return sim_messagef (SCPE_OPENERR, "Error initializing each sector with its address: %s\n", 
                                                   (r == SCPE_OK) ? sim_error_text (r) : "sectors written not what was requested");
                }
            sim_messagef (SCPE_OK, "%s%d: Initialized To Sector Address %u/%u sectors.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)(lba + sects_written), (uint32)total_sectors, (int)((((float)lba)*100)/total_sectors));
            }
        sim_messagef (SCPE_OK, "%s%d: Initialized To Sector Address %u sectors.  100%% complete.       \n", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)total_sectors);
        free (init_buf);
        }
    if (pdp11tracksize)
        sim_disk_pdp11_bad_block (uptr, pdp11tracksize, sector_size/sizeof(uint16));
    }

if (sim_switches & SWMASK ('K')) {
    t_stat r = SCPE_OK;
    t_lba lba, sect;
    uint32 capac_factor = ((dptr->dwidth / dptr->aincr) >= 32) ? 8 : ((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;
    t_seccnt sects_verify;
    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_verify) {
        sects = sectors_per_buffer;
        if (lba + sects > total_sectors)
            sects = total_sectors - lba;
        r = sim_disk_rdsect (uptr, lba, verify_buf, &sects_verify, sects);
        if (r == SCPE_OK) {
            if (sects != sects_verify)
                sim_printf ("\n%s%d: Verification Error on lbn %d(0x%X) of %d(0x%X) Requested %u sectors, read %u sectors.\n", sim_dname (dptr), (int)(uptr-dptr->units), (int)(lba+sect), (int)(lba+sect), (int)total_sectors, (int)total_sectors, sects, sects_verify);
            for (sect = 0; sect < sects_verify; 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;
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
                    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;
                    }
                }
            }
        sim_messagef (SCPE_OK, "%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));
        }
    sim_messagef (SCPE_OK, "%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_size = get_filesystem_size (uptr);
container_size = size_function (uptr->fileref);
current_unit_size = ((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1);
if (container_size && (container_size != (t_offset)-1)) {
    if (dontautosize) {
        t_addr saved_capac = uptr->capac;








        if ((filesystem_size != (t_offset)-1) &&










            (filesystem_size > current_unit_size)) {
            if (!sim_quiet) {
                uptr->capac = (t_addr)(filesystem_size/(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 ((container_size < current_unit_size) && 
            ((DKUF_F_VHD == DK_GET_FMT (uptr)) || (0 != (uptr->flags & UNIT_RO)))) {

            if (!sim_quiet) {




                uptr->capac = (t_addr)(container_size/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
                sim_printf ("%s%d: non expandable disk container '%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 {          /* Autosize */
        if (filesystem_size != (t_offset)-1) {              /* Known file system data size AND */
            if (filesystem_size > container_size)           /*    Data size greater than container size? */
                container_size = filesystem_size +          /*       Use file system data size */
                             (pdp11tracksize * sector_size);/*       plus any bad block data beyond the file system */
            }
        else {                                              /* Unrecognized file system */
            if (container_size < current_unit_size)         /*     Use MAX of container or current device size */
                if ((DKUF_F_VHD != DK_GET_FMT (uptr)) &&    /*     when size can be expanded */
                    (0 == (uptr->flags & UNIT_RO)))
                    container_size = current_unit_size;     /*     Use MAX of container or current device size */
            }
        uptr->capac = (t_addr)(container_size/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));  /* update current size */
        }
    }




#if defined (SIM_ASYNCH_IO)
sim_disk_set_async (uptr, completion_delay);
#endif
uptr->io_flush = _sim_disk_io_flush;

return SCPE_OK;







|

|




>
>
>
>

|


|


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

>
>
>
>

|
>


>





|














>
>
>







2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
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
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
                    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;
                    }
                }
            }
        sim_messagef (SCPE_OK, "%s%d: Verified containing Sector Address %u/%u sectors.  %d%% complete.\r", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)lba, (uint32)total_sectors, (int)((((float)lba)*100)/total_sectors));
        }
    sim_messagef (SCPE_OK, "%s%d: Verified containing Sector Address %u sectors.  100%% complete.         \n", sim_dname (dptr), (int)(uptr-dptr->units), (uint32)lba);
    free (verify_buf);
    uptr->dynflags |= UNIT_DISK_CHK;
    }

if (get_disk_footer (uptr) != SCPE_OK) {
    sim_disk_detach (uptr);
    return SCPE_OPENERR;
    }
filesystem_size = get_filesystem_size (uptr);
container_size = sim_disk_size (uptr);
current_unit_size = ((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1);
if (container_size && (container_size != (t_offset)-1)) {
    if (dontchangecapac) {
        t_addr saved_capac = uptr->capac;

        if (filesystem_size == (t_offset)-1)    /* No file system found? */
            filesystem_size = container_size;   /* Assume full container */
        if (drivetypes != NULL) {
            /* Walk through all potential drive types until we find one the right size */
            while (*drivetypes != NULL) {
                char cmd[CBUFSIZE];
                t_stat st;

                uptr->flags &= ~UNIT_ATT;   /* temporarily mark as un-attached */
                sprintf (cmd, "%s %s", sim_uname (uptr), *drivetypes);
                st = set_cmd (0, cmd);
                uptr->flags |= UNIT_ATT;    /* restore attached indicator */
                if (st == SCPE_OK)
                    current_unit_size = ((t_offset)uptr->capac)*ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1);
                if (current_unit_size >= filesystem_size)
                    break;
                ++drivetypes;
                }
            if (filesystem_size > current_unit_size) {
                if (!sim_quiet) {
                    uptr->capac = (t_addr)(filesystem_size/(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_FSSIZE;
                }
            }
        if ((container_size != current_unit_size) && 
            ((DKUF_F_VHD == DK_GET_FMT (uptr)) || (0 != (uptr->flags & UNIT_RO)) ||
             (ctx->footer))) {
            if (!sim_quiet) {
                int32 saved_switches = sim_switches;
                const char *container_dtype = ctx->footer ? (const char *)ctx->footer->DriveType : "";

                sim_switches = SWMASK ('R');
                uptr->capac = (t_addr)(container_size/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));
                sim_printf ("%s%d: non expandable %s disk container '%s' is %s than simulated device (%s %s ", 
                            sim_dname (dptr), (int)(uptr-dptr->units), container_dtype, cptr, (container_size < current_unit_size) ? "smaller" : "larger", sprint_capac (dptr, uptr), (container_size < current_unit_size) ? "<" : ">");
                uptr->capac = saved_capac;
                sim_printf ("%s)\n", sprint_capac (dptr, uptr));
                sim_switches = saved_switches;
                }
            sim_disk_detach (uptr);
            return SCPE_OPENERR;
            }
        }
    else {          /* Autosize by changing capacity */
        if (filesystem_size != (t_offset)-1) {              /* Known file system data size AND */
            if (filesystem_size > container_size)           /*    Data size greater than container size? */
                container_size = filesystem_size +          /*       Use file system data size */
                             (pdp11tracksize * sector_size);/*       plus any bad block data beyond the file system */
            }
        else {                                              /* Unrecognized file system */
            if (container_size < current_unit_size)         /*     Use MAX of container or current device size */
                if ((DKUF_F_VHD != DK_GET_FMT (uptr)) &&    /*     when size can be expanded */
                    (0 == (uptr->flags & UNIT_RO)))
                    container_size = current_unit_size;     /*     Use MAX of container or current device size */
            }
        uptr->capac = (t_addr)(container_size/(ctx->capac_factor*((dptr->flags & DEV_SECTORS) ? 512 : 1)));  /* update current size */
        }
    }

if (dtype && (created || (ctx->footer == NULL)))
    store_disk_footer (uptr, dtype);

#if defined (SIM_ASYNCH_IO)
sim_disk_set_async (uptr, completion_delay);
#endif
uptr->io_flush = _sim_disk_io_flush;

return SCPE_OK;
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;

ctx = (struct disk_context *)uptr->disk_ctx;
fileref = uptr->fileref;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_detach(unit=%d,filename='%s')\n", (int)(uptr-ctx->dptr->units), uptr->filename);

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* Simh */
        close_function = fclose;
        break;
    case DKUF_F_VHD:                                    /* Virtual Disk */
        close_function = sim_vhd_disk_close;







|







2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
    return SCPE_IERR;
if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;

ctx = (struct disk_context *)uptr->disk_ctx;
fileref = uptr->fileref;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_detach(unit=%d,filename='%s')\n", (int)(uptr - ctx->dptr->units), uptr->filename);

switch (DK_GET_FMT (uptr)) {                            /* case on format */
    case DKUF_F_STD:                                    /* Simh */
        close_function = fclose;
        break;
    case DKUF_F_VHD:                                    /* Virtual Disk */
        close_function = sim_vhd_disk_close;
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
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)
    sim_disk_set_fmt (uptr, 0, "AUTO", NULL);           /* restore file format */
if (close_function (fileref) == EOF)
    return SCPE_IOERR;
return SCPE_OK;
}

t_stat sim_disk_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{

























fprintf (st, "%s Disk Attach Help\n\n", dptr->name);

fprintf (st, "Disk container files can be one of 3 different types:\n\n");

fprintf (st, "    SIMH   A disk is an unstructured binary file of the size appropriate\n");
fprintf (st, "           for the disk drive being simulated\n");
fprintf (st, "    VHD    Virtual Disk format which is described in the \"Microsoft\n");
fprintf (st, "           Virtual Hard Disk (VHD) Image Format Specification\".  The\n");
fprintf (st, "           VHD implementation includes support for 1) Fixed (Preallocated)\n");
fprintf (st, "           disks, 2) Dynamically Expanding disks, and 3) Differencing disks.\n");
fprintf (st, "    RAW    platform specific access to physical disk or CDROM drives\n\n");











fprintf (st, "Virtual (VHD) Disks  supported conform to \"Virtual Hard Disk Image Format\n");
fprintf (st, "Specification\", Version 1.0 October 11, 2006.\n");
fprintf (st, "Dynamically expanding disks never change their \"Virtual Size\", but they don't\n");
fprintf (st, "consume disk space on the containing storage until the virtual sectors in the\n");
fprintf (st, "disk are actually written to (i.e. a 2GB Dynamic disk container file with only\n");
fprintf (st, "30MB of data will initially be about 30MB in size and this size will grow up to\n");
fprintf (st, "2GB as different sectors are written to.  The VHD format contains metadata\n");
fprintf (st, "which describes the drive size and the simh device type in use when the VHD\n");
fprintf (st, "was created.  This metadata is therefore available whenever that VHD is\n");
fprintf (st, "attached to an emulated disk device in the future so the device type and\n");
fprintf (st, "size can be automatically be configured.\n\n");

if (0 == (uptr-dptr->units)) {
    if (dptr->numunits > 1) {
        uint32 i;

        for (i=0; i < dptr->numunits; ++i)
            if (dptr->units[i].flags & UNIT_ATTABLE)





                fprintf (st, "  sim> ATTACH {switches} %s%d diskfile\n", dptr->name, i);

        }











    else
        fprintf (st, "  sim> ATTACH {switches} %s diskfile\n", dptr->name);

    }

else
    fprintf (st, "  sim> ATTACH {switches} %s diskfile\n\n", dptr->name);
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");







>












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


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












<
|
|

|
|
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
|
<
>
|
>

|







2826
2827
2828
2829
2830
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
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
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
2939
2940
2941
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 (ctx->footer);
free (uptr->disk_ctx);
uptr->disk_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)
    sim_disk_set_fmt (uptr, 0, "AUTO", NULL);           /* restore file format */
if (close_function (fileref) == EOF)
    return SCPE_IOERR;
return SCPE_OK;
}

t_stat sim_disk_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr)
{
static struct example_fields {
    const char *dname;
    const char *dtype;
    const char *dsize;
    const char *dtype2;
    const char *dsize2;
    const char *dtype3;
    const char *dsize3;
    const char *dtype4;
    const char *dsize4;
    } ex_data[] = {
        {"RQ", "RD54", "159MB", "RX50", "409KB", "RA81", "456MB", "RA92", "1505MB"},
        {"RP", "RM03",  "33MW", "RM03",  "33MW", "RP07", "258MW", "RM03",  "15MW"},
        {"RP", "RM03",  "39MW", "RM03",  "39MW", "RP07", "110MW", "RM03",  "15MW"},
    };
struct example_fields *ex = &ex_data[0];

if (strcmp (dptr->name, "RP") == 0)
    ex = &ex_data[1];
if (strstr (sim_name, "-10")) {
    ex = &ex_data[2];
    if (strstr (sim_name, "PDP") == NULL)
        ex->dname = "RPA";
    }

fprintf (st, "%s Disk Attach Help\n\n", dptr->name);

fprintf (st, "Disk container files can be one of several different types:\n\n");
if (strstr (sim_name, "-10") == NULL) {
    fprintf (st, "    SIMH   A disk is an unstructured binary file of the size appropriate\n");
    fprintf (st, "           for the disk drive being simulated accessed by C runtime APIs\n");
    fprintf (st, "    VHD    Virtual Disk format which is described in the \"Microsoft\n");
    fprintf (st, "           Virtual Hard Disk (VHD) Image Format Specification\".  The\n");
    fprintf (st, "           VHD implementation includes support for 1) Fixed (Preallocated)\n");
    fprintf (st, "           disks, 2) Dynamically Expanding disks, and 3) Differencing disks.\n");
    fprintf (st, "    RAW    platform specific access to physical disk or CDROM drives\n\n");
    }
else {
    fprintf (st, "    SIMH   A disk is an unstructured binary file of 64bit integers\n"
                 "           access by C runtime APIs\n");
    fprintf (st, "    VHD    A disk is an unstructured binary file of 64bit integers\n"
                 "           contained in a VHD container\n");
    fprintf (st, "    RAW    A disk is an unstructured binary file of 64bit integers\n"
                 "           accessed by direct read/write APIs\n");
    fprintf (st, "    DBD9   Compatible with KLH10 is a packed big endian word\n");
    fprintf (st, "    DLD9   Compatible with KLH10 is a packed little endian word\n\n");
    }
fprintf (st, "Virtual (VHD) Disks  supported conform to \"Virtual Hard Disk Image Format\n");
fprintf (st, "Specification\", Version 1.0 October 11, 2006.\n");
fprintf (st, "Dynamically expanding disks never change their \"Virtual Size\", but they don't\n");
fprintf (st, "consume disk space on the containing storage until the virtual sectors in the\n");
fprintf (st, "disk are actually written to (i.e. a 2GB Dynamic disk container file with only\n");
fprintf (st, "30MB of data will initially be about 30MB in size and this size will grow up to\n");
fprintf (st, "2GB as different sectors are written to.  The VHD format contains metadata\n");
fprintf (st, "which describes the drive size and the simh device type in use when the VHD\n");
fprintf (st, "was created.  This metadata is therefore available whenever that VHD is\n");
fprintf (st, "attached to an emulated disk device in the future so the device type and\n");
fprintf (st, "size can be automatically be configured.\n\n");


if (dptr->numunits > 1) {
    uint32 i, attachable_count = 0, out_count = 0, skip_count;

    for (i=0; i < dptr->numunits; ++i)
        if ((dptr->units[i].flags & UNIT_ATTABLE) &&
            !(dptr->units[i].flags & UNIT_DIS))
            ++attachable_count;
    for (i=0; (i < dptr->numunits) && (out_count < 2); ++i)
        if ((dptr->units[i].flags & UNIT_ATTABLE) &&
            !(dptr->units[i].flags & UNIT_DIS)) {
            fprintf (st, "  sim> ATTACH {switches} %s%d diskfile\n", dptr->name, i);
            ++out_count;
            }
    if (attachable_count > 4) {
        fprintf (st, "       .\n");
        fprintf (st, "       .\n");
        fprintf (st, "       .\n");
        }
    skip_count = attachable_count - 2;
    for (i=0; i < dptr->numunits; ++i)
        if ((dptr->units[i].flags & UNIT_ATTABLE) &&
            !(dptr->units[i].flags & UNIT_DIS)) {
            if (skip_count == 0)
                fprintf (st, "  sim> ATTACH {switches} %s%d diskfile\n", dptr->name, i);
            else

                --skip_count;
            }
    }
else
    fprintf (st, "  sim> ATTACH {switches} %s diskfile\n", dptr->name);
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");
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
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");

fprintf (st, "  sim> atta rq0 RA81.vhd\n");
fprintf (st, "  sim> show rq0\n");
fprintf (st, "  RQ0, 456MB, attached to RA81.vhd, write enabled, RA81, autosize, VHD format\n");

fprintf (st, "  sim> set rq2 ra92\n");
fprintf (st, "  sim> att rq2 -f vhd RA92.vhd\n");
fprintf (st, "  RQ2: creating new file\n");
fprintf (st, "  sim> sho rq2\n");
fprintf (st, "  RQ2, 1505MB, attached to RA92.vhd, write enabled, RA92, autosize, VHD format\n");
fprintf (st, "  sim> ! dir RA92.vhd\n");
fprintf (st, "   Volume in drive H is New Volume\n");
fprintf (st, "   Volume Serial Number is F8DE-510C\n\n");
fprintf (st, "   Directory of H:\\Data\n\n");
fprintf (st, "  04/14/2011  12:57 PM             5,120 RA92.vhd\n");
fprintf (st, "                 1 File(s)          5,120 bytes\n");

fprintf (st, "  sim> atta rq3 -d RA92-1-Diff.vhd RA92.vhd\n");

fprintf (st, "  sim> atta rq3 -c RA92-1.vhd RA92.vhd\n");
fprintf (st, "  RQ3: creating new virtual disk 'RA92-1.vhd'\n");
fprintf (st, "  RQ3: Copied 1505MB.  99%% complete.\n");
fprintf (st, "  RQ3: Copied 1505MB. Done.\n");
fprintf (st, "  sim> sh rq3\n");
fprintf (st, "  RQ3, 1505MB, attached to RA92-1.vhd, write enabled, RA92, autosize, VHD format\n");
fprintf (st, "  sim>  ! dir RA92*\n");
fprintf (st, "   Volume in drive H is New Volume\n");
fprintf (st, "   Volume Serial Number is F8DE-510C\n\n");
fprintf (st, "   Directory of H:\\Data\n\n");
fprintf (st, "  04/14/2011  01:12 PM             5,120 RA92-1.vhd\n");
fprintf (st, "  04/14/2011  12:58 PM             5,120 RA92.vhd\n");
fprintf (st, "                 2 File(s)         10,240 bytes\n");
fprintf (st, "  sim> sho rq2\n");
fprintf (st, "  RQ2, 1505MB, not attached, write enabled, RA92, autosize, VHD format\n");
fprintf (st, "  sim> set rq2 ra81\n");
fprintf (st, "  sim> set rq2 noauto\n");
fprintf (st, "  sim> sho rq2\n");
fprintf (st, "  RQ2, 456MB, not attached, write enabled, RA81, noautosize, VHD format\n");
fprintf (st, "  sim> set rq2 format=simh\n");
fprintf (st, "  sim> sho rq2\n");
fprintf (st, "  RQ2, 456MB, not attached, write enabled, RA81, noautosize, SIMH format\n");

fprintf (st, "  sim> atta rq2 -c RA81-Copy.vhd VMS055.dsk\n");
fprintf (st, "  RQ2: creating new virtual disk 'RA81-Copy.vhd'\n");
fprintf (st, "  RQ2: Copied 456MB.  99%% complete.\n");
fprintf (st, "  RQ2: Copied 456MB. Done.\n");
fprintf (st, "  sim> sho rq2\n");
fprintf (st, "  RQ2, 456MB, attached to RA81-Copy.vhd, write enabled, RA81, noautosize, VHD format\n");
return SCPE_OK;
}

t_bool sim_disk_vhd_support (void)
{
return SCPE_OK == sim_vhd_disk_implemented ();
}

t_bool sim_disk_raw_support (void)
{
return SCPE_OK == sim_os_disk_implemented_raw ();
}

t_stat sim_disk_reset (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_reset(unit=%d)\n", (int)(uptr-ctx->dptr->units));

_sim_disk_io_flush(uptr);
AIO_VALIDATE(uptr);
AIO_UPDATE_QUEUE;
return SCPE_OK;
}








>
|
|
>

|
|
|
|
|
|
>
|
|
|
>
|
|
|
|
|
|
|
<

|

>
|
>
|
|
|
|
|
|
|
<
<

|
|

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




















|







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
2978
2979
2980
2981

2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994


2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
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");
if (strstr (sim_name, "-10") == NULL) {
    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 %s\n", ex->dname);
fprintf (st, "    %s, address=20001468-2000146B*, no vector, 4 units\n", ex->dname);
fprintf (st, "    %s0, %s, not attached, write enabled, %s, autosize, AUTO detect format\n", ex->dname, ex->dsize, ex->dtype);
fprintf (st, "    %s1, %s, not attached, write enabled, %s, autosize, AUTO detect format\n", ex->dname, ex->dsize, ex->dtype);
fprintf (st, "    %s2, %s, not attached, write enabled, %s, autosize, AUTO detect format\n", ex->dname, ex->dsize, ex->dtype);
fprintf (st, "    %s3, %s, not attached, write enabled, %s, autosize, AUTO detect format\n", ex->dname, ex->dsize2, ex->dtype2);
fprintf (st, "  sim> # attach an existing VHD and determine its size and type automatically\n");
fprintf (st, "  sim> attach %s0 %s.vhd\n", ex->dname, ex->dtype3);
fprintf (st, "  sim> show %s0\n", ex->dname);
fprintf (st, "  %s0, %s, attached to %s.vhd, write enabled, %s, autosize, VHD format\n", ex->dname, ex->dsize3, ex->dtype3, ex->dtype3);
fprintf (st, "  sim> # create a new %s drive type VHD\n", ex->dtype4);
fprintf (st, "  sim> set %s2 %s\n", ex->dname, ex->dtype4);
fprintf (st, "  sim> attach %s2 -f vhd %s.vhd\n", ex->dname, ex->dtype4);
fprintf (st, "  %s2: creating new file\n", ex->dname);
fprintf (st, "  sim> show %s2\n", ex->dname);
fprintf (st, "  %s2, %s, attached to %s.vhd, write enabled, %s, autosize, VHD format\n", ex->dname, ex->dsize4, ex->dtype4, ex->dtype4);
fprintf (st, "  sim> # examine the size consumed by the %s VHD file\n", ex->dsize4);
fprintf (st, "  sim> dir %s.vhd\n", ex->dtype4);

fprintf (st, "   Directory of H:\\Data\n\n");
fprintf (st, "  04/14/2011  12:57 PM             5,120 %s.vhd\n", ex->dtype4);
fprintf (st, "                 1 File(s)          5,120 bytes\n");
fprintf (st, "  sim> # create a differencing vhd (%s-1-Diff.vhd) with %s.vhd as parent\n", ex->dtype4, ex->dtype4);
fprintf (st, "  sim> attach %s3 -d %s-1-Diff.vhd %s.vhd\n", ex->dname, ex->dtype4, ex->dtype4);
fprintf (st, "  sim> # create a VHD (%s-1.vhd) which is a copy of an existing disk\n", ex->dtype4);
fprintf (st, "  sim> attach %s3 -c %s-1.vhd %s.vhd\n", ex->dname, ex->dtype4, ex->dtype4);
fprintf (st, "  %s3: creating new virtual disk '%s-1.vhd'\n", ex->dname, ex->dtype4);
fprintf (st, "  %s3: Copied %s.  99%% complete.\n", ex->dname, ex->dsize4);
fprintf (st, "  %s3: Copied %s. Done.\n", ex->dname, ex->dsize4);
fprintf (st, "  sim> show %s3\n", ex->dname);
fprintf (st, "  %s3, %s, attached to %s-1.vhd, write enabled, %s, autosize, VHD format\n", ex->dname, ex->dsize4, ex->dtype4, ex->dtype4);
fprintf (st, "  sim> dir %s*\n", ex->dtype4);


fprintf (st, "   Directory of H:\\Data\n\n");
fprintf (st, "  04/14/2011  01:12 PM             5,120 %s-1.vhd\n", ex->dtype4);
fprintf (st, "  04/14/2011  12:58 PM             5,120 %s.vhd\n", ex->dtype4);
fprintf (st, "                 2 File(s)         10,240 bytes\n");
fprintf (st, "  sim> show %s2\n", ex->dname);
fprintf (st, "  %s2, %s, not attached, write enabled, %s, autosize, VHD format\n", ex->dname, ex->dsize4, ex->dtype4);
fprintf (st, "  sim> set %s2 %s\n", ex->dname, ex->dtype3);
fprintf (st, "  sim> set %s2 noauto\n", ex->dname);
fprintf (st, "  sim> show %s2\n", ex->dname);
fprintf (st, "  %s2, %s, not attached, write enabled, %s, noautosize, VHD format\n", ex->dname, ex->dsize3, ex->dtype3);
fprintf (st, "  sim> set %s2 format=simh\n", ex->dname);
fprintf (st, "  sim> show %s2\n", ex->dname);
fprintf (st, "  %s2, %s, not attached, write enabled, %s, noautosize, SIMH format\n", ex->dname, ex->dsize3, ex->dtype3);
fprintf (st, "  sim> # create a VHD from an existing SIMH format disk\n");
fprintf (st, "  sim> attach %s2 -c %s-Copy.vhd XYZZY.dsk\n", ex->dname, ex->dtype3);
fprintf (st, "  %s2: creating new virtual disk '%s-Copy.vhd'\n", ex->dname, ex->dtype3);
fprintf (st, "  %s2: Copied %s.  99%% complete.\n", ex->dname, ex->dsize3);
fprintf (st, "  %s2: Copied %s. Done.\n", ex->dname, ex->dsize3);
fprintf (st, "  sim> show %s2\n", ex->dname);
fprintf (st, "  %s2, %s, attached to %s-Copy.vhd, write enabled, %s, noautosize, VHD format\n", ex->dname, ex->dsize3, ex->dtype3, ex->dtype3);
return SCPE_OK;
}

t_bool sim_disk_vhd_support (void)
{
return SCPE_OK == sim_vhd_disk_implemented ();
}

t_bool sim_disk_raw_support (void)
{
return SCPE_OK == sim_os_disk_implemented_raw ();
}

t_stat sim_disk_reset (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

if (!(uptr->flags & UNIT_ATT))                          /* attached? */
    return SCPE_OK;

sim_debug_unit (ctx->dbit, uptr, "sim_disk_reset(unit=%d)\n", (int)(uptr - ctx->dptr->units));

_sim_disk_io_flush(uptr);
AIO_VALIDATE(uptr);
AIO_UPDATE_QUEUE;
return SCPE_OK;
}

2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
return stat;
}

void sim_disk_data_trace(UNIT *uptr, const uint8 *data, size_t lba, size_t len, const char* txt, int detail, uint32 reason)
{
DEVICE *dptr = find_dev_from_unit (uptr);

if (sim_deb && (dptr->dctrl & reason)) {
    char pos[32];

    sprintf (pos, "lbn: %08X ", (unsigned int)lba);
    sim_data_trace(dptr, uptr, (detail ? data : NULL), pos, len, txt, reason);
    }
}


/* OS Specific RAW Disk I/O support */

#if defined _WIN32

static void _set_errno_from_status (DWORD dwStatus)
{







|






<







3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166

3167
3168
3169
3170
3171
3172
3173
return stat;
}

void sim_disk_data_trace(UNIT *uptr, const uint8 *data, size_t lba, size_t len, const char* txt, int detail, uint32 reason)
{
DEVICE *dptr = find_dev_from_unit (uptr);

if (sim_deb && ((uptr->dctrl | dptr->dctrl) & reason)) {
    char pos[32];

    sprintf (pos, "lbn: %08X ", (unsigned int)lba);
    sim_data_trace(dptr, uptr, (detail ? data : NULL), pos, len, txt, reason);
    }
}


/* OS Specific RAW Disk I/O support */

#if defined _WIN32

static void _set_errno_from_status (DWORD dwStatus)
{
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
return SCPE_OK;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
long long addr;


sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);



















addr = ((long long)lba) * ctx->sector_size;


















memset (&pos, 0, sizeof (pos));
pos.Offset = (DWORD)addr;
pos.OffsetHigh = (DWORD)(addr >> 32);
if (ReadFile ((HANDLE)(uptr->fileref), buf, sects * ctx->sector_size, (LPDWORD)sectsread, &pos)) {



    if (sectsread)
        *sectsread /= ctx->sector_size;
    return SCPE_OK;
    }
_set_errno_from_status (GetLastError ());
return SCPE_IOERR;
}

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
long long addr;



sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);



addr = ((long long)lba) * ctx->sector_size;
memset (&pos, 0, sizeof (pos));



pos.Offset = (DWORD)addr;
pos.OffsetHigh = (DWORD)(addr >> 32);
if (WriteFile ((HANDLE)(uptr->fileref), buf, sects * ctx->sector_size, (LPDWORD)sectswritten, &pos)) {



    if (sectswritten)
        *sectswritten /= ctx->sector_size;







    return SCPE_OK;
    }













_set_errno_from_status (GetLastError ());
return SCPE_IOERR;
}

#elif defined (__linux) || defined (__linux__) || defined (__sun) || defined (__sun__) || defined (__hpux) || defined (_AIX)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#if defined(HAVE_SYS_IOCTL)
#include <sys/ioctl.h>







|
>

|
>
>
>
>
>
>

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



|
>
>
>
|
|











>
>

|

>
>


>
>
>
|
|
|
>
>
>

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




|







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
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
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
return SCPE_OK;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
long long addr = ((long long)lba) * ctx->sector_size;
DWORD bytestoread = sects * ctx->sector_size;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);
if (sectsread)
    *sectsread = 0;
memset (&pos, 0, sizeof (pos));
while (bytestoread) {
    DWORD bytesread;
    DWORD sectorbytes;

    pos.Offset = (DWORD)addr;
    pos.OffsetHigh = (DWORD)(addr >> 32);
    if (!ReadFile ((HANDLE)(uptr->fileref), buf, bytestoread, &bytesread, &pos)) {
        if (ERROR_HANDLE_EOF == GetLastError ()) {  /* Return 0's for reads past EOF */
            memset (buf, 0, bytestoread);
            if (sectsread)
                *sectsread += bytestoread / ctx->sector_size;
            return SCPE_OK;
            }
        _set_errno_from_status (GetLastError ());
        return SCPE_IOERR;
        }
    sectorbytes = (bytesread / ctx->sector_size) * ctx->sector_size; 
    if (sectsread)
        *sectsread += sectorbytes / ctx->sector_size;
    bytestoread -= sectorbytes;
    if (bytestoread == 0)
        break;
    buf +=  sectorbytes;
    addr += sectorbytes;
    }
return SCPE_OK;
}

static t_stat sim_os_disk_read (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *bytesread, uint32 bytes)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_read(unit=%d, addr=0x%X, bytes=%u)\n", (int)(uptr - ctx->dptr->units), (uint32)addr, bytes);

memset (&pos, 0, sizeof (pos));
pos.Offset = (DWORD)addr;
pos.OffsetHigh = (DWORD)(addr >> 32);
if (ReadFile ((HANDLE)(uptr->fileref), buf, (DWORD)bytes, (LPDWORD)bytesread, &pos))
    return SCPE_OK;
if (ERROR_HANDLE_EOF == GetLastError ()) {  /* Return 0's for reads past EOF */
    memset (buf, 0, bytes);
    if (bytesread)
        *bytesread = bytes;
    return SCPE_OK;
    }
_set_errno_from_status (GetLastError ());
return SCPE_IOERR;
}

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
long long addr;
DWORD byteswritten;
DWORD bytestowrite = sects * ctx->sector_size;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

if (sectswritten)
    *sectswritten = 0;
addr = ((long long)lba) * ctx->sector_size;
memset (&pos, 0, sizeof (pos));
while (bytestowrite) {
    DWORD sectorbytes;

    pos.Offset = (DWORD)addr;
    pos.OffsetHigh = (DWORD)(addr >> 32);
    if (!WriteFile ((HANDLE)(uptr->fileref), buf, bytestowrite, &byteswritten, &pos)) {
        _set_errno_from_status (GetLastError ());
        return SCPE_IOERR;
        }
    if (sectswritten)
        *sectswritten += byteswritten / ctx->sector_size;
    sectorbytes = (byteswritten / ctx->sector_size) * ctx->sector_size;
    bytestowrite -= sectorbytes;
    if (bytestowrite == 0)
        break;
    buf += sectorbytes;
    addr += sectorbytes;
    }
return SCPE_OK;
}

static t_stat sim_os_disk_write (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *byteswritten, uint32 bytes)
{
OVERLAPPED pos;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_write(unit=%d, lba=0x%X, bytes=%u)\n", (int)(uptr - ctx->dptr->units), (uint32)addr, bytes);

memset (&pos, 0, sizeof (pos));
pos.Offset = (DWORD)addr;
pos.OffsetHigh = (DWORD)(addr >> 32);
if (WriteFile ((HANDLE)(uptr->fileref), buf, bytes, (LPDWORD)byteswritten, &pos))
    return SCPE_OK;
_set_errno_from_status (GetLastError ());
return SCPE_IOERR;
}

#elif defined (__linux) || defined (__linux__) || defined (__APPLE__)|| defined (__sun) || defined (__sun__) || defined (__hpux) || defined (_AIX)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#if defined(HAVE_SYS_IOCTL)
#include <sys/ioctl.h>
2700
2701
2702
2703
2704
2705
2706
2707
2708

2709
2710
2711




2712
2713
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
#endif
return TRUE;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
off_t addr;
ssize_t bytesread;


sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);





addr = ((off_t)lba) * ctx->sector_size;
bytesread = pread((int)((long)uptr->fileref), buf, sects * ctx->sector_size, addr);
if (bytesread < 0) {







    if (sectsread)




















        *sectsread = 0;
    return SCPE_IOERR;
    }
if (sectsread)
    *sectsread = bytesread / ctx->sector_size;
return SCPE_OK;
}

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
off_t addr;
ssize_t byteswritten;


sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr-ctx->dptr->units), lba, sects);





addr = ((off_t)lba) * ctx->sector_size;
byteswritten = pwrite((int)((long)uptr->fileref), buf, sects * ctx->sector_size, addr);
if (byteswritten < 0) {


    if (sectswritten)
        *sectswritten = 0;







    return SCPE_IOERR;
    }








if (sectswritten)





    *sectswritten = byteswritten / ctx->sector_size;
return SCPE_OK;
}

static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
if (sector_size) {
#if defined(BLKSSZGET)







|

>

|

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

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


|
|






|

>

|

>
>
>
>
|
|
|
>
>

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







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
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
#endif
return TRUE;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
off_t addr = ((off_t)lba) * ctx->sector_size;
ssize_t bytesread;
size_t bytestoread = sects * ctx->sector_size;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_rdsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

if (sectsread)
    *sectsread = 0;
while (bytestoread) {
    size_t sectorbytes;

    bytesread = pread((int)((long)uptr->fileref), buf, bytestoread, addr);
    if (bytesread < 0) {
        return SCPE_IOERR;
        }
    if (bytesread == 0) {   /* read zeros at/past EOF */
        bytesread = bytestoread;
        memset (buf, 0, bytesread);
        }
    sectorbytes = (bytesread / ctx->sector_size) * ctx->sector_size;
    if (sectsread)
        *sectsread += sectorbytes / ctx->sector_size;
    bytestoread -= sectorbytes;
    if (bytestoread == 0)
        break;
    buf += sectorbytes;
    addr += sectorbytes;
    }
return SCPE_OK;
}

static t_stat sim_os_disk_read (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *rbytesread, uint32 bytes)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
ssize_t bytesread;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_read(unit=%d, addr=0x%X, bytes=%u)\n", (int)(uptr - ctx->dptr->units), (uint32)addr, bytes);

bytesread = pread((int)((long)uptr->fileref), buf, bytes, (off_t)addr);
if (bytesread < 0) {
    if (rbytesread)
        *rbytesread = 0;
    return SCPE_IOERR;
    }
if (rbytesread)
    *rbytesread = bytesread;
return SCPE_OK;
}

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
off_t addr = ((off_t)lba) * ctx->sector_size;
ssize_t byteswritten;
size_t bytestowrite = sects * ctx->sector_size;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_wrsect(unit=%d, lba=0x%X, sects=%d)\n", (int)(uptr - ctx->dptr->units), lba, sects);

if (sectswritten)
    *sectswritten = 0;
while (bytestowrite) {
    size_t sectorbytes;

    byteswritten = pwrite((int)((long)uptr->fileref), buf, bytestowrite, addr);
    if (byteswritten < 0) {
        return SCPE_IOERR;
        }
    if (sectswritten)
        *sectswritten += byteswritten / ctx->sector_size;
    sectorbytes = (byteswritten / ctx->sector_size) * ctx->sector_size;
    bytestowrite -= sectorbytes;
    if (bytestowrite == 0)
        break;
    buf += sectorbytes;
    addr += sectorbytes;
    }
return SCPE_OK;
}

static t_stat sim_os_disk_write (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *rbyteswritten, uint32 bytes)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
ssize_t byteswritten;

sim_debug_unit (ctx->dbit, uptr, "sim_os_disk_write(unit=%d, addr=0x%X, bytes=%u)\n", (int)(uptr - ctx->dptr->units), (uint32)addr, bytes);

if (rbyteswritten)
    *rbyteswritten = 0;
byteswritten = pwrite((int)((long)uptr->fileref), buf, bytes, (off_t)addr);
if (byteswritten < 0)
    return SCPE_IOERR;
if (rbyteswritten)
    *rbyteswritten = byteswritten;
return SCPE_OK;
}

static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
if (sector_size) {
#if defined(BLKSSZGET)
2810
2811
2812
2813
2814
2815
2816





2817
2818
2819





2820
2821
2822
2823
2824
2825
2826
return FALSE;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
return SCPE_NOFNC;
}






static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{





return SCPE_NOFNC;
}

static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
return SCPE_NOFNC;
}







>
>
>
>
>



>
>
>
>
>







3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
return FALSE;
}

static t_stat sim_os_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
return SCPE_NOFNC;
}

static t_stat sim_os_disk_read (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *bytesread, uint32 bytes)
{
return SCPE_NOFNC;
}

static t_stat sim_os_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
return SCPE_NOFNC;
}

static t_stat sim_os_disk_write (UNIT *uptr, t_offset addr, uint8 *buf, uint32 *byteswritten, uint32 bytes)
{
return SCPE_NOFNC;
}

static t_stat sim_os_disk_info_raw (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
return SCPE_NOFNC;
}
2874
2875
2876
2877
2878
2879
2880





2881
2882
2883
2884
2885
2886
2887
{
}

static t_offset sim_vhd_disk_size (FILE *f)
{
return (t_offset)-1;
}






static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
return SCPE_IOERR;
}

static t_stat sim_vhd_disk_clearerr (UNIT *uptr)







>
>
>
>
>







4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
{
}

static t_offset sim_vhd_disk_size (FILE *f)
{
return (t_offset)-1;
}

static t_stat sim_vhd_disk_info (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
return SCPE_NOFNC;
}

static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
return SCPE_IOERR;
}

static t_stat sim_vhd_disk_clearerr (UNIT *uptr)
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
}

static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype)
{
return SCPE_NOFNC;
}

static const char *sim_vhd_disk_get_dtype (FILE *f)
{
return NULL;
}

#else

/*++







|







4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
}

static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype)
{
return SCPE_NOFNC;
}

static const char *sim_vhd_disk_get_dtype (FILE *f, uint32 *SectorSize, uint32 *xfer_element_size, char sim_name[64])
{
return NULL;
}

#else

/*++
3066
3067
3068
3069
3070
3071
3072



3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
    */
    uint8 Reserved1[11];
    /*
    This field is an extension to the VHD spec and includes a simh drive type
    name as a nul terminated string.
    */
    uint8 DriveType[16];



    /*
    This field contains zeroes. It is 400 bytes in size.
    */
    uint8 Reserved[400];
    } VHD_Footer;

/*
For dynamic and differencing disk images, the "Data Offset" field within
the image footer points to a secondary structure that provides additional
information about the disk image. The dynamic disk header should appear on
a sector (512-byte) boundary.







>
>
>

|

|







4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
    */
    uint8 Reserved1[11];
    /*
    This field is an extension to the VHD spec and includes a simh drive type
    name as a nul terminated string.
    */
    uint8 DriveType[16];
    uint32 DriveSectorSize;
    uint32 DriveTransferElementSize;
    uint8 CreatingSimulator[64];
    /*
    This field contains zeroes. It is 328 bytes in size.
    */
    uint8 Reserved[328];
    } VHD_Footer;

/*
For dynamic and differencing disk images, the "Data Offset" field within
the image footer points to a secondary structure that provides additional
information about the disk image. The dynamic disk header should appear on
a sector (512-byte) boundary.
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229

3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245

3246
3247
3248
3249
3250
3251
3252
#define VHD_BAT_FREE_ENTRY (0xFFFFFFFF)
#define VHD_DATA_BLOCK_ALIGNMENT ((uint64)4096)    /* Optimum when underlying storage has 4k sectors */

#define VHD_DT_Fixed                 2  /* Fixed hard disk */
#define VHD_DT_Dynamic               3  /* Dynamic hard disk */
#define VHD_DT_Differencing          4  /* Differencing hard disk */

static uint32 NtoHl(uint32 value);

static uint64 NtoHll(uint64 value);

typedef struct VHD_IOData *VHDHANDLE;

static t_stat ReadFilePosition(FILE *File, void *buf, size_t bufsize, size_t *bytesread, uint64 position)
{
uint32 err = sim_fseeko (File, (t_offset)position, SEEK_SET);
size_t i;

if (bytesread)
    *bytesread = 0;
if (!err) {
    i = fread (buf, 1, bufsize, File);
    err = ferror (File);
    if ((!err) && bytesread)
        *bytesread = i;

    }
return (err ? SCPE_IOERR : SCPE_OK);
}

static t_stat WriteFilePosition(FILE *File, void *buf, size_t bufsize, size_t *byteswritten, uint64 position)
{
uint32 err = sim_fseeko (File, (t_offset)position, SEEK_SET);
size_t i;

if (byteswritten)
    *byteswritten = 0;
if (!err) {
    i = fwrite (buf, 1, bufsize, File);
    err = ferror (File);
    if ((!err) && byteswritten)
        *byteswritten = i;

    }
return (err ? SCPE_IOERR : SCPE_OK);
}

static uint32
CalculateVhdFooterChecksum(void *data,
                           size_t size)







<
|
<












<
|

>













<
|

>







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
#define VHD_BAT_FREE_ENTRY (0xFFFFFFFF)
#define VHD_DATA_BLOCK_ALIGNMENT ((uint64)4096)    /* Optimum when underlying storage has 4k sectors */

#define VHD_DT_Fixed                 2  /* Fixed hard disk */
#define VHD_DT_Dynamic               3  /* Dynamic hard disk */
#define VHD_DT_Differencing          4  /* Differencing hard disk */


#define VHD_Internal_SectorSize     512


typedef struct VHD_IOData *VHDHANDLE;

static t_stat ReadFilePosition(FILE *File, void *buf, size_t bufsize, size_t *bytesread, uint64 position)
{
uint32 err = sim_fseeko (File, (t_offset)position, SEEK_SET);
size_t i;

if (bytesread)
    *bytesread = 0;
if (!err) {
    i = fread (buf, 1, bufsize, File);

    if (bytesread)
        *bytesread = i;
    err = ferror (File);
    }
return (err ? SCPE_IOERR : SCPE_OK);
}

static t_stat WriteFilePosition(FILE *File, void *buf, size_t bufsize, size_t *byteswritten, uint64 position)
{
uint32 err = sim_fseeko (File, (t_offset)position, SEEK_SET);
size_t i;

if (byteswritten)
    *byteswritten = 0;
if (!err) {
    i = fwrite (buf, 1, bufsize, File);

    if (byteswritten)
        *byteswritten = i;
    err = ferror (File);
    }
return (err ? SCPE_IOERR : SCPE_OK);
}

static uint32
CalculateVhdFooterChecksum(void *data,
                           size_t size)
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
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#endif
#endif
#ifndef __BYTE_ORDER__
#define __BYTE_ORDER__ UNKNOWN
#endif
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static uint32
NtoHl(uint32 value)
{
uint8 *l = (uint8 *)&value;
return (uint32)l[3] | ((uint32)l[2]<<8) | ((uint32)l[1]<<16) | ((uint32)l[0]<<24);
}

static uint64
NtoHll(uint64 value)
{
uint8 *l = (uint8 *)&value;
uint64 highresult = (uint64)l[3] | ((uint64)l[2]<<8) | ((uint64)l[1]<<16) | ((uint64)l[0]<<24);
uint32 lowresult = (uint64)l[7] | ((uint64)l[6]<<8) | ((uint64)l[5]<<16) | ((uint64)l[4]<<24);
return (highresult << 32) | lowresult;
}
#elif  __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
static uint32
NtoHl(uint32 value)
{
return value;
}

static uint64
NtoHll(uint64 value)
{
return value;
}
#else
static uint32







<
<
<
<
<
<
<









<
<
<
<
<
<







4448
4449
4450
4451
4452
4453
4454







4455
4456
4457
4458
4459
4460
4461
4462
4463






4464
4465
4466
4467
4468
4469
4470
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#endif
#endif
#ifndef __BYTE_ORDER__
#define __BYTE_ORDER__ UNKNOWN
#endif
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__







static uint64
NtoHll(uint64 value)
{
uint8 *l = (uint8 *)&value;
uint64 highresult = (uint64)l[3] | ((uint64)l[2]<<8) | ((uint64)l[1]<<16) | ((uint64)l[0]<<24);
uint32 lowresult = (uint64)l[7] | ((uint64)l[6]<<8) | ((uint64)l[5]<<16) | ((uint64)l[4]<<24);
return (highresult << 32) | lowresult;
}
#elif  __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__






static uint64
NtoHll(uint64 value)
{
return value;
}
#else
static uint32
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
    sum = CalculateVhdFooterChecksum (sDynamic, sizeof(*sDynamic));
    sDynamic->Checksum = NtoHl (saved_sum);
    if ((sum != saved_sum) || (memcmp ("cxsparse", sDynamic->Cookie, sizeof (sDynamic->Cookie)))) {
        Return = errno;
        goto Return_Cleanup;
        }
    if (aBAT) {
        *aBAT = (uint32*) malloc(512*((sizeof(**aBAT)*NtoHl(sDynamic->MaxTableEntries)+511)/512));
        if (ReadFilePosition(File,
                             *aBAT,
                             sizeof (**aBAT)*NtoHl(sDynamic->MaxTableEntries),
                             NULL,
                             NtoHll (sDynamic->TableOffset))) {
            Return = EINVAL;                            /* File Corrupt */
            goto Return_Cleanup;
            }
        }
    if (szParentVHDPath && ParentVHDPathSize) {







|


|







4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
    sum = CalculateVhdFooterChecksum (sDynamic, sizeof(*sDynamic));
    sDynamic->Checksum = NtoHl (saved_sum);
    if ((sum != saved_sum) || (memcmp ("cxsparse", sDynamic->Cookie, sizeof (sDynamic->Cookie)))) {
        Return = errno;
        goto Return_Cleanup;
        }
    if (aBAT) {
        *aBAT = (uint32*) calloc(1, VHD_Internal_SectorSize * ((sizeof(**aBAT) * NtoHl(sDynamic->MaxTableEntries) + VHD_Internal_SectorSize - 1) / VHD_Internal_SectorSize));
        if (ReadFilePosition(File,
                             *aBAT,
                             sizeof (**aBAT) * NtoHl(sDynamic->MaxTableEntries),
                             NULL,
                             NtoHll (sDynamic->TableOffset))) {
            Return = EINVAL;                            /* File Corrupt */
            goto Return_Cleanup;
            }
        }
    if (szParentVHDPath && ParentVHDPathSize) {
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552



3553
3554
3555
3556
3557
3558
3559
    };

static t_stat sim_vhd_disk_implemented (void)
{
return SCPE_OK;
}

static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype)
{
VHDHANDLE hVHD  = (VHDHANDLE)f;
int Status = 0;

memset (hVHD->Footer.DriveType, '\0', sizeof hVHD->Footer.DriveType);
memcpy (hVHD->Footer.DriveType, dtype, ((1+strlen (dtype)) < sizeof (hVHD->Footer.DriveType)) ? (1+strlen (dtype)) : sizeof (hVHD->Footer.DriveType));



hVHD->Footer.Checksum = 0;
hVHD->Footer.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Footer, sizeof(hVHD->Footer)));

if (NtoHl (hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (WriteFilePosition(hVHD->File,
                          &hVHD->Footer,
                          sizeof(hVHD->Footer),







|






>
>
>







4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
    };

static t_stat sim_vhd_disk_implemented (void)
{
return SCPE_OK;
}

static t_stat sim_vhd_disk_set_dtype (FILE *f, const char *dtype, uint32 SectorSize, uint32 xfer_element_size)
{
VHDHANDLE hVHD  = (VHDHANDLE)f;
int Status = 0;

memset (hVHD->Footer.DriveType, '\0', sizeof hVHD->Footer.DriveType);
memcpy (hVHD->Footer.DriveType, dtype, ((1+strlen (dtype)) < sizeof (hVHD->Footer.DriveType)) ? (1+strlen (dtype)) : sizeof (hVHD->Footer.DriveType));
hVHD->Footer.DriveSectorSize = NtoHl (SectorSize);
hVHD->Footer.DriveTransferElementSize = NtoHl (xfer_element_size);
strncpy ((char *)hVHD->Footer.CreatingSimulator, sim_name, sizeof (hVHD->Footer.CreatingSimulator) - 1);
hVHD->Footer.Checksum = 0;
hVHD->Footer.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Footer, sizeof(hVHD->Footer)));

if (NtoHl (hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (WriteFilePosition(hVHD->File,
                          &hVHD->Footer,
                          sizeof(hVHD->Footer),
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601






3602
3603
3604
3605
3606
3607
3608
    }
Cleanup_Return:
if (Status)
    return SCPE_IOERR;
return SCPE_OK;
}

static const char *sim_vhd_disk_get_dtype (FILE *f)
{
VHDHANDLE hVHD  = (VHDHANDLE)f;







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;







|



>
>
>
>
>
>







4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
    }
Cleanup_Return:
if (Status)
    return SCPE_IOERR;
return SCPE_OK;
}

static const char *sim_vhd_disk_get_dtype (FILE *f, uint32 *SectorSize, uint32 *xfer_element_size, char sim_name[64])
{
VHDHANDLE hVHD  = (VHDHANDLE)f;

if (SectorSize)
    *SectorSize = NtoHl (hVHD->Footer.DriveSectorSize);
if (xfer_element_size)
    *xfer_element_size = NtoHl (hVHD->Footer.DriveTransferElementSize);
if (sim_name)
    memcpy (sim_name, hVHD->Footer.CreatingSimulator, 64);
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;
3833
3834
3835
3836
3837
3838
3839












3840
3841
3842
3843
3844
3845
3846

static t_offset sim_vhd_disk_size (FILE *f)
{
VHDHANDLE hVHD = (VHDHANDLE)f;

return (t_offset)(NtoHll (hVHD->Footer.CurrentSize));
}













#include <stdlib.h>
#include <time.h>
static void
_rand_uuid_gen (void *uuidaddr)
{
int i;







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







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

static t_offset sim_vhd_disk_size (FILE *f)
{
VHDHANDLE hVHD = (VHDHANDLE)f;

return (t_offset)(NtoHll (hVHD->Footer.CurrentSize));
}

static t_stat sim_vhd_disk_info (FILE *f, uint32 *sector_size, uint32 *removable, uint32 *is_cdrom)
{
if (sector_size)
    *sector_size = 512;
if (removable)
    *removable = FALSE;
if (is_cdrom)
    *is_cdrom = FALSE;
return SCPE_OK;
}


#include <stdlib.h>
#include <time.h>
static void
_rand_uuid_gen (void *uuidaddr)
{
int i;
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
VHD_DynamicDiskHeader Dynamic;
uint32 *BAT = NULL;
time_t now;
uint32 i;
FILE *File = NULL;
uint32 Status = 0;
uint32 BytesPerSector = 512;
uint64 SizeInBytes = ((uint64)SizeInSectors)*BytesPerSector;
uint64 TableOffset;
uint32 MaxTableEntries;
VHDHANDLE hVHD = NULL;

if (SizeInBytes > ((uint64)(1024*1024*1024))*2040) {
    Status = EFBIG;
    goto Cleanup_Return;
    }
File = sim_fopen (szVHDPath, "rb");
if (File) {
    fclose (File);
    File = NULL;







|




|







5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
VHD_DynamicDiskHeader Dynamic;
uint32 *BAT = NULL;
time_t now;
uint32 i;
FILE *File = NULL;
uint32 Status = 0;
uint32 BytesPerSector = 512;
uint64 SizeInBytes = ((uint64)SizeInSectors) * BytesPerSector;
uint64 TableOffset;
uint32 MaxTableEntries;
VHDHANDLE hVHD = NULL;

if (SizeInBytes > ((uint64)(1024 * 1024 * 1024)) * 2040) {
    Status = EFBIG;
    goto Cleanup_Return;
    }
File = sim_fopen (szVHDPath, "rb");
if (File) {
    fclose (File);
    File = NULL;
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953

memset (&Footer, 0, sizeof(Footer));
memcpy (Footer.Cookie, "conectix", 8);
Footer.Features = NtoHl (0x00000002);;
Footer.FileFormatVersion = NtoHl (0x00010000);;
Footer.DataOffset = NtoHll (bFixedVHD ? ((long long)-1) : (long long)(sizeof(Footer)));
time (&now);
Footer.TimeStamp = NtoHl ((uint32)(now-946684800));
memcpy (Footer.CreatorApplication, "simh", 4);
Footer.CreatorVersion = NtoHl (0x00040000);
memcpy (Footer.CreatorHostOS, "Wi2k", 4);
Footer.OriginalSize = NtoHll (SizeInBytes);
Footer.CurrentSize = NtoHll (SizeInBytes);
uuid_gen (Footer.UniqueID);
Footer.DiskType = NtoHl (bFixedVHD ? VHD_DT_Fixed : VHD_DT_Dynamic);







|







5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145

memset (&Footer, 0, sizeof(Footer));
memcpy (Footer.Cookie, "conectix", 8);
Footer.Features = NtoHl (0x00000002);;
Footer.FileFormatVersion = NtoHl (0x00010000);;
Footer.DataOffset = NtoHll (bFixedVHD ? ((long long)-1) : (long long)(sizeof(Footer)));
time (&now);
Footer.TimeStamp = NtoHl ((uint32)(now - 946684800));
memcpy (Footer.CreatorApplication, "simh", 4);
Footer.CreatorVersion = NtoHl (0x00040000);
memcpy (Footer.CreatorHostOS, "Wi2k", 4);
Footer.OriginalSize = NtoHll (SizeInBytes);
Footer.CurrentSize = NtoHll (SizeInBytes);
uuid_gen (Footer.UniqueID);
Footer.DiskType = NtoHl (bFixedVHD ? VHD_DT_Fixed : VHD_DT_Dynamic);
4260
4261
4262
4263
4264
4265
4266


4267
4268
4269
4270
4271
4272
4273
    }
hVHD->Dynamic.TableOffset = NtoHll (((LocatorPosition+LocatorsWritten*BytesPerSector + VHD_DATA_BLOCK_ALIGNMENT - 1)/VHD_DATA_BLOCK_ALIGNMENT)*VHD_DATA_BLOCK_ALIGNMENT);
hVHD->Dynamic.Checksum = 0;
hVHD->Dynamic.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Dynamic, sizeof(hVHD->Dynamic)));
hVHD->Footer.Checksum = 0;
hVHD->Footer.DiskType = NtoHl (VHD_DT_Differencing);
memcpy (hVHD->Footer.DriveType, ParentFooter.DriveType, sizeof (hVHD->Footer.DriveType));


hVHD->Footer.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Footer, sizeof(hVHD->Footer)));

if (WriteFilePosition (hVHD->File,
                       &hVHD->Footer,
                       sizeof (hVHD->Footer),
                       NULL,
                       0)) {







>
>







5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
    }
hVHD->Dynamic.TableOffset = NtoHll (((LocatorPosition+LocatorsWritten*BytesPerSector + VHD_DATA_BLOCK_ALIGNMENT - 1)/VHD_DATA_BLOCK_ALIGNMENT)*VHD_DATA_BLOCK_ALIGNMENT);
hVHD->Dynamic.Checksum = 0;
hVHD->Dynamic.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Dynamic, sizeof(hVHD->Dynamic)));
hVHD->Footer.Checksum = 0;
hVHD->Footer.DiskType = NtoHl (VHD_DT_Differencing);
memcpy (hVHD->Footer.DriveType, ParentFooter.DriveType, sizeof (hVHD->Footer.DriveType));
hVHD->Footer.DriveSectorSize = ParentFooter.DriveSectorSize;
hVHD->Footer.DriveTransferElementSize = ParentFooter.DriveTransferElementSize;
hVHD->Footer.Checksum = NtoHl (CalculateVhdFooterChecksum (&hVHD->Footer, sizeof(hVHD->Footer)));

if (WriteFilePosition (hVHD->File,
                       &hVHD->Footer,
                       sizeof (hVHD->Footer),
                       NULL,
                       0)) {
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
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
                       uint8 *buf,
                       t_seccnt sects,
                       t_seccnt *sectsread,
                       uint32 SectorSize,
                       t_lba lba)
{
uint64 BlockOffset = ((uint64)lba)*SectorSize;
uint32 BlocksRead = 0;
uint32 SectorsInRead;
size_t BytesRead = 0;

if (!hVHD || (hVHD->File == NULL)) {
    errno = EBADF;
    return SCPE_IOERR;
    }
if ((BlockOffset + sects*SectorSize) > (uint64)NtoHll (hVHD->Footer.CurrentSize)) {
    errno = ERANGE;
    return SCPE_IOERR;
    }


if (NtoHl (hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (ReadFilePosition(hVHD->File,
                         buf,
                         sects*SectorSize,
                         &BytesRead,
                         BlockOffset)) {
        if (sectsread)
            *sectsread = (t_seccnt)(BytesRead/SectorSize);
        return SCPE_IOERR;
        }
    if (sectsread)
        *sectsread /= SectorSize;
    return SCPE_OK;
    }
/* We are now dealing with a Dynamically expanding or differencing disk */
while (sects) {
    uint32 SectorsPerBlock = NtoHl (hVHD->Dynamic.BlockSize)/SectorSize;
    uint64 BlockNumber = lba/SectorsPerBlock;
    uint32 BitMapBytes = (7+(NtoHl (hVHD->Dynamic.BlockSize)/SectorSize))/8;
    uint32 BitMapSectors = (BitMapBytes+SectorSize-1)/SectorSize;

    SectorsInRead = SectorsPerBlock - lba%SectorsPerBlock;
    if (SectorsInRead > sects)
        SectorsInRead = sects;
    if (hVHD->BAT[BlockNumber] == VHD_BAT_FREE_ENTRY) {
        if (!hVHD->Parent)
            memset (buf, 0, SectorSize*SectorsInRead);
        else {
            if (ReadVirtualDiskSectors(hVHD->Parent,
                                       buf,
                                       SectorsInRead,
                                       NULL,
                                       SectorSize,
                                       lba)) {
                if (sectsread)
                    *sectsread = BlocksRead;
                return FALSE;
                }
            }
        }
    else {
        BlockOffset = SectorSize*((uint64)(NtoHl (hVHD->BAT[BlockNumber]) + lba%SectorsPerBlock + BitMapSectors));
        if (ReadFilePosition(hVHD->File,
                             buf,
                             SectorsInRead*SectorSize,
                             NULL,
                             BlockOffset)) {
            if (sectsread)
                *sectsread = BlocksRead;
            return SCPE_IOERR;
            }
        }
    sects -= SectorsInRead;
    buf = (uint8 *)(((char *)buf) + SectorSize*SectorsInRead);
    lba += SectorsInRead;
    BlocksRead += SectorsInRead;
    }
if (sectsread)
    *sectsread = BlocksRead;
return SCPE_OK;
}

static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
VHDHANDLE hVHD = (VHDHANDLE)uptr->fileref;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;







|











>
>











|






|
|















|




|
|


|



|




|

|


|







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
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
                       uint8 *buf,
                       t_seccnt sects,
                       t_seccnt *sectsread,
                       uint32 SectorSize,
                       t_lba lba)
{
uint64 BlockOffset = ((uint64)lba)*SectorSize;
uint32 SectorsRead = 0;
uint32 SectorsInRead;
size_t BytesRead = 0;

if (!hVHD || (hVHD->File == NULL)) {
    errno = EBADF;
    return SCPE_IOERR;
    }
if ((BlockOffset + sects*SectorSize) > (uint64)NtoHll (hVHD->Footer.CurrentSize)) {
    errno = ERANGE;
    return SCPE_IOERR;
    }
if (sectsread)
    *sectsread = 0;
if (NtoHl (hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (ReadFilePosition(hVHD->File,
                         buf,
                         sects*SectorSize,
                         &BytesRead,
                         BlockOffset)) {
        if (sectsread)
            *sectsread = (t_seccnt)(BytesRead/SectorSize);
        return SCPE_IOERR;
        }
    if (sectsread)
        *sectsread = (t_seccnt)(BytesRead/SectorSize);
    return SCPE_OK;
    }
/* We are now dealing with a Dynamically expanding or differencing disk */
while (sects) {
    uint32 SectorsPerBlock = NtoHl (hVHD->Dynamic.BlockSize)/SectorSize;
    uint64 BlockNumber = lba/SectorsPerBlock;
    uint32 BitMapBytes = (7+(NtoHl (hVHD->Dynamic.BlockSize)/VHD_Internal_SectorSize))/8;
    uint32 BitMapSectors = (BitMapBytes+VHD_Internal_SectorSize-1)/VHD_Internal_SectorSize;

    SectorsInRead = SectorsPerBlock - lba%SectorsPerBlock;
    if (SectorsInRead > sects)
        SectorsInRead = sects;
    if (hVHD->BAT[BlockNumber] == VHD_BAT_FREE_ENTRY) {
        if (!hVHD->Parent)
            memset (buf, 0, SectorSize*SectorsInRead);
        else {
            if (ReadVirtualDiskSectors(hVHD->Parent,
                                       buf,
                                       SectorsInRead,
                                       NULL,
                                       SectorSize,
                                       lba)) {
                if (sectsread)
                    *sectsread = SectorsRead;
                return FALSE;
                }
            }
        }
    else { 
        BlockOffset = VHD_Internal_SectorSize * ((uint64)(NtoHl (hVHD->BAT[BlockNumber]) + BitMapSectors))+ (SectorSize * (lba % SectorsPerBlock));
        if (ReadFilePosition(hVHD->File,
                             buf,
                             SectorsInRead * SectorSize,
                             NULL,
                             BlockOffset)) {
            if (sectsread)
                *sectsread = SectorsRead;
            return SCPE_IOERR;
            }
        }
    sects -= SectorsInRead;
    buf = (uint8 *)(((char *)buf) + SectorSize * SectorsInRead);
    lba += SectorsInRead;
    SectorsRead += SectorsInRead;
    }
if (sectsread)
    *sectsread = SectorsRead;
return SCPE_OK;
}

static t_stat sim_vhd_disk_rdsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectsread, t_seccnt sects)
{
VHDHANDLE hVHD = (VHDHANDLE)uptr->fileref;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
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
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
                        uint8 *buf,
                        t_seccnt sects,
                        t_seccnt *sectswritten,
                        uint32 SectorSize,
                        t_lba lba)
{
uint64 BlockOffset = ((uint64)lba)*SectorSize;
uint32 BlocksWritten = 0;
uint32 SectorsInWrite;
size_t BytesWritten = 0;

if (!hVHD || !hVHD->File) {
    errno = EBADF;
    return SCPE_IOERR;
    }
if ((BlockOffset + sects*SectorSize) > (uint64)NtoHll(hVHD->Footer.CurrentSize)) {
    errno = ERANGE;
    return SCPE_IOERR;
    }


if (NtoHl(hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (WriteFilePosition(hVHD->File,
                          buf,
                          sects*SectorSize,
                          &BytesWritten,
                          BlockOffset)) {
        if (sectswritten)
            *sectswritten = (t_seccnt)(BytesWritten/SectorSize);
        return SCPE_IOERR;
        }
    if (sectswritten)
        *sectswritten /= SectorSize;
    return SCPE_OK;
    }
/* We are now dealing with a Dynamically expanding or differencing disk */
while (sects) {
    uint32 SectorsPerBlock = NtoHl(hVHD->Dynamic.BlockSize)/SectorSize;
    uint64 BlockNumber = lba/SectorsPerBlock;
    uint32 BitMapBytes = (7+(NtoHl(hVHD->Dynamic.BlockSize)/SectorSize))/8;
    uint32 BitMapSectors = (BitMapBytes+SectorSize-1)/SectorSize;

    if (BlockNumber >= NtoHl(hVHD->Dynamic.MaxTableEntries)) {
        if (sectswritten)
            *sectswritten = BlocksWritten;
        return SCPE_EOF;
        }
    SectorsInWrite = 1;
    if (hVHD->BAT[BlockNumber] == VHD_BAT_FREE_ENTRY) {
        uint8 *BitMap = NULL;
        uint32 BitMapBufferSize = VHD_DATA_BLOCK_ALIGNMENT;
        uint8 *BitMapBuffer = NULL;
        void *BlockData = NULL;
        uint8 *BATUpdateBufferAddress;
        uint32 BATUpdateBufferSize;
        uint64 BATUpdateStorageAddress;

        if (!hVHD->Parent && BufferIsZeros(buf, SectorSize))
            goto IO_Done;
        /* Need to allocate a new Data Block. */
        BlockOffset = sim_fsize_ex (hVHD->File);
        if (((int64)BlockOffset) == -1)
            return SCPE_IOERR;
        if (BitMapSectors*SectorSize > BitMapBufferSize)
            BitMapBufferSize = BitMapSectors*SectorSize;
        BitMapBuffer = (uint8 *)calloc(1, BitMapBufferSize + SectorSize*SectorsPerBlock);
        if (BitMapBufferSize > BitMapSectors*SectorSize)
            BitMap = BitMapBuffer + BitMapBufferSize-BitMapBytes;
        else
            BitMap = BitMapBuffer;
        memset(BitMap, 0xFF, BitMapBytes);
        BlockOffset -= sizeof(hVHD->Footer);
        if (0 == (BlockOffset & ~(VHD_DATA_BLOCK_ALIGNMENT-1)))
            {  // Already aligned, so use padded BitMapBuffer
            if (WriteFilePosition(hVHD->File,
                                  BitMapBuffer,
                                  BitMapBufferSize + SectorSize*SectorsPerBlock,
                                  NULL,
                                  BlockOffset)) {
                free (BitMapBuffer);
                return SCPE_IOERR;
                }
            BlockOffset += BitMapBufferSize;
            }
        else
            {
            // align the data portion of the block to the desired alignment
            // compute the address of the data portion of the block
            BlockOffset += BitMapSectors*SectorSize;
            // round up this address to the desired alignment
            BlockOffset += VHD_DATA_BLOCK_ALIGNMENT-1;
            BlockOffset &= ~(VHD_DATA_BLOCK_ALIGNMENT-1);
            BlockOffset -= BitMapSectors*SectorSize;
            if (WriteFilePosition(hVHD->File,
                                  BitMap,
                                  SectorSize * (BitMapSectors + SectorsPerBlock),
                                  NULL,
                                  BlockOffset)) {
                free (BitMapBuffer);
                return SCPE_IOERR;
                }
            BlockOffset += BitMapSectors*SectorSize;
            }
        free(BitMapBuffer);
        BitMapBuffer = BitMap = NULL;
        /* the BAT block address is the beginning of the block bitmap */
        BlockOffset -= BitMapSectors*SectorSize;
        hVHD->BAT[BlockNumber] = NtoHl((uint32)(BlockOffset/SectorSize));
        BlockOffset += SectorSize * (SectorsPerBlock + BitMapSectors);
        if (WriteFilePosition(hVHD->File,
                              &hVHD->Footer,
                              sizeof(hVHD->Footer),
                              NULL,
                              BlockOffset))
            goto Fatal_IO_Error;
        /* Since a large VHD can have a pretty large BAT, and we've only changed one longword bat entry







|











>
>



|



|



|




|
|
|
|



|












|





|
|
|
|
|




|



|











|


|
|


|





|




|
|
|







5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
                        uint8 *buf,
                        t_seccnt sects,
                        t_seccnt *sectswritten,
                        uint32 SectorSize,
                        t_lba lba)
{
uint64 BlockOffset = ((uint64)lba)*SectorSize;
uint32 SectorsWritten = 0;
uint32 SectorsInWrite;
size_t BytesWritten = 0;

if (!hVHD || !hVHD->File) {
    errno = EBADF;
    return SCPE_IOERR;
    }
if ((BlockOffset + sects*SectorSize) > (uint64)NtoHll(hVHD->Footer.CurrentSize)) {
    errno = ERANGE;
    return SCPE_IOERR;
    }
if (sectswritten)
    *sectswritten = 0;
if (NtoHl(hVHD->Footer.DiskType) == VHD_DT_Fixed) {
    if (WriteFilePosition(hVHD->File,
                          buf,
                          sects * SectorSize,
                          &BytesWritten,
                          BlockOffset)) {
        if (sectswritten)
            *sectswritten = (t_seccnt)(BytesWritten / SectorSize);
        return SCPE_IOERR;
        }
    if (sectswritten)
        *sectswritten = (t_seccnt)(BytesWritten/SectorSize);
    return SCPE_OK;
    }
/* We are now dealing with a Dynamically expanding or differencing disk */
while (sects) {
    uint32 SectorsPerBlock = NtoHl(hVHD->Dynamic.BlockSize) / SectorSize;
    uint64 BlockNumber = lba / SectorsPerBlock;
    uint32 BitMapBytes = (7 + (NtoHl(hVHD->Dynamic.BlockSize) / VHD_Internal_SectorSize)) / 8;
    uint32 BitMapSectors = (BitMapBytes + VHD_Internal_SectorSize - 1) / VHD_Internal_SectorSize;

    if (BlockNumber >= NtoHl(hVHD->Dynamic.MaxTableEntries)) {
        if (sectswritten)
            *sectswritten = SectorsWritten;
        return SCPE_EOF;
        }
    SectorsInWrite = 1;
    if (hVHD->BAT[BlockNumber] == VHD_BAT_FREE_ENTRY) {
        uint8 *BitMap = NULL;
        uint32 BitMapBufferSize = VHD_DATA_BLOCK_ALIGNMENT;
        uint8 *BitMapBuffer = NULL;
        void *BlockData = NULL;
        uint8 *BATUpdateBufferAddress;
        uint32 BATUpdateBufferSize;
        uint64 BATUpdateStorageAddress;

        if (!hVHD->Parent && BufferIsZeros(buf, SectorsInWrite * SectorSize))
            goto IO_Done;
        /* Need to allocate a new Data Block. */
        BlockOffset = sim_fsize_ex (hVHD->File);
        if (((int64)BlockOffset) == -1)
            return SCPE_IOERR;
        if (BitMapSectors*VHD_Internal_SectorSize > BitMapBufferSize)
            BitMapBufferSize = BitMapSectors * VHD_Internal_SectorSize;
        BitMapBuffer = (uint8 *)calloc(1, BitMapBufferSize + SectorSize * SectorsPerBlock);
        if (BitMapBufferSize > BitMapSectors * VHD_Internal_SectorSize)
            BitMap = BitMapBuffer + BitMapBufferSize - BitMapBytes;
        else
            BitMap = BitMapBuffer;
        memset(BitMap, 0xFF, BitMapBytes);
        BlockOffset -= sizeof(hVHD->Footer);
        if (0 == (BlockOffset & (VHD_DATA_BLOCK_ALIGNMENT-1)))
            {  // Already aligned, so use padded BitMapBuffer
            if (WriteFilePosition(hVHD->File,
                                  BitMapBuffer,
                                  BitMapBufferSize + SectorSize * SectorsPerBlock,
                                  NULL,
                                  BlockOffset)) {
                free (BitMapBuffer);
                return SCPE_IOERR;
                }
            BlockOffset += BitMapBufferSize;
            }
        else
            {
            // align the data portion of the block to the desired alignment
            // compute the address of the data portion of the block
            BlockOffset += BitMapSectors * VHD_Internal_SectorSize;
            // round up this address to the desired alignment
            BlockOffset += VHD_DATA_BLOCK_ALIGNMENT-1;
            BlockOffset &= ~(VHD_DATA_BLOCK_ALIGNMENT - 1);
            BlockOffset -= BitMapSectors * VHD_Internal_SectorSize;
            if (WriteFilePosition(hVHD->File,
                                  BitMap,
                                  (BitMapSectors * VHD_Internal_SectorSize) + (SectorSize * SectorsPerBlock),
                                  NULL,
                                  BlockOffset)) {
                free (BitMapBuffer);
                return SCPE_IOERR;
                }
            BlockOffset += BitMapSectors * VHD_Internal_SectorSize;
            }
        free(BitMapBuffer);
        BitMapBuffer = BitMap = NULL;
        /* the BAT block address is the beginning of the block bitmap */
        BlockOffset -= BitMapSectors * VHD_Internal_SectorSize;
        hVHD->BAT[BlockNumber] = NtoHl((uint32)(BlockOffset / VHD_Internal_SectorSize));
        BlockOffset += (BitMapSectors * VHD_Internal_SectorSize) + (SectorSize * SectorsPerBlock);
        if (WriteFilePosition(hVHD->File,
                              &hVHD->Footer,
                              sizeof(hVHD->Footer),
                              NULL,
                              BlockOffset))
            goto Fatal_IO_Error;
        /* Since a large VHD can have a pretty large BAT, and we've only changed one longword bat entry
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
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
            BATUpdateStorageAddress = NtoHll(hVHD->Dynamic.TableOffset);
            }
        else {
            BATUpdateBufferSize = VHD_DATA_BLOCK_ALIGNMENT;
            BATUpdateStorageAddress = NtoHll(hVHD->Dynamic.TableOffset) + BATUpdateBufferAddress - ((uint8 *)hVHD->BAT);
            }
        /* If the total BAT is smaller than one VHD_DATA_BLOCK_ALIGNMENT, then be sure to only write out the BAT data */
        if ((size_t)(BATUpdateBufferAddress - (uint8 *)hVHD->BAT + BATUpdateBufferSize) > 512*((sizeof(*hVHD->BAT)*NtoHl(hVHD->Dynamic.MaxTableEntries) + 511)/512))
            BATUpdateBufferSize = (uint32)(512*((sizeof(*hVHD->BAT)*NtoHl(hVHD->Dynamic.MaxTableEntries) + 511)/512) - (BATUpdateBufferAddress - ((uint8 *)hVHD->BAT)));
        if (WriteFilePosition(hVHD->File,
                              BATUpdateBufferAddress,
                              BATUpdateBufferSize,
                              NULL,
                              BATUpdateStorageAddress))
            goto Fatal_IO_Error;
        if (hVHD->Parent)
            { /* Need to populate data block contents from parent VHD */
            uint32 BlockSectors = SectorsPerBlock;

            BlockData = malloc(SectorsPerBlock*SectorSize);

            if (((lba/SectorsPerBlock)*SectorsPerBlock + BlockSectors) > ((uint64)NtoHll (hVHD->Footer.CurrentSize))/SectorSize)
                BlockSectors = (uint32)(((uint64)NtoHll (hVHD->Footer.CurrentSize))/SectorSize - (lba/SectorsPerBlock)*SectorsPerBlock);
            if (ReadVirtualDiskSectors(hVHD->Parent,
                                       (uint8*) BlockData,
                                       BlockSectors,
                                       NULL,
                                       SectorSize,
                                       (lba/SectorsPerBlock)*SectorsPerBlock))
                goto Fatal_IO_Error;
            if (WriteVirtualDiskSectors(hVHD,
                                        (uint8*) BlockData,
                                        BlockSectors,
                                        NULL,
                                        SectorSize,
                                        (lba/SectorsPerBlock)*SectorsPerBlock))
                goto Fatal_IO_Error;
            free(BlockData);
            }
        continue;
Fatal_IO_Error:
        free (BitMap);
        free (BlockData);
        fclose (hVHD->File);
        hVHD->File = NULL;
        return SCPE_IOERR;
        }
    else {
        BlockOffset = 512*((uint64)(NtoHl(hVHD->BAT[BlockNumber]) + lba%SectorsPerBlock + BitMapSectors));
        SectorsInWrite = SectorsPerBlock - lba%SectorsPerBlock;
        if (SectorsInWrite > sects)
            SectorsInWrite = sects;
        if (WriteFilePosition(hVHD->File,
                              buf,
                              SectorsInWrite*SectorSize,
                              NULL,

                              BlockOffset)) {
            if (sectswritten)
                *sectswritten = BlocksWritten;
            return SCPE_IOERR;
            }
        }
IO_Done:
    sects -= SectorsInWrite;
    buf = (uint8 *)(((char *)buf) + SectorsInWrite*SectorSize);
    lba += SectorsInWrite;
    BlocksWritten += SectorsInWrite;
    }
if (sectswritten)
    *sectswritten = BlocksWritten;
return SCPE_OK;
}

static t_stat sim_vhd_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
VHDHANDLE hVHD = (VHDHANDLE)uptr->fileref;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

return WriteVirtualDiskSectors(hVHD, buf, sects, sectswritten, ctx->sector_size, lba);
}
#endif




























































































































t_stat sim_disk_test (DEVICE *dptr)
{







































return SCPE_OK;
}







|
|










|

|
|





|






|












|
|




|
<
>


|





|

|


|












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


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


5786
5787
5788
5789
5790
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
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
5850
5851
5852
5853
5854
5855
5856
5857
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
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
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
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
            BATUpdateStorageAddress = NtoHll(hVHD->Dynamic.TableOffset);
            }
        else {
            BATUpdateBufferSize = VHD_DATA_BLOCK_ALIGNMENT;
            BATUpdateStorageAddress = NtoHll(hVHD->Dynamic.TableOffset) + BATUpdateBufferAddress - ((uint8 *)hVHD->BAT);
            }
        /* If the total BAT is smaller than one VHD_DATA_BLOCK_ALIGNMENT, then be sure to only write out the BAT data */
        if ((size_t)(BATUpdateBufferAddress - (uint8 *)hVHD->BAT + BATUpdateBufferSize) > VHD_Internal_SectorSize * ((sizeof(*hVHD->BAT)*NtoHl(hVHD->Dynamic.MaxTableEntries) + VHD_Internal_SectorSize - 1)/VHD_Internal_SectorSize))
            BATUpdateBufferSize = (uint32)(VHD_Internal_SectorSize * ((sizeof(*hVHD->BAT) * NtoHl(hVHD->Dynamic.MaxTableEntries) + VHD_Internal_SectorSize - 1)/VHD_Internal_SectorSize) - (BATUpdateBufferAddress - ((uint8 *)hVHD->BAT)));
        if (WriteFilePosition(hVHD->File,
                              BATUpdateBufferAddress,
                              BATUpdateBufferSize,
                              NULL,
                              BATUpdateStorageAddress))
            goto Fatal_IO_Error;
        if (hVHD->Parent)
            { /* Need to populate data block contents from parent VHD */
            uint32 BlockSectors = SectorsPerBlock;

            BlockData = malloc(SectorsPerBlock * SectorSize);

            if (((lba / SectorsPerBlock) * SectorsPerBlock + BlockSectors) > ((uint64)NtoHll (hVHD->Footer.CurrentSize)) / SectorSize)
                BlockSectors = (uint32)(((uint64)NtoHll (hVHD->Footer.CurrentSize)) / SectorSize - (lba / SectorsPerBlock) * SectorsPerBlock);
            if (ReadVirtualDiskSectors(hVHD->Parent,
                                       (uint8*) BlockData,
                                       BlockSectors,
                                       NULL,
                                       SectorSize,
                                       (lba / SectorsPerBlock) * SectorsPerBlock))
                goto Fatal_IO_Error;
            if (WriteVirtualDiskSectors(hVHD,
                                        (uint8*) BlockData,
                                        BlockSectors,
                                        NULL,
                                        SectorSize,
                                        (lba / SectorsPerBlock) * SectorsPerBlock))
                goto Fatal_IO_Error;
            free(BlockData);
            }
        continue;
Fatal_IO_Error:
        free (BitMap);
        free (BlockData);
        fclose (hVHD->File);
        hVHD->File = NULL;
        return SCPE_IOERR;
        }
    else {
        BlockOffset = VHD_Internal_SectorSize * ((uint64)(NtoHl(hVHD->BAT[BlockNumber]) + BitMapSectors)) + (SectorSize * (lba % SectorsPerBlock));
        SectorsInWrite = SectorsPerBlock - lba % SectorsPerBlock;
        if (SectorsInWrite > sects)
            SectorsInWrite = sects;
        if (WriteFilePosition(hVHD->File,
                              buf,
                              SectorsInWrite * SectorSize,

                              &BytesWritten,
                              BlockOffset)) {
            if (sectswritten)
                *sectswritten = SectorsWritten + BytesWritten / SectorSize;
            return SCPE_IOERR;
            }
        }
IO_Done:
    sects -= SectorsInWrite;
    buf = (uint8 *)(((char *)buf) + SectorsInWrite * SectorSize);
    lba += SectorsInWrite;
    SectorsWritten += SectorsInWrite;
    }
if (sectswritten)
    *sectswritten = SectorsWritten;
return SCPE_OK;
}

static t_stat sim_vhd_disk_wrsect (UNIT *uptr, t_lba lba, uint8 *buf, t_seccnt *sectswritten, t_seccnt sects)
{
VHDHANDLE hVHD = (VHDHANDLE)uptr->fileref;
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;

return WriteVirtualDiskSectors(hVHD, buf, sects, sectswritten, ctx->sector_size, lba);
}
#endif

/* disk testing */

#include <setjmp.h>

struct disk_test_coverage {
    t_lba total_sectors;
    uint32 max_xfer_size;
    t_seccnt max_xfer_sectors;
    uint32 wsetbits;
    uint32 *wbitmap;
    uint32 *data;
    };

static t_stat sim_disk_test_exercise (UNIT *uptr)
{
struct disk_context *ctx = (struct disk_context *)uptr->disk_ctx;
struct disk_test_coverage *c = (struct disk_test_coverage *)calloc (1, sizeof (*c));
t_stat r = SCPE_OK;
uint32 uint32s_per_sector = (ctx->sector_size / sizeof (*c->data));
DEVICE *dptr = find_dev_from_unit (uptr);
uint32 capac_factor = ((dptr->dwidth / dptr->aincr) >= 32) ? 8 : ((dptr->dwidth / dptr->aincr) == 16) ? 2 : 1; /* capacity units (quadword: 8, word: 2, byte: 1) */
uint32 tries = 0;
t_bool unexpected_data = FALSE;

c->max_xfer_size = 1024*1024;
c->max_xfer_sectors = c->max_xfer_size / ctx->sector_size;
c->total_sectors = (t_lba)((uptr->capac*capac_factor)/(ctx->sector_size/((dptr->flags & DEV_SECTORS) ? ((ctx->sector_size >=  512) ? 512 : ctx->sector_size): 1)));
c->data = (uint32 *)malloc (c->max_xfer_size);
c->wbitmap = (uint32 *)calloc ((c->total_sectors + 32)/32, sizeof (*c->wbitmap));
#define BITMAP_IS_SET(n) (c->wbitmap[(n) >> 5] & (1 << ((n) & 0x1f)))
#define SET_BITMAP(n) c->wbitmap[(n) >> 5] |= (1 << ((n) & 0x1f))
/* Randomly populate the whole drive container with known data (sector # in each sector) */
srand (0);
while (c->wsetbits < c->total_sectors) {
    t_lba start_lba = (rand () % c->total_sectors);
    t_lba end_lba = start_lba + 1 + (rand () % (c->max_xfer_sectors - 1));
    t_lba lba;
    t_seccnt i, sectors_to_write, sectors_written;

    if (end_lba > c->total_sectors)
        end_lba = c->total_sectors;
    if (BITMAP_IS_SET(start_lba)) {
        ++tries;
        if (tries < 30)
            continue;
        while (BITMAP_IS_SET(start_lba))
            start_lba = (1 + start_lba) % c->total_sectors;
        end_lba = start_lba + 1;
        }
    tries = 0;
    for (lba = start_lba; lba < end_lba; lba++) {
        if (BITMAP_IS_SET(lba)) {
            end_lba = lba;
            break;
            }
        SET_BITMAP(lba);
        ++c->wsetbits;
        }
    sectors_to_write = end_lba - start_lba;
    for (i=0; i < sectors_to_write * uint32s_per_sector; i++)
        c->data[i] = start_lba + i / uint32s_per_sector;
    r = sim_disk_wrsect (uptr, start_lba, (uint8 *)c->data, &sectors_written, sectors_to_write);
    if (r != SCPE_OK) {
        sim_printf ("Error writing sectors %u thru %u: %s\n", start_lba, end_lba - 1, sim_error_text (r));
        break;
        }
    else {
        if (sectors_to_write != sectors_written) {
            sim_printf ("Unexpectedly wrote %u sectors instead of %u sectors starting at lba %u\n", sectors_written, sectors_to_write, start_lba);
            break;
            }
        }
    }
if (r == SCPE_OK) {
    t_seccnt sectors_read, sectors_to_read, sector_to_check;
    t_lba lba;

    sim_printf("Writing OK\n");
    for (lba = 0; (lba < c->total_sectors) && (r == SCPE_OK); lba += sectors_read) {
        sectors_to_read = 1 + (rand () % (c->max_xfer_sectors - 1));
        if (lba + sectors_to_read > c->total_sectors)
            sectors_to_read = c->total_sectors - lba;
        r = sim_disk_rdsect (uptr, lba, (uint8 *)c->data, &sectors_read, sectors_to_read);
        if (r == SCPE_OK) {
            if (sectors_read != sectors_to_read) {
                sim_printf ("Only returned %u sectors when reading %u sectors from lba %u\n", sectors_read, sectors_to_read, lba);
                r = SCPE_INCOMP;
                }
            }
        else
            sim_printf ("Error reading %u sectors at lba %u, %u read - %s\n", sectors_to_read, lba, sectors_read, sim_error_text (r));
        for (sector_to_check = 0; sector_to_check < sectors_read; ++sector_to_check) {
            uint32 i;

            for (i = 0; i < uint32s_per_sector; i++)
                if (c->data[i + sector_to_check * uint32s_per_sector] != (lba + sector_to_check)) {
                    sim_printf ("Sector %u(0x%X) has unexpected data at offset 0x%X: 0x%08X\n", 
                                lba + sector_to_check, lba + sector_to_check, i, c->data[i + sector_to_check * uint32s_per_sector]);
                    unexpected_data = TRUE;
                    break;
                    }
            }
        }
    if ((r == SCPE_OK) && !unexpected_data)
        sim_printf("Reading OK\n");
    else {
        sim_printf("Reading BAD\n");
        r = SCPE_IERR;
        }
    }
free (c->data);
free (c->wbitmap);
free (c);
if (r == SCPE_OK) {
    char *filename = strdup (uptr->filename);

    sim_disk_detach (uptr);
    (void)remove (filename);
    free (filename);
    }
return r;
}

t_stat sim_disk_test (DEVICE *dptr)
{
const char *fmt[] = {"VHD", "VHD", "SIMH", "RAW", NULL};
uint32 sect_size[] = {4096, 1024, 512, 256, 128, 64, 0};
uint32 xfr_size[] = {1, 2, 4, 8, 0};
int x, s, f;
UNIT *uptr = &dptr->units[0];
char filename[256];
t_stat r;
int32 saved_switches = sim_switches & ~SWMASK('T');
SIM_TEST_INIT;

for (x = 0; xfr_size[x] != 0; x++) {
    for (f = 0; fmt[f] != 0; f++) {
        for (s = 0; sect_size[s] != 0; s++) {
            snprintf (filename, sizeof (filename) - 1, "Test-%u-%u.%s", sect_size[s], xfr_size[x], fmt[f]);
            if ((f > 0) && (strcmp (fmt[f], "VHD") == 0) && (strcmp (fmt[f - 1], "VHD") == 0)) { /* Second VHD is Fixed */
                sim_switches |= SWMASK('X');
                snprintf (filename, sizeof (filename) - 1, "Test-%u-%u-Fixed.%s", sect_size[s], xfr_size[x], fmt[f]);
                }
            else
                sim_switches = saved_switches;
            (void)remove (filename);        /* Remove any prior remnants */
            r = sim_disk_set_fmt (uptr, 0, fmt[f], NULL);
            if (r != SCPE_OK)
                break;
            sim_printf ("Testing %s (%s) using %s\n", sim_uname (uptr), sprint_capac (dptr, uptr), filename);
            if (strcmp (fmt[f], "RAW") == 0) {
                /* There is no innate creation of RAW containers, so create the empty container using SIMH format */
                sim_disk_set_fmt (uptr, 0, "SIMH", NULL);
                sim_disk_attach_ex (uptr, filename, sect_size[s], xfr_size[x], TRUE, 0, NULL, 0, 0, NULL);
                sim_disk_detach (uptr);
                sim_disk_set_fmt (uptr, 0, fmt[f], NULL);
                }
            r = sim_disk_attach_ex (uptr, filename, sect_size[s], xfr_size[x], TRUE, 0, NULL, 0, 0, NULL);
            if (r != SCPE_OK)
                break;
            SIM_TEST(sim_disk_test_exercise (uptr));
            }
        }
    }
return SCPE_OK;
}

Changes to src/SIMH/sim_disk.h.

64
65
66
67
68
69
70
71



72














73
74
75
76
77
78
79

#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);







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







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

#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 dontchangecapac, 
                        uint32 debugbit, 
                        const char *drivetype, 
                        uint32 pdp11_tracksize, 
                        int completion_delay);
t_stat sim_disk_attach_ex (UNIT *uptr, 
                           const char *cptr, 
                           size_t sector_size, 
                           size_t xfer_element_size, 
                           t_bool dontchangecapac,      /* if false just change uptr->capac as needed */
                           uint32 dbit,                 /* debug bit */
                           const char *dtype,           /* drive type */
                           uint32 pdp11tracksize,       /* BAD144 track */
                           int completion_delay,        /* Minimum Delay for asynch I/O completion */
                           const char **drivetypes);    /* list of drive types (from smallest to largest) */
                                                        /* to try and fit the container/file system into */
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);

Changes to src/SIMH/sim_ether.c.

375
376
377
378
379
380
381

382
383
384
385
386
387
388
#include <unistd.h>
#endif

#define MAX(a,b) (((a) > (b)) ? (a) : (b))

/* 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)
{







>







375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#include <unistd.h>
#endif

#define MAX(a,b) (((a) > (b)) ? (a) : (b))

/* Internal routines - forward declarations */
static int _eth_get_system_id (char *buf, size_t buf_size);
static int _eth_devices (int max, ETH_LIST* dev);   /* get ethernet devices on host */

/*============================================================================*/
/*                  OS-independant ethernet routines                          */
/*============================================================================*/

t_stat eth_mac_scan (ETH_MAC* mac, const char* strmac)
{
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
  /* 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));
  strlcpy (state.sim, sim_name, sizeof(state.sim));
  getcwd (state.cwd, sizeof(state.cwd));
  if (uptr)
    strlcpy (state.uname, sim_uname (uptr), sizeof(state.uname));
  cptr = strchr (strmac, '>');
  if (cptr) {
    state.file[sizeof(state.file)-1] = '\0';
    strlcpy (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) {







|








|







414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
  /* 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));
  strlcpy (state.sim, sim_name, sizeof(state.sim));
  if (getcwd (state.cwd, sizeof(state.cwd))) {};
  if (uptr)
    strlcpy (state.uname, sim_uname (uptr), sizeof(state.uname));
  cptr = strchr (strmac, '>');
  if (cptr) {
    state.file[sizeof(state.file)-1] = '\0';
    strlcpy (state.file, cptr + 1, sizeof(state.file));
    if ((f = fopen (state.file, "r"))) {
      filebuf[sizeof(filebuf)-1] = '\0';
      if (fgets (filebuf, sizeof(filebuf)-1, f)) {};
      strmac = filebuf;
      fclose (f);
      strcpy (state.file, "");  /* avoid saving */
      }
    }
  cptr = strchr (strmac, '/');
  if (cptr) {
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
}

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);








|


|
















|







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
}

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);
}

static 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);

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
  /* 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)) &&
        (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)) &&







|



















|







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
  /* 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)) &&
        (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)) &&
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
  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;
}







<







747
748
749
750
751
752
753

754
755
756
757
758
759
760
  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;


#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;
}
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
#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);
}







<
|














<
<
<














<







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
#endif

t_stat eth_show (FILE* st, UNIT* uptr, int32 val, CONST void* desc)
{
  ETH_LIST  list[ETH_MAX_DEVICE];
  int number;


  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, CONST char *desc)
{
return eth_show (st, uptr, val, NULL);
}
958
959
960
961
962
963
964
965
966


967
968
969
970
971
972
973
  {return SCPE_NOFNC;}
t_stat eth_filter (ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                   ETH_BOOL all_multicast, ETH_BOOL promiscuous)
  {return SCPE_NOFNC;}
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;}
t_stat sim_ether_test (DEVICE *dptr)
  {return SCPE_OK;}
#else    /* endif unimplemented */







|

>
>







953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
  {return SCPE_NOFNC;}
t_stat eth_filter (ETH_DEV* dev, int addr_count, ETH_MAC* const addresses,
                   ETH_BOOL all_multicast, ETH_BOOL promiscuous)
  {return SCPE_NOFNC;}
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;}
const char *eth_version (void)
  {return NULL;}
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;}
t_stat sim_ether_test (DEVICE *dptr)
  {return SCPE_OK;}
#else    /* endif unimplemented */
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
/* 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
#define __STR(tok) __STR_QUOTE(tok)
                          "libpcap." __STR(HAVE_DLOPEN);
#endif
static const char* no_pcap = 

#if defined(_WIN32) || defined(__CYGWIN__)
                          "wpcap load failure";


#else
                          "libpcap load failure";
#endif



/* define pointers to pcap functions needed */
static void    (*p_pcap_close) (pcap_t *);
static int     (*p_pcap_compile) (pcap_t *, struct bpf_program *, const char *, int, bpf_u_int32);
static int     (*p_pcap_datalink) (pcap_t *);
static int     (*p_pcap_dispatch) (pcap_t *, int, pcap_handler, u_char *);
static int     (*p_pcap_findalldevs) (pcap_if_t **, char *);







>
>
>






<
<


|
>

|
>
>

|

>
>







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
/* 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 */

#define __STR_QUOTE(tok) #tok
#define __STR(tok) __STR_QUOTE(tok)
static const char* lib_name =
#if defined(_WIN32) || defined(__CYGWIN__)
                          "wpcap.dll";
#elif defined(__APPLE__)
                          "/usr/lib/libpcap.A.dylib";
#else


                          "libpcap." __STR(HAVE_DLOPEN);
#endif

static char no_pcap[PCAP_ERRBUF_SIZE] =
#if defined(_WIN32) || defined(__CYGWIN__)
    "wpcap.dll failed to load, install Npcap or WinPcap 4.1.3 to use pcap networking";
#elif defined(__APPLE__)
    "/usr/lib/libpcap.A.dylib failed to load, install libpcap to use pcap networking";
#else
    "libpcap." __STR(HAVE_DLOPEN) " failed to load, install libpcap to use pcap networking";
#endif
#undef __STR
#undef __STR_QUOTE

/* define pointers to pcap functions needed */
static void    (*p_pcap_close) (pcap_t *);
static int     (*p_pcap_compile) (pcap_t *, struct bpf_program *, const char *, int, bpf_u_int32);
static int     (*p_pcap_datalink) (pcap_t *);
static int     (*p_pcap_dispatch) (pcap_t *, int, pcap_handler, u_char *);
static int     (*p_pcap_findalldevs) (pcap_if_t **, char *);
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
          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\n", lib_name);
#ifdef _WIN32
        sim_printf ("Eth: You must install Npcap or WinPcap 4.x to use networking\n");
#else
        sim_printf ("Eth: You must install libpcap to use networking\n");
#endif
        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */
        lib_loaded = 1;
      }








<
<
<
<
<
<







1150
1151
1152
1153
1154
1155
1156






1157
1158
1159
1160
1161
1162
1163
          hLib = LoadLibraryA(lib_name);
        }
#else
      hLib = dlopen(lib_name, RTLD_NOW);
#endif
      if (hLib == 0) {
        /* failed to load DLL */






        lib_loaded = 2;
        break;
      } else {
        /* library loaded OK */
        lib_loaded = 1;
      }

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
#endif
      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_messagef (SCPE_OK, "%s\n", p_pcap_lib_version());
      }
      break;
    default:                /* loaded or failed */
      break;
  }
  return (lib_loaded == 1) ? 1 : 0;
}

/* define functions with dynamic revectoring */
void pcap_close(pcap_t* a) {
  if (a && (load_pcap() != 0)) {
    p_pcap_close(a);
  }
}

/* Some platforms's pcap.h have an ancient declaration of pcap_compile which doesn't have a const in the bpf string argument */
#if !defined (BPF_CONST_STRING)
int pcap_compile(pcap_t* a, struct bpf_program* b, char* c, int d, bpf_u_int32 e) {
#else
int pcap_compile(pcap_t* a, struct bpf_program* b, const char* c, int d, bpf_u_int32 e) {
#endif
  if (a && (load_pcap() != 0)) {
    return p_pcap_compile(a, b, c, d, e);
  } else {
    return 0;
  }
}


















int pcap_datalink(pcap_t* a) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_datalink(a);
  } else {
    return 0;
  }
}

int pcap_dispatch(pcap_t* a, int b, pcap_handler c, u_char* d) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_dispatch(a, b, c, d);
  } else {
    return 0;
  }
}

int pcap_findalldevs(pcap_if_t** a, char* b) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_findalldevs(a, b);
  } else {
    *a = 0;
    strcpy(b, no_pcap);

    return -1;
  }
}

void pcap_freealldevs(pcap_if_t* a) {
  if (a && (load_pcap() != 0)) {
    p_pcap_freealldevs(a);
  }
}

void pcap_freecode(struct bpf_program* a) {
  if (a && (load_pcap() != 0)) {
    p_pcap_freecode(a);
  }
}

char* pcap_geterr(pcap_t* a) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_geterr(a);
  } else {
    return (char*) "";
  }
}

int pcap_lookupnet(const char* a, bpf_u_int32* b, bpf_u_int32* c, char* d) {







<
<
<
<
<









|










|






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

|







|







|




>





|





|





|







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
      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);





      break;
    default:                /* loaded or failed */
      break;
  }
  return (lib_loaded == 1) ? 1 : 0;
}

/* define functions with dynamic revectoring */
void pcap_close(pcap_t* a) {
  if (load_pcap() != 0) {
    p_pcap_close(a);
  }
}

/* Some platforms's pcap.h have an ancient declaration of pcap_compile which doesn't have a const in the bpf string argument */
#if !defined (BPF_CONST_STRING)
int pcap_compile(pcap_t* a, struct bpf_program* b, char* c, int d, bpf_u_int32 e) {
#else
int pcap_compile(pcap_t* a, struct bpf_program* b, const char* c, int d, bpf_u_int32 e) {
#endif
  if (load_pcap() != 0) {
    return p_pcap_compile(a, b, c, d, e);
  } else {
    return 0;
  }
}

const char *pcap_lib_version(void) {
  static char buf[256];

  if ((load_pcap() != 0) && (p_pcap_lib_version != NULL)) {
    return p_pcap_lib_version();
  } else {
    sprintf (buf, "%s not installed",
#if defined(_WIN32)
        "npcap or winpcap"
#else
        "libpcap"
#endif
        );
    return buf;
  }
}

int pcap_datalink(pcap_t* a) {
  if (load_pcap() != 0) {
    return p_pcap_datalink(a);
  } else {
    return 0;
  }
}

int pcap_dispatch(pcap_t* a, int b, pcap_handler c, u_char* d) {
  if (load_pcap() != 0) {
    return p_pcap_dispatch(a, b, c, d);
  } else {
    return 0;
  }
}

int pcap_findalldevs(pcap_if_t** a, char* b) {
  if (load_pcap() != 0) {
    return p_pcap_findalldevs(a, b);
  } else {
    *a = 0;
    strcpy(b, no_pcap);
    no_pcap[0] = '\0';
    return -1;
  }
}

void pcap_freealldevs(pcap_if_t* a) {
  if (load_pcap() != 0) {
    p_pcap_freealldevs(a);
  }
}

void pcap_freecode(struct bpf_program* a) {
  if (load_pcap() != 0) {
    p_pcap_freecode(a);
  }
}

char* pcap_geterr(pcap_t* a) {
  if (load_pcap() != 0) {
    return p_pcap_geterr(a);
  } else {
    return (char*) "";
  }
}

int pcap_lookupnet(const char* a, bpf_u_int32* b, bpf_u_int32* c, char* d) {
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
  } else {
    return (pcap_t*) 0;
  }
}

#ifdef _WIN32
int pcap_setmintocopy(pcap_t* a, int b) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_setmintocopy(a, b);
  } else {
    return -1;
  }
}

HANDLE pcap_getevent(pcap_t* a) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_getevent(a);
  } else {
    return (HANDLE) 0;
  }
}

#else
#ifdef MUST_DO_SELECT
int pcap_get_selectable_fd(pcap_t* a) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_get_selectable_fd(a);
  } else {
    return 0;
  }
}
#endif

int pcap_fileno(pcap_t * a) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_fileno(a);
  } else {
    return 0;
  }
}
#endif

int pcap_sendpacket(pcap_t* a, const u_char* b, int c) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_sendpacket(a, b, c);
  } else {
    return 0;
  }
}

int pcap_setfilter(pcap_t* a, struct bpf_program* b) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_setfilter(a, b);
  } else {
    return 0;
  }
}

int pcap_setnonblock(pcap_t* a, int nonblock, char *errbuf) {
  if (a && (load_pcap() != 0)) {
    return p_pcap_setnonblock(a, nonblock, errbuf);
  } else {
    return 0;
  }
}
#endif /* defined(USE_SHARED) && (defined(_WIN32) || defined(HAVE_DLOPEN)) */








|







|









|








|








|







|







|







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
  } else {
    return (pcap_t*) 0;
  }
}

#ifdef _WIN32
int pcap_setmintocopy(pcap_t* a, int b) {
  if (load_pcap() != 0) {
    return p_pcap_setmintocopy(a, b);
  } else {
    return -1;
  }
}

HANDLE pcap_getevent(pcap_t* a) {
  if (load_pcap() != 0) {
    return p_pcap_getevent(a);
  } else {
    return (HANDLE) 0;
  }
}

#else
#ifdef MUST_DO_SELECT
int pcap_get_selectable_fd(pcap_t* a) {
  if (load_pcap() != 0) {
    return p_pcap_get_selectable_fd(a);
  } else {
    return 0;
  }
}
#endif

int pcap_fileno(pcap_t * a) {
  if (load_pcap() != 0) {
    return p_pcap_fileno(a);
  } else {
    return 0;
  }
}
#endif

int pcap_sendpacket(pcap_t* a, const u_char* b, int c) {
  if (load_pcap() != 0) {
    return p_pcap_sendpacket(a, b, c);
  } else {
    return 0;
  }
}

int pcap_setfilter(pcap_t* a, struct bpf_program* b) {
  if (load_pcap() != 0) {
    return p_pcap_setfilter(a, b);
  } else {
    return 0;
  }
}

int pcap_setnonblock(pcap_t* a, int nonblock, char *errbuf) {
  if (load_pcap() != 0) {
    return p_pcap_setnonblock(a, nonblock, errbuf);
  } else {
    return 0;
  }
}
#endif /* defined(USE_SHARED) && (defined(_WIN32) || defined(HAVE_DLOPEN)) */

1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
                                ///< for a complete list of valid codes.
    uint32 Length;              ///< Length of the data field
    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;







|







1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
                                ///< for a complete list of valid codes.
    uint32 Length;              ///< Length of the data field
    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 ntddndis.h */

static int pcap_mac_if_win32(const char *AdapterName, unsigned char MACAddress[6])
{
  LPADAPTER         lpAdapter;
  PPACKET_OID_DATA  OidData;
  int               Status;
  int               ReturnValue;
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
    const char *patterns[] = {
        "grep [0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]",
        "egrep [0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]",
        NULL};

    memset(command, 0, sizeof(command));
    /* try to force an otherwise unused interface to be turned on */
    snprintf(command, sizeof(command)-1, "ifconfig %s up", devname);
    (void)system(command);
    for (i=0; patterns[i] && (0 == dev->have_host_nic_phy_addr); ++i) {
      snprintf(command, sizeof(command)-1, "ifconfig %s | %s  >NIC.hwaddr", devname, patterns[i]);
      (void)system(command);
      if (NULL != (f = fopen("NIC.hwaddr", "r"))) {
        while (0 == dev->have_host_nic_phy_addr) {
          if (fgets(command, sizeof(command)-1, f)) {
            char *p1, *p2;

            p1 = strchr(command, ':');
            while (p1) {







|
|

|
|







1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
    const char *patterns[] = {
        "grep [0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]",
        "egrep [0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]:[0-9a-fA-F]?[0-9a-fA-F]",
        NULL};

    memset(command, 0, sizeof(command));
    /* try to force an otherwise unused interface to be turned on */
    snprintf(command, sizeof(command)-1, "ifconfig %.*s up", (int)(sizeof(command) - 14), devname);
    if (system(command)) {};
    for (i=0; patterns[i] && (0 == dev->have_host_nic_phy_addr); ++i) {
      snprintf(command, sizeof(command)-1, "ifconfig %.*s | %s  >NIC.hwaddr", (int)(sizeof(command) - (26 + strlen(patterns[i]))), devname, patterns[i]);
      if (system(command)) {};
      if (NULL != (f = fopen("NIC.hwaddr", "r"))) {
        while (0 == dev->have_host_nic_phy_addr) {
          if (fgets(command, sizeof(command)-1, f)) {
            char *p1, *p2;

            p1 = strchr(command, ':');
            while (p1) {
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
              p1 = p2;
              }
            }
          else
            break;
          }
        fclose(f);
        remove("NIC.hwaddr");
        }
      }
    }
#endif
}

#if defined(__APPLE__)







|







1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
              p1 = p2;
              }
            }
          else
            break;
          }
        fclose(f);
        (void)remove("NIC.hwaddr");
        }
      }
    }
#endif
}

#if defined(__APPLE__)
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

  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 */







>
>
|
|

















>
>
|
<
>
|
>
|
<
<
|
>
|
|
<







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

  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;
  if (buf_size < 37)
    return -1;
  reglen = buf_size - 1;
  if ((status = RegQueryValueExA (reghnd, "MachineGuid", NULL, &regtype, (LPBYTE)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 (buf_size < 37)
    return -1;
if ((f = fopen ("/etc/machine-id", "r")) == NULL)

  f = popen ("hostname", "r");
if (f) {
  size_t read_size;



  read_size = fread (buf, 1, buf_size - 1, f);
  buf[read_size] = '\0';
  fclose (f);
  }

while ((strlen (buf) > 0) && sim_isspace(buf[strlen (buf) - 1]))
  buf[strlen (buf) - 1] = '\0';
return 0;
}
#endif

/* Forward declarations */
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

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)) {


    /* Pull buffer off request list */
    dev->write_requests = request->next;
    pthread_mutex_unlock (&dev->writer_lock);

    if (dev->throttle_delay != ETH_THROT_DISABLED_DELAY) {
      uint32 packet_delta_time = sim_os_msec() - dev->throttle_packet_time;
      dev->throttle_events <<= 1;
      dev->throttle_events += (packet_delta_time < dev->throttle_time) ? 1 : 0;
      if ((dev->throttle_events & dev->throttle_mask) == dev->throttle_mask) {
        sim_os_ms_sleep (dev->throttle_delay);
        ++dev->throttle_count;
        }
      dev->throttle_packet_time = sim_os_msec();
      }
    dev->write_status = _eth_write(dev, &request->packet, NULL);

    pthread_mutex_lock (&dev->writer_lock);
    /* Put buffer on free buffer list */
    request->next = dev->write_buffers;
    dev->write_buffers = request;

    }






  }
pthread_mutex_unlock (&dev->writer_lock);

sim_debug(dev->dbit, dev->dptr, "Writer Thread Exiting\n");
return NULL;
}
#endif

t_stat eth_set_async (ETH_DEV *dev, int latency)
{
#if !defined(USE_READER_THREAD) || !defined(SIM_ASYNCH_IO)
char *msg = "Eth: can't operate asynchronously, must poll\n";

return sim_messagef (SCPE_NOFNC, "%s", msg);
#else
int wakeup_needed;

dev->asynch_io = 1;
dev->asynch_io_latency = latency;
pthread_mutex_lock (&dev->lock);







>
>




















>

>
>
>
>
>
>











|
>







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

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)) {
    if (dev->handle == NULL)      /* Shutting down? */
      break;
    /* Pull buffer off request list */
    dev->write_requests = request->next;
    pthread_mutex_unlock (&dev->writer_lock);

    if (dev->throttle_delay != ETH_THROT_DISABLED_DELAY) {
      uint32 packet_delta_time = sim_os_msec() - dev->throttle_packet_time;
      dev->throttle_events <<= 1;
      dev->throttle_events += (packet_delta_time < dev->throttle_time) ? 1 : 0;
      if ((dev->throttle_events & dev->throttle_mask) == dev->throttle_mask) {
        sim_os_ms_sleep (dev->throttle_delay);
        ++dev->throttle_count;
        }
      dev->throttle_packet_time = sim_os_msec();
      }
    dev->write_status = _eth_write(dev, &request->packet, NULL);

    pthread_mutex_lock (&dev->writer_lock);
    /* Put buffer on free buffer list */
    request->next = dev->write_buffers;
    dev->write_buffers = request;
    request = NULL;
    }
  }
/* If we exited these loops with a request allocated, */
/* avoid buffer leaking by putting it on free buffer list */
if (request) {
  request->next = dev->write_buffers;
  dev->write_buffers = request;
  }
pthread_mutex_unlock (&dev->writer_lock);

sim_debug(dev->dbit, dev->dptr, "Writer Thread Exiting\n");
return NULL;
}
#endif

t_stat eth_set_async (ETH_DEV *dev, int latency)
{
#if !defined(USE_READER_THREAD) || !defined(SIM_ASYNCH_IO)
char *msg = "Eth: Can't operate asynchronously, must poll.\n"
            " *** Build with USE_READER_THREAD defined and link with pthreads for asynchronous operation. ***\n";
return sim_messagef (SCPE_NOFNC, "%s", msg);
#else
int wakeup_needed;

dev->asynch_io = 1;
dev->asynch_io_latency = latency;
pthread_mutex_lock (&dev->lock);
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
#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)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);

        }
      else {
        *fd_handle = tun;
        strcpy(savname, ifr.ifr_name);
        }
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    }
  else
    strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);




#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)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);

        }
      else {
        *fd_handle = tun;
        strcpy(savname, devname);
        }
#if defined (__APPLE__)
      if (1) {
        struct ifreq ifr;
        int s;


        memset (&ifr, 0, sizeof(ifr));
        ifr.ifr_addr.sa_family = AF_INET;
        strlcpy(ifr.ifr_name, savname, sizeof(ifr.ifr_name));
        if ((s = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
          if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) >= 0) {
            ifr.ifr_flags |= IFF_UP;
            if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr)) {
              strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
              close(tun);

              }
            }
          close(s);
          }
        }
#endif
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);



  }

#else
  strlcpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }







|







>


|








>
>
>
>











>


|
|


|



>









>









>
>
>
|
>







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
#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 */
    strlcpy(ifr.ifr_name, devname, sizeof(ifr.ifr_name));
    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)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);
        tun = -1;
        }
      else {
        *fd_handle = (SOCKET)tun;
        strcpy(savname, ifr.ifr_name);
        }
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    }
  else
    strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
  if ((tun >= 0) && (errbuf[0] != 0)) {
    close(tun);
    tun = -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)) {
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
        close(tun);
        tun = -1;
        }
      else {
        *fd_handle = (SOCKET)tun;
        memmove(savname, devname, strlen(devname) + 1);
        }
#if defined (__APPLE__)
      if (tun >= 0) {       /* Good so far? */
        struct ifreq ifr;
        int s;

        /* Now make sure the interface is up */
        memset (&ifr, 0, sizeof(ifr));
        ifr.ifr_addr.sa_family = AF_INET;
        strlcpy(ifr.ifr_name, savname, sizeof(ifr.ifr_name));
        if ((s = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
          if (ioctl(s, SIOCGIFFLAGS, (caddr_t)&ifr) >= 0) {
            ifr.ifr_flags |= IFF_UP;
            if (ioctl(s, SIOCSIFFLAGS, (caddr_t)&ifr)) {
              strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
              close(tun);
              tun = -1;
              }
            }
          close(s);
          }
        }
#endif
      }
    else
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    if ((tun >= 0) && (errbuf[0] != 0)) {
      close(tun);
      tun = -1;
      }
    }
#else
  strlcpy(errbuf, "No support for tap: devices", PCAP_ERRBUF_SIZE);
#endif /* !defined(__linux) && !defined(HAVE_BSDTUNTAP) */
  if (0 == errbuf[0]) {
    *eth_api = ETH_API_TAP;
    *handle = (void *)1;  /* Flag used to indicated open */
    }
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
          return sim_messagef (SCPE_OPENERR, "Eth: Invalid vde port number: %s in %s\n", vdeport_s, savname);
      }

    if (!(*handle = (void*) vde_open((char *)vdeswitch_s, (char *)"simh", &voa)))
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = vde_datafd((VDECONN*)(*handle));
      }
#else
    strlcpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE);
#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)))
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
      else {
        *eth_api = ETH_API_NAT;
        *fd_handle = 0;
        }
#else
      strlcpy(errbuf, "No support for nat: network devices", PCAP_ERRBUF_SIZE);







|












|







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
          return sim_messagef (SCPE_OPENERR, "Eth: Invalid vde port number: %s in %s\n", vdeport_s, savname);
      }

    if (!(*handle = (void*) vde_open((char *)vdeswitch_s, (char *)"simh", &voa)))
      strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
    else {
      *eth_api = ETH_API_VDE;
      *fd_handle = (SOCKET)vde_datafd((VDECONN*)(*handle));
      }
#else
    strlcpy(errbuf, "No support for vde: network devices", PCAP_ERRBUF_SIZE);
#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, errbuf, PCAP_ERRBUF_SIZE)))
        strlcpy(errbuf, strerror(errno), PCAP_ERRBUF_SIZE);
      else {
        *eth_api = ETH_API_NAT;
        *fd_handle = 0;
        }
#else
      strlcpy(errbuf, "No support for nat: network devices", PCAP_ERRBUF_SIZE);
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
        if (!*handle) { /* can't open device */
          if (strstr (errbuf, "That device is not up")) {
            char command[1024];

            /* try to force an otherwise unused interface to be turned on */
            memset(command, 0, sizeof(command));
            snprintf(command, sizeof(command)-1, "ifconfig %s up", savname);
            (void)system(command);
            errbuf[0] = '\0';
            *handle = (void*) pcap_open_live(savname, bufsz, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
            }
          }
#endif
        if (!*handle)  /* can't open device */
          return sim_messagef (SCPE_OPENERR, "Eth: pcap_open_live error - %s\n", errbuf);







|







2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
        if (!*handle) { /* can't open device */
          if (strstr (errbuf, "That device is not up")) {
            char command[1024];

            /* try to force an otherwise unused interface to be turned on */
            memset(command, 0, sizeof(command));
            snprintf(command, sizeof(command)-1, "ifconfig %s up", savname);
            if (system(command)) {};
            errbuf[0] = '\0';
            *handle = (void*) pcap_open_live(savname, bufsz, ETH_PROMISC, PCAP_READ_TIMEOUT, errbuf);
            }
          }
#endif
        if (!*handle)  /* can't open device */
          return sim_messagef (SCPE_OPENERR, "Eth: pcap_open_live error - %s\n", errbuf);
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
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 */







|







2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
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 */
2347
2348
2349
2350
2351
2352
2353





2354
2355
2356
2357
2358
2359
2360
2361
#endif /* defined(__hpux) */
  pthread_create (&dev->reader_thread, &attr, _eth_reader, (void *)dev);
  pthread_create (&dev->writer_thread, &attr, _eth_writer, (void *)dev);
  pthread_attr_destroy(&attr);
  }
#endif /* defined (USE_READER_THREAD */
_eth_add_to_open_list (dev);





return SCPE_OK;
}

static t_stat _eth_close_port(int eth_api, pcap_t *pcap, SOCKET pcap_fd)
{
switch (eth_api) {
#ifdef HAVE_PCAP_NETWORK
  case ETH_API_PCAP:







>
>
>
>
>
|







2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
#endif /* defined(__hpux) */
  pthread_create (&dev->reader_thread, &attr, _eth_reader, (void *)dev);
  pthread_create (&dev->writer_thread, &attr, _eth_writer, (void *)dev);
  pthread_attr_destroy(&attr);
  }
#endif /* defined (USE_READER_THREAD */
_eth_add_to_open_list (dev);
/* 
 * install a total filter on a newly opened interface and let the device
 * simulator install an appropriate filter that reflects the device's
 * configuration.
 */
return eth_filter_hash (dev, 0, NULL, FALSE, FALSE, NULL);
}

static t_stat _eth_close_port(int eth_api, pcap_t *pcap, SOCKET pcap_fd)
{
switch (eth_api) {
#ifdef HAVE_PCAP_NETWORK
  case ETH_API_PCAP:
2427
2428
2429
2430
2431
2432
2433
























2434
2435
2436
2437
2438
2439
2440
/* clean up the mess */
free(dev->name);
free(dev->bpf_filter);
eth_zero(dev);
_eth_remove_from_open_list (dev);
return SCPE_OK;
}

























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");







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







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
/* clean up the mess */
free(dev->name);
free(dev->bpf_filter);
eth_zero(dev);
_eth_remove_from_open_list (dev);
return SCPE_OK;
}

const char *eth_version (void)
{
#if defined(HAVE_PCAP_NETWORK)
static char version[256];

if (!version[0]) {
  strlcpy(version, pcap_lib_version(), sizeof(version));
  if (memcmp(pcap_lib_version(), "Npcap", 5) == 0) {
    char maj_min[CBUFSIZE];
    char *c = version;

    while (*c && !isdigit (*c))
      ++c;
    get_glyph (c, maj_min, ',');
    if (strcmp ("0.9990", maj_min) < 0)
      snprintf(version, sizeof(version), "Unsupported - %s", pcap_lib_version());
    }
  }
return version;
#else
return NULL;
#endif
}

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");
3035
3036
3037
3038
3039
3040
3041
3042




3043
3044
3045
3046


3047
3048
3049
3050
3051

3052
3053
3054
3055
3056
3057
3058
/* Do a little shuffling  */
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >> 16);
    
/* Return the bitwise complement of the resulting mishmash  */
return (uint16)(~cksum);
}





static uint16 
pseudo_checksum(uint16 len, uint16 proto, uint16 *src_addr, uint16 *dest_addr, uint8 *buff)
{
uint32 sum;



/* Sum the data first */
sum = 0xffff&(~ip_checksum((uint16 *)buff, len));

/* add the pseudo header which contains the IP source and destinationn addresses */

sum += src_addr[0];
sum += src_addr[1];
sum += dest_addr[0];
sum += dest_addr[1];
/* and the protocol number and the length of the UDP packet */
sum = sum + htons(proto) + htons(len);









>
>
>
>

|


>
>




|
>







3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
/* Do a little shuffling  */
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >> 16);
    
/* Return the bitwise complement of the resulting mishmash  */
return (uint16)(~cksum);
}

/* 
 * src_addr and dest_addr are presented in network byte order
 */

static uint16 
pseudo_checksum(uint16 len, uint16 proto, void *nsrc_addr, void *ndest_addr, uint8 *buff)
{
uint32 sum;
uint16 *src_addr = (uint16 *)nsrc_addr;
uint16 *dest_addr = (uint16 *)ndest_addr;

/* Sum the data first */
sum = 0xffff&(~ip_checksum((uint16 *)buff, len));

/* add the pseudo header which contains the IP source and 
   destination addresses already in network byte order */
sum += src_addr[0];
sum += src_addr[1];
sum += dest_addr[0];
sum += dest_addr[1];
/* and the protocol number and the length of the UDP packet */
sum = sum + htons(proto) + htons(len);

3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
      ++dev->jumbo_dropped; /* Bogus UDP packet length (packet contained length exceeds packet size) frames are dropped */
      return;
      }
    if (UDP->checksum == 0)
      break; /* UDP Checksums are disabled */
    orig_checksum = UDP->checksum;
    UDP->checksum = 0;
    UDP->checksum = pseudo_checksum(ntohs(UDP->length), IPPROTO_UDP, (uint16 *)(&IP->source_ip), (uint16 *)(&IP->dest_ip), (uint8 *)UDP);
    if (orig_checksum != UDP->checksum)
      eth_packet_trace (dev, msg, len, "reading jumbo UDP header Checksum Fixed");
    break;
  case IPPROTO_ICMP:
    ICMP = (struct ICMPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = ICMP->checksum;
    ICMP->checksum = 0;







|







3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
      ++dev->jumbo_dropped; /* Bogus UDP packet length (packet contained length exceeds packet size) frames are dropped */
      return;
      }
    if (UDP->checksum == 0)
      break; /* UDP Checksums are disabled */
    orig_checksum = UDP->checksum;
    UDP->checksum = 0;
    UDP->checksum = pseudo_checksum(ntohs(UDP->length), IPPROTO_UDP, &IP->source_ip, &IP->dest_ip, (uint8 *)UDP);
    if (orig_checksum != UDP->checksum)
      eth_packet_trace (dev, msg, len, "reading jumbo UDP header Checksum Fixed");
    break;
  case IPPROTO_ICMP:
    ICMP = (struct ICMPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = ICMP->checksum;
    ICMP->checksum = 0;
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
      else {
        TCP->data_offset_and_flags = htons(orig_tcp_flags);
        IP->total_len = htons(payload_len + IP_HLEN(IP) + TCP_DATA_OFFSET(TCP));
        }
      IP->checksum = 0;
      IP->checksum = ip_checksum((uint16 *)IP, IP_HLEN(IP));
      TCP->checksum = 0;
      TCP->checksum = pseudo_checksum(ntohs(IP->total_len)-IP_HLEN(IP), IPPROTO_TCP, (uint16 *)(&IP->source_ip), (uint16 *)(&IP->dest_ip), (uint8 *)TCP);
      header.caplen = header.len = 14 + ntohs(IP->total_len);
      eth_packet_trace_ex (dev, ((u_char *)IP)-14, header.len, "reading TCP segment", 1, dev->dbit);
#if ETH_MIN_JUMBO_FRAME < ETH_MAX_PACKET
      if (1) {
        /* Debugging is easier if we read packets directly with pcap
           (i.e. we can use Wireshark to verify packet contents)
           we don't want to do this all the time for 2 reasons:







|







3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
      else {
        TCP->data_offset_and_flags = htons(orig_tcp_flags);
        IP->total_len = htons(payload_len + IP_HLEN(IP) + TCP_DATA_OFFSET(TCP));
        }
      IP->checksum = 0;
      IP->checksum = ip_checksum((uint16 *)IP, IP_HLEN(IP));
      TCP->checksum = 0;
      TCP->checksum = pseudo_checksum(ntohs(IP->total_len)-IP_HLEN(IP), IPPROTO_TCP, &IP->source_ip, &IP->dest_ip, (uint8 *)TCP);
      header.caplen = header.len = 14 + ntohs(IP->total_len);
      eth_packet_trace_ex (dev, ((u_char *)IP)-14, header.len, "reading TCP segment", 1, dev->dbit);
#if ETH_MIN_JUMBO_FRAME < ETH_MAX_PACKET
      if (1) {
        /* Debugging is easier if we read packets directly with pcap
           (i.e. we can use Wireshark to verify packet contents)
           we don't want to do this all the time for 2 reasons:
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
    UDP = (struct UDPHeader *)(((char *)IP)+IP_HLEN(IP));
    if (ntohs(UDP->length) > (len-IP_HLEN(IP)))
      return; /* packet contained length exceeds packet size */
    if (UDP->checksum == 0)
      return; /* UDP Checksums are disabled */
    orig_checksum = UDP->checksum;
    UDP->checksum = 0;
    UDP->checksum = pseudo_checksum(ntohs(UDP->length), IPPROTO_UDP, (uint16 *)(&IP->source_ip), (uint16 *)(&IP->dest_ip), (uint8 *)UDP);
    if (orig_checksum != UDP->checksum)
      eth_packet_trace (dev, msg, len, "reading UDP header Checksum Fixed");
    break;
  case IPPROTO_TCP:
    TCP = (struct TCPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = TCP->checksum;
    TCP->checksum = 0;
    TCP->checksum = pseudo_checksum(ntohs(IP->total_len)-IP_HLEN(IP), IPPROTO_TCP, (uint16 *)(&IP->source_ip), (uint16 *)(&IP->dest_ip), (uint8 *)TCP);
    if (orig_checksum != TCP->checksum)
      eth_packet_trace (dev, msg, len, "reading TCP header Checksum Fixed");
    break;
  case IPPROTO_ICMP:
    ICMP = (struct ICMPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = ICMP->checksum;
    ICMP->checksum = 0;







|







|







3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
    UDP = (struct UDPHeader *)(((char *)IP)+IP_HLEN(IP));
    if (ntohs(UDP->length) > (len-IP_HLEN(IP)))
      return; /* packet contained length exceeds packet size */
    if (UDP->checksum == 0)
      return; /* UDP Checksums are disabled */
    orig_checksum = UDP->checksum;
    UDP->checksum = 0;
    UDP->checksum = pseudo_checksum(ntohs(UDP->length), IPPROTO_UDP, &IP->source_ip, &IP->dest_ip, (uint8 *)UDP);
    if (orig_checksum != UDP->checksum)
      eth_packet_trace (dev, msg, len, "reading UDP header Checksum Fixed");
    break;
  case IPPROTO_TCP:
    TCP = (struct TCPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = TCP->checksum;
    TCP->checksum = 0;
    TCP->checksum = pseudo_checksum(ntohs(IP->total_len)-IP_HLEN(IP), IPPROTO_TCP, &IP->source_ip, &IP->dest_ip, (uint8 *)TCP);
    if (orig_checksum != TCP->checksum)
      eth_packet_trace (dev, msg, len, "reading TCP header Checksum Fixed");
    break;
  case IPPROTO_ICMP:
    ICMP = (struct ICMPHeader *)(((char *)IP)+IP_HLEN(IP));
    orig_checksum = ICMP->checksum;
    ICMP->checksum = 0;
3767
3768
3769
3770
3771
3772
3773

3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
/* make sure device exists */
if (!dev) return SCPE_UNATT;

/* filter count OK? */
if ((addr_count < 0) || (addr_count > ETH_FILTER_MAX))
  return SCPE_ARG;
else

  if (!addresses) return SCPE_ARG;

/* test reflections.  This is done early in this routine since eth_reflect */
/* calls eth_filter recursively and thus changes the state of the device. */
if (dev->reflections == -1)
  eth_reflect(dev);

/* set new filter addresses */
for (i = 0; i < addr_count; i++)
  memcpy(dev->filter_address[i], addresses[i], sizeof(ETH_MAC));
dev->addr_count = addr_count;

/* store other flags */







>
|




|







3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
/* make sure device exists */
if (!dev) return SCPE_UNATT;

/* filter count OK? */
if ((addr_count < 0) || (addr_count > ETH_FILTER_MAX))
  return SCPE_ARG;
else
  if (!addresses && (addr_count != 0)) 
     return SCPE_ARG;

/* test reflections.  This is done early in this routine since eth_reflect */
/* calls eth_filter recursively and thus changes the state of the device. */
if (dev->reflections == -1)
  status = eth_reflect(dev);

/* set new filter addresses */
for (i = 0; i < addr_count; i++)
  memcpy(dev->filter_address[i], addresses[i], sizeof(ETH_MAC));
dev->addr_count = addr_count;

/* store other flags */
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
  }

/* setup BPF filters and other fields to minimize packet delivery */
eth_bpf_filter (dev, dev->addr_count, dev->filter_address, 
                dev->all_multicast, dev->promiscuous, 
                dev->reflections, &dev->physical_addr, 
                dev->have_host_nic_phy_addr ? &dev->host_nic_phy_hw_addr: NULL,
                &dev->hash, buf);

/* get netmask, which is a required argument for compiling.  The value, 
   in our case isn't actually interesting since the filters we generate 
   aren't referencing IP fields, networks or values */

#ifdef USE_BPF
if (dev->eth_api == ETH_API_PCAP) {







|







3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
  }

/* setup BPF filters and other fields to minimize packet delivery */
eth_bpf_filter (dev, dev->addr_count, dev->filter_address, 
                dev->all_multicast, dev->promiscuous, 
                dev->reflections, &dev->physical_addr, 
                dev->have_host_nic_phy_addr ? &dev->host_nic_phy_hw_addr: NULL,
                (dev->hash_filter ? &dev->hash : NULL), buf);

/* get netmask, which is a required argument for compiling.  The value, 
   in our case isn't actually interesting since the filters we generate 
   aren't referencing IP fields, networks or values */

#ifdef USE_BPF
if (dev->eth_api == ETH_API_PCAP) {
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
     get tricky, and would then result in a sort of deviant libpcap.

     This routine exists to allow platform specific code to validate and/or 
     extend the set of available interfaces to include any that are not
     returned by pcap_findalldevs.

*/
int eth_host_devices(int used, int max, ETH_LIST* list)
{
pcap_t* conn = NULL;
int i, j, datalink = 0;

for (i=0; i<used; ++i) {
  /* Cull any non-ethernet interface types */
#if defined(HAVE_PCAP_NETWORK)







|







3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
     get tricky, and would then result in a sort of deviant libpcap.

     This routine exists to allow platform specific code to validate and/or 
     extend the set of available interfaces to include any that are not
     returned by pcap_findalldevs.

*/
static int eth_host_devices(int used, int max, ETH_LIST* list)
{
pcap_t* conn = NULL;
int i, j, datalink = 0;

for (i=0; i<used; ++i) {
  /* Cull any non-ethernet interface types */
#if defined(HAVE_PCAP_NETWORK)
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
  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] = "";
#ifndef DONT_USE_PCAP_FINDALLDEVS
pcap_if_t* alldevs;
pcap_if_t* dev;

memset(list, 0, max*sizeof(*list));
errbuf[0] = '\0';
/* retrieve the device list */
if (pcap_findalldevs(&alldevs, errbuf) == -1) {

  sim_printf ("Eth: error in pcap_findalldevs: %s\n", errbuf);
  }
else {
  /* copy device list into the passed structure */
  for (i=0, dev=alldevs; dev && (i < max); dev=dev->next, ++i) {
    if ((dev->flags & PCAP_IF_LOOPBACK) || (!strcmp("any", dev->name))) continue;
    strlcpy(list[i].name, dev->name, sizeof(list[i].name));
    if (dev->description)







|











>
|







4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
  list[used].eth_api = ETH_API_UDP;
  ++used;
  }

return used;
}

static int _eth_devices(int max, ETH_LIST* list)
{
int i = 0;
char errbuf[PCAP_ERRBUF_SIZE] = "";
#ifndef DONT_USE_PCAP_FINDALLDEVS
pcap_if_t* alldevs;
pcap_if_t* dev;

memset(list, 0, max*sizeof(*list));
errbuf[0] = '\0';
/* retrieve the device list */
if (pcap_findalldevs(&alldevs, errbuf) == -1) {
  if (errbuf[0])
    sim_printf ("Eth: %s\n", errbuf);
  }
else {
  /* copy device list into the passed structure */
  for (i=0, dev=alldevs; dev && (i < max); dev=dev->next, ++i) {
    if ((dev->flags & PCAP_IF_LOOPBACK) || (!strcmp("any", dev->name))) continue;
    strlcpy(list[i].name, dev->name, sizeof(list[i].name));
    if (dev->description)
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
        eth_mac_fmt(host_phy_addr_list[host_phy_addr_listindex], mac);\
        sim_printf ("Eth: host_nic_phy_hw_addr: %s\n", mac);    \
        }                                                       \
      }


memset (&eth_tst, 0, sizeof(eth_tst));
eth_device_count = eth_devices(ETH_MAX_DEVICE, eth_list);
eth_opened = 0;
for (eth_num=0; eth_num<eth_device_count; eth_num++) {
  char eth_name[32];

  if ((0 == memcmp (eth_list[eth_num].name, "nat:", 4)) ||
      (0 == memcmp (eth_list[eth_num].name, "tap:", 4)) ||
      (0 == memcmp (eth_list[eth_num].name, "vde:", 4)) ||







|







4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
        eth_mac_fmt(host_phy_addr_list[host_phy_addr_listindex], mac);\
        sim_printf ("Eth: host_nic_phy_hw_addr: %s\n", mac);    \
        }                                                       \
      }


memset (&eth_tst, 0, sizeof(eth_tst));
eth_device_count = _eth_devices(ETH_MAX_DEVICE, eth_list);
eth_opened = 0;
for (eth_num=0; eth_num<eth_device_count; eth_num++) {
  char eth_name[32];

  if ((0 == memcmp (eth_list[eth_num].name, "nat:", 4)) ||
      (0 == memcmp (eth_list[eth_num].name, "tap:", 4)) ||
      (0 == memcmp (eth_list[eth_num].name, "vde:", 4)) ||

Changes to src/SIMH/sim_ether.h.

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
t_stat eth_filter_hash (ETH_DEV* dev, int addr_count,   /* set filter on incoming packets with AUTODIN II based hash */
                        ETH_MAC* const addresses,
                        ETH_BOOL all_multicast,
                        ETH_BOOL promiscuous,
                        ETH_MULTIHASH* const hash);
t_stat eth_check_address_conflict (ETH_DEV* dev, 
                                   ETH_MAC* const address);
int eth_devices   (int max, ETH_LIST* dev);             /* get ethernet devices on host */
void eth_setcrc   (ETH_DEV* dev, int need_crc);         /* enable/disable CRC mode */
t_stat eth_set_async (ETH_DEV* dev, int latency);       /* set read behavior to be async */
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 */







|







345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
t_stat eth_filter_hash (ETH_DEV* dev, int addr_count,   /* set filter on incoming packets with AUTODIN II based hash */
                        ETH_MAC* const addresses,
                        ETH_BOOL all_multicast,
                        ETH_BOOL promiscuous,
                        ETH_MULTIHASH* const hash);
t_stat eth_check_address_conflict (ETH_DEV* dev, 
                                   ETH_MAC* const address);
const char *eth_version (void);                         /* Version of dynamically loaded library (pcap) */
void eth_setcrc   (ETH_DEV* dev, int need_crc);         /* enable/disable CRC mode */
t_stat eth_set_async (ETH_DEV* dev, int latency);       /* set read behavior to be async */
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 */
376
377
378
379
380
381
382





383
384
385
386
387
388
                  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);
t_stat sim_ether_test (DEVICE *dptr);                   /* unit test routine */






#ifdef  __cplusplus
}
#endif

#endif                                                  /* _SIM_ETHER_H */







>
>
>
>
>






376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
                  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);
t_stat sim_ether_test (DEVICE *dptr);                   /* unit test routine */

#if !defined(SIM_TEST_INIT)    	/* Need stubs for test APIs */
#define SIM_TEST_INIT
#define SIM_TEST(xxx)
#endif

#ifdef  __cplusplus
}
#endif

#endif                                                  /* _SIM_ETHER_H */

Changes to src/SIMH/sim_fio.c.

738
739
740
741
742
743
744


745
746
747
748
749
750
751
{
size_t tot_len = 0, tot_size = 0;
char *tempfilepath = NULL;
char *fullpath = NULL, *result = NULL;
char *c, *name, *ext;
char chr;
const char *p;



if (((*filepath == '\'') || (*filepath == '"')) &&
    (filepath[strlen (filepath) - 1] == *filepath)) {
    size_t temp_size = 1 + strlen (filepath);

    tempfilepath = (char *)malloc (temp_size);
    if (tempfilepath == NULL)







>
>







738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
{
size_t tot_len = 0, tot_size = 0;
char *tempfilepath = NULL;
char *fullpath = NULL, *result = NULL;
char *c, *name, *ext;
char chr;
const char *p;
char filesizebuf[32] = "";
char filedatetimebuf[32] = "";

if (((*filepath == '\'') || (*filepath == '"')) &&
    (filepath[strlen (filepath) - 1] == *filepath)) {
    size_t temp_size = 1 + strlen (filepath);

    tempfilepath = (char *)malloc (temp_size);
    if (tempfilepath == NULL)
776
777
778
779
780
781
782


783
784
785
786
787
788
789
790
    tot_len = 1 + strlen (filepath) + 1 + strlen (dir);
    fullpath = (char *)malloc (tot_len);
    if (fullpath == NULL) {
        free (tempfilepath);
        return NULL;
        }
    strlcpy (fullpath, dir, tot_len);


    strlcat (fullpath, "/", tot_len);
    strlcat (fullpath, filepath, tot_len);
    }
while ((c = strchr (fullpath, '\\')))           /* standardize on / directory separator */
       *c = '/';
if ((fullpath[1] == ':') && islower (fullpath[0]))
    fullpath[0] = toupper (fullpath[0]);
while ((c = strstr (fullpath + 1, "//")))       /* strip out redundant / characters (leaving the option for a leading //) */







>
>
|







778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    tot_len = 1 + strlen (filepath) + 1 + strlen (dir);
    fullpath = (char *)malloc (tot_len);
    if (fullpath == NULL) {
        free (tempfilepath);
        return NULL;
        }
    strlcpy (fullpath, dir, tot_len);
    if ((dir[strlen (dir) - 1] != '/') &&       /* if missing a trailing directory separator? */
        (dir[strlen (dir) - 1] != '\\'))
        strlcat (fullpath, "/", tot_len);       /*  then add one */
    strlcat (fullpath, filepath, tot_len);
    }
while ((c = strchr (fullpath, '\\')))           /* standardize on / directory separator */
       *c = '/';
if ((fullpath[1] == ':') && islower (fullpath[0]))
    fullpath[0] = toupper (fullpath[0]);
while ((c = strstr (fullpath + 1, "//")))       /* strip out redundant / characters (leaving the option for a leading //) */
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
        memmove (c, c + 3, 1 + strlen (c + 3)); /* and removing intervening elements */
    else
        if (*cl == '/')
            memmove (cl, c + 3, 1 + strlen (c + 3));/* and removing intervening elements */
        else
            break;
    }



name = 1 + strrchr (fullpath, '/');
ext = strrchr (name, '.');
if (ext == NULL)
    ext = name + strlen (name);
tot_size = 0;
if (*parts == '\0')             /* empty part specifier means strip only quotes */
    tot_size = strlen (tempfilepath);














for (p = parts; *p; p++) {
    switch (*p) {
        case 'f':
            tot_size += strlen (fullpath);
            break;
        case 'p':
            tot_size += name - fullpath;
            break;
        case 'n':
            tot_size += ext - name;
            break;
        case 'x':
            tot_size += strlen (ext);
            break;






        }
    }
result = (char *)malloc (1 + tot_size);
*result = '\0';
if (*parts == '\0')             /* empty part specifier means strip only quotes */
    strlcat (result, filepath, 1 + tot_size);
for (p = parts; *p; p++) {







>
>
>
|






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














>
>
>
>
>
>







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
        memmove (c, c + 3, 1 + strlen (c + 3)); /* and removing intervening elements */
    else
        if (*cl == '/')
            memmove (cl, c + 3, 1 + strlen (c + 3));/* and removing intervening elements */
        else
            break;
    }
if (!strrchr (fullpath, '/'))
    name = fullpath + strlen (fullpath);
else
    name = 1 + strrchr (fullpath, '/');
ext = strrchr (name, '.');
if (ext == NULL)
    ext = name + strlen (name);
tot_size = 0;
if (*parts == '\0')             /* empty part specifier means strip only quotes */
    tot_size = strlen (tempfilepath);
if (strchr (parts, 't') || strchr (parts, 'z')) {
    struct stat filestat;
    struct tm *tm;

    memset (&filestat, 0, sizeof (filestat));
    (void)stat (fullpath, &filestat);
    if (sizeof (filestat.st_size) == 4)
        sprintf (filesizebuf, "%ld ", (long)filestat.st_size);
    else
        sprintf (filesizebuf, "%" LL_FMT "d ", (LL_TYPE)filestat.st_size);
    tm = localtime (&filestat.st_mtime);
    sprintf (filedatetimebuf, "%02d/%02d/%04d %02d:%02d %cM ", 1 + tm->tm_mon, tm->tm_mday, 1900 + tm->tm_year,
                                                              tm->tm_hour % 12, tm->tm_min, (0 == (tm->tm_hour % 12)) ? 'A' : 'P');
    }
for (p = parts; *p; p++) {
    switch (*p) {
        case 'f':
            tot_size += strlen (fullpath);
            break;
        case 'p':
            tot_size += name - fullpath;
            break;
        case 'n':
            tot_size += ext - name;
            break;
        case 'x':
            tot_size += strlen (ext);
            break;
        case 't':
            tot_size += strlen (filedatetimebuf);
            break;
        case 'z':
            tot_size += strlen (filesizebuf);
            break;
        }
    }
result = (char *)malloc (1 + tot_size);
*result = '\0';
if (*parts == '\0')             /* empty part specifier means strip only quotes */
    strlcat (result, filepath, 1 + tot_size);
for (p = parts; *p; p++) {
848
849
850
851
852
853
854






855
856
857
858
859
860
861
            *ext = '\0';
            strlcat (result, name, 1 + tot_size);
            *ext = chr;
            break;
        case 'x':
            strlcat (result, ext, 1 + tot_size);
            break;






        }
    }
free (fullpath);
free (tempfilepath);
return result;
}








>
>
>
>
>
>







875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
            *ext = '\0';
            strlcat (result, name, 1 + tot_size);
            *ext = chr;
            break;
        case 'x':
            strlcat (result, ext, 1 + tot_size);
            break;
        case 't':
            strlcat (result, filedatetimebuf, 1 + tot_size);
            break;
        case 'z':
            strlcat (result, filesizebuf, 1 + tot_size);
            break;
        }
    }
free (fullpath);
free (tempfilepath);
return result;
}

878
879
880
881
882
883
884
885

886
887
888
889
890
891
892
    const char *backslash = strchr (cptr, '\\');
    const char *slash = strchr (cptr, '/');
    const char *pathsep = (backslash && slash) ? MIN (backslash, slash) : (backslash ? backslash : slash);

    GetFullPathNameA(cptr, sizeof(DirName), DirName, (char **)&c);
    c = strrchr (DirName, '\\');
    *c = '\0';                                  /* Truncate to just directory path */
    if (!pathsep || (!strcmp (slash, "/*")))    /* Separator wasn't mentioned? */

        pathsep = "\\";                         /* Default to Windows backslash */
    if (*pathsep == '/') {                      /* If slash separator? */
        while ((c = strchr (DirName, '\\')))
            *c = '/';                           /* Convert backslash to slash */
        }
    sprintf (&DirName[strlen (DirName)], "%c", *pathsep);
    do {







|
>







911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
    const char *backslash = strchr (cptr, '\\');
    const char *slash = strchr (cptr, '/');
    const char *pathsep = (backslash && slash) ? MIN (backslash, slash) : (backslash ? backslash : slash);

    GetFullPathNameA(cptr, sizeof(DirName), DirName, (char **)&c);
    c = strrchr (DirName, '\\');
    *c = '\0';                                  /* Truncate to just directory path */
    if (!pathsep ||                             /* Separator wasn't mentioned? */
        (slash && (0 == strcmp (slash, "/*")))) 
        pathsep = "\\";                         /* Default to Windows backslash */
    if (*pathsep == '/') {                      /* If slash separator? */
        while ((c = strchr (DirName, '\\')))
            *c = '/';                           /* Convert backslash to slash */
        }
    sprintf (&DirName[strlen (DirName)], "%c", *pathsep);
    do {
918
919
920
921
922
923
924

925
926
927
928
929
930
931
t_stat sim_dir_scan (const char *cptr, DIR_ENTRY_CALLBACK entry, void *context)
{
#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];

memset (DirName, 0, sizeof(DirName));
memset (WholeName, 0, sizeof(WholeName));
strlcpy (WildName, cptr, sizeof(WildName));







>







952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
t_stat sim_dir_scan (const char *cptr, DIR_ENTRY_CALLBACK entry, void *context)
{
#if defined (HAVE_GLOB)
glob_t  paths;
#else
DIR *dir;
#endif
int found_count = 0;
struct stat filestat;
char *c;
char DirName[PATH_MAX + 1], WholeName[PATH_MAX + 1], WildName[PATH_MAX + 1];

memset (DirName, 0, sizeof(DirName));
memset (WholeName, 0, sizeof(WholeName));
strlcpy (WildName, cptr, sizeof(WildName));
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
if (0 == glob (cptr, 0, NULL, &paths)) {
#else
dir = opendir(DirName[0] ? DirName : "/.");
if (dir) {
    struct dirent *ent;
#endif
    t_offset FileSize;
    char FileName[PATH_MAX + 1];
    const char *MatchName = 1 + strrchr (cptr, '/');
    char *p_name;
    struct tm *local;
#if defined (HAVE_GLOB)
    size_t i;
#endif

#if defined (HAVE_GLOB)
    for (i=0; i<paths.gl_pathc; i++) {

        sprintf (FileName, "%s", paths.gl_pathv[i]);
#else
    while ((ent = readdir (dir))) {
#if defined (HAVE_FNMATCH)
        if (fnmatch(MatchName, ent->d_name, 0))
            continue;
#else
        /* only match exact name without fnmatch support */

        if (strcmp(MatchName, ent->d_name) != 0)
            continue;
#endif

        sprintf (FileName, "%s%s", DirName, ent->d_name);
#endif
        p_name = FileName + strlen (DirName);
        memset (&filestat, 0, sizeof (filestat));
        (void)stat (FileName, &filestat);
        FileSize = (t_offset)((filestat.st_mode & S_IFDIR) ? 0 : sim_fsize_name_ex (FileName));
        entry (DirName, p_name, FileSize, &filestat, context);


        }
#if defined (HAVE_GLOB)
    globfree (&paths);
#else
    closedir (dir);
#endif
    }
else
    return SCPE_ARG;

return SCPE_OK;


}
#endif /* !defined(_WIN32) */







|









>

|




|
|
>
|

|
>

|





>
>









>
|
>
>


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
if (0 == glob (cptr, 0, NULL, &paths)) {
#else
dir = opendir(DirName[0] ? DirName : "/.");
if (dir) {
    struct dirent *ent;
#endif
    t_offset FileSize;
    char *FileName;
    const char *MatchName = 1 + strrchr (cptr, '/');
    char *p_name;
    struct tm *local;
#if defined (HAVE_GLOB)
    size_t i;
#endif

#if defined (HAVE_GLOB)
    for (i=0; i<paths.gl_pathc; i++) {
        FileName = (char *)malloc (1 + strlen (paths.gl_pathv[i]));
        sprintf (FileName, "%s", paths.gl_pathv[i]);
#else /* !defined (HAVE_GLOB) */
    while ((ent = readdir (dir))) {
#if defined (HAVE_FNMATCH)
        if (fnmatch(MatchName, ent->d_name, 0))
            continue;
#else /* !defined (HAVE_FNMATCH) */
        /* only match all names or exact name without fnmatch support */
        if ((strcmp(MatchName, "*") != 0) &&
            (strcmp(MatchName, ent->d_name) != 0))
            continue;
#endif /* defined (HAVE_FNMATCH) */
        FileName = (char *)malloc (1 + strlen (DirName) + strlen (ent->d_name));
        sprintf (FileName, "%s%s", DirName, ent->d_name);
#endif /* defined (HAVE_GLOB) */
        p_name = FileName + strlen (DirName);
        memset (&filestat, 0, sizeof (filestat));
        (void)stat (FileName, &filestat);
        FileSize = (t_offset)((filestat.st_mode & S_IFDIR) ? 0 : sim_fsize_name_ex (FileName));
        entry (DirName, p_name, FileSize, &filestat, context);
        free (FileName);
        ++found_count;
        }
#if defined (HAVE_GLOB)
    globfree (&paths);
#else
    closedir (dir);
#endif
    }
else
    return SCPE_ARG;
if (found_count)
    return SCPE_OK;
else
    return SCPE_ARG;
}
#endif /* !defined(_WIN32) */

Changes to src/SIMH/sim_rev.h.

44
45
46
47
48
49
50








51
52
53
54
55
56
57
#define SIM_VERSION_MODE "Current"
#endif

#if defined(SIM_NEED_GIT_COMMIT_ID)
#include ".git-commit-id.h"
#endif









#if !defined(SIM_GIT_COMMIT_ID)
#define SIM_GIT_COMMIT_ID $Format:%H$
#define SIM_GIT_COMMIT_TIME $Format:%aI$
#endif

/*
  The comment section below reflects the manual editing process which was in place







>
>
>
>
>
>
>
>







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#define SIM_VERSION_MODE "Current"
#endif

#if defined(SIM_NEED_GIT_COMMIT_ID)
#include ".git-commit-id.h"
#endif

/*
  Simh's git commit id would be undefined when working with an 
  extracted archive (zip file or tar ball).  To address this 
  problem and record the commit id that the archive was created 
  from, the archive creation process populates the below 
  information as a consequence of the "sim_rev.h export-subst" 
  line in the .gitattributes file.
 */
#if !defined(SIM_GIT_COMMIT_ID)
#define SIM_GIT_COMMIT_ID $Format:%H$
#define SIM_GIT_COMMIT_TIME $Format:%aI$
#endif

/*
  The comment section below reflects the manual editing process which was in place

Changes to src/SIMH/sim_serial.c.

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    int i;
    char desc[SER_DEV_DESC_MAX], *d;

    fprintf(st,"Open Serial Devices:\n");
    for (i=0; i<serial_open_device_count; i++) {
        d = sim_serial_getdesc_byname(serial_open_devices[i].name, desc);
        fprintf(st, " %s\tLn%02d %s%s%s%s\tConfig: %s\n", serial_open_devices[i].line->mp->dptr->name, (int)(serial_open_devices[i].line->mp->ldsc-serial_open_devices[i].line),
                    serial_open_devices[i].line->destination, d ? " {" : "", d ? d : "", d ? ")" : "", serial_open_devices[i].line->serconfig);
        }
    }
return SCPE_OK;
}

SERHANDLE sim_open_serial (char *name, TMLN *lp, t_stat *stat)
{







|







358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    int i;
    char desc[SER_DEV_DESC_MAX], *d;

    fprintf(st,"Open Serial Devices:\n");
    for (i=0; i<serial_open_device_count; i++) {
        d = sim_serial_getdesc_byname(serial_open_devices[i].name, desc);
        fprintf(st, " %s\tLn%02d %s%s%s%s\tConfig: %s\n", serial_open_devices[i].line->mp->dptr->name, (int)(serial_open_devices[i].line->mp->ldsc-serial_open_devices[i].line),
                    serial_open_devices[i].line->destination, ((d != NULL) && (*d != '\0')) ? " (" : "", ((d != NULL) && (*d != '\0'))  ? d : "", ((d != NULL) && (*d != '\0'))  ? ")" : "", serial_open_devices[i].line->serconfig);
        }
    }
return SCPE_OK;
}

SERHANDLE sim_open_serial (char *name, TMLN *lp, t_stat *stat)
{
444
445
446
447
448
449
450
451
452

453
454
455
456
457
458
459
    _serial_add_to_open_list (port, lp, savname, config);

return port;
}

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 };







<

>







444
445
446
447
448
449
450

451
452
453
454
455
456
457
458
459
    _serial_add_to_open_list (port, lp, savname, config);

return port;
}

void sim_close_serial (SERHANDLE port)
{

_serial_remove_from_open_list (port);
sim_close_os_serial (port);
}

t_stat sim_config_serial  (SERHANDLE port, CONST char *sconfig)
{
CONST char *pptr;
CONST char *sptr, *tptr;
SERCONFIG config = { 0 };

Changes to src/SIMH/sim_sock.c.

258
259
260
261
262
263
264

265
266
267
268
269
270
271
    memset(&dhints, 0, sizeof(dhints));
    dhints.ai_family = PF_UNSPEC;
    }
if (service) {
    char *c;

    port = strtoul(service, &c, 10);

    if ((port == 0) || (*c != '\0')) {
        switch (hints->ai_socktype)
            {
            case SOCK_DGRAM:
                se = getservbyname(service, "udp");
                break;
            case SOCK_STREAM:







>







258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    memset(&dhints, 0, sizeof(dhints));
    dhints.ai_family = PF_UNSPEC;
    }
if (service) {
    char *c;

    port = strtoul(service, &c, 10);
    port = htons((unsigned short)port);
    if ((port == 0) || (*c != '\0')) {
        switch (hints->ai_socktype)
            {
            case SOCK_DGRAM:
                se = getservbyname(service, "udp");
                break;
            case SOCK_STREAM:
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
    }

if (hostname) {
    if ((0xffffffff != (ipaddr.s_addr = inet_addr(hostname))) || 
        (0 == strcmp("255.255.255.255", hostname))) {
        fixed[0] = &ipaddr;
        fixed[1] = NULL;
        }
    else {
        if ((0xffffffff != (ipaddr.s_addr = inet_addr(hostname))) || 
            (0 == strcmp("255.255.255.255", hostname))) {
            fixed[0] = &ipaddr;
            fixed[1] = NULL;
            if ((hints->ai_flags & AI_CANONNAME) && !(hints->ai_flags & AI_NUMERICHOST)) {
                he = gethostbyaddr((char *)&ipaddr, 4, AF_INET);
                if (NULL != he)
                    cname = he->h_name;
                else
                    cname = hostname;
                }
            ips = fixed;
            }
        else {
            if (hints->ai_flags & AI_NUMERICHOST)
                return EAI_NONAME;
            he = gethostbyname(hostname);
            if (he) {
                ips = (struct in_addr **)he->h_addr_list;
                if (hints->ai_flags & AI_CANONNAME)
                    cname = he->h_name;
                }
            else {
                switch (h_errno)
                    {
                    case HOST_NOT_FOUND:
                    case NO_DATA:
                        return EAI_NONAME;
                    case TRY_AGAIN:
                        return EAI_AGAIN;
                    default:
                        return EAI_FAIL;
                    }
                }
            }
        }
    }
else {
    if (hints->ai_flags & AI_PASSIVE)
        ipaddr.s_addr = htonl(INADDR_ANY);







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







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
    }

if (hostname) {
    if ((0xffffffff != (ipaddr.s_addr = inet_addr(hostname))) || 
        (0 == strcmp("255.255.255.255", hostname))) {
        fixed[0] = &ipaddr;
        fixed[1] = NULL;






        if ((hints->ai_flags & AI_CANONNAME) && !(hints->ai_flags & AI_NUMERICHOST)) {
            he = gethostbyaddr((char *)&ipaddr, 4, AF_INET);
            if (NULL != he)
                cname = he->h_name;
            else
                cname = hostname;
            }
        ips = fixed;
        }
    else {
        if (hints->ai_flags & AI_NUMERICHOST)
            return EAI_NONAME;
        he = gethostbyname(hostname);
        if (he) {
            ips = (struct in_addr **)he->h_addr_list;
            if (hints->ai_flags & AI_CANONNAME)
                cname = he->h_name;
            }
        else {
            switch (h_errno)
                {
                case HOST_NOT_FOUND:
                case NO_DATA:
                    return EAI_NONAME;
                case TRY_AGAIN:
                    return EAI_AGAIN;
                default:
                    return EAI_FAIL;

                }
            }
        }
    }
else {
    if (hints->ai_flags & AI_PASSIVE)
        ipaddr.s_addr = htonl(INADDR_ANY);
433
434
435
436
437
438
439




440
441
442
443
444
445
446
return 0;
}

#if defined(_WIN32) || defined(__CYGWIN__)

#if !defined(IPV6_V6ONLY)           /* Older XP environments may not define IPV6_V6ONLY */
#define IPV6_V6ONLY           27    /* Treat wildcard bind as AF_INET6-only. */




#endif
/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0;                      /* handle to DLL */
#else
static void *hLib = NULL;                       /* handle to Library */
#endif







>
>
>
>







427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
return 0;
}

#if defined(_WIN32) || defined(__CYGWIN__)

#if !defined(IPV6_V6ONLY)           /* Older XP environments may not define IPV6_V6ONLY */
#define IPV6_V6ONLY           27    /* Treat wildcard bind as AF_INET6-only. */
#endif
#if defined(TEST_INFO_STUBS)
#undef IPV6_V6ONLY
#undef AF_INET6
#endif
/* Dynamic DLL load variables */
#ifdef _WIN32
static HINSTANCE hLib = 0;                      /* handle to DLL */
#else
static void *hLib = NULL;                       /* handle to Library */
#endif
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
        port_len =      length of port buffer

   Outputs:
        host    =       pointer to buffer for IP address (may be NULL), 0 = none
        port    =       pointer to buffer for IP port (may be NULL), 0 = none
        localport
                =       pointer to buffer for local IP port (may be NULL), 0 = none
        result  =       status (SCPE_OK on complete success or SCPE_ARG if 
                        parsing can't happen due to bad syntax, a value is 
                        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_ex (const char *cptr, char *host, size_t hostlen, const char *default_host, char *port, size_t port_len, char *localport, size_t localport_len, const char *default_port)
{







|







684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
        port_len =      length of port buffer

   Outputs:
        host    =       pointer to buffer for IP address (may be NULL), 0 = none
        port    =       pointer to buffer for IP port (may be NULL), 0 = none
        localport
                =       pointer to buffer for local IP port (may be NULL), 0 = none
        result  =       status (0 on complete success or -1 if 
                        parsing can't happen due to bad syntax, a value is 
                        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_ex (const char *cptr, char *host, size_t hostlen, const char *default_host, char *port, size_t port_len, char *localport, size_t localport_len, const char *default_port)
{
741
742
743
744
745
746
747






748
749
750
751
752
753
754
    p_getnameinfo = (getnameinfo_func)s_getnameinfo;
    p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
#endif                                                  /* endif AF_INET6 */
#endif                                                  /* endif _WIN32 */
#if defined (SIGPIPE)
signal (SIGPIPE, SIG_IGN);                              /* no pipe signals */
#endif






}

void sim_cleanup_sock (void)
{
#if defined (_WIN32)
WSACleanup ();
#endif







>
>
>
>
>
>







739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
    p_getnameinfo = (getnameinfo_func)s_getnameinfo;
    p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
#endif                                                  /* endif AF_INET6 */
#endif                                                  /* endif _WIN32 */
#if defined (SIGPIPE)
signal (SIGPIPE, SIG_IGN);                              /* no pipe signals */
#endif
#if defined(TEST_INFO_STUBS)
/* force use of stubs */
p_getaddrinfo = (getaddrinfo_func)s_getaddrinfo;
p_getnameinfo = (getnameinfo_func)s_getnameinfo;
p_freeaddrinfo = (freeaddrinfo_func)s_freeaddrinfo;
#endif
}

void sim_cleanup_sock (void)
{
#if defined (_WIN32)
WSACleanup ();
#endif
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
sta = bind (newsock, preferred->ai_addr, preferred->ai_addrlen);
p_freeaddrinfo(result);
if (sta == SOCKET_ERROR)                                /* bind error? */
    return sim_err_sock (newsock, "bind");
if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* fcntl error? */
        return sim_err_sock (newsock, "fcntl");
    }
sta = listen (newsock, 1);                              /* listen on socket */
if (sta == SOCKET_ERROR)                                /* listen error? */
    return sim_err_sock (newsock, "listen");
return newsock;                                         /* got it! */
}








|







924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
sta = bind (newsock, preferred->ai_addr, preferred->ai_addrlen);
p_freeaddrinfo(result);
if (sta == SOCKET_ERROR)                                /* bind error? */
    return sim_err_sock (newsock, "bind");
if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* fcntl error? */
        return sim_err_sock (newsock, "setnonblock");
    }
sta = listen (newsock, 1);                              /* listen on socket */
if (sta == SOCKET_ERROR)                                /* listen error? */
    return sim_err_sock (newsock, "listen");
return newsock;                                         /* got it! */
}

992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
        }
    }

if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR) {                          /* fcntl error? */
        p_freeaddrinfo (result);
        return sim_err_sock (newsock, "fcntl");
        }
    }
if ((!(opt_flags & SIM_SOCK_OPT_DATAGRAM)) && (opt_flags & SIM_SOCK_OPT_NODELAY)) {
    sta = sim_setnodelay (newsock);                     /* set nodelay */
    if (sta == SOCKET_ERROR) {                          /* setsock error? */
        p_freeaddrinfo (result);
        return sim_err_sock (newsock, "setnodelay");







|







996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
        }
    }

if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR) {                          /* fcntl error? */
        p_freeaddrinfo (result);
        return sim_err_sock (newsock, "setnonblock");
        }
    }
if ((!(opt_flags & SIM_SOCK_OPT_DATAGRAM)) && (opt_flags & SIM_SOCK_OPT_NODELAY)) {
    sta = sim_setnodelay (newsock);                     /* set nodelay */
    if (sta == SOCKET_ERROR) {                          /* setsock error? */
        p_freeaddrinfo (result);
        return sim_err_sock (newsock, "setnodelay");
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
{
int sta = 0, err;
int keepalive = 1;
#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 size;
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int size;
#else 
size_t size; 







|







1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
{
int sta = 0, err;
int keepalive = 1;
#if defined (macintosh) || defined (__linux) || defined (__linux__) || \
    defined (__APPLE__) || defined (__OpenBSD__) || \
    defined(__NetBSD__) || defined(__FreeBSD__) || \
    (defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED)) || \
    defined (__HAIKU__) || defined(__CYGWIN__)
socklen_t size;
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int size;
#else 
size_t size; 
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
    err = WSAGetLastError ();
    if (err != WSAEWOULDBLOCK)
        sim_err_sock(newsock, "accept");
    return INVALID_SOCKET;
    }
if (connectaddr != NULL) {
    *connectaddr = (char *)calloc(1, NI_MAXHOST+1);
#ifdef AF_INET6
    p_getnameinfo((struct sockaddr *)&clientname, size, *connectaddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
    if (0 == memcmp("::ffff:", *connectaddr, 7))        /* is this a IPv4-mapped IPv6 address? */
        memmove(*connectaddr, 7+*connectaddr,           /* prefer bare IPv4 address */
                strlen(*connectaddr) - 7 + 1);          /* length to include terminating \0 */
#else
    strcpy(*connectaddr, inet_ntoa(((struct sockaddr_in *)&connectaddr)->s_addr));
#endif
    }

if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* fcntl error? */
        return sim_err_sock (newsock, "fcntl");
    }

if ((opt_flags & SIM_SOCK_OPT_NODELAY)) {
    sta = sim_setnodelay (newsock);                     /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* setsockopt error? */
        return sim_err_sock (newsock, "setnodelay");
    }







<




<
<
<





|







1070
1071
1072
1073
1074
1075
1076

1077
1078
1079
1080



1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    err = WSAGetLastError ();
    if (err != WSAEWOULDBLOCK)
        sim_err_sock(newsock, "accept");
    return INVALID_SOCKET;
    }
if (connectaddr != NULL) {
    *connectaddr = (char *)calloc(1, NI_MAXHOST+1);

    p_getnameinfo((struct sockaddr *)&clientname, size, *connectaddr, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
    if (0 == memcmp("::ffff:", *connectaddr, 7))        /* is this a IPv4-mapped IPv6 address? */
        memmove(*connectaddr, 7+*connectaddr,           /* prefer bare IPv4 address */
                strlen(*connectaddr) - 7 + 1);          /* length to include terminating \0 */



    }

if (!(opt_flags & SIM_SOCK_OPT_BLOCKING)) {
    sta = sim_setnonblock (newsock);                    /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* fcntl error? */
        return sim_err_sock (newsock, "setnonblock");
    }

if ((opt_flags & SIM_SOCK_OPT_NODELAY)) {
    sta = sim_setnodelay (newsock);                     /* set nonblocking */
    if (sta == SOCKET_ERROR)                            /* setsockopt error? */
        return sim_err_sock (newsock, "setnodelay");
    }
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
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); 







|







1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
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__) || defined(__CYGWIN__)
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); 
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

static int _sim_getaddrname (struct sockaddr *addr, size_t addrsize, char *hostnamebuf, char *portnamebuf)
{
#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 size = (socklen_t)addrsize;
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int size = (int)addrsize;
#else 
size_t size = addrsize; 
#endif
int ret = 0;

#ifdef AF_INET6
*hostnamebuf = '\0';
*portnamebuf = '\0';
ret = p_getnameinfo(addr, size, hostnamebuf, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (0 == memcmp("::ffff:", hostnamebuf, 7))        /* is this a IPv4-mapped IPv6 address? */
    memmove(hostnamebuf, 7+hostnamebuf,            /* prefer bare IPv4 address */
            strlen(hostnamebuf) + 7 - 1);          /* length to include terminating \0 */
if (!ret)
    ret = p_getnameinfo(addr, size, NULL, 0, portnamebuf, NI_MAXSERV, NI_NUMERICSERV);
#else
strcpy(hostnamebuf, inet_ntoa(((struct sockaddr_in *)addr)->s_addr));
sprintf(portnamebuf, "%d", (int)ntohs(((struct sockaddr_in *)addr)->s_port)));
#endif
return ret;
}

int sim_getnames_sock (SOCKET sock, char **socknamebuf, char **peernamebuf)
{
struct sockaddr_storage sockname, 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 socknamesize = (socklen_t)sizeof(sockname);
socklen_t peernamesize = (socklen_t)sizeof(peername);
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int socknamesize = (int)sizeof(sockname);
int peernamesize = (int)sizeof(peername);







|










<








<
<
<
<










|







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

static int _sim_getaddrname (struct sockaddr *addr, size_t addrsize, char *hostnamebuf, char *portnamebuf)
{
#if defined (macintosh) || defined (__linux) || defined (__linux__) || \
    defined (__APPLE__) || defined (__OpenBSD__) || \
    defined(__NetBSD__) || defined(__FreeBSD__) || \
    (defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED)) || \
    defined (__HAIKU__) || defined(__CYGWIN__)
socklen_t size = (socklen_t)addrsize;
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int size = (int)addrsize;
#else 
size_t size = addrsize; 
#endif
int ret = 0;


*hostnamebuf = '\0';
*portnamebuf = '\0';
ret = p_getnameinfo(addr, size, hostnamebuf, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if (0 == memcmp("::ffff:", hostnamebuf, 7))        /* is this a IPv4-mapped IPv6 address? */
    memmove(hostnamebuf, 7+hostnamebuf,            /* prefer bare IPv4 address */
            strlen(hostnamebuf) + 7 - 1);          /* length to include terminating \0 */
if (!ret)
    ret = p_getnameinfo(addr, size, NULL, 0, portnamebuf, NI_MAXSERV, NI_NUMERICSERV);




return ret;
}

int sim_getnames_sock (SOCKET sock, char **socknamebuf, char **peernamebuf)
{
struct sockaddr_storage sockname, peername;
#if defined (macintosh) || defined (__linux) || defined (__linux__) || \
    defined (__APPLE__) || defined (__OpenBSD__) || \
    defined(__NetBSD__) || defined(__FreeBSD__) || \
    (defined(__hpux) && defined(_XOPEN_SOURCE_EXTENDED)) || \
    defined (__HAIKU__) || defined(__CYGWIN__)
socklen_t socknamesize = (socklen_t)sizeof(sockname);
socklen_t peernamesize = (socklen_t)sizeof(peername);
#elif defined (_WIN32) || defined (__EMX__) || \
     (defined (__ALPHA) && defined (__unix__)) || \
     defined (__hpux)
int socknamesize = (int)sizeof(sockname);
int peernamesize = (int)sizeof(peername);

Changes to src/SIMH/sim_sock.h.

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#define SIM_SOCK_OPT_REUSEADDR      0x0001
#define SIM_SOCK_OPT_DATAGRAM       0x0002
#define SIM_SOCK_OPT_NODELAY        0x0004
#define SIM_SOCK_OPT_BLOCKING       0x0008
SOCKET sim_master_sock_ex (const char *hostport, int *parse_status, int opt_flags);
#define sim_master_sock(hostport, parse_status) sim_master_sock_ex(hostport, parse_status, ((sim_switches & SWMASK ('U')) ? SIM_SOCK_OPT_REUSEADDR : 0))
SOCKET sim_connect_sock_ex (const char *sourcehostport, const char *hostport, const char *default_host, const char *default_port, int opt_flags);
#define sim_connect_sock(hostport, default_host, default_port) sim_connect_sock_ex(NULL, hostport, default_host, default_port, 0)
SOCKET sim_accept_conn_ex (SOCKET master, char **connectaddr, int opt_flags);
#define sim_accept_conn(master, connectaddr) sim_accept_conn_ex(master, connectaddr, 0)
int sim_check_conn (SOCKET sock, int rd);
int sim_read_sock (SOCKET sock, char *buf, int nbytes);
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);







|







116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#define SIM_SOCK_OPT_REUSEADDR      0x0001
#define SIM_SOCK_OPT_DATAGRAM       0x0002
#define SIM_SOCK_OPT_NODELAY        0x0004
#define SIM_SOCK_OPT_BLOCKING       0x0008
SOCKET sim_master_sock_ex (const char *hostport, int *parse_status, int opt_flags);
#define sim_master_sock(hostport, parse_status) sim_master_sock_ex(hostport, parse_status, ((sim_switches & SWMASK ('U')) ? SIM_SOCK_OPT_REUSEADDR : 0))
SOCKET sim_connect_sock_ex (const char *sourcehostport, const char *hostport, const char *default_host, const char *default_port, int opt_flags);
#define sim_connect_sock(hostport, default_host, default_port) sim_connect_sock_ex(NULL, hostport, default_host, default_port, SIM_SOCK_OPT_BLOCKING)
SOCKET sim_accept_conn_ex (SOCKET master, char **connectaddr, int opt_flags);
#define sim_accept_conn(master, connectaddr) sim_accept_conn_ex(master, connectaddr, 0)
int sim_check_conn (SOCKET sock, int rd);
int sim_read_sock (SOCKET sock, char *buf, int nbytes);
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);

Changes to src/SIMH/sim_tape.c.

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
#include "sim_tape.h"
#include <ctype.h>

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif

struct sim_tape_fmt {
    const char          *name;                          /* name */
    int32          uflags;                         /* unit flags */
    t_addr              bot;                            /* bot test */
    t_addr              eom_remnant;                    /* potentially unprocessed data */
    };

static struct sim_tape_fmt fmts[MTUF_N_FMT] = {
    { "SIMH", 0,       sizeof (t_mtrlnt) - 1,  sizeof (t_mtrlnt)},
    { "E11",  0,       sizeof (t_mtrlnt) - 1,  sizeof (t_mtrlnt) },
    { "TPC",  UNIT_RO, sizeof (t_tpclnt) - 1,  sizeof (t_tpclnt) },
    { "P7B",  0,       0,                      0 },
    { "AWS",  0,       0,                      0 },
    { "TAR",  0,       0,                      0 },



    { NULL,   0,       0 }
    };

static const uint32 bpi [] = {                          /* tape density table, indexed by MT_DENS constants */
    0,                                                  /*   0 = MT_DENS_NONE -- density not set */
    200,                                                /*   1 = MT_DENS_200  -- 200 bpi NRZI */
    556,                                                /*   2 = MT_DENS_556  -- 556 bpi NRZI */
    800,                                                /*   3 = MT_DENS_800  -- 800 bpi NRZI */







|

|


<
|
<
|
|
|
|
|
|
>
>
>
|







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
#include "sim_tape.h"
#include <ctype.h>

#if defined SIM_ASYNCH_IO
#include <pthread.h>
#endif

static struct sim_tape_fmt {
    const char          *name;                          /* name */
    int32               uflags;                         /* unit flags */
    t_addr              bot;                            /* bot test */
    t_addr              eom_remnant;                    /* potentially unprocessed data */

    } fmts[] = {

    { "SIMH",       0,       sizeof (t_mtrlnt) - 1, sizeof (t_mtrlnt) },
    { "E11",        0,       sizeof (t_mtrlnt) - 1, sizeof (t_mtrlnt) },
    { "TPC",        UNIT_RO, sizeof (t_tpclnt) - 1, sizeof (t_tpclnt) },
    { "P7B",        0,       0,                     0                 },
    { "AWS",        0,       0,                     0                 },
    { "TAR",        UNIT_RO, 0,                     0                 },
    { "ANSI",       UNIT_RO, 0,                     0                 },
    { "FIXED",      UNIT_RO, 0,                     0                 },
    { "DOS11",      UNIT_RO, 0,                     0                 },
    { NULL,         0,       0,                     0                 }
    };

static const uint32 bpi [] = {                          /* tape density table, indexed by MT_DENS constants */
    0,                                                  /*   0 = MT_DENS_NONE -- density not set */
    200,                                                /*   1 = MT_DENS_200  -- 200 bpi NRZI */
    556,                                                /*   2 = MT_DENS_556  -- 556 bpi NRZI */
    800,                                                /*   3 = MT_DENS_800  -- 800 bpi NRZI */
371
372
373
374
375
376
377





































































































































































378
379
380
381
382
383
384
    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)
return sim_messagef (SCPE_NOFNC, "Tape: can't operate asynchronously\r\n");







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







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
    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

typedef struct VOL1 {
    char type[3];               /* VOL  */
    char num;                   /* 1    */
    char ident[6];              /* <ansi <a> characters blank padded > */
    char accessibity;           /* blank */
    char reserved1[13];         /*      */
    char implement[13];         /*      */
    char owner[14];             /*      */
    char reserved2[28];         /*      */
    char standard;              /* 1,3 or 4  */
    } VOL1;

typedef struct HDR1 {       /* Also EOF1, EOV1 */
    char type[3];               /* HDR|EOF|EOV  */
    char num;                   /* 1    */
    char file_ident[17];        /* filename */
    char file_set[6];           /* label ident */
    char file_section[4];       /* 0001 */
    char file_sequence[4];      /* 0001 */
    char generation_number[4];  /* 0001 */
    char version_number[2];     /* 00 */
    char creation_date[6];      /* cyyddd */
    char expiration_date[6];
    char accessibility;         /* space */
    char block_count[6];        /* 000000 */
    char system_code[13];       /* */
    char reserved[7];           /* blank */
    } HDR1;

typedef struct HDR2 {       /* Also EOF2, EOV2 */
    char type[3];               /* HDR  */
    char num;                   /* 2    */
    char record_format;         /* F(fixed)|D(variable)|S(spanned) */
    char block_length[5];       /* label ident */
    char record_length[5];      /*  */
    char reserved_os1[21];      /* */
    char carriage_control;      /* A - Fortran CC, M - Record contained CC, space - CR/LF to be added */
    char reserved_os2[13];      /* */
    char buffer_offset[2];      /* */
    char reserved_std[28];      /* */
    } HDR2;

typedef struct HDR3 {       /* Also EOF3, EOV3 */
    char type[3];               /* HDR  */
    char num;                   /* 2    */
    char record_format;         /* F(fixed)|D(variable)|S(spanned) */
    char block_length[5];       /* label ident */
    char record_length[5];      /*  */
    char reserved_os[35];       /* */
    char buffer_offset[2];      /* */
    char reserved_std[28];      /* */
    } HDR3;

typedef struct HDR4 {       /* Also EOF4, EOV4 */
    char type[3];               /* HDR  */
    char num;                   /* 4    */
    char blank;                 /* blank */
    char extra_name[62];        /*  */
    char extra_name_used[2];    /* 99 */
    char unused[11];
    } HDR4;

typedef struct TAPE_RECORD {
    uint32 size;
    uint8 data[1];
    } TAPE_RECORD;

typedef struct MEMORY_TAPE {
    uint32 ansi_type;       /* ANSI-VMS, ANSI-RT11, ANSI-RSTS, ANSI-RSX11, etc. */
    uint32 file_count;      /* number of labeled files */
    uint32 record_count;    /* number of entries in the record array */
    uint32 array_size;      /* allocated size of records array */
    uint32 block_size;      /* tape block size */
    TAPE_RECORD **records;
    VOL1 vol1;
    } MEMORY_TAPE;

const char HDR3_RMS_STREAM[] = "HDR3020002040000" 
                               "0000000100000000" 
                               "0000000002000000" 
                               "0000000000000000" 
                               "0000            ";
const char HDR3_RMS_STMLF[] =  "HDR3020002050000" 
                               "0000000100000000" 
                               "0000000002000000" 
                               "0000000000000000" 
                               "0000            ";
const char HDR3_RMS_VAR[] =    "HDR3005C02020000" 
                               "0000000100000000" 
                               "0000000000000000" 
                               "0000000000000000" 
                               "0000            ";
const char HDR3_RMS_FIXED[] =  "HDR3020000010000" 
                               "0000000100000000" 
                               "0000000002000000" 
                               "0000000000000000" 
                               "0000            ";
const char HDR3_RMS_VARRSX[] = "HDR300000A020000" 
                               "0000000100000000" 
                               "0000000000000000" 
                               "0000000000000000" 
                               "0000            ";
const char HDR3_RMS_FIXRSX[] = "HDR3020008010000" 
                               "0000000100000000" 
                               "0000000000000000" 
                               "0000000000000000" 
                               "0000            ";

static struct ansi_tape_parameters {
    const char          *name;                  /* operating system */
    const char          *system_code;           /* */
    t_bool              nohdr2;                 /* no HDR2 records */
    t_bool              nohdr3;                 /* no HDR2 records */
    t_bool              fixed_text;             /*  */
    char                vol1_standard;          /* 3 or 4 */
    const char          *hdr3_fixed;            /* HDR3 template for Fixed format files */
    const char          *hdr3_lf_line_endings;  /* HDR3 template for text with LF line ending files */
    const char          *hdr3_crlf_line_endings;/* HDR3 template for text with CRLF line ending files */
    int                 skip_lf_line_endings;
    int                 skip_crlf_line_endings;
    t_bool              y2k_date_bug;
    t_bool              zero_record_length;
    char                record_format;
    char                carriage_control;
    } ansi_args[] = {     /* code       nohdr2 nohdr3 fixed_text lvl hdr3 fir fuxed    hdr3 fir lf      hdr3 for crlf  skLF CRLF Y2KDT  0RecLnt RFM  CC*/
        {"ANSI-VMS"      , "DECFILE11A", FALSE, FALSE, FALSE,    '3', HDR3_RMS_FIXED,  HDR3_RMS_STMLF,  HDR3_RMS_STREAM, 0,   0, FALSE, FALSE,   0,   0},
        {"ANSI-RSX11"    , "DECFILE11A", FALSE, FALSE, FALSE,    '4', HDR3_RMS_FIXRSX, HDR3_RMS_VARRSX, HDR3_RMS_VARRSX, 1,   2, FALSE, FALSE,   0,   0},
        {"ANSI-RT11"     , "DECRT11A",   TRUE,  TRUE,  TRUE,     '3', NULL,            NULL,            NULL,            0,   0, FALSE, FALSE,   0,   0},
        {"ANSI-RSTS"     , "DECRSTS/E",  FALSE, TRUE,  TRUE,     '3', NULL,            NULL,            NULL,            0,   0, TRUE,  TRUE,  'U', 'M'},
        {"ANSI-VAR"      , "DECRSTS/E",  FALSE, TRUE,  FALSE,    '3', NULL,            NULL,            NULL,            1,   2, TRUE,  FALSE, 'D', ' '},
        {NULL}
    };


static MEMORY_TAPE *ansi_create_tape (const char *label, uint32 block_size, uint32 ansi_type);
static MEMORY_TAPE *memory_create_tape (void);
static void memory_free_tape (void *vtape);
static void sim_tape_add_ansi_entry (const char *directory, 
                                     const char *filename,
                                     t_offset FileSize,
                                     const struct stat *filestat,
                                     void *context);
static t_bool memory_tape_add_block (MEMORY_TAPE *tape, uint8 *block, uint32 size);

typedef struct DOS11_HDR {
    uint16 fname[2];        /* File name (RAD50 - 6 characters) */
    uint16 ext;             /* Extension (RAD50 - 3 characters) */
    uint8  prog;            /* Programmer # */
    uint8  proj;            /* Project # */
    uint16 prot;            /* Protection */
    uint16 date;            /* (year - 1970) * 1000 + day of year */
    uint16 fname3;          /* File name (RAD50 - 3 characters) */
    } DOS11_HDR;
#define DOS11_PROT      0233

static void sim_tape_add_dos11_entry (const char *directory,
                                      const char *filename,
                                      t_offset FileSize,
                                      const struct stat *filestat,
                                      void *context);

static t_stat sim_export_tape (UNIT *uptr, const char *export_file);
static FILE *tape_open_and_check_file(const char *filename);
static int tape_classify_file_contents (FILE *f, size_t *max_record_size, t_bool *lf_line_endings, t_bool *crlf_line_endings);


/* Enable asynchronous operation */

t_stat sim_tape_set_async (UNIT *uptr, int latency)
{
#if !defined(SIM_ASYNCH_IO)
return sim_messagef (SCPE_NOFNC, "Tape: can't operate asynchronously\r\n");
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
#if defined (SIM_ASYNCH_IO)
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

sim_tape_clr_async (uptr);
if (sim_asynch_enabled)
    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) || (dptr->debflags)) ? MTSE_DBG_API : 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;
t_bool had_debug = (sim_deb != NULL);
uint32 starting_dctrl = uptr->dctrl;
int32 saved_switches = sim_switches;


if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return sim_messagef (SCPE_2FARG, "Missing Format specifier and filename to attach\n");
    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_TAR) {
    if (sim_switches & SWMASK ('B')) {                  /* Record Size (blocking factor)? */
        uint32 recsize;

        cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
        if (*cptr == 0)                                     /* must be more */
            return sim_messagef (SCPE_2FARG, "Missing Record Size and filename to attach\n");
        recsize = (uint32) get_uint (gbuf, 10, 65536, &r);
        if ((r != SCPE_OK) || (recsize == 0))
            return sim_messagef (SCPE_ARG, "Invalid Tape Record Size: %s\n", gbuf);
        uptr->recsize = recsize;
        sim_switches = sim_switches & ~(SWMASK ('B'));      /* Record Blocking Factor */
        }

    if (uptr->recsize == 0)
        uptr->recsize = TAR_DFLT_RECSIZE;
    }
if ((MT_GET_FMT (uptr) == MTUF_F_TPC) ||
    (MT_GET_FMT (uptr) == MTUF_F_TAR))

    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC and TAR 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);


if ((sim_switches & SWMASK ('D')) && !had_debug) {
    sim_switches |= SWMASK ('E');
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }







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



















>
>





>






|





<
|
<
<
|
|
|
|
|
|
|
|
|
>
|



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







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
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
#if defined (SIM_ASYNCH_IO)
struct tape_context *ctx = (struct tape_context *)uptr->tape_ctx;

sim_tape_clr_async (uptr);
if (sim_asynch_enabled)
    sim_tape_set_async (uptr, ctx->asynch_io_latency);
#endif
if (MT_GET_FMT (uptr) < MTUF_F_ANSI)
    fflush (uptr->fileref);
}

static const char *_sim_tape_format_name (UNIT *uptr)
{
int32 f = MT_GET_FMT (uptr);

if (f == MTUF_F_ANSI)
    return ansi_args[MT_GET_ANSI_TYP (uptr)].name;
else
    return fmts[f].name;
}

/* 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) || (dptr->debflags)) ? MTSE_DBG_API : 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];
char export_file[CBUFSIZE] = "";
uint32 recsize = 0;
t_stat r;
t_bool auto_format = FALSE;
t_bool had_debug = (sim_deb != NULL);
uint32 starting_dctrl = uptr->dctrl;
int32 saved_switches = sim_switches;
MEMORY_TAPE *tape = NULL;

if ((dptr = find_dev_from_unit (uptr)) == NULL)
    return SCPE_NOATT;
if (sim_switches & SWMASK ('F')) {                      /* format spec? */
    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return sim_messagef (SCPE_2FARG, "Missing Format specifier and/or filename to attach\n");
    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 (sim_switches & SWMASK ('B')) {                  /* Record Size (blocking factor)? */


    cptr = get_glyph (cptr, gbuf, 0);                   /* get spec */
    if (*cptr == 0)                                     /* must be more */
        return sim_messagef (SCPE_2FARG, "Missing Record Size and filename to attach\n");
    recsize = (uint32) get_uint (gbuf, 10, 65536, &r);
    if ((r != SCPE_OK) || (recsize == 0))
        return sim_messagef (SCPE_ARG, "Invalid Tape Record Size: %s\n", gbuf);
    uptr->recsize = recsize;
    sim_switches = sim_switches & ~(SWMASK ('B'));      /* Record Blocking Factor */
    }
else {
    if ((MT_GET_FMT (uptr) == MTUF_F_TAR) && (uptr->recsize == 0))
        uptr->recsize = TAR_DFLT_RECSIZE;
    }
if ((MT_GET_FMT (uptr) == MTUF_F_TPC) ||
    (MT_GET_FMT (uptr) == MTUF_F_TAR) ||
    (MT_GET_FMT (uptr) >= MTUF_F_ANSI))
    sim_switches |= SWMASK ('R');                       /* Force ReadOnly attach for TPC, TAR and ANSI tapes */
if (sim_switches & SWMASK ('X'))
    cptr = get_glyph_nc (cptr, export_file, 0);         /* get export file spec */
switch (MT_GET_FMT (uptr)) {
    case MTUF_F_ANSI:
        if (1) {
            const char *ocptr = cptr;
            char label[CBUFSIZE] = "simh";
            int file_errors = 0;

            if ((MT_GET_ANSI_TYP (uptr) == MTAT_F_RT11)  ||
                (MT_GET_ANSI_TYP (uptr) == MTAT_F_RSX11) ||
                (MT_GET_ANSI_TYP (uptr) == MTAT_F_RSTS))
                uptr->recsize = 512;
            if (uptr->recsize == 0)
                uptr->recsize = 2048;
            else {
                if ((uptr->recsize < 512) || (uptr->recsize % 512))
                    return sim_messagef (SCPE_ARG, "Block size of %u is below or not a multiple of the required minimum ANSI size of 512.\n", uptr->recsize); 
                }
            tape = ansi_create_tape (label, uptr->recsize, MT_GET_ANSI_TYP (uptr));
            uptr->fileref = (FILE *)tape;
            if (!uptr->fileref)
                return SCPE_MEM;
            while (*cptr != 0) {                                    /* do all mods */
                uint32 initial_file_count = tape->file_count;

                cptr = get_glyph_nc (cptr, gbuf, ',');              /* get filename */
                r = sim_dir_scan (gbuf, sim_tape_add_ansi_entry, tape);
                if (r != SCPE_OK)
                    sim_messagef (SCPE_ARG, "file not found: %s\n", gbuf);
                if (tape->file_count == initial_file_count)
                    ++file_errors;
                }
            if ((tape->file_count > 0) && (file_errors == 0)) {
                r = SCPE_OK;
                memory_tape_add_block (tape, NULL, 0);  /* Tape Mark */
                uptr->flags |= UNIT_ATT;
                uptr->filename = (char *)malloc (strlen (ocptr) + 1);
                strcpy (uptr->filename, ocptr);
                uptr->tape_eom = tape->record_count;
                }
            else {
                r = SCPE_ARG;
                memory_free_tape (uptr->fileref);
                uptr->fileref = NULL;
                cptr = ocptr;
                }
            }
        break;

    case MTUF_F_FIXED:
        if (1) {
            FILE *f;
            size_t max_record_size;
            t_bool lf_line_endings;
            t_bool crlf_line_endings;
            uint8 *block = NULL;
            int error = FALSE;
            static const uint8 ascii2ebcdic[128] = {
                0000,0001,0002,0003,0067,0055,0056,0057,
                0026,0005,0045,0013,0014,0015,0016,0017,
                0020,0021,0022,0023,0074,0075,0062,0046,
                0030,0031,0077,0047,0034,0035,0036,0037,
                0100,0117,0177,0173,0133,0154,0120,0175,
                0115,0135,0134,0116,0153,0140,0113,0141,
                0360,0361,0362,0363,0364,0365,0366,0367,
                0370,0371,0172,0136,0114,0176,0156,0157,
                0174,0301,0302,0303,0304,0305,0306,0307,
                0310,0311,0321,0322,0323,0324,0325,0326,
                0327,0330,0331,0342,0343,0344,0345,0346,
                0347,0350,0351,0112,0340,0132,0137,0155,
                0171,0201,0202,0203,0204,0205,0206,0207,
                0210,0211,0221,0222,0223,0224,0225,0226,
                0227,0230,0231,0242,0243,0244,0245,0246,
                0247,0250,0251,0300,0152,0320,0241,0007};

            tape = memory_create_tape ();
            uptr->fileref = (FILE *)tape;
            if (!uptr->fileref)
                return SCPE_MEM;
            f = fopen (cptr, "rb");
            if (f == NULL) {
                r = sim_messagef (SCPE_OPENERR, "Can't open: %s - %s\n", cptr, strerror (errno));
                break;
                }
            tape_classify_file_contents (f, &max_record_size, &lf_line_endings, &crlf_line_endings);
            if ((!lf_line_endings) && (!crlf_line_endings)) {   /* binary file? */
                if (uptr->recsize == 0) {
                    r = sim_messagef (SCPE_ARG, "Binary file %s must specify a record size with -B\n", cptr);
                    fclose (f);
                    break;
                    }
                block = (uint8 *)malloc (uptr->recsize);
                tape->block_size = uptr->recsize;
                while (!feof(f) && !error) {
                    size_t data_read = fread (block, 1, tape->block_size, f);
                    if (data_read > 0)
                        error = memory_tape_add_block (tape, block, data_read);
                    }
                }
            else {                                              /* text file */
                if (uptr->recsize == 0)
                    uptr->recsize = max_record_size;
                if (uptr->recsize < max_record_size) {
                    r = sim_messagef (SCPE_ARG, "Text file: %s has lines longer than %d\n", cptr, (int)uptr->recsize);
                    fclose (f);
                    break;
                    }
                tape->block_size = uptr->recsize;
                block = (uint8 *)calloc (1, uptr->recsize + 3);
                while (!feof(f) && !error) {
                    if (fgets ((char *)block, uptr->recsize + 3, f)) {
                        size_t len = strlen ((char *)block);

                        while ((len > 0) && 
                               ((block[len - 1] == '\r') || (block[len - 1] == '\n')))
                            --len;
                        memset (block + len, ' ', uptr->recsize - len);
                        if (sim_switches & SWMASK ('C')) {
                            uint32 i;

                            for (i=0; i<uptr->recsize; i++)
                                block[i] = ascii2ebcdic[block[i]];
                            }
                        error = memory_tape_add_block (tape, block, uptr->recsize);
                        }
                    else
                        error = ferror (f);
                    }
                }
            free (block);
            fclose (f);
            r = SCPE_OK;
            memory_tape_add_block (tape, NULL, 0);  /* Tape Mark */
            memory_tape_add_block (tape, NULL, 0);  /* Tape Mark */
            uptr->flags |= UNIT_ATT;
            uptr->filename = (char *)malloc (strlen (cptr) + 1);
            strcpy (uptr->filename, cptr);
            uptr->tape_eom = tape->record_count;
            }
        break;

    case MTUF_F_DOS11:
        if (1) {
            const char *ocptr = cptr;
            int file_errors = 0;

            uptr->recsize = 512;

            tape = memory_create_tape();
            tape->block_size = uptr->recsize;
            uptr->fileref = (FILE *)tape;
            if (!uptr->fileref)
                return SCPE_MEM;

            while (*cptr != 0) {
                uint32 initial_file_count = tape->file_count;

                cptr = get_glyph_nc (cptr, gbuf, ',');   /* Get filename */
                r = sim_dir_scan (gbuf, sim_tape_add_dos11_entry, tape);
                if (r != SCPE_OK)
                    sim_messagef (SCPE_ARG, "file not found: %s\n", gbuf);
                if (tape->file_count == initial_file_count)
                    ++file_errors;
                }

            if ((tape->file_count > 0) && (file_errors == 0)) {
                r = SCPE_OK;
                memory_tape_add_block (tape, NULL, 0); /* Tape Mark */
                memory_tape_add_block (tape, NULL, 0); /* Tape Mark */
                uptr->flags |= UNIT_ATT;
                uptr->filename = (char *)malloc (strlen (ocptr) + 1);
                strcpy (uptr->filename, ocptr);
                uptr->tape_eom = tape->record_count;
                }
            else {
                r = SCPE_ARG;
                memory_free_tape (uptr->fileref);
                uptr->fileref = NULL;
                cptr = ocptr;
                }
            }
        break;

    case MTUF_F_TAR:
        if (uptr->recsize == 0)
            uptr->recsize = TAR_DFLT_RECSIZE;       /* Apply default block size */
        /* fall through */
    default:
        r = attach_unit (uptr, (CONST char *)cptr);         /* attach unit */
        break;
    }
if (r != SCPE_OK) {                                     /* error? */
    switch (MT_GET_FMT (uptr)) {
        case MTUF_F_ANSI:
        case MTUF_F_TAR:
        case MTUF_F_FIXED:
        case MTUF_F_DOS11:
            r = sim_messagef (r, "Error opening %s format internal tape image generated from: %s\n", _sim_tape_format_name (uptr), cptr);
            break;
        default:
            r = sim_messagef (r, "Error opening %s format tape image: %s - %s\n", _sim_tape_format_name (uptr), cptr, strerror(errno));
            break;
        }
    if (auto_format)    /* format was specified at attach time? */
        sim_tape_set_fmt (uptr, 0, "SIMH", NULL);   /* restore default format */
    uptr->recsize = 0;
    uptr->tape_eom = 0;
    return r;
    }

if ((sim_switches & SWMASK ('D')) && !had_debug) {
    sim_switches |= SWMASK ('E');
    sim_switches &= ~(SWMASK ('D') | SWMASK ('R') | SWMASK ('F'));
    sim_set_debon (0, "STDOUT");
    sim_switches = saved_switches;
    }
559
560
561
562
563
564
565


566
567
568
569
570
571
572
    uptr->io_flush = _sim_tape_io_flush;
    }

if ((sim_switches & SWMASK ('D')) && !had_debug)
    sim_set_deboff (0, "");
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = starting_dctrl;


return r;
}

/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{







>
>







945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
    uptr->io_flush = _sim_tape_io_flush;
    }

if ((sim_switches & SWMASK ('D')) && !had_debug)
    sim_set_deboff (0, "");
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = starting_dctrl;
if ((r == SCPE_OK) && (sim_switches & SWMASK ('X')))
    r = sim_export_tape (uptr, export_file);
return r;
}

/* Detach tape unit */

t_stat sim_tape_detach (UNIT *uptr)
{
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
if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */
if (ctx)
    auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);

MT_CLR_INMRK (uptr);                                    /* Not within an AWS or TAR tapemark */







r = detach_unit (uptr);                                 /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */

    case MTUF_F_TPC:                                    /* TPC */
        if (uptr->filebuf)                              /* free map */
            free (uptr->filebuf);
        uptr->filebuf = NULL;
        break;

    default:
        break;
        }
uptr->hwmark = 0;
uptr->recsize = 0;
uptr->tape_eom = 0;

sim_tape_rewind (uptr);

free (uptr->tape_ctx);
uptr->tape_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)    /* format was determined or specified at attach time? */
    sim_tape_set_fmt (uptr, 0, "SIMH", NULL);   /* restore default format */
return SCPE_OK;
}







|
>
>
>
>
>
>
>
|
















|
|
>







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
if (uptr->io_flush)
    uptr->io_flush (uptr);                              /* flush buffered data */
if (ctx)
    auto_format = ctx->auto_format;

sim_tape_clr_async (uptr);

MT_CLR_INMRK (uptr);                                    /* Not within a TAR tapemark */
if (MT_GET_FMT (uptr) >= MTUF_F_ANSI) {
    memory_free_tape ((void *)uptr->fileref);
    uptr->fileref = NULL;
    uptr->flags &= ~UNIT_ATT;
    r = SCPE_OK;
    }
else
    r = detach_unit (uptr);                             /* detach unit */
if (r != SCPE_OK)
    return r;
switch (f) {                                            /* case on format */

    case MTUF_F_TPC:                                    /* TPC */
        if (uptr->filebuf)                              /* free map */
            free (uptr->filebuf);
        uptr->filebuf = NULL;
        break;

    default:
        break;
        }
uptr->hwmark = 0;
uptr->recsize = 0;
uptr->tape_eom = 0;
uptr->pos = 0;
MT_CLR_PNU (uptr);
MT_CLR_INMRK (uptr);                                    /* Not within a TAR tapemark */
free (uptr->tape_ctx);
uptr->tape_ctx = NULL;
uptr->io_flush = NULL;
if (auto_format)    /* format was determined or specified at attach time? */
    sim_tape_set_fmt (uptr, 0, "SIMH", NULL);   /* restore default format */
return SCPE_OK;
}
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
    else
        fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
    }
else
    fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
fprintf (st, "Attach command switches\n");
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified an attempt to create the indicated\n");
fprintf (st, "                virtual tape will be attempted).\n");
fprintf (st, "    -F          Open the indicated tape container in a specific format (default\n");


fprintf (st, "                is SIMH, alternatives are E11, TPC, P7B, AWS and TAR)\n");
fprintf (st, "    -B          For TAR format tapes, the record size for data read from the\n");
fprintf (st, "                specified file.  This record size will be used for all but\n");
fprintf (st, "                possibly the last record which will be what remains unread.\n");
fprintf (st, "                The default TAR record size is 10240.\n");


fprintf (st, "    -V          Display some summary information about the record structure\n");

fprintf (st, "                contained in the tape image scan performed when it is attached.\n");
fprintf (st, "    -L          Display detailed record size counts observed during attach\n");
fprintf (st, "                validation pass\n");
fprintf (st, "                contained in the tape image scan performed when it is attached.\n");
fprintf (st, "    -D          Causes the internal tape structure information to be displayed\n");
fprintf (st, "                while the tape image is scanned.\n");




























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 && ((uptr->dctrl | 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








|
|
|
>
>
|

|

|
>
>

>
|


<


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












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







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
    else
        fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
    }
else
    fprintf (st, "  sim> ATTACH {switches} %s tapefile\n\n", dptr->name);
fprintf (st, "Attach command switches\n");
fprintf (st, "    -R          Attach Read Only.\n");
fprintf (st, "    -E          Must Exist (if not specified, the default behavior is to\n");
fprintf (st, "                attempt to create the indicated virtual tape file).\n");
fprintf (st, "    -F          Open the indicated tape container in a specific format\n");
fprintf (st, "                (default is SIMH, alternatives are E11, TPC, P7B, AWS, TAR,\n");
fprintf (st, "                ANSI-VMS, ANSI-RT11, ANSI-RSX11, ANSI-RSTS, ANSI-VAR, FIXED,\n");
fprintf (st, "                DOS11)\n");
fprintf (st, "    -B          For TAR format tapes, the record size for data read from the\n");
fprintf (st, "                specified file.  This record size will be used for all but \n");
fprintf (st, "                possibly the last record which will be what remains unread.\n");
fprintf (st, "                The default TAR record size is 10240.  For FIXED format tapes\n");
fprintf (st, "                -B specifies the record size for binary data or the maximum \n");
fprintf (st, "                record size for text data\n");
fprintf (st, "    -V          Display some summary information about the record structure\n");
fprintf (st, "                observed in the tape image observed during the attach\n");
fprintf (st, "                validation pass\n");
fprintf (st, "    -L          Display detailed record size counts observed during attach\n");
fprintf (st, "                validation pass\n");

fprintf (st, "    -D          Causes the internal tape structure information to be displayed\n");
fprintf (st, "                while the tape image is scanned.\n");
fprintf (st, "    -C          Causes FIXED format tape data sets derived from text files to\n");
fprintf (st, "                be converted from ASCII to EBCDIC.\n");
fprintf (st, "    -X          Extract a copy of the attached tape and convert it to a SIMH\n");
fprintf (st, "                format tape image.\n\n");
fprintf (st, "Notes:  ANSI-VMS, ANSI-RT11, ANSI-RSTS, ANSI-RSX11, ANSI-VAR formats allows\n");
fprintf (st, "        one or several files to be presented to as a read only ANSI Level 3\n");
fprintf (st, "        labeled tape with file labels that make each individual file\n");
fprintf (st, "        accessible directly as files on the tape.\n\n");
fprintf (st, "        FIXED format will present the contents of a file (text or binary) as\n");
fprintf (st, "        fixed sized records/blocks with ascii text data optionally converted\n");
fprintf (st, "        to EBCDIC.\n\n");
fprintf (st, "        DOS11 format will present the contents of a file preceeded by a DOS11\n");
fprintf (st, "        14-byte header. All files will be owned by [1,1], have a default\n");
fprintf (st, "        protection of <233> and a date in the range 1972 - 1999 with the\n");
fprintf (st, "        month/day layout as the current year. The file name on the tape\n");
fprintf (st, "        will be sanitized to contain only alphanumeric characters from the\n");
fprintf (st, "        original source file name. Characters 7 - 9 of the file name will be\n");
fprintf (st, "        placed in an otherwise unused word in the header which some DEC\n");
fprintf (st, "        operating systems will be able to process. If the resulting\n");
fprintf (st, "        filename is NULL, a filename in the range 000000 - 999999 will be\n");
fprintf (st, "        generated based of the file position on the tape.\n\n");
fprintf (st, "Examples:\n\n");
fprintf (st, "  sim> ATTACH %s -F ANSI-VMS Hobbyist-USE-ONLY-VA.TXT\n", dptr->name);
fprintf (st, "  sim> ATTACH %s -F ANSI-RSX11 *.TXT,*.ini,*.exe\n", dptr->name);
fprintf (st, "  sim> ATTACH %s -FX ANSI-RSTS RSTS.tap *.TXT,*.SAV\n", dptr->name);
fprintf (st, "  sim> ATTACH %s -F ANSI-RT11 *.TXT,*.TSK\n", dptr->name);
fprintf (st, "  sim> ATTACH %s -FB FIXED 80 SOMEFILE.TXT\n", dptr->name);
fprintf (st, "  sim> ATTACH %s -F DOS11 *.LDA,*.TXT\n\n", dptr->name);
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 && ((uptr->dctrl | ctx->dptr->dctrl) & reason))
    sim_data_trace(ctx->dptr, uptr, (detail ? data : NULL), "", len, txt, reason);
}

static int sim_tape_seek (UNIT *uptr, t_addr pos)
{
if (MT_GET_FMT (uptr) < MTUF_F_ANSI)
    return sim_fseek (uptr->fileref, pos, SEEK_SET);
return 0;
}

static t_offset sim_tape_size (UNIT *uptr)
{
if (MT_GET_FMT (uptr) < MTUF_F_ANSI)
    return sim_fsize_ex (uptr->fileref);
return uptr->tape_eom;
}

/* Read record length forward (internal routine).

   Inputs:
        uptr    =       pointer to tape unit
        bc      =       pointer to returned record length

778
779
780
781
782
783
784
785
786
787
788
789
790
791
792

if ((uptr->tape_eom) && 
    (uptr->pos >= uptr->tape_eom)) {
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return MTSE_EOM;                                    /*     and quit with I/O error status */
    }

if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the initial tape position; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return sim_tape_ioerr (uptr);                       /*     and quit with I/O error status */
    }

switch (f) {                                       /* otherwise the read method depends on the tape format */

    case MTUF_F_STD:







|







1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234

if ((uptr->tape_eom) && 
    (uptr->pos >= uptr->tape_eom)) {
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return MTSE_EOM;                                    /*     and quit with I/O error status */
    }

if (sim_tape_seek (uptr, uptr->pos)) {                  /* set the initial tape position; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return sim_tape_ioerr (uptr);                       /*     and quit with I/O error status */
    }

switch (f) {                                       /* otherwise the read method depends on the tape format */

    case MTUF_F_STD:
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889

            else if (*bc == MTR_GAP)                    /* otherwise if the value is a full gap */
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if (*bc == MTR_FHGAP) {                        /* otherwise if the value if a half gap */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt) / 2;  /*   then back up and resync */

                if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* set the tape position; if it fails */
                    status = sim_tape_ioerr (uptr);                     /*   then quit with I/O error status */
                    break;
                    }

                bufcntr = bufcap;                       /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                /* reset the marker */
                runaway_counter -= sizeof_gap / 2;      /*   and decrement the gap counter */







|
|







1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331

            else if (*bc == MTR_GAP)                    /* otherwise if the value is a full gap */
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if (*bc == MTR_FHGAP) {                        /* otherwise if the value if a half gap */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt) / 2;  /*   then back up and resync */

                if (sim_tape_seek (uptr, uptr->pos)) {          /* set the tape position; if it fails */
                    status = sim_tape_ioerr (uptr);             /*   then quit with I/O error status */
                    break;
                    }

                bufcntr = bufcap;                       /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                /* reset the marker */
                runaway_counter -= sizeof_gap / 2;      /*   and decrement the gap counter */
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

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        if (status == MTSE_OK) {        /* Validate the reverse record size for data records */
            t_mtrlnt rev_lnt;

            if (sim_fseek (uptr->fileref, uptr->pos - sizeof (t_mtrlnt), SEEK_SET)){  /*   then seek to the end of record size; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
                break;
                }

            (void)sim_fread (&rev_lnt,                  /* get the reverse length */
                             sizeof (t_mtrlnt),
                             1,
                             uptr->fileref);

            if (ferror (uptr->fileref)) {               /* if a file I/O error occurred */
                status = sim_tape_ioerr (uptr);         /* report the error and quit */
                break;
                }
            if (rev_lnt != *bc) {           /* size mismatch? */
                status = MTSE_INVRL;
                uptr->pos -= (sizeof (t_mtrlnt) + *bc + sizeof (t_mtrlnt));
                MT_SET_PNU (uptr);                      /* pos not upd */
                break;
                }
            if (sim_fseek (uptr->fileref, saved_pos, SEEK_SET))   /*   then seek back to the beginning of the data; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
            }
        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */







|



















|







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

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        if (status == MTSE_OK) {        /* Validate the reverse record size for data records */
            t_mtrlnt rev_lnt;

            if (sim_tape_seek (uptr, uptr->pos - sizeof (t_mtrlnt))) {  /*   then seek to the end of record size; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
                break;
                }

            (void)sim_fread (&rev_lnt,                  /* get the reverse length */
                             sizeof (t_mtrlnt),
                             1,
                             uptr->fileref);

            if (ferror (uptr->fileref)) {               /* if a file I/O error occurred */
                status = sim_tape_ioerr (uptr);         /* report the error and quit */
                break;
                }
            if (rev_lnt != *bc) {           /* size mismatch? */
                status = MTSE_INVRL;
                uptr->pos -= (sizeof (t_mtrlnt) + *bc + sizeof (t_mtrlnt));
                MT_SET_PNU (uptr);                      /* pos not upd */
                break;
                }
            if (sim_tape_seek (uptr, saved_pos))        /*   then seek back to the beginning of the data; if it fails */
                status = sim_tape_ioerr (uptr);         /*     then quit with I/O error status */
            }
        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */
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
                break;
            else if ((c & P7B_DPAR) != P7B_EOF)
                all_eof = 0;
            }

        if (status == MTSE_OK) {
            *bc = sbc;                                      /* save rec lnt */
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
            uptr->pos = uptr->pos + sbc;                    /* spc over record */
            if (all_eof) {                                  /* tape mark? */
                status = MTSE_TMK;
                *bc = 0;
                }
            }
        break;

    case MTUF_F_AWS:
        MT_CLR_INMRK (uptr);                        /* Not within an AWS tapemark */
        memset (&awshdr, 0, sizeof (awshdr));
        rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);

        if (ferror (uptr->fileref)) {               /* error? */
            MT_SET_PNU (uptr);                      /* pos not upd */
            status = sim_tape_ioerr (uptr);
            break;
            }
        if ((feof (uptr->fileref)) ||               /* eof? */
            (rdcnt < 3)) {

            MT_SET_PNU (uptr);                      /* pos not upd */
            status = MTSE_EOM;
            break;
            }
        uptr->pos += sizeof (t_awshdr);             /* spc over AWS header */
        if (awshdr.rectyp == AWS_TMK) {             /* tape mark? */
            status = MTSE_TMK;
            MT_SET_INMRK (uptr);                    /* within an AWS tapemark */
            }
        else
            if (awshdr.rectyp != AWS_REC) {         /* Unknown record type */
                MT_SET_PNU (uptr);                  /* pos not upd */

                status = MTSE_INVRL;

                }
            else {                                  /* tape data record */
                t_addr saved_pos;



                *bc = (t_mtrlnt)awshdr.nxtlen;      /* save rec lnt */
                uptr->pos += awshdr.nxtlen;         /* spc over record */
                memset (&awshdr, 0, sizeof (t_awslnt));
                saved_pos = (t_addr)sim_ftell (uptr->fileref);
                (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for read */
                (void)sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
                if (awshdr.rectyp == AWS_TMK)
                    MT_SET_INMRK (uptr);            /* within an AWS tapemark */
                if (awshdr.prelen != *bc) {
                    status = MTSE_INVRL;

                    uptr->pos = saved_pos - sizeof (t_awslnt);
                    MT_CLR_INMRK (uptr);            /* not within an AWS tapemark */
                    }
                else
                    (void)sim_fseek (uptr->fileref, saved_pos, SEEK_SET); /* Move back to the data */
                }
        break;

    case MTUF_F_TAR:
        if (uptr->pos < uptr->hwmark) {
            if ((uptr->hwmark - uptr->pos) >= uptr->recsize)
                *bc = (t_mtrlnt)uptr->recsize;              /* TAR record size */
            else
                *bc = (t_mtrlnt)(uptr->hwmark - uptr->pos); /* TAR remnant last record */
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); 
            uptr->pos += *bc;
            MT_CLR_INMRK (uptr);
            }
        else {
            if (MT_TST_INMRK (uptr))
                status = MTSE_EOM;
            else {
                status = MTSE_TMK;
                MT_SET_INMRK (uptr);
                }
            }
        break;



















    default:
        status = MTSE_FMT;
    }

return status;
}







|









|


<
|
|



|

>
|



|
|

<
<
|
|
|
>

>

|
<
>
|
>
|
|
|
|
|
|
|
<
|
|
>
|
<
|
|
|
<








|












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







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
                break;
            else if ((c & P7B_DPAR) != P7B_EOF)
                all_eof = 0;
            }

        if (status == MTSE_OK) {
            *bc = sbc;                                      /* save rec lnt */
            (void)sim_tape_seek (uptr, uptr->pos);          /* for read */
            uptr->pos = uptr->pos + sbc;                    /* spc over record */
            if (all_eof) {                                  /* tape mark? */
                status = MTSE_TMK;
                *bc = 0;
                }
            }
        break;

    case MTUF_F_AWS:
        saved_pos = (t_addr)sim_ftell (uptr->fileref);
        memset (&awshdr, 0, sizeof (awshdr));
        rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);

        if (ferror (uptr->fileref)) {           /* error? */
            MT_SET_PNU (uptr);                  /* pos not upd */
            status = sim_tape_ioerr (uptr);
            break;
            }
        if ((feof (uptr->fileref)) ||           /* eof? */
            (rdcnt < 3)) {
            uptr->tape_eom = uptr->pos;
            MT_SET_PNU (uptr);                  /* pos not upd */
            status = MTSE_EOM;
            break;
            }
        uptr->pos += sizeof (t_awshdr);         /* spc over AWS header */
        if (awshdr.rectyp == AWS_TMK)           /* tape mark? */
            status = MTSE_TMK;


        else {
            if (awshdr.rectyp != AWS_REC) {     /* Unknown record type */
                MT_SET_PNU (uptr);              /* pos not upd */
                uptr->tape_eom = uptr->pos;
                status = MTSE_INVRL;
                break;
                }
            else

                status = MTSE_OK;
            }
        /* tape data record (or tapemark) */
        *bc = (t_mtrlnt)awshdr.nxtlen;          /* save rec lnt */
        uptr->pos += awshdr.nxtlen;             /* spc over record */
        memset (&awshdr, 0, sizeof (t_awslnt));
        saved_pos = (t_addr)sim_ftell (uptr->fileref);/* save record data address */
        (void)sim_tape_seek (uptr, uptr->pos); /* for read */
        rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
        if ((rdcnt == 3) && 

            ((awshdr.prelen != *bc) || ((awshdr.rectyp != AWS_REC) && (awshdr.rectyp != AWS_TMK)))) {
            status = MTSE_INVRL;
            uptr->tape_eom = uptr->pos;
            uptr->pos = saved_pos - sizeof (t_awslnt);

            }
        else
            (void)sim_tape_seek (uptr, saved_pos); /* Move back to the data */

        break;

    case MTUF_F_TAR:
        if (uptr->pos < uptr->hwmark) {
            if ((uptr->hwmark - uptr->pos) >= uptr->recsize)
                *bc = (t_mtrlnt)uptr->recsize;              /* TAR record size */
            else
                *bc = (t_mtrlnt)(uptr->hwmark - uptr->pos); /* TAR remnant last record */
            (void)sim_tape_seek (uptr, uptr->pos); 
            uptr->pos += *bc;
            MT_CLR_INMRK (uptr);
            }
        else {
            if (MT_TST_INMRK (uptr))
                status = MTSE_EOM;
            else {
                status = MTSE_TMK;
                MT_SET_INMRK (uptr);
                }
            }
        break;

    case MTUF_F_ANSI:
    case MTUF_F_FIXED:
    case MTUF_F_DOS11:
        if (1) {
            MEMORY_TAPE *tape = (MEMORY_TAPE *)uptr->fileref;

            if (uptr->pos >= tape->record_count) 
                status = MTSE_EOM;
            else {
                if (tape->records[uptr->pos]->size == 0)
                    status = MTSE_TMK;
                else
                    *bc = tape->records[uptr->pos]->size;
                ++uptr->pos;
                }
            }
        break;

    default:
        status = MTSE_FMT;
    }

return status;
}
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */
*bc = 0;

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 */
    status = MTSE_BOT;                                  /*   then reading backward is not possible */

else switch (f) {                                       /* otherwise 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 */







|

|







1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
MT_CLR_PNU (uptr);                                      /* clear the position-not-updated flag */
*bc = 0;

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) {                                            /* otherwise 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 */
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
                    bufcap = (uint32) uptr->pos         /*   then reduce the capacity accordingly */
                               / sizeof (t_mtrlnt);

                else                                    /* otherwise reset the capacity */
                    bufcap = sizeof (buffer)            /*   to the full size of the buffer */
                               / sizeof (buffer [0]);

                if (sim_fseek (uptr->fileref,                           /* seek back to the location */
                               uptr->pos - bufcap * sizeof (t_mtrlnt),  /*   corresponding to the start */
                               SEEK_SET)) {                             /*     of the buffer; if it fails */
                    status = sim_tape_ioerr (uptr);                     /*         and fail with I/O error status */
                    break;
                    }

                bufcntr = sim_fread (buffer, sizeof (t_mtrlnt), /* fill the buffer */
                                     bufcap, uptr->fileref);    /*   with tape metadata */

                if (ferror (uptr->fileref)) {           /* if a file I/O error occurred */







|
|
|
|







1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
                    bufcap = (uint32) uptr->pos         /*   then reduce the capacity accordingly */
                               / sizeof (t_mtrlnt);

                else                                    /* otherwise reset the capacity */
                    bufcap = sizeof (buffer)            /*   to the full size of the buffer */
                               / sizeof (buffer [0]);

                if (sim_tape_seek (uptr,                /* seek back to the location */
                                   uptr->pos - bufcap * sizeof (t_mtrlnt))) {  /* corresponding to the start */
                                                        /* of the buffer; if it fails */
                    status = sim_tape_ioerr (uptr);     /*         and fail with I/O error status */
                    break;
                    }

                bufcntr = sim_fread (buffer, sizeof (t_mtrlnt), /* fill the buffer */
                                     bufcap, uptr->fileref);    /*   with tape metadata */

                if (ferror (uptr->fileref)) {           /* if a file I/O error occurred */
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
                status = MTSE_TMK;                      /*   then quit with tape mark status */
                break;
                }

            else if (*bc == MTR_GAP)                    /* otherwise if the marker is a full gap */
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if ((*bc & MTR_M_RHGAP) == MTR_RHGAP           /* otherwise if the marker */
              || *bc == MTR_RRGAP) {                            /*   is a half gap */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt) / 2;  /*     then position forward to resync */
                bufcntr = 0;                                    /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                        /* reset the marker */
                runaway_counter -= sizeof_gap / 2;              /*   and decrement the gap counter */
                }

            else {                                              /* otherwise it's a record marker */
                sbc = MTR_L (*bc);                              /* extract the record length */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt)       /* position to the start */
                  - (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);   /*   of the record */

                if (sim_fseek (uptr->fileref,                   /* seek to the start of the data area; if it fails */
                               uptr->pos + sizeof (t_mtrlnt),   /*   then return with I/O error status */
                               SEEK_SET)) {
                    status = sim_tape_ioerr (uptr);
                    break;
                    }
                }
            }
        while (*bc == MTR_GAP && runaway_counter > 0);  /* continue until data or runaway occurs */

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        ppos = sim_tape_tpc_fnd (uptr, (t_addr *) uptr->filebuf); /* find prev rec */
        (void)sim_fseek (uptr->fileref, ppos, SEEK_SET);/* position */
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */

        if (ferror (uptr->fileref))                     /* error? */
            status = sim_tape_ioerr (uptr);
        else if (feof (uptr->fileref))                  /* eof? */
            status = MTSE_EOM;
        else {
            uptr->pos = ppos;                           /* spc over record */
            if (*bc == MTR_TMK)                         /* tape mark? */
                status = MTSE_TMK;
            else
                (void)sim_fseek (uptr->fileref, uptr->pos + sizeof (t_tpclnt), SEEK_SET);
            }
        break;

    case MTUF_F_P7B:
        if (1) {
#define BUF_SZ 512
            uint8 buf[BUF_SZ];
            t_addr buf_offset;
            size_t bytes_in_buf = 0;
            size_t read_size;

            for (sbc = 1, all_eof = 1; (t_addr) sbc <= uptr->pos ; sbc++) {
                if (bytes_in_buf == 0) {        /* Need to Fill Buffer */
                    if (uptr->pos < BUF_SZ) {
                        buf_offset = 0;
                        read_size = (size_t)uptr->pos;

                        }
                    else {
                        buf_offset = uptr->pos - (sbc - 1 + BUF_SZ);
                        read_size = BUF_SZ;

                        }
                    (void)sim_fseek (uptr->fileref, buf_offset, SEEK_SET);
                    bytes_in_buf = sim_fread (buf, sizeof (uint8), read_size, uptr->fileref);
                    if (ferror (uptr->fileref)) {               /* error? */
                        status = sim_tape_ioerr (uptr);
                        break;
                        }
                    if (feof (uptr->fileref)) {                 /* eof? */
                        status = MTSE_EOM;
                        break;
                        }
                    }
                c = buf[--bytes_in_buf];
                if ((c & P7B_DPAR) != P7B_EOF)
                    all_eof = 0;
                if (c & P7B_SOR)                        /* start of record? */
                    break;
                }

            if (status == MTSE_OK) {
                uptr->pos = uptr->pos - sbc;                    /* update position */
                *bc = sbc;                                      /* save rec lnt */
                (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); /* for next read */
                if (all_eof)                                    /* tape mark? */
                    status = MTSE_TMK;
                }
            break;
            }

    case MTUF_F_AWS:
        *bc = sbc = 0;


        while ((sbc == 0) && (status == MTSE_OK)) {
            if (sim_tape_bot (uptr)) {                      /* if we start at BOT */
                status = MTSE_BOT;                          /*   then we're done */
                break;
                }
            (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);/* position */
            memset (&awshdr, 0, sizeof (awshdr));
            rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
            if (ferror (uptr->fileref)) {                   /* error? */
                status = sim_tape_ioerr (uptr);
                break;
                }
            if (feof (uptr->fileref)) {                 /* eof? */
                if ((uptr->pos > sizeof (t_awshdr)) &&
                    (uptr->pos >= sim_fsize (uptr->fileref))) {
                    if (MT_TST_INMRK (uptr)) {
                        status = MTSE_TMK;
                        MT_CLR_INMRK (uptr);
                        uptr->pos -= sizeof (awshdr);

                        }
                    else
                        status = MTSE_EOM;                  /*   then we're done */
                    break;
                    }
                }
            if ((rdcnt != 3) || 
                ((awshdr.rectyp != AWS_REC) && 
                 (awshdr.rectyp != AWS_TMK))) {
                status = MTSE_INVRL;

                break;
                }
            if (MT_TST_INMRK (uptr))                    /* already in a tapemark? */
                awshdr.rectyp = AWS_REC;
            MT_CLR_INMRK (uptr);                        /* No longer in a tapemark */
            *bc = (t_mtrlnt)((awshdr.rectyp == AWS_REC) ? awshdr.prelen : 0);/* save rec lnt */
            sbc = *bc;                                  /* extract the record length */
            if ((awshdr.rectyp != AWS_TMK) ||

                (awshdr.prelen == 0)) {
                uptr->pos -= sizeof (t_awshdr);         /* position to the start of the record */
                uptr->pos -= awshdr.prelen;             /* Including the data length */


                if (sim_fseek (uptr->fileref,           /* seek to the start of the data area; if it fails */
                               uptr->pos + sizeof (t_awshdr),
                               SEEK_SET)) {
                    status = sim_tape_ioerr (uptr);     /* then return with I/O error status */
                    break;

                    }
                }
            if (awshdr.rectyp == AWS_TMK) {             /* tape mark? */

                status = MTSE_TMK;
                if (awshdr.prelen != 0)
                    MT_SET_INMRK (uptr);                /* Flag processing a tapemark header */
                }







            }
        break;

     case MTUF_F_TAR:
         if (uptr->pos == uptr->hwmark) {
             if (MT_TST_INMRK (uptr)) {
                 status = MTSE_TMK;
                 MT_CLR_INMRK (uptr);
                 }
             else {
                 if (uptr->hwmark % uptr->recsize)
                     *bc = (t_mtrlnt)(uptr->hwmark % uptr->recsize);
                 else
                     *bc = (t_mtrlnt)uptr->recsize;
                 }
             }
         else
             *bc = (t_mtrlnt)uptr->recsize;
         if (*bc) {
             uptr->pos -= *bc;



             (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET); 





             }






        break;

   default:
        status = MTSE_FMT;
        }

return status;
}







|
|
|
|

|
|


|
|
|
|

|
|
<














|












|







|




|
<
|
|
>


<

>

|

|



|












|
|
|
|






|
>
>
|
|
|


<


|






<
<
|
|
>
|
<
|
|
|
<




>
|
|
<
<
<
<
<
|
>
|
<
<
|
>
|
|
|
|
<
>
|
<
<
>
|
|
<

>
>
>
>
>
>
>




















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








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
                status = MTSE_TMK;                      /*   then quit with tape mark status */
                break;
                }

            else if (*bc == MTR_GAP)                    /* otherwise if the marker is a full gap */
                runaway_counter -= sizeof_gap;          /*   then decrement the gap counter */

            else if ((*bc & MTR_M_RHGAP) == MTR_RHGAP   /* otherwise if the marker */
              || *bc == MTR_RRGAP) {                    /*   is a half gap */
                uptr->pos = uptr->pos + sizeof (t_mtrlnt) / 2;/* then position forward to resync */
                bufcntr = 0;                            /* mark the buffer as invalid to force a read */

                *bc = (t_mtrlnt)MTR_GAP;                /* reset the marker */
                runaway_counter -= sizeof_gap / 2;      /*   and decrement the gap counter */
                }

            else {                                      /* otherwise it's a record marker */
                sbc = MTR_L (*bc);                      /* extract the record length */
                uptr->pos = uptr->pos - sizeof (t_mtrlnt)/* position to the start */
                  - (f == MTUF_F_STD ? (sbc + 1) & ~1 : sbc);/*   of the record */

                if (sim_tape_seek (uptr,                /* seek to the start of the data area; if it fails */
                               uptr->pos + sizeof (t_mtrlnt))) {/* then return with I/O error status */

                    status = sim_tape_ioerr (uptr);
                    break;
                    }
                }
            }
        while (*bc == MTR_GAP && runaway_counter > 0);  /* continue until data or runaway occurs */

        if (runaway_counter <= 0)                       /* if a tape runaway occurred */
            status = MTSE_RUNAWAY;                      /*   then report it */

        break;                                          /* otherwise the operation succeeded */

    case MTUF_F_TPC:
        ppos = sim_tape_tpc_fnd (uptr, (t_addr *) uptr->filebuf); /* find prev rec */
        (void)sim_tape_seek (uptr, ppos);               /* position */
        (void)sim_fread (&tpcbc, sizeof (t_tpclnt), 1, uptr->fileref);
        *bc = (t_mtrlnt)tpcbc;                          /* save rec lnt */

        if (ferror (uptr->fileref))                     /* error? */
            status = sim_tape_ioerr (uptr);
        else if (feof (uptr->fileref))                  /* eof? */
            status = MTSE_EOM;
        else {
            uptr->pos = ppos;                           /* spc over record */
            if (*bc == MTR_TMK)                         /* tape mark? */
                status = MTSE_TMK;
            else
                (void)sim_tape_seek (uptr, uptr->pos + sizeof (t_tpclnt));
            }
        break;

    case MTUF_F_P7B:
        if (1) {
#define BUF_SZ 512
            uint8 buf[BUF_SZ];
            t_addr buf_offset = uptr->pos;
            size_t bytes_in_buf = 0;
            size_t read_size;

            for (sbc = 1, all_eof = 1; (t_addr) sbc <= uptr->pos ; sbc++) {
                if (bytes_in_buf == 0) {                /* Need to Fill Buffer */

                    if (buf_offset < BUF_SZ) {
                        read_size = (size_t)buf_offset;
                        buf_offset = 0;
                        }
                    else {

                        read_size = BUF_SZ;
                        buf_offset -= BUF_SZ;
                        }
                    (void)sim_tape_seek (uptr, buf_offset);
                    bytes_in_buf = sim_fread (buf, sizeof (uint8), read_size, uptr->fileref);
                    if (ferror (uptr->fileref)) {       /* error? */
                        status = sim_tape_ioerr (uptr);
                        break;
                        }
                    if (feof (uptr->fileref)) {         /* eof? */
                        status = MTSE_EOM;
                        break;
                        }
                    }
                c = buf[--bytes_in_buf];
                if ((c & P7B_DPAR) != P7B_EOF)
                    all_eof = 0;
                if (c & P7B_SOR)                        /* start of record? */
                    break;
                }

            if (status == MTSE_OK) {
                uptr->pos = uptr->pos - sbc;            /* update position */
                *bc = sbc;                              /* save rec lnt */
                (void)sim_tape_seek (uptr, uptr->pos);  /* for next read */
                if (all_eof)                            /* tape mark? */
                    status = MTSE_TMK;
                }
            break;
            }

    case MTUF_F_AWS:
        *bc = 0;
        status = MTSE_OK;
        (void)sim_tape_seek (uptr, uptr->pos);          /* position */
        while (1) {
            if (sim_tape_bot (uptr)) {                  /* if we start at BOT */
                status = MTSE_BOT;                      /*   then we're done */
                break;
                }

            memset (&awshdr, 0, sizeof (awshdr));
            rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
            if (ferror (uptr->fileref)) {               /* error? */
                status = sim_tape_ioerr (uptr);
                break;
                }
            if (feof (uptr->fileref)) {                 /* eof? */
                if ((uptr->pos > sizeof (t_awshdr)) &&
                    (uptr->pos >= sim_fsize (uptr->fileref))) {


                    uptr->tape_eom = uptr->pos;
                    (void)sim_tape_seek (uptr, uptr->pos - sizeof (t_awshdr));/* position */
                    continue;
                    }

                status = MTSE_EOM;
                break;
                }

            if ((rdcnt != 3) || 
                ((awshdr.rectyp != AWS_REC) && 
                 (awshdr.rectyp != AWS_TMK))) {
                status = MTSE_INVRL;
                }
            break;
            }





        if (status != MTSE_OK)
            break;
        if (awshdr.prelen == 0)


            status = MTSE_TMK;
        else {
            if ((uptr->tape_eom > 0) && 
                (uptr->pos >= uptr->tape_eom) && 
                (awshdr.rectyp == AWS_TMK)) {
                status = MTSE_TMK;

                *bc = 0;                                /* save rec lnt */
                }


            else {
                status = MTSE_OK;
                *bc = (t_mtrlnt)awshdr.prelen;          /* save rec lnt */

                }
            }
        uptr->pos -= sizeof (t_awshdr);                 /* position to the start of the record */
        uptr->pos -= *bc;                               /* Including the data length */
        if (sim_tape_seek (uptr,                        /* seek to the start of the data area; if it fails */
                           uptr->pos + sizeof (t_awshdr))) {
            status = sim_tape_ioerr (uptr);             /* then return with I/O error status */
            break;
            }
        break;

     case MTUF_F_TAR:
         if (uptr->pos == uptr->hwmark) {
             if (MT_TST_INMRK (uptr)) {
                 status = MTSE_TMK;
                 MT_CLR_INMRK (uptr);
                 }
             else {
                 if (uptr->hwmark % uptr->recsize)
                     *bc = (t_mtrlnt)(uptr->hwmark % uptr->recsize);
                 else
                     *bc = (t_mtrlnt)uptr->recsize;
                 }
             }
         else
             *bc = (t_mtrlnt)uptr->recsize;
         if (*bc) {
             uptr->pos -= *bc;
             (void)sim_tape_seek (uptr, uptr->pos); 
             }
        break;

    case MTUF_F_ANSI:
    case MTUF_F_FIXED:
    case MTUF_F_DOS11:
        if (1) {
            MEMORY_TAPE *tape = (MEMORY_TAPE *)uptr->fileref;

            --uptr->pos;
            if (tape->records[uptr->pos]->size == 0)
                status = MTSE_TMK;
            else
                *bc = tape->records[uptr->pos]->size;
            }
        break;

   default:
        status = MTSE_FMT;
        }

return status;
}
1435
1436
1437
1438
1439
1440
1441

1442
1443
1444
1445
1446







1447
1448
1449
1450
1451
1452
1453
    }
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);
    uptr->pos = opos;
    return MTSE_INVRL;
    }

i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
if (ferror (uptr->fileref)) {                           /* error? */
    MT_SET_PNU (uptr);
    uptr->pos = opos;
    return sim_tape_ioerr (uptr);







    }
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);







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







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
    }
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max) {                                        /* rec out of range? */
    MT_SET_PNU (uptr);
    uptr->pos = opos;
    return MTSE_INVRL;
    }
if (f < MTUF_F_ANSI) {
    i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
    if (ferror (uptr->fileref)) {                           /* error? */
        MT_SET_PNU (uptr);
        uptr->pos = opos;
        return sim_tape_ioerr (uptr);
        }
    }
else {
    MEMORY_TAPE *tape = (MEMORY_TAPE *)uptr->fileref;

    memcpy (buf, tape->records[uptr->pos - 1]->data, rbc);
    i = rbc;
    }
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
1500
1501
1502
1503
1504
1505
1506

1507
1508
1509







1510
1511
1512
1513
1514
1515
1516
if (st != MTSE_OK) {
    *bc = 0;
    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 */
if (ferror (uptr->fileref))                             /* error? */
    return sim_tape_ioerr (uptr);







for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read Reverse", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}







>
|
|
|
>
>
>
>
>
>
>







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
if (st != MTSE_OK) {
    *bc = 0;
    return st;
    }
*bc = rbc = MTR_L (tbc);                                /* strip error flag */
if (rbc > max)                                          /* rec out of range? */
    return MTSE_INVRL;
if (f < MTUF_F_ANSI) {
    i = (t_mtrlnt) sim_fread (buf, sizeof (uint8), rbc, uptr->fileref); /* read record */
    if (ferror (uptr->fileref))                             /* error? */
        return sim_tape_ioerr (uptr);
    }
else {
    MEMORY_TAPE *tape = (MEMORY_TAPE *)uptr->fileref;

    memcpy (buf, tape->records[uptr->pos]->data, rbc);
    i = rbc;
    }
for ( ; i < rbc; i++)                                   /* fill with 0's */
    buf[i] = 0;
if (f == MTUF_F_P7B)                                    /* p7b? strip SOR */
    buf[0] = buf[0] & P7B_DPAR;
sim_tape_data_trace(uptr, buf, rbc, "Record Read Reverse", (uptr->dctrl | ctx->dptr->dctrl) & MTSE_DBG_DAT, MTSE_DBG_STR);
return (MTR_F (tbc)? MTSE_RECE: MTSE_OK);
}
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
if (sbc == 0)                                           /* nothing to do? */
    return MTSE_OK;
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET))     /* set pos */
    return MTSE_IOERR;
switch (f) {                                            /* case on format */

    case MTUF_F_STD:                                    /* standard */
        sbc = MTR_L ((bc + 1) & ~1);                    /* pad odd length */
        /* fall through into the E11 handler */
    case MTUF_F_E11:                                    /* E11 */







|







2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
sbc = MTR_L (bc);
if ((uptr->flags & UNIT_ATT) == 0)                      /* not attached? */
    return MTSE_UNATT;
if (sim_tape_wrp (uptr))                                /* write prot? */
    return MTSE_WRP;
if (sbc == 0)                                           /* nothing to do? */
    return MTSE_OK;
if (sim_tape_seek (uptr, uptr->pos))                    /* set pos */
    return MTSE_IOERR;
switch (f) {                                            /* case on format */

    case MTUF_F_STD:                                    /* standard */
        sbc = MTR_L ((bc + 1) & ~1);                    /* pad odd length */
        /* fall through into the E11 handler */
    case MTUF_F_E11:                                    /* E11 */
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
static t_stat sim_tape_aws_wrdata (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
t_awshdr awshdr;
size_t   rdcnt;
t_bool   replacing_record;

memset (&awshdr, 0, sizeof (t_awshdr));
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* set pos */
    return MTSE_IOERR;
rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (ferror (uptr->fileref)) {               /* error? */
    MT_SET_PNU (uptr);                      /* pos not upd */
    return sim_tape_ioerr (uptr);
    }
if ((!sim_tape_bot (uptr)) && 
    (((feof (uptr->fileref)) && (rdcnt < 3)) || /* eof? */
     ((awshdr.rectyp != AWS_REC) && (awshdr.rectyp != AWS_TMK)))) {
    MT_SET_PNU (uptr);                      /* pos not upd */
    return MTSE_INVRL;
    }
if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* set pos */
    return MTSE_IOERR;
replacing_record = (awshdr.nxtlen == (t_awslnt)bc) && (awshdr.rectyp == (bc ? AWS_REC : AWS_TMK));
awshdr.nxtlen = (t_awslnt)bc;
awshdr.rectyp = (bc) ? AWS_REC : AWS_TMK;
(void)sim_fwrite (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (bc)
    (void)sim_fwrite (buf, sizeof (uint8), bc, uptr->fileref);







|












|







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
static t_stat sim_tape_aws_wrdata (UNIT *uptr, uint8 *buf, t_mtrlnt bc)
{
t_awshdr awshdr;
size_t   rdcnt;
t_bool   replacing_record;

memset (&awshdr, 0, sizeof (t_awshdr));
if (sim_tape_seek (uptr, uptr->pos))        /* set pos */
    return MTSE_IOERR;
rdcnt = sim_fread (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (ferror (uptr->fileref)) {               /* error? */
    MT_SET_PNU (uptr);                      /* pos not upd */
    return sim_tape_ioerr (uptr);
    }
if ((!sim_tape_bot (uptr)) && 
    (((feof (uptr->fileref)) && (rdcnt < 3)) || /* eof? */
     ((awshdr.rectyp != AWS_REC) && (awshdr.rectyp != AWS_TMK)))) {
    MT_SET_PNU (uptr);                      /* pos not upd */
    return MTSE_INVRL;
    }
if (sim_tape_seek (uptr, uptr->pos))        /* set pos */
    return MTSE_IOERR;
replacing_record = (awshdr.nxtlen == (t_awslnt)bc) && (awshdr.rectyp == (bc ? AWS_REC : AWS_TMK));
awshdr.nxtlen = (t_awslnt)bc;
awshdr.rectyp = (bc) ? AWS_REC : AWS_TMK;
(void)sim_fwrite (&awshdr, sizeof (t_awslnt), 3, uptr->fileref);
if (bc)
    (void)sim_fwrite (buf, sizeof (uint8), bc, uptr->fileref);
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
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;
(void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);         /* set pos */
(void)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_unit (MTSE_DBG_STR, uptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */







|







2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
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;
(void)sim_tape_seek (uptr, uptr->pos);                  /* set pos */
(void)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_unit (MTSE_DBG_STR, uptr, "wr_lnt: lnt: %d, pos: %" T_ADDR_FMT "u\n", dat, uptr->pos);
uptr->pos = uptr->pos + sizeof (t_mtrlnt);              /* move tape */
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
    return MTSE_WRP;                                    /*   then we cannot write */

else if (gap_size == 0 || format != MTUF_F_STD)         /* otherwise if zero length or gaps aren't supported */
    return MTSE_OK;                                     /*   then take no action */

file_size = sim_fsize (uptr->fileref);                  /* get the file size */

if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) {   /* position the tape; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return sim_tape_ioerr (uptr);                       /*     and quit with I/O error status */
    }

/* Read tape records and allocate them to the gap until the amount required is
   consumed.








|







2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
    return MTSE_WRP;                                    /*   then we cannot write */

else if (gap_size == 0 || format != MTUF_F_STD)         /* otherwise if zero length or gaps aren't supported */
    return MTSE_OK;                                     /*   then take no action */

file_size = sim_fsize (uptr->fileref);                  /* get the file size */

if (sim_tape_seek (uptr, uptr->pos)) {                  /* position the tape; if it fails */
    MT_SET_PNU (uptr);                                  /*   then set position not updated */
    return sim_tape_ioerr (uptr);                       /*     and quit with I/O error status */
    }

/* Read tape records and allocate them to the gap until the amount required is
   consumed.

1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
        MT_SET_PNU (uptr);                              /* set the position-not-updated flag */
        return MTSE_INVRL;                              /*   and return an invalid record length error */
        }

    else if (meta == MTR_FHGAP) {                       /* half gap? */
        uptr->pos = uptr->pos - meta_size / 2;          /* backup to resync */

        if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* position the tape; if it fails */
            return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

        gap_alloc = gap_alloc + meta_size / 2;          /* allocate marker space */
        gap_needed = gap_needed - meta_size / 2;        /* reduce requirement */
        }

    else if (uptr->pos + MTR_L (meta) + meta_size > file_size) {    /* rec len out of range? */
        gap_alloc = gap_alloc + gap_needed;                         /* presume overwritten tape */







|
|







2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
        MT_SET_PNU (uptr);                              /* set the position-not-updated flag */
        return MTSE_INVRL;                              /*   and return an invalid record length error */
        }

    else if (meta == MTR_FHGAP) {                       /* half gap? */
        uptr->pos = uptr->pos - meta_size / 2;          /* backup to resync */

        if (sim_tape_seek (uptr, uptr->pos))            /* position the tape; if it fails */
            return sim_tape_ioerr (uptr);               /*   then quit with I/O error status */

        gap_alloc = gap_alloc + meta_size / 2;          /* allocate marker space */
        gap_needed = gap_needed - meta_size / 2;        /* reduce requirement */
        }

    else if (uptr->pos + MTR_L (meta) + meta_size > file_size) {    /* rec len out of range? */
        gap_alloc = gap_alloc + gap_needed;                         /* presume overwritten tape */
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
    else {                                              /* data record */
        sbc = MTR_L (meta);                             /* get record data length */
        rec_size = ((sbc + 1) & ~1) + meta_size * 2;    /* overall size in bytes */

        if (rec_size < gap_needed + min_rec_size) {         /* rec too small? */
            uptr->pos = uptr->pos - meta_size + rec_size;   /* position past record */

            if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* position the tape; if it fails */
                return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

            gap_alloc = gap_alloc + rec_size;               /* allocate record */
            gap_needed = gap_needed - rec_size;             /* reduce requirement */
            }

        else {                                              /* record size OK */
            uptr->pos = uptr->pos - meta_size + gap_needed; /* position to end of gap */







|
|







2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
    else {                                              /* data record */
        sbc = MTR_L (meta);                             /* get record data length */
        rec_size = ((sbc + 1) & ~1) + meta_size * 2;    /* overall size in bytes */

        if (rec_size < gap_needed + min_rec_size) {         /* rec too small? */
            uptr->pos = uptr->pos - meta_size + rec_size;   /* position past record */

            if (sim_tape_seek (uptr, uptr->pos))            /* position the tape; if it fails */
                return sim_tape_ioerr (uptr);               /*   then quit with I/O error status */

            gap_alloc = gap_alloc + rec_size;               /* allocate record */
            gap_needed = gap_needed - rec_size;             /* reduce requirement */
            }

        else {                                              /* record size OK */
            uptr->pos = uptr->pos - meta_size + gap_needed; /* position to end of gap */
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

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 */
    return MTSE_WRP;                                    /*   then we cannot write */

else if (gap_size == 0 || format != MTUF_F_STD)         /* otherwise if the gap length is zero or unsupported */
    return MTSE_OK;                                     /*   then take no action */

gap_pos = uptr->pos;                                    /* save the starting position */

if (gap_size == meta_size) {                            /* if the request is for a single metadatum */
    if (sim_tape_bot (uptr))                            /*   then if the unit is positioned at the BOT */
        return MTSE_BOT;                                /*     then erasing backward is not possible */
    else                                                /*   otherwise */
        uptr->pos -= meta_size;                         /*     back up the file pointer */

    if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /* position the tape; if it fails */
        return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

    (void)sim_fread (&metadatum, meta_size, 1, uptr->fileref);/* read a metadatum */

    if (ferror (uptr->fileref))                             /* if a file I/O error occurred */
        return sim_tape_ioerr (uptr);                       /*   then report the error and quit */

    else if (metadatum == MTR_TMK)                          /* otherwise if a tape mark is present */
        if (sim_fseek (uptr->fileref, uptr->pos, SEEK_SET)) /*   then reposition the tape; if it fails */
            return sim_tape_ioerr (uptr);                   /*     then quit with I/O error status */

        else {                                              /*   otherwise */
            metadatum = MTR_GAP;                            /*     replace it with an erase gap marker */

            xfer = sim_fwrite (&metadatum, meta_size,   /* write the gap marker */
                               1, uptr->fileref);

            if (ferror (uptr->fileref) || xfer == 0)    /* if a file I/O error occurred */
                return sim_tape_ioerr (uptr);           /* report the error and quit */
            else                                        /* otherwise the write succeeded */
                status = MTSE_OK;                       /*   so return success */
            }

    else if (metadatum == MTR_GAP)                      /* otherwise if a gap already exists */
        status = MTSE_OK;                               /*   then take no additional action */

    else {                                              /* otherwise a data record is present */
        uptr->pos = gap_pos;                            /*   so restore the starting position */
        return MTSE_INVRL;                              /*     and fail with invalid record length status */
        }
    }

else {                                                  /* otherwise it's an erase record request */
    status = sim_tape_rdlntr (uptr, &rec_size);         /*   so get the length of the preceding record */

    if (status == MTSE_OK                               /* if the read succeeded */
      && gap_size == rec_size + 2 * meta_size) {        /*   and the gap will exactly overlay the record */
        gap_pos = uptr->pos;                            /*     then save the gap start position */

        status = tape_erase_fwd (uptr, gap_size);       /* erase the record */

        if (status == MTSE_OK)                          /* if the gap write succeeded */
            uptr->pos = gap_pos;                        /*   the reposition back to the start of the gap */
        }







|










|








|








|

















|
|







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
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629

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 */
    return MTSE_WRP;                                    /*   then we cannot write */

else if ((gap_size == 0) || (format != MTUF_F_STD))     /* otherwise if the gap length is zero or unsupported */
    return MTSE_OK;                                     /*   then take no action */

gap_pos = uptr->pos;                                    /* save the starting position */

if (gap_size == meta_size) {                            /* if the request is for a single metadatum */
    if (sim_tape_bot (uptr))                            /*   then if the unit is positioned at the BOT */
        return MTSE_BOT;                                /*     then erasing backward is not possible */
    else                                                /*   otherwise */
        uptr->pos -= meta_size;                         /*     back up the file pointer */

    if (sim_tape_seek (uptr, uptr->pos))                /* position the tape; if it fails */
        return sim_tape_ioerr (uptr);                   /*   then quit with I/O error status */

    (void)sim_fread (&metadatum, meta_size, 1, uptr->fileref);/* read a metadatum */

    if (ferror (uptr->fileref))                             /* if a file I/O error occurred */
        return sim_tape_ioerr (uptr);                       /*   then report the error and quit */

    else if (metadatum == MTR_TMK)                          /* otherwise if a tape mark is present */
        if (sim_tape_seek (uptr, uptr->pos))                /*   then reposition the tape; if it fails */
            return sim_tape_ioerr (uptr);                   /*     then quit with I/O error status */

        else {                                              /*   otherwise */
            metadatum = MTR_GAP;                            /*     replace it with an erase gap marker */

            xfer = sim_fwrite (&metadatum, meta_size,   /* write the gap marker */
                               1, uptr->fileref);

            if (ferror (uptr->fileref) || (xfer == 0))  /* if a file I/O error occurred */
                return sim_tape_ioerr (uptr);           /* report the error and quit */
            else                                        /* otherwise the write succeeded */
                status = MTSE_OK;                       /*   so return success */
            }

    else if (metadatum == MTR_GAP)                      /* otherwise if a gap already exists */
        status = MTSE_OK;                               /*   then take no additional action */

    else {                                              /* otherwise a data record is present */
        uptr->pos = gap_pos;                            /*   so restore the starting position */
        return MTSE_INVRL;                              /*     and fail with invalid record length status */
        }
    }

else {                                                  /* otherwise it's an erase record request */
    status = sim_tape_rdlntr (uptr, &rec_size);         /*   so get the length of the preceding record */

    if ((status == MTSE_OK) &&                          /* if the read succeeded */
        (gap_size == rec_size + 2 * meta_size)) {       /*   and the gap will exactly overlay the record */
        gap_pos = uptr->pos;                            /*     then save the gap start position */

        status = tape_erase_fwd (uptr, gap_size);       /* erase the record */

        if (status == MTSE_OK)                          /* if the gap write succeeded */
            uptr->pos = gap_pos;                        /*   the reposition back to the start of the gap */
        }
2661
2662
2663
2664
2665
2666
2667
2668
2669

2670
2671
2672
2673
2674
2675
2676
2677
2678

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_unit (ctx->dbit, uptr, "sim_tape_rewind(unit=%d)\n", (int)(uptr-ctx->dptr->units));
    }
uptr->pos = 0;
if (uptr->flags & UNIT_ATT)
    (void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);

MT_CLR_PNU (uptr);
MT_CLR_INMRK (uptr);                                    /* Not within an AWS or TAR tapemark */
return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP







|
|
>

|







3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166

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_unit (ctx->dbit, uptr, "sim_tape_rewind(unit=%d)\n", (int)(uptr-ctx->dptr->units));
    }
uptr->pos = 0;
if (uptr->flags & UNIT_ATT) {
    (void)sim_tape_seek (uptr, uptr->pos);
    }
MT_CLR_PNU (uptr);
MT_CLR_INMRK (uptr);                                    /* Not within a TAR tapemark */
return MTSE_OK;
}

t_stat sim_tape_rewind_a (UNIT *uptr, TAPE_PCALLBACK callback)
{
t_stat r = MTSE_OK;
AIO_CALLSETUP
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780

/* Test for BOT */

t_bool sim_tape_bot (UNIT *uptr)
{
uint32 f = MT_GET_FMT (uptr);

return (uptr->pos <= fmts[f].bot)? TRUE: FALSE;
}

/* Test for end of tape */

t_bool sim_tape_eot (UNIT *uptr)
{
return (uptr->capac && (uptr->pos >= uptr->capac))? TRUE: FALSE;







|







3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268

/* Test for BOT */

t_bool sim_tape_bot (UNIT *uptr)
{
uint32 f = MT_GET_FMT (uptr);

return ((uptr->pos <= fmts[f].bot) && (!MT_TST_INMRK (uptr))) ? TRUE: FALSE;
}

/* Test for end of tape */

t_bool sim_tape_eot (UNIT *uptr)
{
return (uptr->capac && (uptr->pos >= uptr->capac))? TRUE: FALSE;
2804
2805
2806
2807
2808
2809
2810
2811


2812







2813
2814




2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836

if (uptr == NULL)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if (cptr == NULL)
    return SCPE_ARG;
for (f = 0; f < MTUF_N_FMT; f++) {


    if (fmts[f].name && (strcmp (cptr, fmts[f].name) == 0)) {







        uptr->flags = (uptr->flags & ~MTUF_FMT) |
            (f << MTUF_V_FMT) | fmts[f].uflags;




        return SCPE_OK;
        }
    }
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)
{







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



|






<
<
<
|
<







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

if (uptr == NULL)
    return SCPE_IERR;
if (uptr->flags & UNIT_ATT)
    return SCPE_ALATT;
if (cptr == NULL)
    return SCPE_ARG;
for (f = 0; fmts[f].name; f++) {
    if (MATCH_CMD(fmts[f].name, cptr) == 0) {
        uint32 a = 0;

        if (f == MTUF_F_ANSI) {
            for (a = 0; ansi_args[a].name; a++)
                if (MATCH_CMD(ansi_args[a].name, cptr) == 0)
                    break;
            if (ansi_args[a].name == NULL)
                return sim_messagef (SCPE_ARG, "Unknown ANSI tape format: %s\n", cptr);
            }
        uptr->flags &= ~UNIT_RO;
        uptr->flags |= fmts[f].uflags;
        uptr->dynflags &= ~UNIT_M_TAPE_FMT;
        uptr->dynflags |= (f << UNIT_V_TAPE_FMT);
        uptr->dynflags &= ~UNIT_M_TAPE_ANSI;
        uptr->dynflags |= (a << UNIT_V_TAPE_ANSI);
        return SCPE_OK;
        }
    }
return sim_messagef (SCPE_ARG, "Unknown tape format: %s\n", cptr);
}

/* Show tape format */

t_stat sim_tape_show_fmt (FILE *st, UNIT *uptr, int32 val, CONST void *desc)
{



fprintf (st, "%s format", _sim_tape_format_name (uptr));

return SCPE_OK;
}

/* Map a TPC format tape image */

static uint32 sim_tape_tpc_map (UNIT *uptr, t_addr *map, uint32 mapsize)
{
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856


2857
2858
2859
2860
2861
2862
2863
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_unit (MTSE_DBG_STR, uptr, "tpc_map: tape_size: %" T_ADDR_FMT "u\n", tape_size);
for (objc = 0, sizec = 0, tpos = 0;; ) {
    (void)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) {







|
|

>
>







3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
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_unit (MTSE_DBG_STR, uptr, "tpc_map: tape_size: %" T_ADDR_FMT "u\n", tape_size);
for (objc = 0, sizec = 0, tpos = 0;; ) {
    (void)sim_tape_seek (uptr, tpos);
    i = sim_fread (&bc, sizeof (bc), 1, uptr->fileref);
    if (i == 0)     /* past or at eof? */
        break;
    if (bc > 65535) /* Range check length value to satisfy Coverity */
        break;
    if (countmap[bc] == 0)
        sizec++;
    ++countmap[bc];
    if (map && (objc < mapsize))
        map[objc] = tpos;
    if (bc) {
2936
2937
2938
2939
2940
2941
2942




2943
2944
2945
2946
2947
2948
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
2978
2979
2980
2981
2982
2983

2984
2985
2986

2987

2988
2989

2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006

3007
3008
3009
3010

3011
3012
3013
3014

3015
3016
3017
3018
3019





3020

3021
3022

3023

3024
3025

3026
3027
3028
3029





3030
3031
3032
3033
3034
3035
3036
static char msgbuf[64];

if (stat <= MTSE_MAX_ERR)
    return mtse_errors[stat];
sprintf(msgbuf, "Error %d", stat);
return msgbuf;
}





static t_stat sim_tape_validate_tape (UNIT *uptr)
{
t_addr saved_pos = uptr->pos;
uint32 record_in_file = 0;
uint32 data_total = 0;
uint32 tapemark_total = 0;
uint32 record_total = 0;
uint32 unique_record_sizes = 0;
uint32 remaining_data = 0;


uint32 *rec_sizes = NULL;
t_stat r = SCPE_OK;
t_stat r_f;
t_stat r_r;
t_stat r_s;
uint8 *buf_f = NULL;
uint8 *buf_r = NULL;
t_mtrlnt bc_f;
t_mtrlnt bc_r;
t_mtrlnt bc_s;
t_mtrlnt bc;
t_addr pos_f;
t_addr pos_r;


t_mtrlnt max = MTR_MAXLEN;

if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;
buf_f = (uint8 *)calloc (1, max);
if (buf_f == NULL)
    return SCPE_MEM;
buf_r = (uint8 *)calloc (1, max);
if (buf_r == NULL) {
    free (buf_f);
    return SCPE_MEM;
    }
rec_sizes = (uint32 *)calloc (max + 1, sizeof (*rec_sizes));
if (rec_sizes == NULL) {
    free (buf_f);
    free (buf_r);
    return SCPE_MEM;
    }

r = sim_tape_rewind (uptr);
while (r == SCPE_OK) {
    if (stop_cpu)   /* SIGINT? */

        break;

    pos_f = uptr->pos;
    r_f = sim_tape_rdrecf (uptr, buf_f, &bc_f, max);

    switch (r_f) {
    case MTSE_OK:                                   /* no error */
    case MTSE_TMK:                                  /* tape mark */
        if (r_f == MTSE_OK)
            ++record_total;
        else
            ++tapemark_total;
        data_total += bc_f;
        if (bc_f != 0) {
            if (rec_sizes[bc_f] == 0)
                ++unique_record_sizes;
            ++rec_sizes[bc_f];
            }
        r_r = sim_tape_rdrecr (uptr, buf_r, &bc_r, max);
        pos_r = uptr->pos;
        if (r_r != r_f) {
            sim_printf ("Forward Record Read returned: %s, Reverse read returned: %s\n", sim_tape_error_text (r_f), sim_tape_error_text (r_r));

            break;
            }
        if (bc_f != bc_r) {
            sim_printf ("Forward Record Read record length: %d, Reverse read record length: %d\n", bc_f, bc_r);

            break;
            }
        if (0 != memcmp (buf_f, buf_r, bc_f)) {
            sim_printf ("%d byte record contents differ when read forward amd backwards start from position %" T_ADDR_FMT "u\n", bc_f, pos_f);

            break;
            }
        memset (buf_f, 0, bc_f);
        memset (buf_r, 0, bc_f);
        if (pos_f != pos_r) {





            sim_printf ("Unexpected tape file position between forward and reverse record read: (%" T_ADDR_FMT "u, %" T_ADDR_FMT "u\n", pos_f, pos_r);

            break;
            }

        r_s = sim_tape_sprecf (uptr, &bc_s);

        if (r_s != r_f) {
            sim_printf ("Unexpected Space Record Status: %s vs %s\n", sim_tape_error_text (r_s), sim_tape_error_text (r_f));

            break;
            }
        if (bc_s != bc_f) {
            sim_printf ("Unexpected Space Record Length: %d vs %d\n", bc_s, bc_f);





            break;
            }
        r = SCPE_OK;
        break;
    case MTSE_INVRL:                                /* invalid rec lnt */
    case MTSE_FMT:                                  /* invalid format */
    case MTSE_BOT:                                  /* beginning of tape */







>
>
>
>










>
>













>
>


















>


|
>

>


>

















>




>




>



|

>
>
>
>
>
|
>
|
|
>

>


>




>
>
>
>
>







3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
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
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
3564
static char msgbuf[64];

if (stat <= MTSE_MAX_ERR)
    return mtse_errors[stat];
sprintf(msgbuf, "Error %d", stat);
return msgbuf;
}

#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif

static t_stat sim_tape_validate_tape (UNIT *uptr)
{
t_addr saved_pos = uptr->pos;
uint32 record_in_file = 0;
uint32 data_total = 0;
uint32 tapemark_total = 0;
uint32 record_total = 0;
uint32 unique_record_sizes = 0;
uint32 remaining_data = 0;
uint32 gaps = 0;
uint32 gap_bytes = 0;
uint32 *rec_sizes = NULL;
t_stat r = SCPE_OK;
t_stat r_f;
t_stat r_r;
t_stat r_s;
uint8 *buf_f = NULL;
uint8 *buf_r = NULL;
t_mtrlnt bc_f;
t_mtrlnt bc_r;
t_mtrlnt bc_s;
t_mtrlnt bc;
t_addr pos_f;
t_addr pos_r;
t_addr pos_fa;
t_addr pos_sa;
t_mtrlnt max = MTR_MAXLEN;

if (!(uptr->flags & UNIT_ATT))
    return SCPE_UNATT;
buf_f = (uint8 *)calloc (1, max);
if (buf_f == NULL)
    return SCPE_MEM;
buf_r = (uint8 *)calloc (1, max);
if (buf_r == NULL) {
    free (buf_f);
    return SCPE_MEM;
    }
rec_sizes = (uint32 *)calloc (max + 1, sizeof (*rec_sizes));
if (rec_sizes == NULL) {
    free (buf_f);
    free (buf_r);
    return SCPE_MEM;
    }

r = sim_tape_rewind (uptr);
while (r == SCPE_OK) {
    if (stop_cpu) { /* SIGINT? */
        stop_cpu = FALSE;
        break;
        }
    pos_f = uptr->pos;
    r_f = sim_tape_rdrecf (uptr, buf_f, &bc_f, max);
    pos_fa = uptr->pos;
    switch (r_f) {
    case MTSE_OK:                                   /* no error */
    case MTSE_TMK:                                  /* tape mark */
        if (r_f == MTSE_OK)
            ++record_total;
        else
            ++tapemark_total;
        data_total += bc_f;
        if (bc_f != 0) {
            if (rec_sizes[bc_f] == 0)
                ++unique_record_sizes;
            ++rec_sizes[bc_f];
            }
        r_r = sim_tape_rdrecr (uptr, buf_r, &bc_r, max);
        pos_r = uptr->pos;
        if (r_r != r_f) {
            sim_printf ("Forward Record Read returned: %s, Reverse read returned: %s\n", sim_tape_error_text (r_f), sim_tape_error_text (r_r));
            r = MAX(r_f, r_r);
            break;
            }
        if (bc_f != bc_r) {
            sim_printf ("Forward Record Read record length: %d, Reverse read record length: %d\n", bc_f, bc_r);
            r = MTSE_RECE;
            break;
            }
        if (0 != memcmp (buf_f, buf_r, bc_f)) {
            sim_printf ("%d byte record contents differ when read forward amd backwards start from position %" T_ADDR_FMT "u\n", bc_f, pos_f);
            r = MTSE_RECE;
            break;
            }
        memset (buf_f, 0, bc_f);
        memset (buf_r, 0, bc_r);
        if (pos_f != pos_r) {
            if (MT_GET_FMT (uptr) == MTUF_F_STD) {
                ++gaps;
                gap_bytes += (uint32)(pos_r - pos_f);
                }
            else {
                sim_printf ("Unexpected tape file position between forward and reverse record read: (%" T_ADDR_FMT "u, %" T_ADDR_FMT "u)\n", pos_f, pos_r);
                r = MTSE_RECE;
                break;
                }
            }
        r_s = sim_tape_sprecf (uptr, &bc_s);
        pos_sa = uptr->pos;
        if (r_s != r_f) {
            sim_printf ("Unexpected Space Record Status: %s vs %s\n", sim_tape_error_text (r_s), sim_tape_error_text (r_f));
            r = MAX(r_s, r_f);
            break;
            }
        if (bc_s != bc_f) {
            sim_printf ("Unexpected Space Record Length: %d vs %d\n", bc_s, bc_f);
            r = MTSE_RECE;
            break;
            }
        if (pos_fa != pos_sa) {
            sim_printf ("Unexpected tape file position after forward and skip record: (%" T_ADDR_FMT "u, %" T_ADDR_FMT "u)\n", pos_fa, pos_sa);
            break;
            }
        r = SCPE_OK;
        break;
    case MTSE_INVRL:                                /* invalid rec lnt */
    case MTSE_FMT:                                  /* invalid format */
    case MTSE_BOT:                                  /* beginning of tape */
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067


3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
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
3112
        r = r_f;
        break;
        }
    }
uptr->tape_eom = uptr->pos;
if ((!stop_cpu) &&
    ((r != MTSE_EOM) || (sim_switches & SWMASK ('V')) || (sim_switches & SWMASK ('L')) ||
     ((uint32)(sim_fsize_ex (uptr->fileref) - (t_offset)uptr->pos) > fmts[MT_GET_FMT (uptr)].eom_remnant) ||
     (unique_record_sizes > 2 * tapemark_total))) {
    remaining_data = (uint32)(sim_fsize_ex (uptr->fileref) - (t_offset)uptr->tape_eom);
    sim_printf ("Tape Image '%s' scanned as %s format.\n", uptr->filename, fmts[MT_GET_FMT (uptr)].name);
    if (r != MTSE_EOM)
        sim_printf ("After processing ");
    else
        sim_printf ("contains ");
    sim_printf ("%u bytes of tape data (%u records, %u tapemarks)\n",
                data_total, record_total, tapemark_total);
    if ((record_total > 0) && (sim_switches & SWMASK ('L'))) {
        sim_printf ("Comprising %d different sized records (in record size order):\n", unique_record_sizes);
        for (bc = 0; bc <= max; bc++) {
            if (rec_sizes[bc])
                sim_printf ("%8u %u byte records\n", rec_sizes[bc], (uint32)bc);
            }


        }
    if (r != MTSE_EOM)
        sim_printf ("Read Tape Record Returned Unexpected Status: %s\n", sim_tape_error_text (r));
    if (remaining_data > fmts[MT_GET_FMT (uptr)].eom_remnant)
        sim_printf ("%u bytes of unexamined data remain in the tape image file\n", remaining_data);
    }
if ((!stop_cpu) && 
    (unique_record_sizes > 2 * tapemark_total)) {
    sim_printf ("An unreasonable number of record sizes(%u) vs tape marks (%u) have been found\n", unique_record_sizes, tapemark_total);
    sim_printf ("The tape format (%s) might not be correct for the '%s' tape image\n", fmts[MT_GET_FMT (uptr)].name, uptr->filename);
    }

free (buf_f);
free (buf_r);
free (rec_sizes);
uptr->pos = saved_pos;
(void)sim_fseek (uptr->fileref, uptr->pos, SEEK_SET);
return SCPE_OK;
}

/* Find the preceding record in a TPC file */

static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map)
{
uint32 lo, hi, p;


if (map == NULL)
    return 0;
lo = 0;
hi = uptr->hwmark - 1;
do {
    p = (lo + hi) >> 1;
    if (uptr->pos == map[p])
        return ((p == 0)? map[p]: map[p - 1]);

    else if (uptr->pos < map[p])
        hi = p - 1;

    else lo = p + 1;

    }
while (lo <= hi);
return ((p == 0)? map[p]: map[p - 1]);
}

/* Set tape capacity */








|

|
|
<
<
<
<
|
|

|


|

>
>


|

|



|
|






|


















>
|
|
>
|
>







3573
3574
3575
3576
3577
3578
3579
3580
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
        r = r_f;
        break;
        }
    }
uptr->tape_eom = uptr->pos;
if ((!stop_cpu) &&
    ((r != MTSE_EOM) || (sim_switches & SWMASK ('V')) || (sim_switches & SWMASK ('L')) ||
     ((uint32)(sim_tape_size (uptr) - (t_offset)uptr->pos) > fmts[MT_GET_FMT (uptr)].eom_remnant) ||
     (unique_record_sizes > 2 * tapemark_total))) {
    remaining_data = (uint32)(sim_tape_size (uptr) - (t_offset)uptr->tape_eom);
    sim_messagef (SCPE_OK, "Tape Image %s'%s' scanned as %s format.\n", ((MT_GET_FMT (uptr) == MTUF_F_ANSI) ? "made from " : ""), uptr->filename, (MT_GET_FMT (uptr) == MTUF_F_ANSI) ? ansi_args[MT_GET_ANSI_TYP (uptr)].name : fmts[MT_GET_FMT (uptr)].name);




    sim_messagef (SCPE_OK, "%s %u bytes of tape data (%u records, %u tapemarks)\n",
                           (r != MTSE_EOM) ? "After processing" : "contains", data_total, record_total, tapemark_total);
    if ((record_total > 0) && (sim_switches & SWMASK ('L'))) {
        sim_messagef (SCPE_OK, "Comprising %d different sized records (in record size order):\n", unique_record_sizes);
        for (bc = 0; bc <= max; bc++) {
            if (rec_sizes[bc])
                sim_messagef (SCPE_OK, "%8u %u byte record%s\n", rec_sizes[bc], (uint32)bc, (rec_sizes[bc] != 1) ? "s" : "");
            }
        if (gaps)
            sim_messagef (SCPE_OK, "%8u gap%s totalling %u bytes %s seen\n", gaps, (gaps != 1) ? "s" : "", gap_bytes, (gaps != 1) ? "were" : "was");
        }
    if (r != MTSE_EOM)
        sim_messagef (SCPE_OK, "Read Tape Record Returned Unexpected Status: %s\n", sim_tape_error_text (r));
    if (remaining_data > fmts[MT_GET_FMT (uptr)].eom_remnant)
        sim_messagef (SCPE_OK, "%u bytes of unexamined data remain in the tape image file\n", remaining_data);
    }
if ((!stop_cpu) && 
    (unique_record_sizes > 2 * tapemark_total)) {
    sim_messagef (SCPE_OK, "A potentially unreasonable number of record sizes(%u) vs tape marks (%u) have been found\n", unique_record_sizes, tapemark_total);
    sim_messagef (SCPE_OK, "The tape format (%s) might not be correct for the '%s' tape image\n", fmts[MT_GET_FMT (uptr)].name, uptr->filename);
    }

free (buf_f);
free (buf_r);
free (rec_sizes);
uptr->pos = saved_pos;
(void)sim_tape_seek (uptr, uptr->pos);
return SCPE_OK;
}

/* Find the preceding record in a TPC file */

static t_addr sim_tape_tpc_fnd (UNIT *uptr, t_addr *map)
{
uint32 lo, hi, p;


if (map == NULL)
    return 0;
lo = 0;
hi = uptr->hwmark - 1;
do {
    p = (lo + hi) >> 1;
    if (uptr->pos == map[p])
        return ((p == 0)? map[p]: map[p - 1]);
    else {
        if (uptr->pos < map[p])
            hi = p - 1;
        else
            lo = p + 1;
        }
    }
while (lo <= hi);
return ((p == 0)? map[p]: map[p - 1]);
}

/* Set tape capacity */

3284
3285
3286
3287
3288
3289
3290


3291
3292
3293
3294
3295
3296
3297
static t_stat sim_tape_test_create_tape_files (UNIT *uptr, const char *filename, int files, int records, int max_size)
{
FILE *fSIMH = NULL;
FILE *fE11 = NULL;
FILE *fTPC = NULL;
FILE *fP7B = NULL;
FILE *fAWS = NULL;


FILE *fTAR = NULL;
FILE *fTAR2 = NULL;
int i, j, k;
t_tpclnt tpclnt;
t_mtrlnt mtrlnt;
t_awslnt awslnt;
t_awslnt awslnt_last = 0;







>
>







3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
static t_stat sim_tape_test_create_tape_files (UNIT *uptr, const char *filename, int files, int records, int max_size)
{
FILE *fSIMH = NULL;
FILE *fE11 = NULL;
FILE *fTPC = NULL;
FILE *fP7B = NULL;
FILE *fAWS = NULL;
FILE *fAWS2 = NULL;
FILE *fAWS3 = NULL;
FILE *fTAR = NULL;
FILE *fTAR2 = NULL;
int i, j, k;
t_tpclnt tpclnt;
t_mtrlnt mtrlnt;
t_awslnt awslnt;
t_awslnt awslnt_last = 0;
3344
3345
3346
3347
3348
3349
3350








3351
3352
3353
3354
3355
3356
3357
sprintf (name, "%s.2.tar", filename);
fTAR2 = fopen (name, "wb");
if (fTAR2  == NULL)
    goto Done_Files;
sprintf (name, "%s.aws", filename);
fAWS = fopen (name, "wb");
if (fAWS  == NULL)








    goto Done_Files;
sprintf (name, "aws %s.aws.tape", filename);
(void)remove (name);
sim_switches = SWMASK ('F') | (sim_switches & SWMASK ('D')) | SWMASK ('N');
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = MTSE_DBG_STR | MTSE_DBG_DAT;
aws_stat = sim_tape_attach_ex (uptr, name, (saved_switches & SWMASK ('D')) ? MTSE_DBG_STR | MTSE_DBG_DAT: 0, 0);







>
>
>
>
>
>
>
>







3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
sprintf (name, "%s.2.tar", filename);
fTAR2 = fopen (name, "wb");
if (fTAR2  == NULL)
    goto Done_Files;
sprintf (name, "%s.aws", filename);
fAWS = fopen (name, "wb");
if (fAWS  == NULL)
    goto Done_Files;
sprintf (name, "%s.2.aws", filename);
fAWS2 = fopen (name, "wb");
if (fAWS2  == NULL)
    goto Done_Files;
sprintf (name, "%s.3.aws", filename);
fAWS3 = fopen (name, "wb");
if (fAWS3  == NULL)
    goto Done_Files;
sprintf (name, "aws %s.aws.tape", filename);
(void)remove (name);
sim_switches = SWMASK ('F') | (sim_switches & SWMASK ('D')) | SWMASK ('N');
if (sim_switches & SWMASK ('D'))
    uptr->dctrl = MTSE_DBG_STR | MTSE_DBG_DAT;
aws_stat = sim_tape_attach_ex (uptr, name, (saved_switches & SWMASK ('D')) ? MTSE_DBG_STR | MTSE_DBG_DAT: 0, 0);
3369
3370
3371
3372
3373
3374
3375





3376
3377
3378
3379
3380


3381
3382
3383
3384
3385
3386
3387
            buf[k] = rand () & 0xFF;
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fSIMH);
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fE11);
        (void)sim_fwrite (&tpclnt,       sizeof (tpclnt),       1, fTPC);
        (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
        (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
        (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);





        awslnt_last = awslnt;
        (void)sim_fwrite (buf, 1, rec_size, fSIMH);
        (void)sim_fwrite (buf, 1, rec_size, fE11);
        (void)sim_fwrite (buf, 1, rec_size, fTPC);
        (void)sim_fwrite (buf, 1, rec_size, fAWS);


        stat = sim_tape_wrrecf (uptr, buf, rec_size);
        if (MTSE_OK != stat)
            goto Done_Files;
        if (rec_size & 1) {
            (void)sim_fwrite (&tpclnt, 1, 1, fSIMH);
            (void)sim_fwrite (&tpclnt, 1, 1, fTPC);
            }







>
>
>
>
>





>
>







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
            buf[k] = rand () & 0xFF;
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fSIMH);
        (void)sim_fwrite (&mtrlnt,       sizeof (mtrlnt),       1, fE11);
        (void)sim_fwrite (&tpclnt,       sizeof (tpclnt),       1, fTPC);
        (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
        (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
        (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);
        if (i == 0) {
            (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS3);
            (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS3);
            (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS3);
            }
        awslnt_last = awslnt;
        (void)sim_fwrite (buf, 1, rec_size, fSIMH);
        (void)sim_fwrite (buf, 1, rec_size, fE11);
        (void)sim_fwrite (buf, 1, rec_size, fTPC);
        (void)sim_fwrite (buf, 1, rec_size, fAWS);
        if (i == 0)
            (void)sim_fwrite (buf, 1, rec_size, fAWS3);
        stat = sim_tape_wrrecf (uptr, buf, rec_size);
        if (MTSE_OK != stat)
            goto Done_Files;
        if (rec_size & 1) {
            (void)sim_fwrite (&tpclnt, 1, 1, fSIMH);
            (void)sim_fwrite (&tpclnt, 1, 1, fTPC);
            }
3399
3400
3401
3402
3403
3404
3405





3406
3407
3408
3409






3410
3411
3412
3413
3414
3415
3416
    (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
    (void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
    buf[0] = P7B_SOR | P7B_EOF;
    (void)sim_fwrite (buf, 1, 1, fP7B);
    (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
    (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
    (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);





    awslnt_last = 0;
    stat = sim_tape_wrtmk (uptr);
    if (MTSE_OK != stat)
        goto Done_Files;






    }
mtrlnt = tpclnt = 0;
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
(void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
awslnt_last = awslnt;
awsrec_typ = AWS_TMK;







>
>
>
>
>




>
>
>
>
>
>







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
3970
3971
3972
3973
    (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
    (void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
    buf[0] = P7B_SOR | P7B_EOF;
    (void)sim_fwrite (buf, 1, 1, fP7B);
    (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS);
    (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS);
    (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS);
    if (i == 0) {
        (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS3);
        (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS3);
        (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS3);
        }
    awslnt_last = 0;
    stat = sim_tape_wrtmk (uptr);
    if (MTSE_OK != stat)
        goto Done_Files;
    if (i == 0) {
        mtrlnt = MTR_GAP;
        for (j=0; j<rec_size; j++)
            (void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
        mtrlnt = 0;
        }
    }
mtrlnt = tpclnt = 0;
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fSIMH);
(void)sim_fwrite (&mtrlnt, sizeof (mtrlnt), 1, fE11);
(void)sim_fwrite (&tpclnt, sizeof (tpclnt), 1, fTPC);
awslnt_last = awslnt;
awsrec_typ = AWS_TMK;
3437
3438
3439
3440
3441
3442
3443







3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454




3455
3456
3457
3458
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
for (j=0; j<records; j++) {
    memset (buf, j, 10240);
    (void)sim_fwrite (buf, 1, 10240, fTAR);
    (void)sim_fwrite (buf, 1, 10240, fTAR2);
    }
memset (buf, j, 10240);
(void)sim_fwrite (buf, 1, 5120, fTAR2);







Done_Files:
if (fSIMH)
    fclose (fSIMH);
if (fE11)
    fclose (fE11);
if (fTPC)
    fclose (fTPC);
if (fP7B)
    fclose (fP7B);
if (fAWS)
    fclose (fAWS);




if (fTAR)
    fclose (fTAR);
if (fTAR2)
    fclose (fTAR2);
free (buf);
sim_tape_detach (uptr);
if (stat == SCPE_OK) {
    char name1[CBUFSIZE], name2[CBUFSIZE];

    sprintf (name1, "\"%s.aws\"", filename);
    sprintf (name2, "\"%s.aws.tape\"", filename);
    sim_switches = SWMASK ('F');
    if (sim_cmp_string (name1, name2))
        stat = 1;
    }
sim_switches = saved_switches;
return stat;
}

static t_stat sim_tape_test_process_tape_file (UNIT *uptr, const char *filename, const char *format)
{
char args[256];

t_stat stat;








sprintf (args, "%s %s.%s", format, filename, format);
sim_tape_detach (uptr);
sim_switches |= SWMASK ('F') | SWMASK ('L');    /* specific-format and detailed record report */
stat = sim_tape_attach_ex (uptr, args, 0, 0);
if (stat != SCPE_OK)
    return stat;
sim_tape_detach (uptr);
sim_switches = 0;
return SCPE_OK;
}

static t_stat sim_tape_test_remove_tape_files (UNIT *uptr, const char *filename)
{
char name[256];

sprintf (name, "%s.simh", filename);
(void)remove (name);


sprintf (name, "%s.e11", filename);


(void)remove (name);
sprintf (name, "%s.tpc", filename);
(void)remove (name);


sprintf (name, "%s.p7b", filename);
(void)remove (name);


sprintf (name, "%s.aws", filename);




(void)remove (name);
sprintf (name, "%s.tar", filename);
(void)remove (name);
sprintf (name, "%s.2.tar", filename);


(void)remove (name);
return SCPE_OK;
}

static t_stat sim_tape_test_density_string (void)
{
char buf[128];







>
>
>
>
>
>
>











>
>
>
>



















|


>


>
>
>
>
>
>
>
|
















>
>

>
>



>
>


>
>

>
>
>
>




>
>







3994
3995
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
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
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
for (j=0; j<records; j++) {
    memset (buf, j, 10240);
    (void)sim_fwrite (buf, 1, 10240, fTAR);
    (void)sim_fwrite (buf, 1, 10240, fTAR2);
    }
memset (buf, j, 10240);
(void)sim_fwrite (buf, 1, 5120, fTAR2);
for (j=0; j<3; j++) {
    awslnt_last = awslnt = 0;
    awsrec_typ = AWS_TMK;
    (void)sim_fwrite (&awslnt,       sizeof (awslnt),       1, fAWS2);
    (void)sim_fwrite (&awslnt_last,  sizeof (awslnt_last),  1, fAWS2);
    (void)sim_fwrite (&awsrec_typ,   sizeof (awsrec_typ),   1, fAWS2);
    }
Done_Files:
if (fSIMH)
    fclose (fSIMH);
if (fE11)
    fclose (fE11);
if (fTPC)
    fclose (fTPC);
if (fP7B)
    fclose (fP7B);
if (fAWS)
    fclose (fAWS);
if (fAWS2)
    fclose (fAWS2);
if (fAWS3)
    fclose (fAWS3);
if (fTAR)
    fclose (fTAR);
if (fTAR2)
    fclose (fTAR2);
free (buf);
sim_tape_detach (uptr);
if (stat == SCPE_OK) {
    char name1[CBUFSIZE], name2[CBUFSIZE];

    sprintf (name1, "\"%s.aws\"", filename);
    sprintf (name2, "\"%s.aws.tape\"", filename);
    sim_switches = SWMASK ('F');
    if (sim_cmp_string (name1, name2))
        stat = 1;
    }
sim_switches = saved_switches;
return stat;
}

static t_stat sim_tape_test_process_tape_file (UNIT *uptr, const char *filename, const char *format, t_awslnt recsize)
{
char args[256];
char str_recsize[16] = "";
t_stat stat;

if (recsize) {
    sim_switches |= SWMASK ('B');
    sprintf (str_recsize, " %d", (int)recsize);
    }
if (NULL == strchr (filename, '*'))
    sprintf (args, "%s%s %s.%s", format, str_recsize, filename, format);
else
    sprintf (args, "%s%s %s", format, str_recsize, filename);
sim_tape_detach (uptr);
sim_switches |= SWMASK ('F') | SWMASK ('L');    /* specific-format and detailed record report */
stat = sim_tape_attach_ex (uptr, args, 0, 0);
if (stat != SCPE_OK)
    return stat;
sim_tape_detach (uptr);
sim_switches = 0;
return SCPE_OK;
}

static t_stat sim_tape_test_remove_tape_files (UNIT *uptr, const char *filename)
{
char name[256];

sprintf (name, "%s.simh", filename);
(void)remove (name);
sprintf (name, "%s.2.simh", filename);
(void)remove (name);
sprintf (name, "%s.e11", filename);
(void)remove (name);
sprintf (name, "%s.2.e11", filename);
(void)remove (name);
sprintf (name, "%s.tpc", filename);
(void)remove (name);
sprintf (name, "%s.2.tpc", filename);
(void)remove (name);
sprintf (name, "%s.p7b", filename);
(void)remove (name);
sprintf (name, "%s.2.p7b", filename);
(void)remove (name);
sprintf (name, "%s.aws", filename);
(void)remove (name);
sprintf (name, "%s.2.aws", filename);
(void)remove (name);
sprintf (name, "%s.3.aws", filename);
(void)remove (name);
sprintf (name, "%s.tar", filename);
(void)remove (name);
sprintf (name, "%s.2.tar", filename);
(void)remove (name);
sprintf (name, "%s.3.tar", filename);
(void)remove (name);
return SCPE_OK;
}

static t_stat sim_tape_test_density_string (void)
{
char buf[128];
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
























3578
3579
3580
3581
3582

































































































































































































































































































































































































































































































































































































































































SIM_TEST(sim_tape_test_density_string ());

SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

SIM_TEST(sim_tape_test_create_tape_files (dptr->units, "TapeTestFile1", 2, 5, 4096));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tar"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.2", "tar"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "aws"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "p7b"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tpc"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "e11"));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "simh"));

























SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

return SCPE_OK;
}








































































































































































































































































































































































































































































































































































































































































|


|


|


|


|


|


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





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
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
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
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
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
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
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
4361
4362
4363
4364
4365
4366
4367
4368
4369
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
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
4584
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
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
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
SIM_TEST(sim_tape_test_density_string ());

SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

SIM_TEST(sim_tape_test_create_tape_files (dptr->units, "TapeTestFile1", 2, 5, 4096));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.*", "ansi-vms", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.*", "ansi-rsx11", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.*", "ansi-rt11", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.*", "ansi-rsts", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.*", "ansi-var", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tar", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "aws", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.3", "aws", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.2", "aws", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1.2", "tar", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "aws", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "p7b", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "tpc", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "e11", 0));

sim_switches = saved_switches;
SIM_TEST(sim_tape_test_process_tape_file (dptr->units, "TapeTestFile1", "simh", 0));

SIM_TEST(sim_tape_test_remove_tape_files (dptr->units, "TapeTestFile1"));

return SCPE_OK;
}

static void ansi_date (time_t datetime, char date[6], t_bool y2k_date_bug)
    {
    struct tm *lt;
    char buf[20];

    lt = localtime (&datetime);
    if (y2k_date_bug)
        sprintf (buf, " %c%c%03d", '0' + (lt->tm_year / 10), 
                                   '0' + (lt->tm_year % 10), 
                                   lt->tm_yday + 1);
    else
        sprintf (buf, "%c%02d%03d", (lt->tm_year < 100) ? ' ' : '0' + (lt->tm_year/100 - 1), 
                                    lt->tm_year % 100, 
                                    lt->tm_yday + 1);
    memcpy (date, buf, 6);
    }

/* 
 * This isn't quite ANSI 'a' since several ANSI allowed characters
 * are either illegal file names on many DEC systems or are confusing
 * to OS file name parsers.
 */
static void to_ansi_a (char *out, const char *in, size_t size)
    {
    memset (out, ' ', size);
    while (size--) {
        if (isupper (*in) || isdigit (*in))
            *(out++) = *in++;
        else {
            if (*in == '\0')
                break;
            if (islower (*in)) {
                *(out++) = toupper (*in);
                ++in;
                }
            else {
                if (strchr ("-.$_/", *in))
                    *(out++) = *in++;
                else
                    ++in;
                }
            }
        }
    }

static void ansi_make_VOL1 (VOL1 *vol, const char *ident, uint32 ansi_type)
    {
    memset (vol, ' ', sizeof (*vol));
    memcpy (vol->type, "VOL", 3);
    vol->num = '1';
    to_ansi_a (vol->ident, ident, sizeof (vol->ident));
    vol->standard = ansi_args[ansi_type].vol1_standard;
    }

static void ansi_make_HDR1 (HDR1 *hdr1, VOL1 *vol, HDR4 *hdr4, const char *filename, uint32 ansi_type)
    {
    const char *fn;
    struct stat statb;
    char extra_name_used[3] = "00";
    char *fn_cpy, *c, *ext;

    memset (&statb, 0, sizeof (statb));
    (void)stat (filename, &statb);
    if (!(fn = strrchr (filename, '/')) && !(fn = strrchr (filename, '\\')))
        fn = filename;
    else
        ++fn;                                   /* skip over slash or backslash */
    fn_cpy = (char *)malloc (strlen (fn) + 1);
    strcpy (fn_cpy, fn);
    fn = fn_cpy;
    ext = strrchr (fn_cpy, '.');
    if (ext) {
        while (((c = strchr (fn_cpy, '.')) != NULL) && 
               (c != ext))
            *c = '_';                              /* translate extra .'s to _ */
        }
    memset (hdr1, ' ', sizeof (*hdr1));
    memcpy (hdr1->type, "HDR", 3);
    hdr1->num = '1';
    memset (hdr4, ' ', sizeof (*hdr1));
    memcpy (hdr4->type, "HDR", 3);
    hdr4->num = '4';
    to_ansi_a (hdr1->file_ident, fn, sizeof (hdr1->file_ident));
    if (strlen (fn) > 17) {
        to_ansi_a (hdr4->extra_name, fn + 17, sizeof (hdr4->extra_name));
        sprintf (extra_name_used, "%02d", (int)(strlen (fn) - 17));
        }
    memcpy (hdr4->extra_name_used, extra_name_used, 2);
    memcpy (hdr1->file_set, vol->ident, sizeof (hdr1->file_set));
    memcpy (hdr1->file_section, "0001", 4);
    memcpy (hdr1->file_sequence, "0001", 4);
    memcpy (hdr1->generation_number, "0001", 4);    /* generation_number and version_number */
    memcpy (hdr1->version_number, "00", 2);         /* combine to produce VMS version # ;1 here */
    ansi_date (statb.st_mtime, hdr1->creation_date, ansi_args[ansi_type].y2k_date_bug);
    memcpy (hdr1->expiration_date, " 00000", 6);
    memcpy (hdr1->block_count, "000000", 6);
    to_ansi_a (hdr1->system_code, ansi_args[ansi_type].system_code, sizeof (hdr1->system_code));
    free (fn_cpy);
    }

static void ansi_make_HDR2 (HDR2 *hdr, t_bool fixed_record, size_t block_size, size_t record_size, uint32 ansi_type)
    {
    char size[12];
    struct ansi_tape_parameters *ansi = &ansi_args[ansi_type];

    memset (hdr, ' ', sizeof (*hdr));
    memcpy (hdr->type, "HDR", 3);
    hdr->num = '2';
    hdr->record_format = ansi->record_format ? ansi->record_format : (fixed_record ? 'F' : 'D');
    sprintf (size, "%05d", (int)block_size);
    memcpy (hdr->block_length, size, sizeof (hdr->block_length));
    sprintf (size, "%05d", (ansi->zero_record_length)? 0 : (int)record_size);
    memcpy (hdr->record_length, size, sizeof (hdr->record_length));
    hdr->carriage_control = ansi->carriage_control ? ansi->carriage_control : (fixed_record ? 'M' : ' ');
    memcpy (hdr->buffer_offset, "00", 2);
    }

static void ansi_fill_text_buffer (FILE *f, char *buf, size_t buf_size, size_t record_skip_ending, t_bool fixed_text)
    {
    long start;
    char *tmp = (char *)calloc (2 + buf_size, sizeof (*buf));
    size_t offset = 0;

    while (1) {
        size_t rec_size;
        char rec_size_str[16];

        start = ftell (f);
        if (start < 0)
            break;
        if (!fgets (tmp, buf_size, f))
            break;
        rec_size = strlen (tmp);
        if (!fixed_text) {
            if (rec_size >= record_skip_ending)
                rec_size -= record_skip_ending;
            if ((rec_size + 4) > (int)(buf_size - offset)) { /* room for record? */
                (void)fseek (f, start, SEEK_SET);
                break;
                }
            sprintf (rec_size_str, "%04u", (int)(rec_size + 4));
            memcpy (buf + offset, rec_size_str, 4);
            memcpy (buf + offset + 4, tmp, rec_size);
            offset += 4 + rec_size;
            }
        else {
            size_t move_size;

            if ((tmp[rec_size - 2] != '\r') &&
                (tmp[rec_size - 1] == '\n')) {
                memcpy (&tmp[rec_size - 1], "\r\n", 3);
                rec_size += 1;
                }
            if (offset + rec_size < buf_size)
                move_size = rec_size;
            else
                move_size = buf_size - offset;
            /* We've got a line that stradles a block boundary */
            memcpy (buf + offset, tmp, move_size);
            offset += move_size;
            if (offset == buf_size) {
                (void)fseek (f, start + move_size, SEEK_SET);
                break;
                }
            }
        }
    if (buf_size > offset) {
        if (fixed_text)
            memset (buf + offset, 0, buf_size - offset);
        else
            memset (buf + offset, '^', buf_size - offset);
        }
    free (tmp);
    }

static t_bool memory_tape_add_block (MEMORY_TAPE *tape, uint8 *block, uint32 size)
{
TAPE_RECORD *rec;

if (tape->array_size <= tape->record_count) {
    TAPE_RECORD **new_records;
    new_records = (TAPE_RECORD **)realloc (tape->records, (tape->array_size + 1000) * sizeof (*tape->records));
    if (new_records == NULL)
        return TRUE;                /* no memory error */
    tape->records = new_records;
    memset (tape->records + tape->array_size, 0, 1000 * sizeof (*tape->records));
    tape->array_size += 1000;
    }
rec = (TAPE_RECORD *)malloc (sizeof (*rec) + size);
if (rec == NULL)
    return TRUE;                    /* no memory error */
rec->size = size;
memcpy (rec->data, block, size);
tape->records[tape->record_count++] = rec;
return FALSE;
}

static void memory_free_tape (void *vtape)
{
uint32 i;
MEMORY_TAPE *tape = (MEMORY_TAPE *)vtape;

for (i=0; i<tape->record_count; i++) {
    free (tape->records[i]);
    tape->records[i] = NULL;
    }
free (tape->records);
free (tape);
}

MEMORY_TAPE *memory_create_tape (void)
{
MEMORY_TAPE *tape = (MEMORY_TAPE *)calloc (1, sizeof (*tape));

if (NULL == tape)
    return tape;
tape->ansi_type = -1;
return tape;
}

static const char rad50[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ%.%0123456789";

static uint16 dos11_ascR50(char *inbuf)
{
uint16 value;

value = (strchr (rad50, *inbuf++) - rad50) * 03100;
value += (strchr (rad50, *inbuf++) - rad50) * 050;
value += (strchr (rad50, *inbuf++) - rad50);

return value;
}

/*
 * Sanitize a filename to generate a DOS-11 compatible version. Ignore
 * non-alphanumerics, upper case lower case characters and terminate on '.'
 */
static void dos11_sanitize(char *buf, int len, const char *inbuf)
{
    while ((len != 0) && (*inbuf != '\0') && (*inbuf !='.')) {
    char ch = toupper (*inbuf++);

    if (isalnum(ch)) {
        *buf++ = ch;
        len--;
        }
    }
}

static int dos11_copy_ascii_file(FILE *f, MEMORY_TAPE *tape, char *buf, size_t bufSize)
{
char ch, tmp[512];
t_bool crlast = FALSE;
int error = 0;
size_t i, data_read, offset = 0;

memset (buf, 0, bufSize);

while (!feof (f) && !error) {
    data_read = fread (tmp, 1, sizeof (tmp), f);
    if (data_read > 0)
        for (i = 0; i < data_read; i++) {
            ch = tmp[i];
            if (ch == '\n') {
                if (!crlast) {
                    buf[offset++] = '\r';
                    if (offset == bufSize) {
                        error = memory_tape_add_block (tape, (uint8 *)buf, bufSize);
                        offset = 0;
                        memset (buf, 0, bufSize);
                        }
                    }
                buf[offset++] = ch;
                if (offset == bufSize) {
                    error = memory_tape_add_block (tape, (uint8 *)buf, bufSize);
                    offset = 0;
                    memset (buf, 0, bufSize);
                    }
                crlast = FALSE;
                }
            else {
                crlast = ch == '\r';

                buf[offset++] = ch;
                if (offset == bufSize) {
                    error = memory_tape_add_block (tape, (uint8 *)buf, bufSize);
                    offset = 0;
                    memset (buf, 0, bufSize);
                    }
                }
            }
    }
    if (offset != 0)
        error = memory_tape_add_block (tape, (uint8 *)buf, bufSize);

return error;
}

static void sim_tape_add_dos11_entry (const char *directory,
                                      const char *filename,
                                      t_offset FileSize,
                                      const struct stat *filestat,
                                      void *context)
{
MEMORY_TAPE *tape = (MEMORY_TAPE *)context;
char FullPath[PATH_MAX + 1];
FILE *f;
size_t max_record_size;
t_bool lf_line_endings;
t_bool crlf_line_endings;
uint8 *block = NULL;
int error = 0;
DOS11_HDR hdr;
char fname[9], ext[3];
const char *ptr;
struct tm *tm;
time_t now = time (NULL);
uint16 today;
int year;

/*
 * Compute a suitable year for file creation date. This year will have the
 * same calendar as the current year but will be in the 20th century so that
 * DOS/BATCH-11 will be able to interpret it correctly.
 */
tm = localtime (&now);
year = tm->tm_year + 1900;
while (year >= 2000)
    year -= 28;

today = ((year - 70) * 1000) + tm->tm_yday + 1;

sprintf (FullPath, "%s%s", directory, filename);
f = tape_open_and_check_file(FullPath);
 if (f == NULL)
    return;

tape_classify_file_contents (f, &max_record_size, &lf_line_endings, &crlf_line_endings);

memset (&hdr, 0, sizeof (hdr));
memset (fname, ' ', sizeof (fname));
memset (ext, ' ', sizeof (ext));

dos11_sanitize (fname, sizeof (fname), filename);
ptr = strchr (filename, '.');
if (ptr != NULL)
    dos11_sanitize (ext, sizeof (ext), ++ptr);

/*
 * If we were unable to generate a valid DOS11 filename, generate one based
 * on the file number on the tape (000000 - 999999).
 */
if (fname[0] == ' ') {
  char temp[10];

  sprintf(temp, "%06u   ", tape->file_count % 100000);
  memcpy(fname, temp, sizeof(fname));
}

hdr.fname[0] = dos11_ascR50 (&fname[0]);
hdr.fname[1] = dos11_ascR50 (&fname[3]);
hdr.ext = dos11_ascR50 (&ext[0]);
hdr.prog = 1;
hdr.proj = 1;
hdr.prot = DOS11_PROT;
hdr.date = today;
hdr.fname3 = dos11_ascR50 (&fname[6]);

memory_tape_add_block (tape, (uint8 *)&hdr, sizeof (hdr));

rewind (f);
block = (uint8 *)calloc (tape->block_size, 1);

if (lf_line_endings || crlf_line_endings)
    error = dos11_copy_ascii_file (f, tape, (char *)block, tape->block_size);
else {
    size_t data_read;

    while (!feof (f) && !error) {
        data_read = fread (block, 1, tape->block_size, f);
        if (data_read > 0)
            error = memory_tape_add_block (tape, block, data_read);
        }
    } 

fclose (f);
free (block);
memory_tape_add_block (tape, NULL, 0);
++tape->file_count;
}

static FILE *tape_open_and_check_file(const char *filename)
{
FILE *file = fopen(filename, "rb");

if (file != NULL) {
    struct stat statb;

    memset (&statb, 0, sizeof (statb));
    if (fstat (fileno (file), &statb) == 0) {
        if (((S_IFDIR | S_IFREG) & statb.st_mode) == S_IFREG)
            return file;

        sim_printf ("Can't put a %s on tape: %s\n",
                    statb.st_mode & S_IFREG ? "directory" : "non regular file",
                    filename);
        fclose (file);
        return NULL;
        }
    sim_printf ("Can't stat: %s\n", filename);
    fclose (file);
    return NULL;
    }
sim_printf ("Can't open: %s - %s\n", filename, strerror (errno));
return NULL;
}

static int tape_classify_file_contents (FILE *f, size_t *max_record_size, t_bool *lf_line_endings, t_bool *crlf_line_endings)
{
long pos = -1;
long last_cr = -1;
long last_lf = -1;
long line_start = 0;
int chr;
long non_print_chars = 0;
long lf_lines = 0;
long crlf_lines = 0;

*max_record_size = 0;
*lf_line_endings = FALSE;
*crlf_line_endings = FALSE;
rewind (f);
while (EOF != (chr = fgetc (f))) {
    ++pos;
    if (!isprint (chr) && (chr != '\r') && (chr != '\n') && (chr != '\t') && (chr != '\f'))
        ++non_print_chars;
    if (chr == '\r')
        last_cr = pos;
    if (chr == '\n') {
        long line_size;

        if (last_cr == (pos - 1)) {
            ++crlf_lines;
            line_size = (pos - (line_start - 2));
            }
        else {
            ++lf_lines;
            line_size = (pos - (line_start - 1));
            }
        if ((line_size + 4) > (long)(*max_record_size + 4))
            *max_record_size = line_size + 4;
        line_start = pos + 1;
        last_lf = pos;
        }
    }
rewind (f);
if (non_print_chars)
    *max_record_size = 512;
else {
    if ((crlf_lines > 0) && (lf_lines == 0)) {
        *lf_line_endings = FALSE;
        *crlf_line_endings = TRUE;
        }
    else {
        if ((lf_lines > 0) && (crlf_lines == 0)) {
            *lf_line_endings = TRUE;
            *crlf_line_endings = FALSE;
            }
        }
    }
return 0;
}

MEMORY_TAPE *ansi_create_tape (const char *label, uint32 block_size, uint32 ansi_type)
{
MEMORY_TAPE *tape = memory_create_tape ();

if (NULL == tape)
    return tape;
tape->block_size = block_size;
tape->ansi_type = ansi_type;
ansi_make_VOL1 (&tape->vol1, label, ansi_type);
memory_tape_add_block (tape, (uint8 *)&tape->vol1, sizeof (tape->vol1));
return tape;
}

static int ansi_add_file_to_tape (MEMORY_TAPE *tape, const char *filename)
{
FILE *f;
struct ansi_tape_parameters *ansi = &ansi_args[tape->ansi_type];
uint8 *block = NULL;
size_t max_record_size;
t_bool lf_line_endings;
t_bool crlf_line_endings;
char file_sequence[5];
int block_count = 0;
char block_count_string[17];
int error = FALSE;
HDR1 hdr1;
HDR2 hdr2;
HDR3 hdr3;
HDR4 hdr4;

f = tape_open_and_check_file(filename);
if (f == NULL)
    return TRUE;

tape_classify_file_contents (f, &max_record_size, &lf_line_endings, &crlf_line_endings);
ansi_make_HDR1 (&hdr1, &tape->vol1, &hdr4, filename, tape->ansi_type);
sprintf (file_sequence, "%04d", 1 + tape->file_count);
memcpy (hdr1.file_sequence, file_sequence, sizeof (hdr1.file_sequence));
if (ansi->fixed_text)
    max_record_size = 512;
ansi_make_HDR2 (&hdr2, !lf_line_endings && !crlf_line_endings, tape->block_size, (tape->ansi_type > MTUF_F_ANSI) ? 512 : max_record_size, tape->ansi_type);

if (!ansi->nohdr3) {               /* Need HDR3? */
    if (!lf_line_endings && !crlf_line_endings)         /* Binary File? */
        memcpy (&hdr3, ansi->hdr3_fixed, sizeof (hdr3));
    else {                                              /* Text file */
        if ((lf_line_endings) && !(ansi->fixed_text))
            memcpy (&hdr3, ansi->hdr3_lf_line_endings, sizeof (hdr3));
        else
            memcpy (&hdr3, ansi->hdr3_crlf_line_endings, sizeof (hdr3));
        }
    }
memory_tape_add_block (tape, (uint8 *)&hdr1, sizeof (hdr1));
if (!ansi->nohdr2)
    memory_tape_add_block (tape, (uint8 *)&hdr2, sizeof (hdr2));
if (!ansi->nohdr3)
    memory_tape_add_block (tape, (uint8 *)&hdr3, sizeof (hdr3));
if ((0 != memcmp (hdr4.extra_name_used, "00", 2)) && !ansi->nohdr3 && !ansi->nohdr2)
    memory_tape_add_block (tape, (uint8 *)&hdr4, sizeof (hdr4));
memory_tape_add_block (tape, NULL, 0);        /* Tape Mark */
rewind (f);
block = (uint8 *)calloc (tape->block_size, 1);
while (!feof(f) && !error) {
    size_t data_read = tape->block_size;

    if (lf_line_endings || crlf_line_endings)       /* text file? */
        ansi_fill_text_buffer (f, (char *)block, tape->block_size, 
                               crlf_line_endings ? ansi->skip_crlf_line_endings : ansi->skip_lf_line_endings, 
                               ansi->fixed_text);
    else
        data_read = fread (block, 1, tape->block_size, f);
    if (data_read > 0)
        error = memory_tape_add_block (tape, block, data_read);
    if (!error)
        ++block_count;
    }
fclose (f);
free (block);
memory_tape_add_block (tape, NULL, 0);        /* Tape Mark */
memcpy (hdr1.type, "EOF", sizeof (hdr1.type));
memcpy (hdr2.type, "EOF", sizeof (hdr2.type));
memcpy (hdr3.type, "EOF", sizeof (hdr3.type));
memcpy (hdr4.type, "EOF", sizeof (hdr4.type));
sprintf (block_count_string, "%06d", block_count);
memcpy (hdr1.block_count, block_count_string, sizeof (hdr1.block_count));
memory_tape_add_block (tape, (uint8 *)&hdr1, sizeof (hdr1));
if (!ansi->nohdr2)
    memory_tape_add_block (tape, (uint8 *)&hdr2, sizeof (hdr2));
if (!ansi->nohdr3)
    memory_tape_add_block (tape, (uint8 *)&hdr3, sizeof (hdr3));
if ((0 != memcmp (hdr4.extra_name_used, "00", 2)) && !ansi->nohdr3 && !ansi->nohdr2)
    memory_tape_add_block (tape, (uint8 *)&hdr4, sizeof (hdr4));
memory_tape_add_block (tape, NULL, 0);        /* Tape Mark */
if (sim_switches & SWMASK ('V'))
    sim_messagef (SCPE_OK, "%17.17s%62.62s\n\t%d blocks of data\n", hdr1.file_ident, hdr4.extra_name, block_count);
++tape->file_count;
return error;
}

static void sim_tape_add_ansi_entry (const char *directory, 
                                     const char *filename,
                                     t_offset FileSize,
                                     const struct stat *filestat,
                                     void *context)
{
MEMORY_TAPE *tape = (MEMORY_TAPE *)context;
char FullPath[PATH_MAX + 1];

sprintf (FullPath, "%s%s", directory, filename);

(void)ansi_add_file_to_tape (tape, FullPath);
}

/* export an existing tape to a SIMH tape image */
static t_stat sim_export_tape (UNIT *uptr, const char *export_file)
{
t_stat r;
FILE *f;
t_addr saved_pos = uptr->pos;
uint8 *buf = NULL;
t_mtrlnt bc, sbc;
t_mtrlnt max = MTR_MAXLEN;

if ((export_file == NULL) || (*export_file == '\0'))
    return sim_messagef (SCPE_ARG, "Missing tape export file specification\n");
f = fopen (export_file, "wb");
if (f == NULL)
    return sim_messagef (SCPE_OPENERR, "Can't open SIMH tape image file: %s - %s\n", export_file, strerror (errno));

buf = (uint8 *)calloc (max, 1);
if (buf == NULL) {
    fclose (f);
    return SCPE_MEM;
    }
r = sim_tape_rewind (uptr);
while (r == SCPE_OK) {
    r = sim_tape_rdrecf (uptr, buf, &bc, max);
    switch (r) {
        case MTSE_OK:
            sbc = ((bc + 1) & ~1);              /* word alignment for SIMH format data */
            if ((1   != sim_fwrite (&bc, sizeof (bc),   1, f)) ||
                (sbc != sim_fwrite (buf, 1,           sbc, f))         ||
                (1   != sim_fwrite (&bc, sizeof (bc),   1, f)))
                r = sim_messagef (SCPE_IOERR, "Error writing file: %s - %s\n", export_file, strerror (errno));
            else
                r = SCPE_OK;
            break;

        case MTSE_TMK:
            bc = 0;
            if (1 != sim_fwrite (&bc, sizeof (bc), 1, f))
                r = sim_messagef (SCPE_IOERR, "Error writing file: %s - %s\n", export_file, strerror (errno));
            else
                r = SCPE_OK;
            break;

        default:
            break;
        }
    }
if (r == MTSE_EOM)
    r = SCPE_OK;
free (buf);
fclose (f);
uptr->pos = saved_pos;
return r;
}

Changes to src/SIMH/sim_tape.h.

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
    } t_awshdr;

/* TAR tape format */
#define TAR_DFLT_RECSIZE     10240                      /* Default Fixed record size */

/* Unit flags */

#define MTUF_V_PNU      (UNIT_V_UF + 0)                 /* position not upd */
#define MTUF_V_WLK      (UNIT_V_UF + 1)                 /* write locked */
#define MTUF_V_FMT      (UNIT_V_UF + 2)                 /* tape file format */



#define MTUF_W_FMT      3                               /* 3b of formats */
#define MTUF_N_FMT      (1u << MTUF_W_FMT)              /* number of formats */




#define MTUF_M_FMT      ((1u << MTUF_W_FMT) - 1)
#define MTUF_F_STD       0                              /* SIMH format */
#define MTUF_F_E11       1                              /* E11 format */
#define MTUF_F_TPC       2                              /* TPC format */
#define MTUF_F_P7B       3                              /* P7B format */
#define MTUF_F_AWS       4                              /* AWS format */
#define MTUF_F_TAR       5                              /* TAR format */
#define MTUF_V_UF       (MTUF_V_FMT + MTUF_W_FMT)
#define MTUF_PNU        (1u << MTUF_V_PNU)
#define MTUF_WLK        (1u << MTUF_V_WLK)
#define MTUF_FMT        (MTUF_M_FMT << MTUF_V_FMT)
#define MTUF_WRP        (MTUF_WLK | UNIT_RO)

#define MT_F_STD        (MTUF_F_STD << MTUF_V_FMT)
#define MT_F_E11        (MTUF_F_E11 << MTUF_V_FMT)
#define MT_F_TPC        (MTUF_F_TPC << MTUF_V_FMT)
#define MT_F_P7B        (MTUF_F_P7B << MTUF_V_FMT)
#define MT_F_AWS        (MTUF_F_AWS << MTUF_V_FMT)
#define MT_F_TAR        (MTUF_F_TAR << MTUF_V_FMT)

#define MT_SET_PNU(u)   (u)->flags = (u)->flags | MTUF_PNU
#define MT_CLR_PNU(u)   (u)->flags = (u)->flags & ~MTUF_PNU
#define MT_TST_PNU(u)   ((u)->flags & MTUF_PNU)
#define MT_SET_INMRK(u) (u)->dynflags = (u)->dynflags | UNIT_TAPE_MRK
#define MT_CLR_INMRK(u) (u)->dynflags = (u)->dynflags & ~UNIT_TAPE_MRK
#define MT_TST_INMRK(u) ((u)->dynflags & UNIT_TAPE_MRK)
#define MT_GET_FMT(u)   (((u)->flags >> MTUF_V_FMT) & MTUF_M_FMT)


/* sim_tape_position Position Flags */
#define MTPOS_V_REW     3
#define MTPOS_M_REW     (1u << MTPOS_V_REW)            /* Rewind First */
#define MTPOS_V_REV     2
#define MTPOS_M_REV     (1u << MTPOS_V_REV)            /* Reverse Direction */
#define MTPOS_V_OBJ     1







<
|

>
>
>
|
|
>
>
>
>
|
|
|
|
|
|
<
|
<

<


<
<
<
<
<
<
<
|
|
|



|
>







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
    } t_awshdr;

/* TAR tape format */
#define TAR_DFLT_RECSIZE     10240                      /* Default Fixed record size */

/* Unit flags */


#define MTUF_V_WLK      (UNIT_V_UF + 0)                 /* write locked */
#define MTUF_V_FMT      (UNIT_V_UF + 2)                 /* tape file format */
#define MTUF_F_STD      0                               /* SIMH format */
#define MTUF_F_E11      1                               /* E11 format */
#define MTUF_F_TPC      2                               /* TPC format */
#define MTUF_F_P7B      3                               /* P7B format */
#define MTUF_F_AWS      4                               /* AWS format */
#define MTUF_F_TAR      5                               /* TAR format */
#define MTUF_F_ANSI     6                               /* ANSI format */
#define MTUF_F_FIXED    7                               /* FIXED format */
#define MTUF_F_DOS11    8                               /* DOS11 format */

#define MTAT_F_VMS      0                               /* VMS ANSI type */
#define MTAT_F_RSX11    1                               /* RSX-11 ANSI type */
#define MTAT_F_RSTS     2                               /* RSTS ANSI type */
#define MTAT_F_RT11     3                               /* RT-11 ANSI type */


#define MTUF_V_UF       (MTUF_V_WLK + 1)

#define MTUF_WLK        (1u << MTUF_V_WLK)

#define MTUF_WRP        (MTUF_WLK | UNIT_RO)








#define MT_SET_PNU(u)   (u)->dynflags |= UNIT_TAPE_PNU
#define MT_CLR_PNU(u)   (u)->dynflags &= ~UNIT_TAPE_PNU
#define MT_TST_PNU(u)   ((u)->dynflags & UNIT_TAPE_PNU)
#define MT_SET_INMRK(u) (u)->dynflags = (u)->dynflags | UNIT_TAPE_MRK
#define MT_CLR_INMRK(u) (u)->dynflags = (u)->dynflags & ~UNIT_TAPE_MRK
#define MT_TST_INMRK(u) ((u)->dynflags & UNIT_TAPE_MRK)
#define MT_GET_FMT(u)   (((u)->dynflags >> UNIT_V_TAPE_FMT) & ((1 << UNIT_S_TAPE_FMT) - 1))
#define MT_GET_ANSI_TYP(u)   (((u)->dynflags >> UNIT_V_TAPE_ANSI) & ((1 << UNIT_S_TAPE_ANSI) - 1))

/* sim_tape_position Position Flags */
#define MTPOS_V_REW     3
#define MTPOS_M_REW     (1u << MTPOS_V_REW)            /* Rewind First */
#define MTPOS_V_REV     2
#define MTPOS_M_REV     (1u << MTPOS_V_REV)            /* Reverse Direction */
#define MTPOS_V_OBJ     1

Changes to src/SIMH/sim_timer.c.

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
}

#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 double sim_stop_time = 0;                    /* time when sim_stop_timer_services was called */


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 double sim_timer_stop_time = 0;
static uint32 sim_rom_delay = 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_drift_pct = SIM_THROT_DRIFT_PCT_DFLT;
static uint32 sim_throt_state = SIM_THROT_STATE_INIT;
static double sim_throt_cps;
static double sim_throt_peak_cps;
static double sim_throt_inst_start;
static uint32 sim_throt_sleep_time = 0;
static int32 sim_throt_wait = 0;
static uint32 sim_throt_delay = 3;
#define CLK_TPS 10
#define CLK_INIT (SIM_INITIAL_IPS/CLK_TPS)
static int32 sim_int_clk_tps;
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;









>
>
>



|
>

|





|














|
|

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







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
}

#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 */

int32 sim_vm_initial_ips = SIM_INITIAL_IPS;

static int32 sim_precalibrate_ips = SIM_INITIAL_IPS;
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_stop_time = 0;                    /* time when sim_stop_timer_services was called */
double sim_time_at_sim_prompt =  0;                 /* time spent processing commands from sim> prompt */

static uint32 sim_idle_rate_ms = 0;                 /* Minimum Sleep time */
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 = 100;
static double sim_timer_stop_time = 0;
static uint32 sim_rom_delay = 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_drift_pct = SIM_THROT_DRIFT_PCT_DFLT;
static uint32 sim_throt_state = SIM_THROT_STATE_INIT;
static double sim_throt_cps;
static double sim_throt_peak_cps;
static double sim_throt_inst_start;
static uint32 sim_throt_sleep_time = 0;
static int32 sim_throt_wait = 0;
static uint32 sim_throt_delay = 3;
#define CLK_TPS 100
#define CLK_INIT (sim_precalibrate_ips/CLK_TPS)
static int32 sim_int_clk_tps;

typedef struct RTC {
    UNIT *clock_unit;               /* registered ticking clock unit */
    UNIT *timer_unit;               /* points to related clock assist unit (sim_timer_units) */
    UNIT *clock_cosched_queue;
    int32 cosched_interval;
    uint32 ticks;                   /* ticks */
    uint32 hz;                      /* tick rate */
    uint32 last_hz;                 /* prior tick rate */
    uint32 rtime;                   /* real time (usecs) */
    uint32 vtime;                   /* virtual time (usecs) */
    double gtime;                   /* instruction time */
    uint32 nxintv;                  /* next interval */
    int32 based;                    /* base delay */
    int32 currd;                    /* current delay */
    int32 initd;                    /* initial delay */
    uint32 elapsed;                 /* seconds since init */
    uint32 calibrations;            /* calibration count */
    double clock_skew_max;          /* asynchronous max skew */
    double clock_tick_size;         /* 1/hz */
    uint32 calib_initializations;   /* Initialization Count */
    double calib_tick_time;         /* ticks time */
    double calib_tick_time_tot;     /* ticks time - total*/
    uint32 calib_ticks_acked;       /* ticks Acked */
    uint32 calib_ticks_acked_tot;   /* ticks Acked - total */
    uint32 clock_ticks;             /* ticks delivered since catchup base */
    uint32 clock_ticks_tot;         /* ticks delivered since catchup base - total */
    double clock_init_base_time;    /* reference time for clock initialization */
    double clock_tick_start_time;   /* reference time when ticking started */
    double clock_catchup_base_time; /* reference time for catchup ticks */
    uint32 clock_catchup_ticks;     /* Record of catchups */
    uint32 clock_catchup_ticks_tot; /* Record of catchups - total */
    uint32 clock_catchup_ticks_curr;/* Record of catchups in this second */
    t_bool clock_catchup_pending;   /* clock tick catchup pending */
    t_bool clock_catchup_eligible;  /* clock tick catchup eligible */
    uint32 clock_time_idled;        /* total time idled */
    uint32 clock_time_idled_last;   /* total time idled as of the previous second */
    uint32 clock_calib_skip_idle;   /* Calibrations skipped due to idling */
    uint32 clock_calib_gap2big;     /* Calibrations skipped Gap Too Big */
    uint32 clock_calib_backwards;   /* Calibrations skipped Clock Running Backwards */
    } RTC;

RTC rtcs[SIM_NTIMERS+1];
UNIT sim_timer_units[SIM_NTIMERS+1];/* Clock assist units                         */
                                    /* one for each timer and one for an internal */
                                    /* clock if no clocks are registered.         */


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;


700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
    }
}

/* 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 t_bool _sim_coschedule_cancel (UNIT *uptr);
static t_bool _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);









|







749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    }
}

/* 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 (RTC *rtc, int32 time);
static void _rtcn_configure_calibrated_clock (int32 newtmr);
static t_bool _sim_coschedule_cancel (UNIT *uptr);
static t_bool _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);


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
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_last_hz[SIM_NTIMERS+1] = { 0 };         /* prior 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 */
static uint32 sim_idle_cyc_ms = 0;                      /* Cycles per millisecond while not idling */
static uint32 sim_idle_cyc_sleep = 0;                   /* Cycles per minimum sleep interval */
static double sim_idle_end_time = 0.0;                  /* Time when last idle completed */

UNIT sim_timer_units[SIM_NTIMERS+1];                    /* Clock assist units                         */
                                                        /* one for each timer and one for an internal */
                                                        /* clock if no clocks are registered.         */
UNIT sim_stop_unit;                                     /* Stop unit                         */
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);
t_stat sim_timer_stop_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 */
#define DBG_CHK       0x100                 /* check scheduled activation time*/
#define DBG_INT       0x200                 /* internal timer activities */
#define DBG_GET       0x400                 /* get_time 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"},
  {"GETTIME", DBG_GET, "get_time activities"},
  {"INTER",   DBG_INT, "Internal timer activities"},
  {"THROT",   DBG_THR, "Throttling activities"},
  {"MUX",     DBG_MUX, "Tmxr scheduling activities"},
  {"CHECK",   DBG_CHK, "Check scheduled activation time"},
  {0}
};

/* Forward device declarations */
extern DEVICE sim_timer_dev;
extern DEVICE sim_throttle_dev;
extern DEVICE sim_stop_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);

}

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", uptr ? 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_last_hz[tmr] = rtc_hz[tmr];
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 ();
    if ((rtc_last_hz[tmr] != 0) && 
        (rtc_last_hz[tmr] != ticksper) && 
        (ticksper != 0))
        rtc_currd[tmr] = (int32)(sim_timer_inst_per_sec () / ticksper);
    rtc_last_hz[tmr] = rtc_hz[tmr];
    rtc_hz[tmr] = ticksper;
    _rtcn_configure_calibrated_clock (tmr);
    if (ticksper != 0) {


        rtc_clock_tick_size[tmr] = 1.0 / ticksper;
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) currd=%d\n", ticksper, tmr, rtc_currd[tmr]);
        }






    else
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) timer stopped currd was %d\n", ticksper, tmr, rtc_currd[tmr]);
    }
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 (!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 tmr=%d against internal 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 ((last_idle_pct == 0) && (delta_rtime != 0)) {
    sim_idle_cyc_ms = (uint32)((new_gtime - rtc_gtime[tmr]) / delta_rtime);
    if ((sim_idle_rate_ms != 0) && (delta_rtime > 1))
        sim_idle_cyc_sleep = (uint32)((new_gtime - rtc_gtime[tmr]) / (delta_rtime / sim_idle_rate_ms));
    }
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 */
else
    rtc_based[tmr] = (int32) (((double) rtc_based[tmr] * (double) rtc_nxintv[tmr]) /
                                ((double) delta_rtime));/* new base rate */
delta_vtime = rtc_vtime[tmr] - rtc_rtime[tmr];          /* gap */
if (delta_vtime > SIM_TMAX)                             /* limit gap */
    delta_vtime = SIM_TMAX;

else if (delta_vtime < -SIM_TMAX)
    delta_vtime = -SIM_TMAX;

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_clock_cosched_queue[tmr] = QUEUE_LIST_END;



    }
sim_stop_unit.action = &sim_timer_stop_svc;
SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
sim_register_internal_device (&sim_timer_dev);          /* Register Clock Assist device */
sim_register_internal_device (&sim_throttle_dev);       /* Register Throttle Device */
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 */
sim_set_rom_delay_factor (sim_get_rom_delay_factor ()); /* initialize ROM delay factor */

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))







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

<
<
<


>





>












>






>


















>

|
>
|
|
>









>
>
>
>
>
>
>








>



|

|
|

|


|


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




|

>
>
>
>
>
>
>
|




>







>
|
>
>
|
|
|
|

|
|
|


>
>
|
|
|
>
>
>
>
>
>

|



|
|
|

|
|
>
|

|
|
|
>
>
|
|
|
|

|
|
|

|
>
>
>
>
>
|

|



|
|
|
>
>
>
>
>
>
|

|
|
|
|






|
|
|
|
>
>
>
|
|

<
|
<
>
>
|
|
|
|
|
|
>
|
|
|
|
>


|

|

|
>
|

|

|
|
|
|
|
>
|
|
|
>
|

|



|
|

|

|
|

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

|
>
>
|
|
>
|
|









|












>
>
>

>
>
>
|
|
|
>
>
>











|







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
else
    return 0;
}
#endif /* defined(SIM_ASYNCH_CLOCKS) */

/* OS independent clock calibration package */



































static uint32 sim_idle_cyc_ms = 0;                          /* Cycles per millisecond while not idling */
static uint32 sim_idle_cyc_sleep = 0;                       /* Cycles per minimum sleep interval */
static double sim_idle_end_time = 0.0;                      /* Time when last idle completed */




UNIT sim_stop_unit;                                     /* Stop unit                         */
UNIT sim_internal_timer_unit;                           /* Internal calibration timer */
int32 sim_internal_timer_time;                          /* Pending internal timer delay */
UNIT sim_throttle_unit;                                 /* one for throttle */

t_stat sim_throt_svc (UNIT *uptr);
t_stat sim_timer_tick_svc (UNIT *uptr);
t_stat sim_timer_stop_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 */
#define DBG_CHK       0x100                 /* check scheduled activation time*/
#define DBG_INT       0x200                 /* internal timer activities */
#define DBG_GET       0x400                 /* get_time activities */
#define DBG_TIK       0x800                 /* tick 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"},
  {"TICK",    DBG_TIK, "Calibration tick activities"},
  {"TIME",    DBG_TIM, "Activation and scheduling activities"},
  {"GETTIME", DBG_GET, "get_time activities"},
  {"INTER",   DBG_INT, "Internal timer activities"},
  {"THROT",   DBG_THR, "Throttling activities"},
  {"MUX",     DBG_MUX, "Tmxr scheduling activities"},
  {"CHECK",   DBG_CHK, "Check scheduled activation time"},
  {0}
};

/* Forward device declarations */
extern DEVICE sim_timer_dev;
extern DEVICE sim_throttle_dev;
extern DEVICE sim_stop_dev;


void sim_rtcn_init_all (void)
{
int32 tmr;
RTC *rtc;

for (tmr = 0; tmr <= SIM_NTIMERS; tmr++) {
    rtc = &rtcs[tmr];
    if (rtc->initd != 0)
        sim_rtcn_init (rtc->initd, tmr);
    }
}

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)
{
return sim_rtcn_init_unit_ticks (uptr, time, tmr, 0);
}

int32 sim_rtcn_init_unit_ticks (UNIT *uptr, int32 time, int32 tmr, int32 ticksper)
{
RTC *rtc;
        
if (time == 0)
    time = 1;
if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr >= SIM_NTIMERS))
        return time;
    }
rtc = &rtcs[tmr];
/*
 * 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.
 */
if (rtc->currd)
    time = rtc->currd;
if (!uptr)
    uptr = rtc->clock_unit;
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_init_unit(unit=%s, time=%d, tmr=%d)\n", uptr ? sim_uname(uptr) : "", time, tmr);
if (uptr) {
    if (!rtc->clock_unit)
        sim_register_clock_unit_tmr (uptr, tmr);
    }
rtc->gtime = sim_gtime();
rtc->rtime = sim_is_running ? sim_os_msec () : sim_stop_time;
rtc->vtime = rtc->rtime;
rtc->nxintv = 1000;
rtc->ticks = 0;
rtc->last_hz = rtc->hz;
rtc->hz = ticksper;
rtc->based = time;
rtc->currd = time;
rtc->initd = time;
rtc->elapsed = 0;
rtc->calibrations = 0;
rtc->clock_ticks_tot += rtc->clock_ticks;
rtc->clock_ticks = 0;
rtc->calib_tick_time_tot += rtc->calib_tick_time;
rtc->calib_tick_time = 0;
rtc->clock_catchup_pending = FALSE;
rtc->clock_catchup_eligible = FALSE;
rtc->clock_catchup_ticks_tot += rtc->clock_catchup_ticks;
rtc->clock_catchup_ticks = 0;
rtc->clock_catchup_ticks_curr = 0;
rtc->calib_ticks_acked_tot += rtc->calib_ticks_acked;
rtc->calib_ticks_acked = 0;
++rtc->calib_initializations;
rtc->clock_init_base_time = sim_timenow_double ();
_rtcn_configure_calibrated_clock (tmr);
return time;
}

int32 sim_rtcn_calb_tick (int32 tmr)
{
RTC *rtc = &rtcs[tmr];

return sim_rtcn_calb (rtc->hz, tmr);
}

int32 sim_rtcn_calb (uint32 ticksper, int32 tmr)
{
uint32 new_rtime, delta_rtime, last_idle_pct, catchup_ticks_curr;
int32 delta_vtime;
double new_gtime;
int32 new_currd;
int32 itmr;
RTC *rtc;

if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr >= SIM_NTIMERS))
        return 10000;
    }
rtc = &rtcs[tmr];
if (rtc->hz != ticksper) {                          /* changing tick rate? */
    uint32 prior_hz = rtc->hz;

    if (rtc->hz == 0)
        rtc->clock_tick_start_time = sim_timenow_double ();
    if ((rtc->last_hz != 0) && 
        (rtc->last_hz != ticksper) && 
        (ticksper != 0))
        rtc->currd = (int32)(sim_timer_inst_per_sec () / ticksper);
    rtc->last_hz = rtc->hz;
    rtc->hz = ticksper;
    _rtcn_configure_calibrated_clock (tmr);
    if (ticksper != 0) {
        RTC *crtc = &rtcs[sim_calb_tmr];

        rtc->clock_tick_size = 1.0 / ticksper;
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) currd=%d, prior_hz=%d\n", ticksper, tmr, rtc->currd, (int)prior_hz);

        if ((tmr != sim_calb_tmr) && rtc->clock_unit && (ticksper > crtc->hz)) {
            sim_catchup_ticks = TRUE;
            sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(%d) - forcing catchup ticks for %s ticking at %d, host tick rate %ds\n", tmr, sim_uname (rtc->clock_unit), ticksper, sim_os_tick_hz);
            _rtcn_tick_catchup_check (rtc, 0);
            }
        }
    else
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d,tmr=%d) timer stopped currd was %d, prior_hz=%d\n", ticksper, tmr, rtc->currd, (int)prior_hz);
    }
if (ticksper == 0)                                      /* running? */
    return 10000;
if (rtc->clock_unit == NULL) {                      /* Not using TIMER units? */
    rtc->clock_ticks += 1;
    rtc->calib_tick_time += rtc->clock_tick_size;
    }
if (rtc->clock_catchup_pending) {                   /* catchup tick? */
    ++rtc->clock_catchup_ticks;                     /* accumulating which were catchups */
    ++rtc->clock_catchup_ticks_curr;
    rtc->clock_catchup_pending = FALSE;
    }
rtc->ticks += 1;                                    /* count ticks */
if (rtc->ticks < ticksper)                          /* 1 sec yet? */
    return rtc->currd;
catchup_ticks_curr = rtc->clock_catchup_ticks_curr;
rtc->clock_catchup_ticks_curr = 0;
rtc->ticks = 0;                                     /* reset ticks */
rtc->elapsed += 1;                                  /* count sec */
if (!rtc_avail)                                     /* no timer? */
    return rtc->currd;
if (sim_calb_tmr != tmr) {
    rtc->currd = (int32)(sim_timer_inst_per_sec()/ticksper);
    sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(tmr=%d) calibrated against internal system tmr=%d, tickper=%d (result: %d)\n", tmr, sim_calb_tmr, ticksper, rtc->currd);
    return rtc->currd;
    }
new_rtime = sim_os_msec ();                         /* wall time */
if (!sim_signaled_int_char && 
    ((new_rtime - sim_last_poll_kbd_time) > 500)) {
    sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(tmr=%d) gratuitious keyboard poll after %d msecs\n", tmr, (int)(new_rtime - sim_last_poll_kbd_time));
    (void)sim_poll_kbd ();
    }
++rtc->calibrations;                                /* count calibrations */
sim_debug (DBG_TRC, &sim_timer_dev, "sim_rtcn_calb(ticksper=%d, tmr=%d)\n", ticksper, tmr);
if (new_rtime < rtc->rtime) {                       /* 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;                   /* Count statistic */
    sim_debug (DBG_CAL, &sim_timer_dev, "time running backwards - OldTime: %u, NewTime: %u, result: %d\n", rtc->rtime, new_rtime, rtc->currd);
    rtc->vtime = rtc->rtime = new_rtime;            /* reset wall time */
    rtc->nxintv = 1000;
    rtc->based = rtc->currd;
    if (rtc->clock_catchup_eligible) {
        rtc->clock_catchup_base_time = sim_timenow_double();
        rtc->calib_tick_time = 0.0;
        }
    return rtc->currd;                              /* can't calibrate */
    }
delta_rtime = new_rtime - rtc->rtime;               /* elapsed wtime */
rtc->rtime = new_rtime;                             /* adv wall time */
rtc->vtime += 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;                     /* Count statistic */
    rtc->vtime = rtc->rtime;                        /* sync virtual and real time */
    rtc->nxintv = 1000;                             /* reset next interval */
    rtc->gtime = sim_gtime();                       /* save instruction time */
    rtc->based = rtc->currd;
    if (rtc->clock_catchup_eligible)
        rtc->calib_tick_time += ((double)delta_rtime / 1000.0);/* advance tick time */
    sim_debug (DBG_CAL, &sim_timer_dev, "gap too big: delta = %d - result: %d\n", delta_rtime, rtc->currd);
    return rtc->currd;                              /* can't calibr */
    }

last_idle_pct = 0;                                  /* normally force calibration */

if (tmr != SIM_NTIMERS) {
    if (delta_rtime != 0)                           /* avoid divide by zero  */
        last_idle_pct = MIN(100, (uint32)(100.0 * (((double)(rtc->clock_time_idled - rtc->clock_time_idled_last)) / ((double)delta_rtime))));
    rtc->clock_time_idled_last = rtc->clock_time_idled;
    if (last_idle_pct > sim_idle_calib_pct) {
        rtc->rtime = new_rtime;                     /* save wall time */
        rtc->vtime += 1000;                         /* adv sim time */
        rtc->gtime = sim_gtime();                   /* save instruction time */
        rtc->based = rtc->currd;
        ++rtc->clock_calib_skip_idle;
        sim_debug (DBG_CAL, &sim_timer_dev, "skipping calibration due to idling (%d%%) - result: %d\n", last_idle_pct, rtc->currd);
        return rtc->currd;                          /* avoid calibrating idle checks */
        }
    }
new_gtime = sim_gtime();
if ((last_idle_pct == 0) && (delta_rtime != 0)) {
    sim_idle_cyc_ms = (uint32)((new_gtime - rtc->gtime) / delta_rtime);
    if ((sim_idle_rate_ms != 0) && (delta_rtime > 1))
        sim_idle_cyc_sleep = (uint32)((new_gtime - rtc->gtime) / (delta_rtime / sim_idle_rate_ms));
    }
if (sim_asynch_timer || (catchup_ticks_curr > 0)) {
    /* An asynchronous clock or when catchup ticks have  */
    /* occurred, we merely needs to divide the number of */
    /* instructions actually executed by the clock rate. */
    new_currd = (int32)((new_gtime - rtc->gtime)/ticksper);
    /* avoid excessive swings in the calibrated result */
    if (new_currd > 10*rtc->currd)              /* don't swing big too fast */
        new_currd = 10*rtc->currd;
    else {
        if (new_currd < rtc->currd/10)          /* don't swing small too fast */
            new_currd = rtc->currd/10;
        }
    rtc->based = rtc->currd = new_currd;
    rtc->gtime = new_gtime;                     /* save instruction time */
    sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(%s tmr=%d, tickper=%d) catchups=%u, idle=%d%% result: %d\n", 
                    sim_asynch_timer ? "asynch" : "catchup", tmr, ticksper, catchup_ticks_curr, last_idle_pct, rtc->currd);
    return rtc->currd;                          /* calibrated result */
    }
rtc->gtime = 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 = rtc->based * ticksper;         /* slew wide */
else
    rtc->based = (int32) (((double) rtc->based * (double) rtc->nxintv) /
                                ((double) delta_rtime));/* new base rate */
delta_vtime = rtc->vtime - rtc->rtime;          /* gap */
if (delta_vtime > SIM_TMAX)                     /* limit gap */
    delta_vtime = SIM_TMAX;
else {
    if (delta_vtime < -SIM_TMAX)
        delta_vtime = -SIM_TMAX;
    }
rtc->nxintv = 1000 + delta_vtime;                   /* next wtime */
rtc->currd = (int32) (((double) rtc->based * (double) rtc->nxintv) /
    1000.0);                                        /* next delay */
if (rtc->based <= 0)                                /* never negative or zero! */
    rtc->based = 1;
if (rtc->currd <= 0)                                /* never negative or zero! */
    rtc->currd = 1;
sim_debug (DBG_CAL, &sim_timer_dev, "sim_rtcn_calb(tmr=%d, tickper=%d) (delta_rtime=%d, delta_vtime=%d, base=%d, nxintv=%u, catchups=%u, idle=%d%%, result: %d)\n", 
                                    tmr, ticksper, (int)delta_rtime, (int)delta_vtime, rtc->based, rtc->nxintv, catchup_ticks_curr, last_idle_pct, rtc->currd);
/* Adjust calibration for other timers which depend on this timer's calibration */
for (itmr=0; itmr<=SIM_NTIMERS; itmr++) {
    RTC *irtc = &rtcs[itmr];

    if ((itmr != tmr) && (irtc->hz != 0))
        irtc->currd = (rtc->currd * ticksper) / irtc->hz;
    }
AIO_SET_INTERRUPT_LATENCY(rtc->currd * ticksper);   /* set interrrupt latency */
return rtc->currd;
}

/* Prior interfaces - default to timer 0 */

int32 sim_rtc_init (int32 time)
{
return sim_rtcn_init (time, 0);
}

int32 sim_rtc_calb (uint32 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");
/* Clear the event queue before initializing the timer subsystem */
while (sim_clock_queue != QUEUE_LIST_END)
    sim_cancel (sim_clock_queue);
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    rtc->timer_unit = &sim_timer_units[tmr];
    rtc->timer_unit->action = &sim_timer_tick_svc;
    rtc->timer_unit->flags = UNIT_DIS | UNIT_IDLE;
    if (rtc->clock_cosched_queue)
        while (rtc->clock_cosched_queue != QUEUE_LIST_END)
            sim_cancel (rtc->clock_cosched_queue);
    rtc->clock_cosched_queue = QUEUE_LIST_END;
    }
sim_stop_unit.action = &sim_timer_stop_svc;
SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
sim_register_internal_device (&sim_timer_dev);          /* Register Clock Assist device */
sim_register_internal_device (&sim_throttle_dev);       /* Register Throttle Device */
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 */
sim_set_rom_delay_factor (sim_get_rom_delay_factor ()); /* initialize ROM delay factor */

sim_stop_time = 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))
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
{
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_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 cycles/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, "  Ticks:                     %s\n", sim_fmt_numeric ((double)(rtc_clock_ticks[tmr])));
    if (rtc_clock_ticks_tot[tmr]+rtc_clock_ticks[tmr] != rtc_clock_ticks[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)







|

|
|
|

|
|




|
|
|

|
>
|
|

|
>
>
>
>
>
>
>
>
>
>


>
>
|


|



|



|
|
|
|
|

|

|
|
|
|
|
|
|
|
|

|
|

|
|
|
|
|

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



|
|






|
|


|



|
|







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
{
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_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 %s/sec\n", sim_fmt_numeric (inst_per_sec), sim_vm_interval_units);
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" : 
                                                     (rtcs[calb_tmr].clock_unit ? sim_uname(rtcs[calb_tmr].clock_unit) : "")));
if (calb_tmr == SIM_NTIMERS)
    fprintf (st, "Catchup Ticks:                  %s\n", sim_catchup_ticks ? "Enabled" : "Disabled");
fprintf (st, "Pre-Calibration Estimated Rate: %s\n", sim_fmt_numeric ((double)sim_precalibrate_ips));
if (sim_idle_calib_pct == 100)
    fprintf (st, "Calibration:                    Always\n");
else
    fprintf (st, "Calibration:                    Skipped when Idle exceeds %d%%\n", sim_idle_calib_pct);
#if defined(SIM_ASYNCH_CLOCKS)
fprintf (st, "Asynchronous Clocks:            %s\n", sim_asynch_timer ? "Active" : "Available");
#endif
if (sim_time_at_sim_prompt != 0.0) {
    double prompt_time = 0.0;
    if (!sim_is_running)
        prompt_time = ((double)(sim_os_msec () - sim_stop_time)) / 1000.0;
    fprintf (st, "Time at sim> prompt:            %s\n", sim_fmt_secs (sim_time_at_sim_prompt + prompt_time));
    }

fprintf (st, "\n");
for (tmr=clocks=0; tmr<=SIM_NTIMERS; ++tmr) {
    RTC *rtc = &rtcs[tmr];

    if (0 == rtc->initd)
        continue;
    
    if (rtc->clock_unit) {
        ++clocks;
        fprintf (st, "%s clock device is %s%s%s\n", sim_name, 
                                                    (tmr == SIM_NTIMERS) ? "Internal Calibrated Timer(" : "", 
                                                    sim_uname(rtc->clock_unit), 
                                                    (tmr == SIM_NTIMERS) ? ")" : "");
        }

    fprintf (st, "%s%sTimer %d:\n", sim_asynch_timer ? "Asynchronous " : "", rtc->hz ? "Calibrated " : "Uncalibrated ", tmr);
    if (rtc->hz) {
        fprintf (st, "  Running at:                %d Hz\n", rtc->hz);
        fprintf (st, "  Tick Size:                 %s\n", sim_fmt_secs (rtc->clock_tick_size));
        fprintf (st, "  Ticks in current second:   %d\n",   rtc->ticks);
        }
    fprintf (st, "  Seconds Running:           %s (%s)\n",   sim_fmt_numeric ((double)rtc->elapsed), sim_fmt_secs ((double)rtc->elapsed));
    if (tmr == calb_tmr) {
        fprintf (st, "  Calibration Opportunities: %s\n",   sim_fmt_numeric ((double)rtc->calibrations));
        if (sim_idle_calib_pct && (sim_idle_calib_pct != 100))
            fprintf (st, "  Calib Skip when Idle >:    %u%%\n",   sim_idle_calib_pct);
        if (rtc->clock_calib_skip_idle)
            fprintf (st, "  Calibs Skip While Idle:    %s\n",   sim_fmt_numeric ((double)rtc->clock_calib_skip_idle));
        if (rtc->clock_calib_backwards)
            fprintf (st, "  Calibs Skip Backwards:     %s\n",   sim_fmt_numeric ((double)rtc->clock_calib_backwards));
        if (rtc->clock_calib_gap2big)
            fprintf (st, "  Calibs Skip Gap Too Big:   %s\n",   sim_fmt_numeric ((double)rtc->clock_calib_gap2big));
        }
    if (rtc->gtime)
        fprintf (st, "  Instruction Time:          %.0f\n", rtc->gtime);
    if ((!sim_asynch_timer) && (sim_throt_type == SIM_THROT_NONE)) {
        fprintf (st, "  Real Time:                 %u\n",   rtc->rtime);
        fprintf (st, "  Virtual Time:              %u\n",   rtc->vtime);
        fprintf (st, "  Next Interval:             %s\n",   sim_fmt_numeric ((double)rtc->nxintv));
        fprintf (st, "  Base Tick Delay:           %s\n",   sim_fmt_numeric ((double)rtc->based));
        fprintf (st, "  Initial Insts Per Tick:    %s\n",   sim_fmt_numeric ((double)rtc->initd));
        }
    fprintf (st, "  Current Insts Per Tick:    %s\n",   sim_fmt_numeric ((double)rtc->currd));
    fprintf (st, "  Initializations:           %d\n",   rtc->calib_initializations);
    fprintf (st, "  Ticks:                     %s\n", sim_fmt_numeric ((double)(rtc->clock_ticks)));
    if (rtc->clock_ticks_tot+rtc->clock_ticks != rtc->clock_ticks)
        fprintf (st, "  Total Ticks:               %s\n", sim_fmt_numeric ((double)(rtc->clock_ticks_tot+rtc->clock_ticks)));
    if (rtc->clock_skew_max != 0.0)
        fprintf (st, "  Peak Clock Skew:           %s%s\n", sim_fmt_secs (fabs(rtc->clock_skew_max)), (rtc->clock_skew_max < 0) ? " fast" : " slow");
    if (rtc->calib_ticks_acked)
        fprintf (st, "  Ticks Acked:               %s\n",   sim_fmt_numeric ((double)rtc->calib_ticks_acked));
    if (rtc->calib_ticks_acked_tot+rtc->calib_ticks_acked != rtc->calib_ticks_acked)
        fprintf (st, "  Total Ticks Acked:         %s\n",   sim_fmt_numeric ((double)(rtc->calib_ticks_acked_tot+rtc->calib_ticks_acked)));
    if (rtc->calib_tick_time)
        fprintf (st, "  Tick Time:                 %s\n",   sim_fmt_secs (rtc->calib_tick_time));
    if (rtc->calib_tick_time_tot+rtc->calib_tick_time != rtc->calib_tick_time)
        fprintf (st, "  Total Tick Time:           %s\n",   sim_fmt_secs (rtc->calib_tick_time_tot+rtc->calib_tick_time));
    if (rtc->clock_catchup_ticks)
        fprintf (st, "  Catchup Ticks Sched:       %s\n",   sim_fmt_numeric ((double)rtc->clock_catchup_ticks));
    if (rtc->clock_catchup_ticks_curr)
        fprintf (st, "  Catchup Ticks this second: %s\n",   sim_fmt_numeric ((double)rtc->clock_catchup_ticks_curr));
    if (rtc->clock_catchup_ticks_tot+rtc->clock_catchup_ticks != rtc->clock_catchup_ticks)
        fprintf (st, "  Total Catchup Ticks Sched: %s\n",   sim_fmt_numeric ((double)(rtc->clock_catchup_ticks_tot+rtc->clock_catchup_ticks)));
    if (rtc->clock_init_base_time) {
        _double_to_timespec (&now, rtc->clock_init_base_time);
        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) {
        _double_to_timespec (&now, rtc->clock_tick_start_time);
        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 (sim_catchup_ticks && rtc->clock_catchup_eligible) {
        _double_to_timespec (&now, rtc->clock_catchup_base_time+rtc->calib_tick_time);
        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);
        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)
        fprintf (st, "  Total Time Idled:          %s\n",   sim_fmt_secs (rtc->clock_time_idled/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)
1245
1246
1247
1248
1249
1250
1251

1252

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
            time_t_due = (time_t)due.tv_sec;
            fprintf (st, " after %s due at %8.8s.%06d\n", tim, 11+ctime(&time_t_due), (int)(due.tv_nsec/1000));
            }
        }
    }
#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 #%d clock (%s) co-schedule event queue status\n",
                 sim_name, tmr, 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");







>
|
>

|



|

|







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
            time_t_due = (time_t)due.tv_sec;
            fprintf (st, " after %s due at %8.8s.%06d\n", tim, 11+ctime(&time_t_due), (int)(due.tv_nsec/1000));
            }
        }
    }
#endif /* SIM_ASYNCH_CLOCKS */
for (tmr=0; tmr<=SIM_NTIMERS; ++tmr) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == NULL)
        continue;
    if (rtc->clock_cosched_queue != QUEUE_LIST_END) {
        int32 accum;

        fprintf (st, "%s #%d clock (%s) co-schedule event queue status\n",
                 sim_name, tmr, sim_uname(rtc->clock_unit));
        accum = 0;
        for (uptr = rtc->clock_cosched_queue; 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");
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
}

REG sim_timer_reg[] = {
    { DRDATAD (IDLE_CYC_MS,      sim_idle_cyc_ms,        32, "Cycles Per Millisecond"), PV_RSPC|REG_RO},
    { DRDATAD (IDLE_CYC_SLEEP,   sim_idle_cyc_sleep,     32, "Cycles Per Minimum Sleep"), PV_RSPC|REG_RO},
    { DRDATAD (IDLE_STABLE,      sim_idle_stable,        32, "IDLE stability delay"), PV_RSPC},
    { DRDATAD (ROM_DELAY,        sim_rom_delay,          32, "ROM memory reference delay"), PV_RSPC|REG_RO},
    { DRDATAD (TICK_RATE_0,      rtc_hz[0],              32, "Timer 0 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_0,      rtc_currd[0],           32, "Timer 0 Tick Size") },
    { DRDATAD (TICK_RATE_1,      rtc_hz[1],              32, "Timer 1 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_1,      rtc_currd[1],           32, "Timer 1 Tick Size") },
    { DRDATAD (TICK_RATE_2,      rtc_hz[2],              32, "Timer 2 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_2,      rtc_currd[2],           32, "Timer 2 Tick Size") },
    { DRDATAD (TICK_RATE_3,      rtc_hz[3],              32, "Timer 3 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_3,      rtc_currd[3],           32, "Timer 3 Tick Size") },
    { DRDATAD (TICK_RATE_4,      rtc_hz[4],              32, "Timer 4 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_4,      rtc_currd[4],           32, "Timer 4 Tick Size") },
    { DRDATAD (TICK_RATE_5,      rtc_hz[5],              32, "Timer 5 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_5,      rtc_currd[5],           32, "Timer 5 Tick Size") },
    { DRDATAD (TICK_RATE_6,      rtc_hz[6],              32, "Timer 6 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_6,      rtc_currd[6],           32, "Timer 6 Tick Size") },
    { DRDATAD (TICK_RATE_7,      rtc_hz[7],              32, "Timer 7 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_7,      rtc_currd[7],           32, "Timer 7 Tick Size") },
    { DRDATAD (INTERNAL_TICK_RATE,sim_int_clk_tps,       32, "Internal Timer Ticks Per Second") },
    { DRDATAD (INTERNAL_TICK_SIZE,rtc_currd[SIM_NTIMERS],32, "Internal Timer Tick Size") },
    { NULL }
    };

REG sim_throttle_reg[] = {
    { DRDATAD (THROT_MS_START,   sim_throt_ms_start,     32, "Throttle measurement start time"), PV_RSPC|REG_RO},
    { DRDATAD (THROT_MS_STOP,    sim_throt_ms_stop,      32, "Throttle measurement stop time"), PV_RSPC|REG_RO},
    { DRDATAD (THROT_TYPE,       sim_throt_type,         32, "Throttle type"), PV_RSPC|REG_RO},







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

|







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
}

REG sim_timer_reg[] = {
    { DRDATAD (IDLE_CYC_MS,      sim_idle_cyc_ms,        32, "Cycles Per Millisecond"), PV_RSPC|REG_RO},
    { DRDATAD (IDLE_CYC_SLEEP,   sim_idle_cyc_sleep,     32, "Cycles Per Minimum Sleep"), PV_RSPC|REG_RO},
    { DRDATAD (IDLE_STABLE,      sim_idle_stable,        32, "IDLE stability delay"), PV_RSPC},
    { DRDATAD (ROM_DELAY,        sim_rom_delay,          32, "ROM memory reference delay"), PV_RSPC|REG_RO},
    { DRDATAD (TICK_RATE_0,      rtcs[0].hz,             32, "Timer 0 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_0,      rtcs[0].currd,          32, "Timer 0 Tick Size") },
    { DRDATAD (TICK_RATE_1,      rtcs[1].hz,             32, "Timer 1 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_1,      rtcs[1].currd,          32, "Timer 1 Tick Size") },
    { DRDATAD (TICK_RATE_2,      rtcs[2].hz,             32, "Timer 2 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_2,      rtcs[2].currd,          32, "Timer 2 Tick Size") },
    { DRDATAD (TICK_RATE_3,      rtcs[3].hz,             32, "Timer 3 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_3,      rtcs[3].currd,          32, "Timer 3 Tick Size") },
    { DRDATAD (TICK_RATE_4,      rtcs[4].hz,             32, "Timer 4 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_4,      rtcs[4].currd,          32, "Timer 4 Tick Size") },
    { DRDATAD (TICK_RATE_5,      rtcs[5].hz,             32, "Timer 5 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_5,      rtcs[5].currd,          32, "Timer 5 Tick Size") },
    { DRDATAD (TICK_RATE_6,      rtcs[6].hz,             32, "Timer 6 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_6,      rtcs[6].currd,          32, "Timer 6 Tick Size") },
    { DRDATAD (TICK_RATE_7,      rtcs[7].hz,             32, "Timer 7 Ticks Per Second") },
    { DRDATAD (TICK_SIZE_7,      rtcs[7].currd,          32, "Timer 7 Tick Size") },
    { DRDATAD (INTERNAL_TICK_RATE,sim_int_clk_tps,       32, "Internal Timer Ticks Per Second") },
    { DRDATAD (INTERNAL_TICK_SIZE,rtcs[SIM_NTIMERS].currd,32, "Internal Timer Tick Size") },
    { NULL }
    };

REG sim_throttle_reg[] = {
    { DRDATAD (THROT_MS_START,   sim_throt_ms_start,     32, "Throttle measurement start time"), PV_RSPC|REG_RO},
    { DRDATAD (THROT_MS_STOP,    sim_throt_ms_stop,      32, "Throttle measurement stop time"), PV_RSPC|REG_RO},
    { DRDATAD (THROT_TYPE,       sim_throt_type,         32, "Throttle type"), PV_RSPC|REG_RO},
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
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 = SCPE_OK;
int32 newpct;
char gbuf[CBUFSIZE];

if (cptr == NULL)
    return SCPE_ARG;




cptr = get_glyph_nc (cptr, gbuf, 0);              /* get argument */
if (isdigit (gbuf[0]))
    newpct = (int32) get_uint (cptr, 10, 100, &r);
else {
    if (MATCH_CMD (gbuf, "ALWAYS") == 0)
        newpct = 0;
    else
        r = SCPE_ARG;
    }
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 stop time */

t_stat sim_timer_set_stop (int32 flag, CONST char *cptr)
{







|

>















<
<



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







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
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 = SCPE_OK;



if (cptr == NULL)
    return SCPE_ARG;
if (1) {
    int32 newpct;
    char gbuf[CBUFSIZE];

    cptr = get_glyph (cptr, gbuf, 0);                 /* get argument */
    if (isdigit (gbuf[0]))
        newpct = (int32) get_uint (gbuf, 10, 100, &r);
    else {
        if (MATCH_CMD (gbuf, "ALWAYS") == 0)
            newpct = 100;
        else
            r = SCPE_ARG;
        }
    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 stop time */

t_stat sim_timer_set_stop (int32 flag, CONST char *cptr)
{
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

t_bool sim_idle (uint32 tmr, int sin_cyc)
{
uint32 w_ms, w_idle, act_ms;
int32 act_cyc;
static t_bool in_nowait = FALSE;
double cyc_since_idle;





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);
    sim_interval -= sin_cyc;
    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]);
    sim_interval -= sin_cyc;
    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]));
    sim_interval -= sin_cyc;
    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);
if (sim_idle_cyc_ms == 0) {
    sim_idle_cyc_ms = (rtc_currd[tmr] * rtc_hz[tmr]) / 1000;/* cycles per msec */
    if (sim_idle_rate_ms != 0)
        sim_idle_cyc_sleep = (rtc_currd[tmr] * rtc_hz[tmr]) / (1000 / sim_idle_rate_ms);/* cycles per sleep */
    }
if ((sim_idle_rate_ms == 0) || (sim_idle_cyc_ms == 0)) {/* not possible? */
    sim_interval -= sin_cyc;
    sim_debug (DBG_IDL, &sim_timer_dev, "not possible idle_rate_ms=%d - cyc/ms=%d\n", sim_idle_rate_ms, sim_idle_cyc_ms);
    return FALSE;
    }
w_ms = (uint32) sim_interval / sim_idle_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? */
    sim_interval -= sin_cyc;
    if (!in_nowait)
        sim_debug (DBG_IDL, &sim_timer_dev, "no wait, too short: %d usecs\n", w_idle);
    in_nowait = TRUE;
    return FALSE;
    }


in_nowait = 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);
cyc_since_idle = sim_gtime() - sim_idle_end_time;       /* time since prior idle */
act_ms = sim_idle_ms_sleep (w_ms);                      /* wait */
rtc_clock_time_idled[tmr] += act_ms;
act_cyc = act_ms * sim_idle_cyc_ms;
if (cyc_since_idle > sim_idle_cyc_sleep)
    act_cyc -= sim_idle_cyc_sleep / 2;                  /* account for half an interval's worth of cycles */
else
    act_cyc -= (int32)cyc_since_idle;                   /* acount for cycles executed */
sim_interval = sim_interval - act_cyc;                  /* count down sim_interval to reflect idle period */
sim_idle_end_time = sim_gtime();                        /* save idle completed time */
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)
{







>

>
>
>
|
|



>
>
>
>






|
|
|

|
<
<
<
<
<





|











|










|

|












|
|


|
|





>
>


|

|


|








|

|







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

t_bool sim_idle (uint32 tmr, int sin_cyc)
{
uint32 w_ms, w_idle, act_ms;
int32 act_cyc;
static t_bool in_nowait = FALSE;
double cyc_since_idle;
RTC *rtc = &rtcs[tmr];

if (rtc->hz == 0)                                       /* specified timer is not running? */
    tmr = sim_calb_tmr;                                 /* use calibrated timer instead */
rtc = &rtcs[tmr];
if (rtc->clock_catchup_pending) {                       /* Catchup clock tick pending due to ack? */
    sim_debug (DBG_TIK, &sim_timer_dev, "sim_idle(tmr=%d, sin_cyc=%d) - accelerating pending catch-up tick before idling %s\n", tmr, sin_cyc, sim_uname (rtc->clock_unit));
    sim_activate_abs (&sim_timer_units[tmr], 0);
    sim_interval -= sin_cyc;
    return FALSE;
    }
if (_rtcn_tick_catchup_check (rtc, -1)) {               /* Check for slow clock tick? */
    sim_interval -= sin_cyc;
    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 < sim_idle_stable)) {             /* or calibrated timer not stable? */
    sim_debug (DBG_IDL, &sim_timer_dev, "Can't idle: %s - elapsed: %d and %d/%d\n", !sim_idle_enab ? "idle disabled" : 
                                                                             ((rtc->elapsed < sim_idle_stable) ? "not stable" : 
                                                                                                                     ((sim_clock_queue != QUEUE_LIST_END) ? sim_uname (sim_clock_queue) : 
                                                                                                                                                            "")), rtc->elapsed, rtc->ticks, rtc->hz);





    sim_interval -= sin_cyc;
    return FALSE;
    }
/*
   When a simulator is in an instruction path (or under other conditions 
   which would indicate idling), the countdown of sim_interval may 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 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);
if (sim_idle_cyc_ms == 0) {
    sim_idle_cyc_ms = (rtc->currd * rtc->hz) / 1000;/* cycles per msec */
    if (sim_idle_rate_ms != 0)
        sim_idle_cyc_sleep = (rtc->currd * rtc->hz) / (1000 / sim_idle_rate_ms);/* cycles per minimum sleep */
    }
if ((sim_idle_rate_ms == 0) || (sim_idle_cyc_ms == 0)) {/* not possible? */
    sim_interval -= sin_cyc;
    sim_debug (DBG_IDL, &sim_timer_dev, "not possible idle_rate_ms=%d - cyc/ms=%d\n", sim_idle_rate_ms, sim_idle_cyc_ms);
    return FALSE;
    }
w_ms = (uint32) sim_interval / sim_idle_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)
    w_idle = (sim_interval * 1000) / rtc->currd;        /* 1000 * pending fraction of tick */
else
    w_idle = (w_ms * 1000) / sim_idle_rate_ms;          /* 1000 * intervals to wait */
if ((w_idle < 500) || (w_ms == 0)) {                    /* shorter than 1/2 the interval or */
    sim_interval -= sin_cyc;                            /* minimal sleep time? */
    if (!in_nowait)
        sim_debug (DBG_IDL, &sim_timer_dev, "no wait, too short: %d usecs\n", w_idle);
    in_nowait = TRUE;
    return FALSE;
    }
if (w_ms > 1000)                                        /* too long a wait (runaway calibration) */
    sim_debug (DBG_TIK, &sim_timer_dev, "waiting too long: w_ms=%d usecs, w_idle=%d usecs, sim_interval=%d, rtc->currd=%d\n", w_ms, w_idle, sim_interval, rtc->currd);
in_nowait = FALSE;
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event in %d %s\n", w_ms, sim_interval, sim_vm_interval_units);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "sleeping for %d ms - pending event on %s in %d %s\n", w_ms, sim_uname(sim_clock_queue), sim_interval, sim_vm_interval_units);
cyc_since_idle = sim_gtime() - sim_idle_end_time;       /* time since prior idle */
act_ms = sim_idle_ms_sleep (w_ms);                      /* wait */
rtc->clock_time_idled += act_ms;
act_cyc = act_ms * sim_idle_cyc_ms;
if (cyc_since_idle > sim_idle_cyc_sleep)
    act_cyc -= sim_idle_cyc_sleep / 2;                  /* account for half an interval's worth of cycles */
else
    act_cyc -= (int32)cyc_since_idle;                   /* acount for cycles executed */
sim_interval = sim_interval - act_cyc;                  /* count down sim_interval to reflect idle period */
sim_idle_end_time = sim_gtime();                        /* save idle completed time */
if (sim_clock_queue == QUEUE_LIST_END)
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event in %d %s\n", act_ms, sim_interval, sim_vm_interval_units);
else
    sim_debug (DBG_IDL, &sim_timer_dev, "slept for %d ms - pending event on %s in %d %s\n", act_ms, sim_uname(sim_clock_queue), sim_interval, sim_vm_interval_units);
return TRUE;
}

/* Set idling - implicitly disables throttling */

t_stat sim_set_idle (UNIT *uptr, int32 val, CONST char *cptr, void *desc)
{
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
        sim_throt_state = SIM_THROT_STATE_THROTTLE;         /* force state */
        sim_throt_wait = sim_throt_val;
        }
    }
if (sim_throt_type == SIM_THROT_SPC)    /* Set initial value while correct one is determined */
    sim_throt_cps = (int32)((1000.0 * sim_throt_val) / (double)sim_throt_sleep_time);
else
    sim_throt_cps = SIM_INITIAL_IPS;
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:
        if (sim_throt_wait) {
            fprintf (st, "Throttle:                      %d%% of %s cycles per second\n", sim_throt_val, sim_fmt_numeric (sim_throt_peak_cps));
            fprintf (st, "Throttling by sleeping for:    %d ms every %d cycles\n", sim_throt_sleep_time, sim_throt_wait);
            }
        else
            fprintf (st, "Throttle:                      %d%%\n", sim_throt_val);
        break;

    case SIM_THROT_SPC:
        fprintf (st, "Throttle:                      %d/%d\n", sim_throt_val, sim_throt_sleep_time);
        fprintf (st, "Throttling by sleeping for:    %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) {







|











|

|



|

|




|
|







|







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
        sim_throt_state = SIM_THROT_STATE_THROTTLE;         /* force state */
        sim_throt_wait = sim_throt_val;
        }
    }
if (sim_throt_type == SIM_THROT_SPC)    /* Set initial value while correct one is determined */
    sim_throt_cps = (int32)((1000.0 * sim_throt_val) / (double)sim_throt_sleep_time);
else
    sim_throt_cps = sim_precalibrate_ips;
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 mega%s\n", sim_throt_val, sim_vm_interval_units);
        if (sim_throt_wait)
            fprintf (st, "Throttling by sleeping for:    %d ms every %d %s\n", sim_throt_sleep_time, sim_throt_wait, sim_vm_interval_units);
        break;

    case SIM_THROT_KCYC:
        fprintf (st, "Throttle:                      %d kilo%s\n", sim_throt_val, sim_vm_interval_units);
        if (sim_throt_wait)
            fprintf (st, "Throttling by sleeping for:    %d ms every %d %s\n", sim_throt_sleep_time, sim_throt_wait, sim_vm_interval_units);
        break;

    case SIM_THROT_PCT:
        if (sim_throt_wait) {
            fprintf (st, "Throttle:                      %d%% of %s %s per second\n", sim_throt_val, sim_fmt_numeric (sim_throt_peak_cps), sim_vm_interval_units);
            fprintf (st, "Throttling by sleeping for:    %d ms every %d %s\n", sim_throt_sleep_time, sim_throt_wait, sim_vm_interval_units);
            }
        else
            fprintf (st, "Throttle:                      %d%%\n", sim_throt_val);
        break;

    case SIM_THROT_SPC:
        fprintf (st, "Throttle:                      %d/%d\n", sim_throt_val, sim_throt_sleep_time);
        fprintf (st, "Throttling by sleeping for:    %d ms every %d %s\n", sim_throt_sleep_time, sim_throt_val, sim_vm_interval_units);
        break;

    default:
        fprintf (st, "Throttling:                    Disabled\n");
        break;
        }
    if (sim_throt_type != SIM_THROT_NONE) {
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
       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, delta_inst;




switch (sim_throt_state) {

    case SIM_THROT_STATE_INIT:                          /* take initial reading */
        if ((sim_calb_tmr != -1) && (rtc_hz[sim_calb_tmr] != 0)) {
            if (rtc_calibrations[sim_calb_tmr] < sim_throt_delay) {
                sim_throt_ms_start = sim_os_msec ();
                sim_throt_inst_start = sim_gtime ();
                sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Deferring until stable (%d more seconds)\n", (int)(sim_throt_delay - rtc_calibrations[sim_calb_tmr]));
                return sim_activate (uptr, rtc_hz[sim_calb_tmr]*rtc_currd[sim_calb_tmr]);
                }
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Computing Throttling values based on the last second's execution rate\n");
            sim_throt_state = SIM_THROT_STATE_TIME;
            if (sim_throt_peak_cps < (double)(rtc_hz[sim_calb_tmr] * rtc_currd[sim_calb_tmr])) 
                sim_throt_peak_cps = (double)rtc_hz[sim_calb_tmr] * rtc_currd[sim_calb_tmr];
            return sim_throt_svc (uptr);
            }
        else
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Calibrated timer not available. Falling back to legacy method\n");
        sim_idle_ms_sleep (sim_idle_rate_ms);           /* start on a tick boundary to calibrate */
        sim_throt_ms_start = sim_os_msec ();
        sim_throt_inst_start = sim_gtime ();







>

>
>



|
|


|
|



|
|







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
       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, delta_inst;
RTC *rtc = NULL;

if (sim_calb_tmr != -1)
    rtc = &rtcs[sim_calb_tmr];
switch (sim_throt_state) {

    case SIM_THROT_STATE_INIT:                          /* take initial reading */
        if ((sim_calb_tmr != -1) && (rtc->hz != 0)) {
            if (rtc->calibrations < sim_throt_delay) {
                sim_throt_ms_start = sim_os_msec ();
                sim_throt_inst_start = sim_gtime ();
                sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Deferring until stable (%d more seconds)\n", (int)(sim_throt_delay - rtc->calibrations));
                return sim_activate (uptr, rtc->hz * rtc->currd);
                }
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Computing Throttling values based on the last second's execution rate\n");
            sim_throt_state = SIM_THROT_STATE_TIME;
            if (sim_throt_peak_cps < (double)(rtc->hz * rtc->currd)) 
                sim_throt_peak_cps = (double)rtc->hz * rtc->currd;
            return sim_throt_svc (uptr);
            }
        else
            sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc(INIT) Calibrated timer not available. Falling back to legacy method\n");
        sim_idle_ms_sleep (sim_idle_rate_ms);           /* start on a tick boundary to calibrate */
        sim_throt_ms_start = sim_os_msec ();
        sim_throt_inst_start = sim_gtime ();
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
        if (delta_ms < SIM_THROT_MSMIN) {               /* not enough time? */
            if (delta_inst >= 100000000.0) {            /* 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_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Not enough time.  %d ms executing %.f instructions.\n", 
                                (int)delta_ms, delta_inst);
            sim_throt_wait = (int32)(delta_inst * SIM_THROT_WMUL);
            sim_throt_inst_start = sim_gtime();
            sim_idle_ms_sleep (sim_idle_rate_ms);       /* start on a tick boundart to calibrate */
            sim_throt_ms_start = sim_os_msec ();
            }
        else {                                          /* long enough */
            a_cps = (((double) delta_inst) * 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 = (sim_throt_peak_cps * sim_throt_val) / 100.0;
            if (d_cps > a_cps) {
                sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() CPU too slow.  Values a_cps = %f, d_cps = %f\n", 
                                                    a_cps, d_cps);
                sim_throt_state = SIM_THROT_STATE_INIT;
                sim_printf ("*********** WARNING ***********\n");
                sim_printf ("Host CPU is too slow to simulate %s instructions per second\n", sim_fmt_numeric(d_cps));
                sim_printf ("Host CPU can only simulate %s instructions per second\n", sim_fmt_numeric(sim_throt_peak_cps));
                sim_printf ("Throttling disabled.\n");
                sim_set_throt (0, NULL);
                return SCPE_OK;
                }
            while (1) {
                sim_throt_wait = (int32)                /* cycles between sleeps */
                    ((a_cps * d_cps * ((double) sim_throt_sleep_time)) /







|
|



















|
|







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
        if (delta_ms < SIM_THROT_MSMIN) {               /* not enough time? */
            if (delta_inst >= 100000000.0) {            /* 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_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() Not enough time.  %d ms executing %.f %s.\n", 
                                (int)delta_ms, delta_inst, sim_vm_interval_units);
            sim_throt_wait = (int32)(delta_inst * SIM_THROT_WMUL);
            sim_throt_inst_start = sim_gtime();
            sim_idle_ms_sleep (sim_idle_rate_ms);       /* start on a tick boundart to calibrate */
            sim_throt_ms_start = sim_os_msec ();
            }
        else {                                          /* long enough */
            a_cps = (((double) delta_inst) * 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 = (sim_throt_peak_cps * sim_throt_val) / 100.0;
            if (d_cps > a_cps) {
                sim_debug (DBG_THR, &sim_timer_dev, "sim_throt_svc() CPU too slow.  Values a_cps = %f, d_cps = %f\n", 
                                                    a_cps, d_cps);
                sim_throt_state = SIM_THROT_STATE_INIT;
                sim_printf ("*********** WARNING ***********\n");
                sim_printf ("Host CPU is too slow to simulate %s %s per second\n", sim_fmt_numeric(d_cps), sim_vm_interval_units);
                sim_printf ("Host CPU can only simulate %s %s per second\n", sim_fmt_numeric(sim_throt_peak_cps), sim_vm_interval_units);
                sim_printf ("Throttling disabled.\n");
                sim_set_throt (0, NULL);
                return SCPE_OK;
                }
            while (1) {
                sim_throt_wait = (int32)                /* cycles between sleeps */
                    ((a_cps * d_cps * ((double) sim_throt_sleep_time)) /
1907
1908
1909
1910
1911
1912
1913

1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
            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_currd[tmr] = (int32)(sim_throt_cps / rtc_hz[tmr]);/* use throttle calibration */
                    rtc_ticks[tmr] = rtc_hz[tmr] - 1;                     /* force clock calibration on next tick */
                    rtc_rtime[tmr] = sim_throt_ms_start - 1000 + 1000/rtc_hz[tmr];/* adjust calibration parameters to reflect throttled rate */
                    rtc_gtime[tmr] = sim_throt_inst_start - sim_throt_cps + sim_throt_cps/rtc_hz[tmr];
                    rtc_nxintv[tmr] = 1000;
                    rtc_based[tmr] = rtc_currd[tmr];
                    if (sim_clock_unit[tmr])
                        sim_activate_abs (sim_clock_unit[tmr], rtc_currd[tmr]);/* reschedule next tick */
                    }
                }
            }
        break;

    case SIM_THROT_STATE_THROTTLE:                      /* throttling */
        sim_idle_ms_sleep (sim_throt_sleep_time);







>
|
|
|
|
|
|
|
|
|







2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
            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++) {
                rtc = &rtcs[tmr];
                if (rtc->hz) {                                      /* running? */
                    rtc->currd = (int32)(sim_throt_cps / rtc->hz);/* use throttle calibration */
                    rtc->ticks = rtc->hz - 1;                     /* force clock calibration on next tick */
                    rtc->rtime = sim_throt_ms_start - 1000 + 1000/rtc->hz;/* adjust calibration parameters to reflect throttled rate */
                    rtc->gtime = sim_throt_inst_start - sim_throt_cps + sim_throt_cps/rtc->hz;
                    rtc->nxintv = 1000;
                    rtc->based = rtc->currd;
                    if (rtc->clock_unit)
                        sim_activate_abs (rtc->clock_unit, rtc->currd);/* reschedule next tick */
                    }
                }
            }
        break;

    case SIM_THROT_STATE_THROTTLE:                      /* throttling */
        sim_idle_ms_sleep (sim_throt_sleep_time);
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
}

/* Clock assist activites */
t_stat sim_timer_tick_svc (UNIT *uptr)
{
int32 tmr = (int32)(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(tmr=%d) - scheduling %s - cosched interval: %d\n", tmr, 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 (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END)
    sim_clock_cosched_queue[tmr]->time = sim_cosched_interval[tmr];
if ((stat == SCPE_OK)                               && 
    (sim_cosched_interval[tmr] <= 0)                &&
    (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END)) {
    UNIT *sptr = sim_clock_cosched_queue[tmr];
    UNIT *cptr = QUEUE_LIST_END;

    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;
        }
    /* Gather any queued events which are scheduled for right now */
    do {
        cptr = sim_clock_cosched_queue[tmr];
        sim_clock_cosched_queue[tmr] = cptr->next;
        if (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
            sim_clock_cosched_queue[tmr]->time += sim_cosched_interval[tmr];
            sim_cosched_interval[tmr] = sim_clock_cosched_queue[tmr]->time;
            }
        else
            sim_cosched_interval[tmr]  = 0;
        } while ((sim_cosched_interval[tmr] <= 0) &&
                 (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END));
    if (cptr != QUEUE_LIST_END)
        cptr->next = QUEUE_LIST_END;
    /* Now dispatch that list (in order). */
    while (sptr != QUEUE_LIST_END) {
        cptr = sptr;
        sptr = sptr->next;
        cptr->next = NULL;







>

|
|








|
|

|
|
|
|

|
|
|


|




|

|
|



|
|
|
|
|


|
|
|







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
}

/* Clock assist activites */
t_stat sim_timer_tick_svc (UNIT *uptr)
{
int32 tmr = (int32)(uptr-sim_timer_units);
t_stat stat;
RTC *rtc = &rtcs[tmr];

rtc->clock_ticks += 1;
rtc->calib_tick_time += rtc->clock_tick_size;
/*
 * 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(tmr=%d) - scheduling %s - cosched interval: %d\n", tmr, sim_uname (rtc->clock_unit), rtc->cosched_interval);
if (rtc->clock_unit->action == NULL)
    return SCPE_IERR;
stat = rtc->clock_unit->action (rtc->clock_unit);
--rtc->cosched_interval;                    /* Countdown ticks */
if (rtc->clock_cosched_queue != QUEUE_LIST_END)
    rtc->clock_cosched_queue->time = rtc->cosched_interval;
if ((stat == SCPE_OK)                               && 
    (rtc->cosched_interval <= 0)                &&
    (rtc->clock_cosched_queue != QUEUE_LIST_END)) {
    UNIT *sptr = rtc->clock_cosched_queue;
    UNIT *cptr = QUEUE_LIST_END;

    if (rtc->clock_catchup_eligible) {      /* calibration started? */
        struct timespec now;
        double skew;

        clock_gettime(CLOCK_REALTIME, &now);
        skew = (_timespec_to_double(&now) - (rtc->calib_tick_time+rtc->clock_catchup_base_time));

        if (fabs(skew) > fabs(rtc->clock_skew_max))
            rtc->clock_skew_max = skew;
        }
    /* Gather any queued events which are scheduled for right now */
    do {
        cptr = rtc->clock_cosched_queue;
        rtc->clock_cosched_queue = cptr->next;
        if (rtc->clock_cosched_queue != QUEUE_LIST_END) {
            rtc->clock_cosched_queue->time += rtc->cosched_interval;
            rtc->cosched_interval = rtc->clock_cosched_queue->time;
            }
        else
            rtc->cosched_interval  = 0;
        } while ((rtc->cosched_interval <= 0) &&
                 (rtc->clock_cosched_queue != QUEUE_LIST_END));
    if (cptr != QUEUE_LIST_END)
        cptr->next = QUEUE_LIST_END;
    /* Now dispatch that list (in order). */
    while (sptr != QUEUE_LIST_END) {
        cptr = sptr;
        sptr = sptr->next;
        cptr->next = NULL;
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
 *      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)
{



if ((!sim_catchup_ticks) || 
    ((tmr < 0) || (tmr >= SIM_NTIMERS)))
    return FALSE;






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] = sim_timenow_double();
    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_hz[tmr] > 0) && 
    rtc_clock_catchup_eligible[tmr])
    {
    double tnow = sim_timenow_double();

    if (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;







>
>
>





|





|

>
>
>
|
<

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

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

|
|



|
>
|
|
|
>
>
>



|




>
>
|

>
|
|
|







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
 *      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.
 *
 * The clock tick UNIT that will be scheduled to run for catchup ticks
 * must be specified with sim_rtcn_init_unit().
 */

/* _rtcn_tick_catchup_check - idle simulator until next event or for specified interval

   Inputs:
        RTC =   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 (RTC *rtc, int32 time)
{
int32 tmr;
t_bool bReturn = FALSE;

if (!sim_catchup_ticks)

    return FALSE;
if (time == -1) {
    for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
        rtc = &rtcs[tmr];
        if ((rtc->hz > 0) && rtc->clock_catchup_eligible)
            {
            double tnow = sim_timenow_double();

            if (tnow > (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))) {
                if (!rtc->clock_catchup_pending) {
                    sim_debug (DBG_TIK, &sim_timer_dev, "_rtcn_tick_catchup_check(%d) - scheduling catchup tick %d for %s which is behind %s\n", time, 1 + rtc->ticks, sim_uname (rtc->clock_unit), sim_fmt_secs (tnow - (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))));
                    rtc->clock_catchup_pending = TRUE;
                    sim_activate_abs (rtc->timer_unit, 0);
                    bReturn = TRUE;
                    }
                else
                    sim_debug (DBG_TIK, &sim_timer_dev, "_rtcn_tick_catchup_check(%d) - already pending catchup tick %d for %s which is behind %s\n", time, 1 + rtc->ticks, sim_uname (rtc->clock_unit), sim_fmt_secs (tnow - (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))));
                }
            }
        }
    }
if ((!rtc->clock_catchup_eligible) &&           /* not eligible yet? */
    (time != -1)) {                             /* called from ack? */
    rtc->clock_catchup_base_time = sim_timenow_double();
    rtc->clock_ticks_tot += rtc->clock_ticks;
    rtc->clock_ticks = 0;
    rtc->calib_tick_time_tot += rtc->calib_tick_time;
    rtc->calib_tick_time = 0.0;
    rtc->clock_catchup_ticks_tot += rtc->clock_catchup_ticks;
    rtc->clock_catchup_ticks = 0;
    rtc->calib_ticks_acked_tot += rtc->calib_ticks_acked;
    rtc->calib_ticks_acked = 0;
    rtc->clock_catchup_eligible = TRUE;
    sim_debug (DBG_QUE, &sim_timer_dev, "_rtcn_tick_catchup_check() - Enabling catchup ticks for %s\n", sim_uname (rtc->clock_unit));
    bReturn = TRUE;
    }
if ((rtc->hz > 0) && 
    rtc->clock_catchup_eligible)
    {
    double tnow = sim_timenow_double();

    if (tnow > (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))) {
        if (!rtc->clock_catchup_pending) {
            sim_debug (DBG_TIK, &sim_timer_dev, "_rtcn_tick_catchup_check(%d) - scheduling catchup tick %d for %s which is behind %s\n", time, 1 + rtc->ticks, sim_uname (rtc->clock_unit), sim_fmt_secs (tnow - (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))));
            rtc->clock_catchup_pending = TRUE;
            sim_activate_abs (rtc->timer_unit, (time < 0) ? 0 : time);
            }
        else
            sim_debug (DBG_TIK, &sim_timer_dev, "_rtcn_tick_catchup_check(%d) - already pending catchup tick %d for %s which is behind %s\n", time, 1 + rtc->ticks, sim_uname (rtc->clock_unit), sim_fmt_secs (tnow - (rtc->clock_catchup_base_time + (rtc->calib_tick_time + rtc->clock_tick_size))));
        return TRUE;
        }
    }
return bReturn;
}

t_stat sim_rtcn_tick_ack (uint32 time, int32 tmr)
{
RTC *rtc;

if ((tmr < 0) || (tmr > SIM_NTIMERS))
    return SCPE_TIMER;
rtc = &rtcs[tmr];
sim_debug (DBG_ACK, &sim_timer_dev, "sim_rtcn_tick_ack - for %s\n", sim_uname (rtc->clock_unit));
_rtcn_tick_catchup_check (rtc, (int32)time);
++rtc->calib_ticks_acked;
return SCPE_OK;
}


static double _timespec_to_double (struct timespec *time)
{
return ((double)time->tv_sec)+(double)(time->tv_nsec)/1000000000.0;
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

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.
 */

static t_stat sim_timer_clock_tick_svc (UNIT *uptr)
{
sim_debug(DBG_INT, &sim_timer_dev, "sim_timer_clock_tick_svc()\n");
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, OR when asynch clocks are enabled, the internal clock
  is always run.










 */
static void _rtcn_configure_calibrated_clock (int32 newtmr)
{
int32 tmr;


/* Look for a timer running slower or the same as 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) &&
        (sim_clock_unit[tmr]))


        break;
    }
if (tmr == SIM_NTIMERS) {                   /* None found? */
    if ((tmr != newtmr) && (!sim_is_active (&SIM_INTERNAL_UNIT))) {
        if ((sim_calb_tmr != SIM_NTIMERS) &&/* not 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(newtmr=%d) - Cleaning up stopped timer %s support\n", newtmr, sim_uname(sim_clock_unit[sim_calb_tmr]));
            /* Migrate any coscheduled devices to the standard queue */
            /* with appropriate usecs_remaining reflecting their currently */
            /* scheduled firing time.  sim_process_event() will coschedule */
            /* appropriately. */
            /* temporarily restore prior hz to get correct remaining time */
            rtc_hz[sim_calb_tmr] = rtc_last_hz[sim_calb_tmr];
            while (sim_clock_cosched_queue[sim_calb_tmr] != QUEUE_LIST_END) {
                UNIT *uptr = sim_clock_cosched_queue[sim_calb_tmr];
                double usecs_remaining = sim_timer_activate_time_usecs (uptr) - 1;

                _sim_coschedule_cancel (uptr);
                _sim_activate (uptr, 1);
                uptr->usecs_remaining = usecs_remaining;
                }
            rtc_hz[sim_calb_tmr] = 0;                           /* back to 0 */
            if (sim_clock_unit[sim_calb_tmr])
                sim_cancel (sim_clock_unit[sim_calb_tmr]);
            sim_cancel (&sim_timer_units[sim_calb_tmr]);

            }
        /* Start the internal timer */
        sim_calb_tmr = SIM_NTIMERS;
        sim_debug (DBG_CAL|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Starting Internal Calibrated Timer at %dHz\n", newtmr, sim_int_clk_tps);
        SIM_INTERNAL_UNIT.action = &sim_timer_clock_tick_svc;
        SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
        sim_register_internal_device (&sim_int_timer_dev);      /* Register Internal timer device */
        sim_rtcn_init_unit (&SIM_INTERNAL_UNIT, (CLK_INIT*CLK_TPS)/sim_int_clk_tps, SIM_INTERNAL_CLK);
        SIM_INTERNAL_UNIT.action (&SIM_INTERNAL_UNIT);          /* Force tick to activate timer */
        }
    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|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Stopping Internal Calibrated Timer, New Timer = %d (%dHz)\n", newtmr, tmr, rtc_hz[tmr]);
    rtc_initd[SIM_NTIMERS] = 0;
    rtc_hz[SIM_NTIMERS] = 0;
    sim_register_clock_unit_tmr (NULL, SIM_INTERNAL_CLK);
    sim_cancel (&SIM_INTERNAL_UNIT);
    sim_cancel (&sim_timer_units[SIM_NTIMERS]);
    }
else {
    if ((sim_calb_tmr != -1) &&
        (rtc_hz[sim_calb_tmr] == 0)) {

        /* Migrate any coscheduled devices to the standard queue */
        /* with appropriate usecs_remaining reflecting their currently */
        /* scheduled firing time.  sim_process_event() will coschedule */
        /* appropriately. */
        /* temporarily restore prior hz to get correct remaining time */
        rtc_hz[sim_calb_tmr] = rtc_last_hz[sim_calb_tmr];
        while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
            UNIT *uptr = sim_clock_cosched_queue[tmr];
            double usecs_remaining = sim_timer_activate_time_usecs (uptr) - 1;

            _sim_coschedule_cancel (uptr);
            _sim_activate (uptr, 1);
            uptr->usecs_remaining = usecs_remaining;
            }
        rtc_hz[sim_calb_tmr] = 0;                           /* back to 0 */
        }
    sim_debug (DBG_CAL|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Changing Calibrated Timer from %d (%dHz) to %d (%dHz)\n", newtmr, 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)
{







|
|
|
|
>

|
|
|
|

|



















>
>
>
>
>
>
>
>
>
>




>




|
>
|
|
>
>





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

|
|
|
|
|
|
|
|
>







|







|
|
|
|





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

|
|
|
|
|
|
|
>







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

return NULL;
}

#endif /* defined(SIM_ASYNCH_CLOCKS) */

/*
   In the event that there are no active calibrated 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 100Hz.
 */

static t_stat sim_timer_clock_tick_svc (UNIT *uptr)
{
sim_debug(DBG_INT, &sim_timer_dev, "sim_timer_clock_tick_svc()\n");
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, OR when asynch clocks are enabled, the internal clock
  is always run.

  Some simulators have clocks that have dynamically programmable tick 
  rates. Such a clock is only a reliable candidate to be the calibrated 
  clock if it uses a single tick rate rather than changing the tick rate 
  on the fly.  Generally most systems like this, under normal conditions
  don't change their tick rates unless they're running something that is
  examining the behavior of the clock system (like a diagnostic).  Under 
  these conditions this clock is removed from the potential selection as
  "the" calibrated clock all others are relative to and if necessary, an
  internal calibrated clock is selected.
 */
static void _rtcn_configure_calibrated_clock (int32 newtmr)
{
int32 tmr;
RTC *rtc, *crtc;

/* Look for a timer running slower or the same as the host system clock */
sim_int_clk_tps = MIN(CLK_TPS, sim_os_tick_hz);
for (tmr=0; tmr<SIM_NTIMERS; tmr++) {
    rtc = &rtcs[tmr];
    if ((rtc->hz) &&                        /* is calibrated AND */
        (rtc->hz <= (uint32)sim_os_tick_hz) && /* slower than OS tick rate AND */
        (rtc->clock_unit) &&                /* clock has been registered AND */
        ((rtc->last_hz == 0) ||             /* first calibration call OR */
         (rtc->last_hz == rtc->hz)))        /* subsequent calibration call with an unchanged tick rate */
        break;
    }
if (tmr == SIM_NTIMERS) {                   /* None found? */
    if ((tmr != newtmr) && (!sim_is_active (&SIM_INTERNAL_UNIT))) {
        if ((sim_calb_tmr != SIM_NTIMERS) &&/* not internal timer? */
            (sim_calb_tmr != -1)) {         /* previously active? */
            crtc = &rtcs[sim_calb_tmr];
            if (!crtc->hz) {                /* now stopped? */
                sim_debug (DBG_CAL, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Cleaning up stopped timer %s support\n", newtmr, sim_uname(crtc->clock_unit));
                /* Migrate any coscheduled devices to the standard queue */
                /* with appropriate usecs_remaining reflecting their currently */
                /* scheduled firing time.  sim_process_event() will coschedule */
                /* appropriately. */
                /* temporarily restore prior hz to get correct remaining time */
                crtc->hz = crtc->last_hz;
                while (crtc->clock_cosched_queue != QUEUE_LIST_END) {
                    UNIT *uptr = crtc->clock_cosched_queue;
                    double usecs_remaining = sim_timer_activate_time_usecs (uptr) - 1;

                    _sim_coschedule_cancel (uptr);
                    _sim_activate (uptr, 1);
                    uptr->usecs_remaining = usecs_remaining;
                    }
                crtc->hz = 0;                           /* back to 0 */
                if (crtc->clock_unit)
                    sim_cancel (crtc->clock_unit);
                sim_cancel (crtc->timer_unit);
                }
            }
        /* Start the internal timer */
        sim_calb_tmr = SIM_NTIMERS;
        sim_debug (DBG_CAL|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Starting Internal Calibrated Timer at %dHz\n", newtmr, sim_int_clk_tps);
        SIM_INTERNAL_UNIT.action = &sim_timer_clock_tick_svc;
        SIM_INTERNAL_UNIT.flags = UNIT_IDLE;
        sim_register_internal_device (&sim_int_timer_dev);      /* Register Internal timer device */
        sim_rtcn_init_unit_ticks (&SIM_INTERNAL_UNIT, (int32)((CLK_INIT*CLK_TPS)/sim_int_clk_tps), SIM_INTERNAL_CLK, sim_int_clk_tps);
        SIM_INTERNAL_UNIT.action (&SIM_INTERNAL_UNIT);          /* Force tick to activate timer */
        }
    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|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Stopping Internal Calibrated Timer, New Timer = %d (%dHz)\n", newtmr, tmr, rtc->hz);
    rtcs[SIM_NTIMERS].initd = 0;
    rtcs[SIM_NTIMERS].hz = 0;
    sim_register_clock_unit_tmr (NULL, SIM_INTERNAL_CLK);
    sim_cancel (&SIM_INTERNAL_UNIT);
    sim_cancel (&sim_timer_units[SIM_NTIMERS]);
    }
else {
    if (sim_calb_tmr != -1) {
        crtc = &rtcs[sim_calb_tmr];
        if (crtc->hz == 0) {
            /* Migrate any coscheduled devices to the standard queue */
            /* with appropriate usecs_remaining reflecting their currently */
            /* scheduled firing time.  sim_process_event() will coschedule */
            /* appropriately. */
            /* temporarily restore prior hz to get correct remaining time */
            crtc->hz = crtc->last_hz;
            while (crtc->clock_cosched_queue != QUEUE_LIST_END) {
                UNIT *uptr = crtc->clock_cosched_queue;
                double usecs_remaining = sim_timer_activate_time_usecs (uptr) - 1;

                _sim_coschedule_cancel (uptr);
                _sim_activate (uptr, 1);
                uptr->usecs_remaining = usecs_remaining;
                }
            crtc->hz = 0;                          /* back to 0 */
            }
        sim_debug (DBG_CAL|DBG_INT, &sim_timer_dev, "_rtcn_configure_calibrated_clock(newtmr=%d) - Changing Calibrated Timer from %d (%dHz) to %d (%dHz)\n", newtmr, sim_calb_tmr, crtc->last_hz, tmr, rtc->hz);
        }
    sim_calb_tmr = tmr;
    }
sim_calb_tmr = tmr;
}

static t_stat sim_timer_clock_reset (DEVICE *dptr)
{
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
    sim_calb_tmr = -1;
    }
return SCPE_OK;
}

void sim_start_timer_services (void)
{



/* 



 * If we're quickly running again after being stopped for less than
 * the time of one calibrated clock tick, then don't force a complete 
 * recalibration of any timers that may have been previously running.
 */
if ((sim_calb_tmr_last != -1) && 




    ((sim_timenow_double () - sim_stop_time) < rtc_clock_tick_size[sim_calb_tmr_last])) {
    int32 clock_time = sim_activate_time (sim_clock_unit[sim_calb_tmr_last]);



    sim_calb_tmr = sim_calb_tmr_last;
    sim_cancel (sim_clock_unit[sim_calb_tmr]);
    sim_activate (&sim_timer_units[sim_calb_tmr], clock_time);
    sim_debug (DBG_TRC, &sim_timer_dev, "sim_start_timer_services() - restarting with previously calibrated timer %d (%s) at %d\n", sim_calb_tmr, sim_uname (sim_clock_unit[sim_calb_tmr]), clock_time);

    }
else {

    sim_debug (DBG_TRC, &sim_timer_dev, "sim_start_timer_services() - starting from scratch\n");
    sim_rtcn_init_all ();                                   /* re-init clocks */
    _rtcn_configure_calibrated_clock (sim_calb_tmr);



    }
if (sim_timer_stop_time > sim_gtime())
    sim_activate_abs (&sim_stop_unit, (int32)(sim_timer_stop_time - sim_gtime()));
#if defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_asynch_timer) {
    pthread_attr_t attr;







>
>
>
|
>
>
>
|
|
<
<
|
>
>
>
>
|
|
|
>
>
|
|
<
|
>


>
|
<
<
>
>
>







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
    sim_calb_tmr = -1;
    }
return SCPE_OK;
}

void sim_start_timer_services (void)
{
int32 tmr;
uint32 sim_prompt_time = (sim_gtime () > 0) ? (sim_os_msec () - sim_stop_time) : 0;
int32 registered_units = 0;

sim_time_at_sim_prompt +=  (((double)sim_prompt_time) / 1000.0);
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->initd) {                /* calibrated clock initialized? */


        rtc->rtime += sim_prompt_time;
        rtc->vtime += sim_prompt_time;
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_start_timer_services(tmr=%d) - adjusting calibration real time by %d ms\n", tmr, (int)sim_prompt_time);
        if (rtc->clock_catchup_eligible)
            rtc->calib_tick_time += (((double)sim_prompt_time) / 1000.0);
        if (rtc->clock_unit)
            ++registered_units;
        }
    }
if (registered_units == 1)
    sim_catchup_ticks = FALSE;
if (sim_calb_tmr == -1) {

    sim_debug (DBG_CAL, &sim_timer_dev, "sim_start_timer_services() - starting from scratch\n");
    _rtcn_configure_calibrated_clock (sim_calb_tmr);
    }
else {
    if (sim_calb_tmr == SIM_NTIMERS) {
        sim_debug (DBG_CAL, &sim_timer_dev, "sim_start_timer_services() - restarting internal timer after %d %s\n", 


                                            sim_internal_timer_time, sim_vm_interval_units);
        sim_activate (&SIM_INTERNAL_UNIT, sim_internal_timer_time);
        }
    }
if (sim_timer_stop_time > sim_gtime())
    sim_activate_abs (&sim_stop_unit, (int32)(sim_timer_stop_time - sim_gtime()));
#if defined(SIM_ASYNCH_CLOCKS)
pthread_mutex_lock (&sim_timer_lock);
if (sim_asynch_timer) {
    pthread_attr_t attr;
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
#endif
}

void sim_stop_timer_services (void)
{
int tmr;

sim_debug (DBG_TRC, &sim_timer_dev, "sim_stop_timer_services(sim_interval=%d)\n", sim_interval);

if (sim_interval < 0)
    sim_interval = 0;               /* No catching up after stopping */

for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    int32 accum;


    if (sim_clock_unit[tmr]) {
        int32 clock_time = _sim_activate_time (&sim_timer_units[tmr]);

        /* Stop clock assist unit and make sure the clock unit has a tick queued */
        if (sim_is_active (&sim_timer_units[tmr])) {
            sim_cancel (&sim_timer_units[tmr]);
            sim_debug (DBG_QUE, &sim_timer_dev, "sim_stop_timer_services() - tmr=%d scheduling %s after %d\n", tmr, sim_uname (sim_clock_unit[tmr]), clock_time);
            _sim_activate (sim_clock_unit[tmr], clock_time);
            }
        /* Move coscheduled units to the standard event queue */
        /* scheduled to fire at the same time as the related */
        /* clock unit is to fire with excess time reflected in */
        /* the unit usecs_remaining value */
        accum = sim_cosched_interval[tmr];
        while (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END) {
            UNIT *cptr = sim_clock_cosched_queue[tmr];
            double usecs_remaining = cptr->usecs_remaining;

            sim_clock_cosched_queue[tmr] = cptr->next;
            cptr->next = NULL;
            cptr->cancel = NULL;
            accum += cptr->time;
            cptr->usecs_remaining = 0.0;
            _sim_activate (cptr, clock_time);
            cptr->usecs_remaining = usecs_remaining + floor(1000000.0 * (accum - ((accum > 0) ? 1 : 0)) * rtc_clock_tick_size[tmr]);
            sim_debug (DBG_QUE, &sim_timer_dev, "sim_stop_timer_services() - tmr=%d scheduling %s after %d and %.0f usecs\n", tmr, sim_uname (cptr), clock_time, cptr->usecs_remaining);
            }
        sim_cosched_interval[tmr] = 0;
        }
    }



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;
sim_stop_time = sim_timenow_double ();              /* record when execution stopped */
#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);







|






>

|
|


|
|
|
|





|
|
|


|





|


|



>
>




<
|







2630
2631
2632
2633
2634
2635
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
#endif
}

void sim_stop_timer_services (void)
{
int tmr;

sim_debug (DBG_TRC, &sim_timer_dev, "sim_stop_timer_services(sim_interval=%d, sim_calb_tmr=%d)\n", sim_interval, sim_calb_tmr);

if (sim_interval < 0)
    sim_interval = 0;               /* No catching up after stopping */

for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    int32 accum;
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit) {
        int32 clock_time = _sim_activate_time (rtc->timer_unit);

        /* Stop clock assist unit and make sure the clock unit has a tick queued */
        if (sim_is_active (rtc->timer_unit)) {
            sim_cancel (rtc->timer_unit);
            sim_debug (DBG_QUE, &sim_timer_dev, "sim_stop_timer_services() - tmr=%d scheduling %s after %d\n", tmr, sim_uname (rtc->clock_unit), clock_time);
            _sim_activate (rtc->clock_unit, clock_time);
            }
        /* Move coscheduled units to the standard event queue */
        /* scheduled to fire at the same time as the related */
        /* clock unit is to fire with excess time reflected in */
        /* the unit usecs_remaining value */
        accum = rtc->cosched_interval;
        while (rtc->clock_cosched_queue != QUEUE_LIST_END) {
            UNIT *cptr = rtc->clock_cosched_queue;
            double usecs_remaining = cptr->usecs_remaining;

            rtc->clock_cosched_queue = cptr->next;
            cptr->next = NULL;
            cptr->cancel = NULL;
            accum += cptr->time;
            cptr->usecs_remaining = 0.0;
            _sim_activate (cptr, clock_time);
            cptr->usecs_remaining = usecs_remaining + floor(1000000.0 * (accum - ((accum > 0) ? 1 : 0)) * rtc->clock_tick_size);
            sim_debug (DBG_QUE, &sim_timer_dev, "sim_stop_timer_services() - tmr=%d scheduling %s after %d and %.0f usecs\n", tmr, sim_uname (cptr), clock_time, cptr->usecs_remaining);
            }
        rtc->cosched_interval = 0;
        }
    }

if (sim_calb_tmr == SIM_NTIMERS)
    sim_internal_timer_time = sim_activate_time (&SIM_INTERNAL_UNIT) - 1;
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_stop_time = sim_os_msec ();                     /* record when execution stopped */
#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);
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
/* 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_inst_per_sec_last;


if (sim_calb_tmr == -1)
    return inst_per_sec;

inst_per_sec = ((double)rtc_currd[sim_calb_tmr])*rtc_hz[sim_calb_tmr];
if (inst_per_sec == 0.0)
    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(uptr);
return sim_timer_activate_after (uptr, (double)((interval * 1000000.0) / sim_timer_inst_per_sec ()));
}

t_stat sim_timer_activate_after (UNIT *uptr, double usec_delay)
{
UNIT *ouptr = uptr;
int inst_delay, tmr;
double inst_delay_d, inst_per_usec;
t_stat stat;


AIO_VALIDATE(uptr);
/* 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;
if (usec_delay < 0.0) {
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - surprising usec value\n", 
               sim_uname(uptr), usec_delay);
    }
if ((sim_is_running) || (tmr <= SIM_NTIMERS))







>



>
|

|















>



|
>
|
>
|


>







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
/* 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_inst_per_sec_last;
RTC *rtc;

if (sim_calb_tmr == -1)
    return inst_per_sec;
rtc = &rtcs[sim_calb_tmr];
inst_per_sec = ((double)rtc->currd) * rtc->hz;
if (inst_per_sec == 0.0)
    inst_per_sec = ((double)rtc->currd) * sim_int_clk_tps;
return inst_per_sec;
}

t_stat sim_timer_activate (UNIT *uptr, int32 interval)
{
AIO_VALIDATE(uptr);
return sim_timer_activate_after (uptr, (double)((interval * 1000000.0) / sim_timer_inst_per_sec ()));
}

t_stat sim_timer_activate_after (UNIT *uptr, double usec_delay)
{
UNIT *ouptr = uptr;
int inst_delay, tmr;
double inst_delay_d, inst_per_usec;
t_stat stat;
RTC *crtc;

AIO_VALIDATE(uptr);
/* If this is a clock unit, we need to schedule the related timer unit instead */
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == uptr) {
        uptr = rtc->timer_unit;
        break;
        }
    }
if (sim_is_active (uptr))                               /* already active? */
    return SCPE_OK;
if (usec_delay < 0.0) {
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - surprising usec value\n", 
               sim_uname(uptr), usec_delay);
    }
if ((sim_is_running) || (tmr <= SIM_NTIMERS))
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
inst_per_usec = sim_timer_inst_per_sec () / 1000000.0;
inst_delay_d = floor(inst_per_usec * usec_delay);
inst_delay = (int32)inst_delay_d;
if ((inst_delay == 0) && (usec_delay != 0))
    inst_delay_d = inst_delay = 1;  /* Minimum non-zero delay is 1 instruction */
if (uptr->usecs_remaining != 0.0)   /* No calibrated timer yet, wait one cycle */
    inst_delay_d = inst_delay = 1;  /* Minimum non-zero delay is 1 instruction */


if ((sim_calb_tmr != -1) && (rtc_hz[sim_calb_tmr])) {       /* Calibrated Timer available? */
    int32 inst_til_tick = sim_activate_time (&sim_timer_units[sim_calb_tmr]) - 1;
    int32 ticks_til_calib = rtc_hz[sim_calb_tmr] - rtc_ticks[sim_calb_tmr];
    double usecs_per_tick = floor (1000000.0 / rtc_hz[sim_calb_tmr]);
    int32 inst_til_calib = inst_til_tick + ((ticks_til_calib - 1) * rtc_currd[sim_calb_tmr]);
    uint32 usecs_til_calib = (uint32)ceil(inst_til_calib / inst_per_usec);

    if ((uptr != &sim_timer_units[sim_calb_tmr]) &&         /* Not scheduling calibrated timer */
        (inst_til_tick > 0)) {                              /* and tick not pending? */
        if (inst_delay_d > (double)inst_til_calib) {        /* long wait? */
            stat = sim_clock_coschedule_tmr (uptr, sim_calb_tmr, ticks_til_calib - 1);
            uptr->usecs_remaining = (stat == SCPE_OK) ? usec_delay - usecs_til_calib : 0.0;
            sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - coscheduling with with calibrated timer(%d), ticks=%d, usecs_remaining=%.0f usecs, inst_til_tick=%d, ticks_til_calib=%d, usecs_til_calib=%u\n", 
                       sim_uname(uptr), usec_delay, sim_calb_tmr, ticks_til_calib, uptr->usecs_remaining, inst_til_tick, ticks_til_calib, usecs_til_calib);
            sim_debug (DBG_CHK, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - result = %.0f usecs, %.0f usecs\n", 
                       sim_uname(uptr), usec_delay, sim_timer_activate_time_usecs (ouptr), sim_timer_activate_time_usecs (uptr));
            return stat;
            }
        if ((usec_delay > (2 * usecs_per_tick)) &&
            (ticks_til_calib > 1)) {                  /* long wait? */
            double usecs_til_tick = floor (inst_til_tick / inst_per_usec);

            stat = sim_clock_coschedule_tmr (uptr, sim_calb_tmr, 0);
            uptr->usecs_remaining = (stat == SCPE_OK) ? usec_delay - usecs_til_tick : 0.0;
            sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - coscheduling with with calibrated timer(%d), ticks=%d, usecs_remaining=%.0f usecs, inst_til_tick=%d, usecs_til_tick=%.0f\n", 
                       sim_uname(uptr), usec_delay, sim_calb_tmr, 0, uptr->usecs_remaining, inst_til_tick, usecs_til_tick);
            sim_debug (DBG_CHK, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - result = %.0f usecs, %.0f usecs\n", 
                       sim_uname(uptr), usec_delay, sim_timer_activate_time_usecs (ouptr), sim_timer_activate_time_usecs (uptr));
            return stat;

            }
        }
    }
/* 
 * We're here to schedule if:
 * No Calibrated Timer, OR
 * Scheduling the Calibrated Timer OR







>
>
|
|
|
|
|
|

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

|
|
|
|
|
|
|
>







2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
inst_per_usec = sim_timer_inst_per_sec () / 1000000.0;
inst_delay_d = floor(inst_per_usec * usec_delay);
inst_delay = (int32)inst_delay_d;
if ((inst_delay == 0) && (usec_delay != 0))
    inst_delay_d = inst_delay = 1;  /* Minimum non-zero delay is 1 instruction */
if (uptr->usecs_remaining != 0.0)   /* No calibrated timer yet, wait one cycle */
    inst_delay_d = inst_delay = 1;  /* Minimum non-zero delay is 1 instruction */
if (sim_calb_tmr != -1) {
    crtc = &rtcs[sim_calb_tmr];
    if (crtc->hz) {                 /* Calibrated Timer available? */
        int32 inst_til_tick = sim_activate_time (crtc->timer_unit) - 1;
        int32 ticks_til_calib = crtc->hz - crtc->ticks;
        double usecs_per_tick = floor (1000000.0 / crtc->hz);
        int32 inst_til_calib = inst_til_tick + ((ticks_til_calib - 1) * crtc->currd);
        uint32 usecs_til_calib = (uint32)ceil(inst_til_calib / inst_per_usec);

        if ((uptr != crtc->timer_unit) &&                   /* Not scheduling calibrated timer */
            (inst_til_tick > 0)) {                          /* and tick not pending? */
            if (inst_delay_d > (double)inst_til_calib) {    /* long wait? */
                stat = sim_clock_coschedule_tmr (uptr, sim_calb_tmr, ticks_til_calib - 1);
                uptr->usecs_remaining = (stat == SCPE_OK) ? usec_delay - usecs_til_calib : 0.0;
                sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - coscheduling with with calibrated timer(%d), ticks=%d, usecs_remaining=%.0f usecs, inst_til_tick=%d, ticks_til_calib=%d, usecs_til_calib=%u\n", 
                           sim_uname(uptr), usec_delay, sim_calb_tmr, ticks_til_calib, uptr->usecs_remaining, inst_til_tick, ticks_til_calib, usecs_til_calib);
                sim_debug (DBG_CHK, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - result = %.0f usecs, %.0f usecs\n", 
                           sim_uname(uptr), usec_delay, sim_timer_activate_time_usecs (ouptr), sim_timer_activate_time_usecs (uptr));
                return stat;
                }
            if ((usec_delay > (2 * usecs_per_tick)) &&
                (ticks_til_calib > 1)) {                    /* long wait? */
                double usecs_til_tick = floor (inst_til_tick / inst_per_usec);

                stat = sim_clock_coschedule_tmr (uptr, sim_calb_tmr, 0);
                uptr->usecs_remaining = (stat == SCPE_OK) ? usec_delay - usecs_til_tick : 0.0;
                sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - coscheduling with with calibrated timer(%d), ticks=%d, usecs_remaining=%.0f usecs, inst_til_tick=%d, usecs_til_tick=%.0f\n", 
                           sim_uname(uptr), usec_delay, sim_calb_tmr, 0, uptr->usecs_remaining, inst_til_tick, usecs_til_tick);
                sim_debug (DBG_CHK, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - result = %.0f usecs, %.0f usecs\n", 
                           sim_uname(uptr), usec_delay, sim_timer_activate_time_usecs (ouptr), sim_timer_activate_time_usecs (uptr));
                return stat;
                }
            }
        }
    }
/* 
 * We're here to schedule if:
 * No Calibrated Timer, OR
 * Scheduling the Calibrated Timer OR
2663
2664
2665
2666
2667
2668
2669


2670
2671
2672
2673
2674
2675
2676
2677
2678

    uptr->a_usec_delay = usec_delay;
    uptr->a_due_time = d_now + (usec_delay / 1000000.0);
    uptr->a_due_gtime = sim_gtime () + (sim_timer_inst_per_sec () * (usec_delay / 1000000.0));
    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(%s, %.0f usecs) - queueing wallclock addition at %.6f\n", 
               sim_uname(uptr), usec_delay, uptr->a_due_time);

    pthread_mutex_lock (&sim_timer_lock);
    for (cptr = sim_wallclock_queue, prvptr = NULL; cptr != QUEUE_LIST_END; cptr = cptr->a_next) {







>
>
|
|







2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868

    uptr->a_usec_delay = usec_delay;
    uptr->a_due_time = d_now + (usec_delay / 1000000.0);
    uptr->a_due_gtime = sim_gtime () + (sim_timer_inst_per_sec () * (usec_delay / 1000000.0));
    uptr->cancel = &_sim_wallclock_cancel;              /* bind cleanup method */
    uptr->a_is_active = &_sim_wallclock_is_active;
    if (tmr <= SIM_NTIMERS) {                            /* Timer Unit? */
        RTC *rtc = &rtcs[tmr];

        rtc->clock_unit->cancel = &_sim_wallclock_cancel;
        rtc->clock_unit->a_is_active = &_sim_wallclock_is_active;
        }

    sim_debug (DBG_TIM, &sim_timer_dev, "sim_timer_activate_after(%s, %.0f usecs) - queueing wallclock addition at %.6f\n", 
               sim_uname(uptr), usec_delay, uptr->a_due_time);

    pthread_mutex_lock (&sim_timer_lock);
    for (cptr = sim_wallclock_queue, prvptr = NULL; cptr != QUEUE_LIST_END; cptr = cptr->a_next) {
2712
2713
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
2759
2760

2761

2762
2763
2764
2765
2766
2767
2768
return stat;
}

/* 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];
        double usecs_remaining = sim_timer_activate_time_usecs (uptr);

        _sim_coschedule_cancel (uptr);
        _sim_activate (uptr, 1);
        uptr->usecs_remaining = usecs_remaining;
        }
    if (sim_clock_unit[tmr]) {
        sim_cancel (sim_clock_unit[tmr]);
        sim_clock_unit[tmr]->dynflags &= ~UNIT_TMR_UNIT;
        }
    sim_clock_unit[tmr] = NULL;
    sim_cancel (&sim_timer_units[tmr]);
    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 */
int32 sim_rtcn_calibrated_tmr (void)
{
return ((rtc_currd[0] && rtc_hz[0]) ? 0 : ((sim_calb_tmr != -1) ? sim_calb_tmr : 0));
}

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);
}








>
>






>



|
|






|
|
|

|
|


|
|
|

|
|






|




>
|
>







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
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
return stat;
}

/* Clock coscheduling routines */

t_stat sim_register_clock_unit_tmr (UNIT *uptr, int32 tmr)
{
RTC *rtc;

if (tmr == SIM_INTERNAL_CLK)
    tmr = SIM_NTIMERS;
else {
    if ((tmr < 0) || (tmr > SIM_NTIMERS))
        return SCPE_IERR;
    }
rtc = &rtcs[tmr];
if (NULL == uptr) {                         /* deregistering? */
    /* Migrate any coscheduled devices to the standard queue */
    /* they will fire and subsequently requeue themselves */
    while (rtc->clock_cosched_queue != QUEUE_LIST_END) {
        UNIT *uptr = rtc->clock_cosched_queue;
        double usecs_remaining = sim_timer_activate_time_usecs (uptr);

        _sim_coschedule_cancel (uptr);
        _sim_activate (uptr, 1);
        uptr->usecs_remaining = usecs_remaining;
        }
    if (rtc->clock_unit) {
        sim_cancel (rtc->clock_unit);
        rtc->clock_unit->dynflags &= ~UNIT_TMR_UNIT;
        }
    rtc->clock_unit = NULL;
    sim_cancel (rtc->timer_unit);
    return SCPE_OK;
    }
if (rtc->clock_unit == NULL)
    rtc->clock_cosched_queue = QUEUE_LIST_END;
rtc->clock_unit = uptr;
uptr->dynflags |= UNIT_TMR_UNIT;
rtc->timer_unit->flags = ((tmr == SIM_NTIMERS) ? 0 : UNIT_DIS) | 
                          (rtc->clock_unit ? UNIT_IDLE : 0);
return SCPE_OK;
}

/* Default timer is 0, otherwise use a calibrated one if it exists */
int32 sim_rtcn_calibrated_tmr (void)
{
return ((rtcs[0].currd && rtcs[0].hz) ? 0 : ((sim_calb_tmr != -1) ? sim_calb_tmr : 0));
}

int32 sim_rtcn_tick_size (int32 tmr)
{
RTC *rtc = &rtcs[tmr];

return (rtc->currd) ? rtc->currd : 10000;
}

t_stat sim_register_clock_unit (UNIT *uptr)
{
return sim_register_clock_unit_tmr (uptr, 0);
}

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
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
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
return sim_clock_coschedule (uptr, interval);
}

/* ticks - 0 means on the next tick, 1 means the second tick, etc.  */

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(%s, tmr=%d, ticks=%d) - already active\n", sim_uname (uptr), tmr, ticks);
    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]) || (rtc_hz[tmr] == 0)) {
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule_tmr(%s, tmr=%d, ticks=%d) - no clock activating after %d instructions\n", sim_uname (uptr), tmr, ticks, ticks * (rtc_currd[tmr] ? rtc_currd[tmr] : rtc_currd[sim_rtcn_calibrated_tmr ()]));
    return sim_activate (uptr, ticks * (rtc_currd[tmr] ? rtc_currd[tmr] : rtc_currd[sim_rtcn_calibrated_tmr ()]));
    }
else {
    UNIT *cptr, *prvptr;
    int32 accum;

    if (sim_clock_cosched_queue[tmr] != QUEUE_LIST_END)
        sim_clock_cosched_queue[tmr]->time = sim_cosched_interval[tmr];
    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 += 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 */
    if (uptr == sim_clock_cosched_queue[tmr])
        sim_cosched_interval[tmr] = sim_clock_cosched_queue[tmr]->time;
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_clock_coschedule_tmr(%s, tmr=%d, ticks=%d, hz=%d) - queueing for clock co-schedule, interval now: %d\n", sim_uname (uptr), tmr, ticks, rtc_hz[tmr], sim_cosched_interval[tmr]);
    }
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 t_bool _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;
                        }







>
>












>
|
|
|





|
|


|






|
|









|
|
|



















>
>
|
|
|





|







2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
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
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
return sim_clock_coschedule (uptr, interval);
}

/* ticks - 0 means on the next tick, 1 means the second tick, etc.  */

t_stat sim_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks)
{
RTC *rtc;

if (ticks < 0)
    return SCPE_ARG;
if (sim_is_active (uptr)) {
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule_tmr(%s, tmr=%d, ticks=%d) - already active\n", sim_uname (uptr), tmr, ticks);
    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);
    }
rtc = &rtcs[tmr];
if ((NULL == rtc->clock_unit) || (rtc->hz == 0)) {
    sim_debug (DBG_TIM, &sim_timer_dev, "sim_clock_coschedule_tmr(%s, tmr=%d, ticks=%d) - no clock activating after %d %s\n", sim_uname (uptr), tmr, ticks, ticks * (rtc->currd ? rtc->currd : rtcs[sim_rtcn_calibrated_tmr ()].currd), sim_vm_interval_units);
    return sim_activate (uptr, ticks * (rtc->currd ? rtc->currd : rtcs[sim_rtcn_calibrated_tmr ()].currd));
    }
else {
    UNIT *cptr, *prvptr;
    int32 accum;

    if (rtc->clock_cosched_queue != QUEUE_LIST_END)
        rtc->clock_cosched_queue->time = rtc->cosched_interval;
    prvptr = NULL;
    accum = 0;
    for (cptr = rtc->clock_cosched_queue; cptr != QUEUE_LIST_END; cptr = cptr->next) {
        if (ticks < (accum + cptr->time))
            break;
        accum += cptr->time;
        prvptr = cptr;
        }
    if (prvptr == NULL) {
        cptr = uptr->next = rtc->clock_cosched_queue;
        rtc->clock_cosched_queue = 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 */
    if (uptr == rtc->clock_cosched_queue)
        rtc->cosched_interval = rtc->clock_cosched_queue->time;
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_clock_coschedule_tmr(%s, tmr=%d, ticks=%d, hz=%d) - queueing for clock co-schedule, interval now: %d\n", sim_uname (uptr), tmr, ticks, rtc->hz, rtc->cosched_interval);
    }
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 t_bool _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++) {
        RTC *rtc = &rtcs[tmr];

        if (rtc->clock_unit) {
            if (uptr == rtc->clock_cosched_queue) {
                nptr = rtc->clock_cosched_queue = uptr->next;
                uptr->next = NULL;
                }
            else {
                UNIT *cptr;

                for (cptr = rtc->clock_cosched_queue;
                     (cptr != QUEUE_LIST_END);
                     cptr = cptr->next) {
                    if (cptr->next == uptr) {
                        nptr = cptr->next = (uptr)->next;
                        uptr->next = NULL;
                        break;
                        }
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
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;
}

t_bool sim_timer_cancel (UNIT *uptr)
{
int32 tmr;

if (!(uptr->dynflags & UNIT_TMR_UNIT))
    return SCPE_IERR;
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {

    if (sim_clock_unit[tmr] == uptr)

        return sim_cancel (&sim_timer_units[tmr]);
    }
return SCPE_IERR;
}

#if defined(SIM_ASYNCH_CLOCKS)
static t_bool _sim_wallclock_cancel (UNIT *uptr)
{
int32 tmr;
t_bool b_return = FALSE;

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;
        sim_debug (DBG_QUE, &sim_timer_dev, "Canceled Queue Pending Timer Event for %s\n", sim_uname(uptr));







>
|
>












>
|
>














|
>
|
>



>







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
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
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++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == uptr)
        return sim_is_active (&sim_timer_units[tmr]);
    }
return FALSE;
}

t_bool sim_timer_cancel (UNIT *uptr)
{
int32 tmr;

if (!(uptr->dynflags & UNIT_TMR_UNIT))
    return SCPE_IERR;
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == uptr)
        return sim_cancel (&sim_timer_units[tmr]);
    }
return SCPE_IERR;
}

#if defined(SIM_ASYNCH_CLOCKS)
static t_bool _sim_wallclock_cancel (UNIT *uptr)
{
int32 tmr;
t_bool b_return = FALSE;

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++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == 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;
        sim_debug (DBG_QUE, &sim_timer_dev, "Canceled Queue Pending Timer Event for %s\n", sim_uname(uptr));
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

2978
2979
2980
2981
2982
2983
2984
            }
        }
    if (uptr->a_next == NULL) {         /* Was canceled? */
        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;
            }
        b_return = TRUE;
        }
    }
pthread_mutex_unlock (&sim_timer_lock);
return b_return;
}

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;







>
>
|
|















|
>
|
>

>







3158
3159
3160
3161
3162
3163
3164
3165
3166
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
3194
3195
3196
            }
        }
    if (uptr->a_next == NULL) {         /* Was canceled? */
        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? */
            RTC *rtc = &rtcs[tmr];

            rtc->clock_unit->cancel = NULL;
            rtc->clock_unit->a_is_active = NULL;
            }
        b_return = TRUE;
        }
    }
pthread_mutex_unlock (&sim_timer_lock);
return b_return;
}

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++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == 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;
3015
3016
3017
3018
3019
3020
3021

3022

3023
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
3055
3056
3057
3058
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 = 0;



        for (cptr = sim_clock_cosched_queue[tmr]; cptr != QUEUE_LIST_END; cptr = cptr->next) {
            if (cptr == sim_clock_cosched_queue[tmr]) {
                if (sim_cosched_interval[tmr] > 0)
                    accum += sim_cosched_interval[tmr];
                }
            else
                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 ((uptr == &sim_timer_units[tmr]) && (uptr->next)){
        return _sim_activate_time (&sim_timer_units[tmr]);
        }
    }
return -1;                                          /* Not found. */    
}

double sim_timer_activate_time_usecs (UNIT *uptr)
{
UNIT *cptr;
int32 tmr;
double result = -1.0;

/* If this is a clock unit, we need to return the related clock assist 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)) {
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) - not active\n", sim_uname (uptr));







>

>
|
|
|
|




|



















>
|
>







3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
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 = 0;
        RTC *rtc = &rtcs[tmr];


        for (cptr = rtc->clock_cosched_queue; cptr != QUEUE_LIST_END; cptr = cptr->next) {
            if (cptr == rtc->clock_cosched_queue) {
                if (rtc->cosched_interval > 0)
                    accum += rtc->cosched_interval;
                }
            else
                accum += cptr->time;
            if (cptr == uptr)
                return (rtc->currd * accum) + sim_activate_time (&sim_timer_units[tmr]);
            }
        }
    }
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    if ((uptr == &sim_timer_units[tmr]) && (uptr->next)){
        return _sim_activate_time (&sim_timer_units[tmr]);
        }
    }
return -1;                                          /* Not found. */    
}

double sim_timer_activate_time_usecs (UNIT *uptr)
{
UNIT *cptr;
int32 tmr;
double result = -1.0;

/* If this is a clock unit, we need to return the related clock assist unit instead */
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->clock_unit == uptr) {
        uptr = &sim_timer_units[tmr];
        break;
        }
    }

if (!sim_is_active (uptr)) {
    sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) - not active\n", sim_uname (uptr));
3090
3091
3092
3093
3094
3095
3096

3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113


3114
3115
3116
3117
3118
3119
3120
3121
3122
    return result;
    }
#endif /* defined(SIM_ASYNCH_CLOCKS) */

if (uptr->cancel == &_sim_coschedule_cancel) {
    for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
        int32 accum = 0;


        for (cptr = sim_clock_cosched_queue[tmr]; cptr != QUEUE_LIST_END; cptr = cptr->next) {
            if (cptr == sim_clock_cosched_queue[tmr]) {
                if (sim_cosched_interval[tmr] > 0)
                    accum += sim_cosched_interval[tmr];
                }
            else
                accum += cptr->time;
            if (cptr == uptr) {
                result = uptr->usecs_remaining + ceil(1000000.0 * ((rtc_currd[tmr] * accum) + sim_activate_time (&sim_timer_units[tmr]) - 1) / sim_timer_inst_per_sec ());
                sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) coscheduled - %.0f usecs, inst_per_sec=%.0f, tmr=%d, ticksize=%d, ticks=%d, inst_til_tick=%d, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), tmr, rtc_currd[tmr], accum, sim_activate_time (&sim_timer_units[tmr]) - 1, uptr->usecs_remaining);
                return result;
                }
            }
        }
    }
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {


    if ((uptr == sim_clock_unit[tmr]) && (uptr->next)) {
        result = sim_clock_unit[tmr]->usecs_remaining + (1000000.0 * (sim_activate_time (&sim_timer_units[tmr]) - 1)) / sim_timer_inst_per_sec ();
        sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) clock - %.0f usecs, inst_per_sec=%.0f, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), uptr->usecs_remaining);
        return result;
        }
    if ((uptr == &sim_timer_units[tmr]) && (uptr->next)){
        result = uptr->usecs_remaining + (1000000.0 * (sim_activate_time (uptr) - 1)) / sim_timer_inst_per_sec ();
        sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) clock - %.0f usecs, inst_per_sec=%.0f, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), uptr->usecs_remaining);
        return result;







>

|
|
|
|




|
|






>
>
|
|







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
    return result;
    }
#endif /* defined(SIM_ASYNCH_CLOCKS) */

if (uptr->cancel == &_sim_coschedule_cancel) {
    for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
        int32 accum = 0;
        RTC *rtc = &rtcs[tmr];

        for (cptr = rtc->clock_cosched_queue; cptr != QUEUE_LIST_END; cptr = cptr->next) {
            if (cptr == rtc->clock_cosched_queue) {
                if (rtc->cosched_interval > 0)
                    accum += rtc->cosched_interval;
                }
            else
                accum += cptr->time;
            if (cptr == uptr) {
                result = uptr->usecs_remaining + ceil(1000000.0 * ((rtc->currd * accum) + sim_activate_time (&sim_timer_units[tmr]) - 1) / sim_timer_inst_per_sec ());
                sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) coscheduled - %.0f usecs, inst_per_sec=%.0f, tmr=%d, ticksize=%d, ticks=%d, inst_til_tick=%d, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), tmr, rtc->currd, accum, sim_activate_time (&sim_timer_units[tmr]) - 1, uptr->usecs_remaining);
                return result;
                }
            }
        }
    }
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if ((uptr == rtc->clock_unit) && (uptr->next)) {
        result = rtc->clock_unit->usecs_remaining + (1000000.0 * (sim_activate_time (&sim_timer_units[tmr]) - 1)) / sim_timer_inst_per_sec ();
        sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) clock - %.0f usecs, inst_per_sec=%.0f, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), uptr->usecs_remaining);
        return result;
        }
    if ((uptr == &sim_timer_units[tmr]) && (uptr->next)){
        result = uptr->usecs_remaining + (1000000.0 * (sim_activate_time (uptr) - 1)) / sim_timer_inst_per_sec ();
        sim_debug (DBG_QUE, &sim_timer_dev, "sim_timer_activate_time_usecs(%s) clock - %.0f usecs, inst_per_sec=%.0f, usecs_remaining=%.0f\n", sim_uname (uptr), result, sim_timer_inst_per_sec (), uptr->usecs_remaining);
        return result;
3195
3196
3197
3198
3199
3200
3201



























































return sim_rom_delay;
}

void sim_set_rom_delay_factor (uint32 delay)
{
sim_rom_delay = delay;
}


































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
return sim_rom_delay;
}

void sim_set_rom_delay_factor (uint32 delay)
{
sim_rom_delay = delay;
}

/* sim_timer_precalibrate_execution_rate
 *
 * The point of this routine is to run a bunch of simulator provided
 * instructions that don't do anything, but run in an effective loop.
 * That loop is run for some 5 million instructions and based on 
 * the time those 5 million instructions take to execute the effective
 * execution rate.  That rate is used to avoid the initial 3 to 5 
 * seconds that normal clock calibration takes.
 *
 */
void sim_timer_precalibrate_execution_rate (void)
{
const char **cmd = sim_clock_precalibrate_commands;
uint32 start, end;
int32 saved_switches = sim_switches;
int32 tmr;
UNIT precalib_unit = { UDATA (&sim_timer_stop_svc, 0, 0) };

if (cmd == NULL)
    return;
sim_run_boot_prep (RU_GO);
while (sim_clock_queue != QUEUE_LIST_END)
    sim_cancel (sim_clock_queue);
while (*cmd)
     exdep_cmd (EX_D, *(cmd++));
sim_switches = saved_switches;
sim_cancel (&SIM_INTERNAL_UNIT);
sim_activate (&precalib_unit, sim_precalibrate_ips);
start = sim_os_msec();
sim_instr();
end = sim_os_msec();
sim_precalibrate_ips = (int32)(1000.0 * (sim_precalibrate_ips / (double)(end - start)));

for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->hz)
        rtc->initd = rtc->currd = (int32)(((double)sim_precalibrate_ips) / rtc->hz);
    }
reset_all_p (0);
sim_run_boot_prep (RU_GO);
for (tmr=0; tmr<=SIM_NTIMERS; tmr++) {
    RTC *rtc = &rtcs[tmr];

    if (rtc->calib_initializations)
        rtc->calib_initializations = 1;
    }
sim_inst_per_sec_last = sim_precalibrate_ips;
sim_idle_stable = 0;
}

double 
sim_host_speed_factor (void)
{
if (sim_precalibrate_ips > sim_vm_initial_ips)
    return 1.0;
return (double)sim_vm_initial_ips / (double)sim_precalibrate_ips;
}

Changes to src/SIMH/sim_timer.h.

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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 */








|







72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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 5000000                     /* 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 */

104
105
106
107
108
109
110

111
112
113

114
115
116
117
118
119
120
121
122
123
#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, int 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);







>



>
|

|







104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#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);
int32 sim_rtcn_init_unit_ticks (UNIT *uptr, int32 time, int32 tmr, int32 ticksper);
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 (uint32 ticksper, int32 tmr);
int32 sim_rtcn_calb_tick (int32 tmr);
int32 sim_rtc_init (int32 time);
int32 sim_rtc_calb (uint32 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, int 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);
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
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);
int32 sim_rtcn_calibrated_tmr (void);
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);
uint32 sim_get_rom_delay_factor (void);
void sim_set_rom_delay_factor (uint32 delay);
int32 sim_rom_read_with_delay (int32 val);


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







>










>













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
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);
void sim_timer_precalibrate_execution_rate (void);
int32 sim_rtcn_tick_size (int32 tmr);
int32 sim_rtcn_calibrated_tmr (void);
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);
uint32 sim_get_rom_delay_factor (void);
void sim_set_rom_delay_factor (uint32 delay);
int32 sim_rom_read_with_delay (int32 val);
double sim_host_speed_factor (void);

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/SIMH/sim_tmxr.c.

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
   "SET dev DISCONNECT[=line]" to tmxr_dscln.  This will cause a telnet 
   connection to be closed, but a serial port will normally have DTR 
   dropped for 500ms and raised again (thus hanging up a modem on that 
   serial port).

     sim> set MUX disconnect=2

   A line which is connected to a serial port can be manually closed by
   adding the -C switch to a disconnect command.

     sim> set -C MUX disconnect=2

    Full Modem Control serial port support.

    This library supports devices which wish to emulate full modem 
    control/signalling for serial ports.  Any device emulation which wishes 
    to support this functionality for attached serial ports must call
    "tmxr_set_modem_control_passthru" before any call to tmxr_attach.  
    This disables automatic DTR (&RTS) manipulation by this library.







<
<
<
<
<







299
300
301
302
303
304
305





306
307
308
309
310
311
312
   "SET dev DISCONNECT[=line]" to tmxr_dscln.  This will cause a telnet 
   connection to be closed, but a serial port will normally have DTR 
   dropped for 500ms and raised again (thus hanging up a modem on that 
   serial port).

     sim> set MUX disconnect=2






    Full Modem Control serial port support.

    This library supports devices which wish to emulate full modem 
    control/signalling for serial ports.  Any device emulation which wishes 
    to support this functionality for attached serial ports must call
    "tmxr_set_modem_control_passthru" before any call to tmxr_attach.  
    This disables automatic DTR (&RTS) manipulation by this library.
1001
1002
1003
1004
1005
1006
1007

1008
1009
1010
1011
1012
1013
1014
int32 *op;
int32 i, j;
int32 ringing = -1;
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! */

    uptr->tmxr = (void *)mp;                            /* Connect UNIT to TMXR */







>







996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
int32 *op;
int32 i, j;
int32 ringing = -1;
char *address;
char msg[512];
uint32 poll_time = sim_os_msec ();

memset (msg, 0, sizeof (msg));
if (mp->last_poll_time == 0) {                          /* first poll initializations */
    UNIT *uptr = mp->uptr;

    if (!uptr)                                          /* Attached ? */
        return -1;                                      /* No connections are possinle! */

    uptr->tmxr = (void *)mp;                            /* Connect UNIT to TMXR */
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
                sim_cancel (mp->ldsc[i].uptr);
            if (mp->ldsc[i].o_uptr)
                sim_cancel (mp->ldsc[i].o_uptr);
            }
        }
    }


if ((poll_time - mp->last_poll_time) < mp->poll_interval*1000)
    return -1;                                          /* too soon to try */

srand((unsigned int)poll_time);
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? */







>
|




















|







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
                sim_cancel (mp->ldsc[i].uptr);
            if (mp->ldsc[i].o_uptr)
                sim_cancel (mp->ldsc[i].o_uptr);
            }
        }
    }

if (sim_is_running && 
    ((poll_time - mp->last_poll_time) < mp->poll_interval*1000))
    return -1;                                          /* too soon to try */

srand((unsigned int)poll_time);
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? */
        snprintf (msg, sizeof (msg) - 1, "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? */
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
                            lp->conn = TRUE;                    /* record connection */
                            lp->sock = lp->connecting;          /* it now looks normal */
                            lp->connecting = 0;
                            lp->ipad = (char *)realloc (lp->ipad, 1+strlen (lp->destination));
                            strcpy (lp->ipad, lp->destination);
                            lp->cnms = sim_os_msec ();
                            sim_getnames_sock (lp->sock, &sockname, &peername);
                            sprintf (msg, "tmxr_poll_conn() - Outgoing Line Connection to %s (%s->%s) established", lp->destination, sockname, peername);
                            tmxr_debug_connect_line (lp, msg);
                            free (sockname);
                            free (peername);
                            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);
                                }
                            return i;
                        case -1:                                /* failed connection */
                            sprintf (msg, "tmxr_poll_conn() - Outgoing Line Connection to %s failed", lp->destination);
                            tmxr_debug_connect_line (lp, msg);
                            tmxr_reset_ln (lp);                 /* retry */
                            break;
                        }
                    }
                break;
            case 1:
                if (lp->master) {                                   /* Check for a pending Telnet/tcp connection */
                    while (INVALID_SOCKET != (newsock = sim_accept_conn_ex (lp->master, &address, (lp->packet ? SIM_SOCK_OPT_NODELAY : 0)))) {/* got a live one? */
                        char *sockname, *peername;

                        sim_getnames_sock (newsock, &sockname, &peername);
                        sprintf (msg, "tmxr_poll_conn() - Incoming Line Connection from %s (%s->%s)", address, peername, sockname);
                        tmxr_debug_connect_line (lp, msg);
                        free (sockname);
                        free (peername);
                        ++mp->sessions;                             /* count the new session */

                        if (lp->destination) {                      /* Virtual Null Modem Cable? */
                            char host[CBUFSIZE];

                            if (sim_parse_addr (lp->destination, host, sizeof(host), NULL, NULL, 0, NULL, address)) {
                                tmxr_msg (newsock, "Rejecting connection from unexpected source\r\n");
                                sprintf (msg, "tmxr_poll_conn() - Rejecting line connection from: %s, Expected: %s", address, host);
                                tmxr_debug_connect_line (lp, msg);
                                sim_close_sock (newsock);
                                free (address);
                                continue;                           /* Try for another connection */
                                }
                            if (lp->connecting) {
                                sprintf (msg, "tmxr_poll_conn() - aborting outgoing line connection attempt to: %s", lp->destination);
                                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)) {







|











|












|






|



|






|







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
                            lp->conn = TRUE;                    /* record connection */
                            lp->sock = lp->connecting;          /* it now looks normal */
                            lp->connecting = 0;
                            lp->ipad = (char *)realloc (lp->ipad, 1+strlen (lp->destination));
                            strcpy (lp->ipad, lp->destination);
                            lp->cnms = sim_os_msec ();
                            sim_getnames_sock (lp->sock, &sockname, &peername);
                            snprintf (msg, sizeof (msg) -1, "tmxr_poll_conn() - Outgoing Line Connection to %s (%s->%s) established", lp->destination, sockname, peername);
                            tmxr_debug_connect_line (lp, msg);
                            free (sockname);
                            free (peername);
                            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);
                                }
                            return i;
                        case -1:                                /* failed connection */
                            snprintf (msg, sizeof (msg) -1, "tmxr_poll_conn() - Outgoing Line Connection to %s failed", lp->destination);
                            tmxr_debug_connect_line (lp, msg);
                            tmxr_reset_ln (lp);                 /* retry */
                            break;
                        }
                    }
                break;
            case 1:
                if (lp->master) {                                   /* Check for a pending Telnet/tcp connection */
                    while (INVALID_SOCKET != (newsock = sim_accept_conn_ex (lp->master, &address, (lp->packet ? SIM_SOCK_OPT_NODELAY : 0)))) {/* got a live one? */
                        char *sockname, *peername;

                        sim_getnames_sock (newsock, &sockname, &peername);
                        snprintf (msg, sizeof (msg) -1, "tmxr_poll_conn() - Incoming Line Connection from %s (%s->%s)", address, peername, sockname);
                        tmxr_debug_connect_line (lp, msg);
                        free (sockname);
                        free (peername);
                        ++mp->sessions;                             /* count the new session */

                        if (lp->destination) {                      /* Virtual Null Modem Cable? */
                            char host[sizeof(msg) - 64];

                            if (sim_parse_addr (lp->destination, host, sizeof(host), NULL, NULL, 0, NULL, address)) {
                                tmxr_msg (newsock, "Rejecting connection from unexpected source\r\n");
                                snprintf (msg, sizeof (msg) -1, "tmxr_poll_conn() - Rejecting line connection from: %s, Expected: %s", address, host);
                                tmxr_debug_connect_line (lp, msg);
                                sim_close_sock (newsock);
                                free (address);
                                continue;                           /* Try for another connection */
                                }
                            if (lp->connecting) {
                                snprintf (msg, sizeof (msg) -1, "tmxr_poll_conn() - aborting outgoing line connection attempt to: %s", lp->destination);
                                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)) {
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291

1292
1293
1294
1295
1296
1297
1298
                break;
            }

    /* Check for needed outgoing connection initiation */

    if (lp->destination && (!lp->sock) && (!lp->connecting) && (!lp->serport) && 
        (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR))) {
        sprintf (msg, "tmxr_poll_conn() - 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 ringing;                                         /* no new connections made */
}








|

|
>







1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
                break;
            }

    /* Check for needed outgoing connection initiation */

    if (lp->destination && (!lp->sock) && (!lp->connecting) && (!lp->serport) && 
        (!lp->modem_control || (lp->modembits & TMXR_MDM_DTR))) {
        snprintf (msg, sizeof (msg) - 1, "tmxr_poll_conn() - 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 ringing;                                         /* no new connections made */
}

1354
1355
1356
1357
1358
1359
1360
1361

1362
1363
1364
1365
1366
1367
1368
    if (lp->connecting) {
        sim_close_sock (lp->connecting);
        lp->connecting = 0;
        }
    if ((!lp->modem_control) || (lp->modembits & TMXR_MDM_DTR)) {
        sprintf (msg, "tmxr_reset_ln_ex() - connecting 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->packet ? SIM_SOCK_OPT_NODELAY : 0));

        }
    }
tmxr_init_line (lp);                                /* initialize line state */
return SCPE_OK;
}

t_stat tmxr_close_ln (TMLN *lp)







|
>







1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
    if (lp->connecting) {
        sim_close_sock (lp->connecting);
        lp->connecting = 0;
        }
    if ((!lp->modem_control) || (lp->modembits & TMXR_MDM_DTR)) {
        sprintf (msg, "tmxr_reset_ln_ex() - connecting 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->packet ? SIM_SOCK_OPT_NODELAY : 0));
        }
    }
tmxr_init_line (lp);                                /* initialize line state */
return SCPE_OK;
}

t_stat tmxr_close_ln (TMLN *lp)
1644
1645
1646
1647
1648
1649
1650
1651

1652
1653
1654
1655
1656
1657
1658
            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->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? */







|
>







1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
            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->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? */
2740
2741
2742
2743
2744
2745
2746
2747

2748

2749
2750
2751
2752
2753
2754
2755
                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);







|
>
|
>







2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
                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 {
                        if (*tptr)
                            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);
2797
2798
2799
2800
2801
2802
2803
2804

2805
2806
2807
2808
2809
2810
2811
                        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) {







|
>







2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
                        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) {
2949
2950
2951
2952
2953
2954
2955
2956

2957
2958
2959
2960
2961
2962
2963
                        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;







|
>







2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
                        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;
3064
3065
3066
3067
3068
3069
3070
3071

3072
3073
3074
3075
3076
3077
3078
                    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));







|
>







3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
                    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));
4398
4399
4400
4401
4402
4403
4404



4405
4406
4407
4408
4409
4410
4411
    fprintf (st, "ports.\n\n");
    if (modem_control) {
        fprintf (st, "The %s device is a full modem control device and therefore is capable of\n", dptr->name);
        fprintf (st, "passing port configuration information and modem signals.\n");
        }
    fprintf (st, "A Telnet listening port can be configured with:\n\n");
    fprintf (st, "   sim> ATTACH %s {interface:}port\n\n", dptr->name);



    fprintf (st, "Line buffering can be enabled for the %s device with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Buffer{=bufsize}\n\n", dptr->name);
    fprintf (st, "Line buffering can be disabled for the %s device with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s NoBuffer\n\n", dptr->name);
    fprintf (st, "The default buffer size is 32k bytes, the max buffer size is 1024k bytes\n\n");
    fprintf (st, "The outbound traffic the %s device can be logged to a file with:\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Log=LogFileName\n\n", dptr->name);







>
>
>







4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
    fprintf (st, "ports.\n\n");
    if (modem_control) {
        fprintf (st, "The %s device is a full modem control device and therefore is capable of\n", dptr->name);
        fprintf (st, "passing port configuration information and modem signals.\n");
        }
    fprintf (st, "A Telnet listening port can be configured with:\n\n");
    fprintf (st, "   sim> ATTACH %s {interface:}port\n\n", dptr->name);
    fprintf (st, "The -U switch can be specified on the attach command that specifies\n");
    fprintf (st, "a listening port.  This will allow a listening port to be reused if\n");
    fprintf (st, "some prior connections haven't completely shutdown.\n\n");
    fprintf (st, "Line buffering can be enabled for the %s device with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Buffer{=bufsize}\n\n", dptr->name);
    fprintf (st, "Line buffering can be disabled for the %s device with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s NoBuffer\n\n", dptr->name);
    fprintf (st, "The default buffer size is 32k bytes, the max buffer size is 1024k bytes\n\n");
    fprintf (st, "The outbound traffic the %s device can be logged to a file with:\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Log=LogFileName\n\n", dptr->name);
4424
4425
4426
4427
4428
4429
4430



4431
4432
4433
4434
4435
4436
4437
        }
    fprintf (st, "Modem Control signalling behaviors can be enabled/disabled on a specific\n");
    fprintf (st, "multiplexer line with:\n\n");
    fprintf (st, "   sim> ATTACH %s Line=n,Modem\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Line=n,NoModem\n\n", dptr->name);
    fprintf (st, "A Telnet listening port can be configured with:\n\n");
    fprintf (st, "   sim> ATTACH %s {interface:}port\n\n", dptr->name);



    if (mux)
        fprintf (st, "Line buffering for all %d lines on the %s device can be configured with:\n\n", mux->lines, dptr->name);
    else
        fprintf (st, "Line buffering for all lines on the %s device can be configured with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Buffer{=bufsize}\n\n", dptr->name);
    if (mux)
        fprintf (st, "Line buffering for all %d lines on the %s device can be disabled with:\n\n", mux->lines, dptr->name);







>
>
>







4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
        }
    fprintf (st, "Modem Control signalling behaviors can be enabled/disabled on a specific\n");
    fprintf (st, "multiplexer line with:\n\n");
    fprintf (st, "   sim> ATTACH %s Line=n,Modem\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Line=n,NoModem\n\n", dptr->name);
    fprintf (st, "A Telnet listening port can be configured with:\n\n");
    fprintf (st, "   sim> ATTACH %s {interface:}port\n\n", dptr->name);
    fprintf (st, "The -U switch can be specified on the attach command that specifies\n");
    fprintf (st, "a listening port.  This will allow a listening port to be reused if\n");
    fprintf (st, "some prior connections haven't completely shutdown.\n\n");
    if (mux)
        fprintf (st, "Line buffering for all %d lines on the %s device can be configured with:\n\n", mux->lines, dptr->name);
    else
        fprintf (st, "Line buffering for all lines on the %s device can be configured with:\n\n", dptr->name);
    fprintf (st, "   sim> ATTACH %s Buffer{=bufsize}\n\n", dptr->name);
    if (mux)
        fprintf (st, "Line buffering for all %d lines on the %s device can be disabled with:\n\n", mux->lines, dptr->name);
4604
4605
4606
4607
4608
4609
4610
4611

4612


4613
4614
4615
4616
4617
4618
4619
4620
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++)
        if (mptr->valid == &tmxr_dscln) {
            fprintf (st, "A specific line on the %s device can be disconnected with:\n\n", dptr->name);
            fprintf (st, "   sim> SET %s %s=n\n\n", dptr->name, mptr->mstring);
            fprintf (st, "This will cause a telnet connection to be closed, but a serial port will\n");
            fprintf (st, "normally have DTR dropped for 500ms and raised again (thus hanging up a\n");
            fprintf (st, "modem on that serial port).\n\n");
            fprintf (st, "A line which is connected to a serial port can be manually closed by\n");

            fprintf (st, "adding the -C switch to a %s command.\n\n", mptr->mstring);


            fprintf (st, "   sim> SET -C %s %s=n\n\n", dptr->name, mptr->mstring);
            }
    }
return SCPE_OK;
}

/* Stub examine and deposit */








|
>
|
>
>
|







4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
    for (mptr = dptr->modifiers; mptr->mask != 0; mptr++)
        if (mptr->valid == &tmxr_dscln) {
            fprintf (st, "A specific line on the %s device can be disconnected with:\n\n", dptr->name);
            fprintf (st, "   sim> SET %s %s=n\n\n", dptr->name, mptr->mstring);
            fprintf (st, "This will cause a telnet connection to be closed, but a serial port will\n");
            fprintf (st, "normally have DTR dropped for 500ms and raised again (thus hanging up a\n");
            fprintf (st, "modem on that serial port).\n\n");
            fprintf (st, "Any lines connected to serial port can be manually closed by unplugging\n");
            fprintf (st, "the serial cable from the host computer.  Dynamically adding or removing\n");
            fprintf (st, "a serial port from a mux while the simulated operating system is running\n");
            fprintf (st, "is guaranteed to have an inconsistent state between the running OS and\n");
            fprintf (st, "the simulated port state.  Restart the simulator without the serial port\n");
            fprintf (st, "attached.\n\n");
            }
    }
return SCPE_OK;
}

/* Stub examine and deposit */

4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
    2. If "val" is non-zero, then "cptr" points to a string that is parsed for
       an explicit line number, and "uptr" is ignored.  For example, if "cptr"
       points to the string "3", then line 3 will be disconnected.

   If the line was connected to a tcp session, the socket associated with the
   line will be closed.  If the line was connected to a serial port, the port
   will NOT be closed, but DTR will be dropped.  After a 500ms delay DTR will
   be raised again.  If the sim_switches -C flag is set, then a serial port 
   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)







|
<







4855
4856
4857
4858
4859
4860
4861
4862

4863
4864
4865
4866
4867
4868
4869
    2. If "val" is non-zero, then "cptr" points to a string that is parsed for
       an explicit line number, and "uptr" is ignored.  For example, if "cptr"
       points to the string "3", then line 3 will be disconnected.

   If the line was connected to a tcp session, the socket associated with the
   line will be closed.  If the line was connected to a serial port, the port
   will NOT be closed, but DTR will be dropped.  After a 500ms delay DTR will
   be raised again.


   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)
4868
4869
4870
4871
4872
4873
4874
4875
4876



4877
4878
4879
4880
4881
4882
4883

if (lp == NULL)                                                 /* bad line number? */
    return status;                                              /* report it */

if ((lp->sock) || (lp->serport)) {                              /* connection active? */
    if (!lp->notelnet)
        tmxr_linemsg (lp, "\r\nOperator disconnected line\r\n\n");/* report closure */
    if (lp->serport && (sim_switches & SWMASK ('C')))
        return tmxr_detach_ln (lp);



    return tmxr_reset_ln_ex (lp, FALSE);                        /* drop the line */
    }

return SCPE_OK;
}









|
|
>
>
>







4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899

if (lp == NULL)                                                 /* bad line number? */
    return status;                                              /* report it */

if ((lp->sock) || (lp->serport)) {                              /* connection active? */
    if (!lp->notelnet)
        tmxr_linemsg (lp, "\r\nOperator disconnected line\r\n\n");/* report closure */
    if (lp->serport && (sim_switches & SWMASK ('C'))) {
        sim_messagef (SCPE_OK, "If you really feel the need to disconnect this serial port, unplug the cable\n");
        sim_messagef (SCPE_OK, "from the serial port on your system.  Alternatively, you should restart the\n");
        sim_messagef (SCPE_OK, "simulator without attaching the serial port in your configuration.\n");
        }
    return tmxr_reset_ln_ex (lp, FALSE);                        /* drop the line */
    }

return SCPE_OK;
}


5422
5423
5424
5425
5426
5427
5428























































            sim_debug (dbits, dptr, " rxnexttime=%.0f (%.0f usecs)", lp->rxnexttime, ((lp->rxnexttime - sim_gtime ()) / sim_timer_inst_per_sec ()) * 1000000.0);
        if (lp->txnexttime != 0.0)
            sim_debug (dbits, dptr, " txnexttime=%.0f (%.0f usecs)", lp->txnexttime, ((lp->txnexttime - sim_gtime ()) / sim_timer_inst_per_sec ()) * 1000000.0);
        sim_debug (dbits, dptr, "\n");
        }
    }
}






























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
            sim_debug (dbits, dptr, " rxnexttime=%.0f (%.0f usecs)", lp->rxnexttime, ((lp->rxnexttime - sim_gtime ()) / sim_timer_inst_per_sec ()) * 1000000.0);
        if (lp->txnexttime != 0.0)
            sim_debug (dbits, dptr, " txnexttime=%.0f (%.0f usecs)", lp->txnexttime, ((lp->txnexttime - sim_gtime ()) / sim_timer_inst_per_sec ()) * 1000000.0);
        sim_debug (dbits, dptr, "\n");
        }
    }
}

/* Testing of sim_sock and tmxr */

#include <setjmp.h>

t_stat tmxr_sock_test (DEVICE *dptr)
{
char cmd[CBUFSIZE], host[CBUFSIZE], port[CBUFSIZE];
int line;
TMXR *tmxr;
TMLN *ln;
int32 tmp1, tmp2;
t_stat stat = SCPE_OK;
SOCKET sock_mux = INVALID_SOCKET;
SOCKET sock_line = INVALID_SOCKET;
SIM_TEST_INIT;

sim_printf ("Testing %s:\n", dptr->name);
SIM_TEST(sim_parse_addr ("", NULL, 0, "localhost", NULL, 0, "1234", NULL) != -1);
SIM_TEST(sim_parse_addr ("", host, 0, "localhost", NULL, 0, "1234", NULL) != -1);
SIM_TEST(sim_parse_addr ("", host, sizeof(host), "localhost", port, 0, "1234", NULL) != -1);
SIM_TEST((sim_parse_addr ("", host, sizeof(host), "localhost", port, sizeof(port), "1234", NULL) == -1) || (strcmp(host, "localhost")) || (strcmp(port,"1234")));
SIM_TEST((sim_parse_addr ("localhost:6666", host, sizeof(host), "localhost", port, sizeof(port), "1234", NULL) == -1) || (strcmp(host, "localhost")) || (strcmp(port,"6666")));
SIM_TEST(sim_parse_addr ("localhost:66666", host, sizeof(host), "localhost", port, sizeof(port), "1234", NULL) != -1);
SIM_TEST((sim_parse_addr ("localhost:telnet", host, sizeof(host), "localhost", port, sizeof(port), "1234", NULL) == -1) || (strcmp(host, "localhost")) || (strcmp(port,"telnet")));
SIM_TEST((sim_parse_addr ("telnet", host, sizeof(host), "localhost", port, sizeof(port), "1234", NULL) == -1) || (strcmp(host, "localhost")) || (strcmp(port,"telnet")));
dptr->dctrl = 0xFFFFFFFF;
dptr->dctrl &= ~TMXR_DBG_TRC;
sprintf (cmd, "%s -u localhost:65500;notelnet", dptr->name);
SIM_TEST(attach_cmd (0, cmd));
tmxr = (TMXR *)dptr->units->tmxr;
ln = &tmxr->ldsc[tmxr->lines - 1];
SIM_TEST(detach_cmd (0, dptr->name));
if (tmxr->lines > 1) {
    tmxr->modem_control = FALSE;
    for (line=0; line < tmxr->lines; line++)
        tmxr->ldsc[line].modem_control = FALSE;
    snprintf (cmd + strlen (cmd), sizeof (cmd) - strlen (cmd), ",Line=%d,localhost:65501", tmxr->lines - 1);
    snprintf (cmd + strlen (cmd), sizeof (cmd) - strlen (cmd), ",Line=0,connect=localhost:65500");
    SIM_TEST(attach_cmd (0, cmd));
    sock_line = sim_connect_sock_ex (NULL, "localhost:65501", NULL, NULL, 0);
    sim_os_ms_sleep (100);
    SIM_TEST((((tmp1 = tmxr_poll_conn (tmxr)) == tmxr->lines - 1) || (tmp1 == 1)) ? SCPE_OK : SCPE_IERR);
    sock_mux = sim_connect_sock ("", "localhost", "65500");
    sim_os_ms_sleep (100);
    SIM_TEST(((tmp2 = tmxr_poll_conn (tmxr)) == 0) || (tmp2 == 2) ? SCPE_OK : SCPE_IERR);
    show_cmd (0, "MUX");
    sim_close_sock (sock_mux);
    sock_mux = INVALID_SOCKET;
    sim_close_sock (sock_line);
    sock_line = INVALID_SOCKET;
    SIM_TEST(detach_cmd (0, dptr->name));
    }
return stat;
}

Changes to src/SIMH/sim_tmxr.h.

303
304
305
306
307
308
309

310
311
312
313
314
315
316
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_locate_line (const char *dev_line, TMLN **lp);
const char *tmxr_send_line_name (const SEND *snd);
const char *tmxr_expect_line_name (const 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)







>







303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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_locate_line (const char *dev_line, TMLN **lp);
const char *tmxr_send_line_name (const SEND *snd);
const char *tmxr_expect_line_name (const EXPECT *exp);
t_stat tmxr_startup (void);
t_stat tmxr_shutdown (void);
t_stat tmxr_sock_test (DEVICE *dptr);
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)

Changes to src/SIMH/sim_video.c.

33
34
35
36
37
38
39




40
41
42
43
44
45



































46
47
48
49
50
51
52
t_bool vid_active = FALSE;
int32 vid_cursor_x;
int32 vid_cursor_y;
t_bool vid_mouse_b1 = FALSE;
t_bool vid_mouse_b2 = FALSE;
t_bool vid_mouse_b3 = FALSE;
static VID_QUIT_CALLBACK vid_quit_callback = NULL;





t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback)
{
vid_quit_callback = callback;
return SCPE_OK;
}




































t_stat vid_show (FILE* st, DEVICE *dptr,  UNIT* uptr, int32 val, CONST char* desc)
{
return vid_show_video (st, uptr, val, desc);
}

#if defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)







>
>
>
>






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







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
t_bool vid_active = FALSE;
int32 vid_cursor_x;
int32 vid_cursor_y;
t_bool vid_mouse_b1 = FALSE;
t_bool vid_mouse_b2 = FALSE;
t_bool vid_mouse_b3 = FALSE;
static VID_QUIT_CALLBACK vid_quit_callback = NULL;
static VID_GAMEPAD_CALLBACK motion_callback[10];
static VID_GAMEPAD_CALLBACK button_callback[10];
static int vid_gamepad_inited = 0;
static int vid_gamepad_ok = 0; /* Or else just joysticks. */

t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback)
{
vid_quit_callback = callback;
return SCPE_OK;
}

static t_stat register_callback (void **array, int n, void *callback)
{
    int i, j = -1;

    if (!vid_gamepad_inited) {
        return SCPE_NOATT;
        }

    for (i = 0; i < n; i++) {
        if (array[i] == callback)
            return SCPE_ALATT;
        if (array[i] == NULL)
            j = i;
        }

    if (j != -1) {
        array[j] = callback;
        return SCPE_OK;
        }

    return SCPE_NXM;
}

t_stat vid_register_gamepad_motion_callback (VID_GAMEPAD_CALLBACK callback)
{
    int n = sizeof (motion_callback) / sizeof (callback);
    return register_callback ((void **)motion_callback, n, (void *)callback);
}

t_stat vid_register_gamepad_button_callback (VID_GAMEPAD_CALLBACK callback)
{
    int n = sizeof (button_callback) / sizeof (callback);
    return register_callback ((void **)button_callback, n, (void *)callback);
}

t_stat vid_show (FILE* st, DEVICE *dptr,  UNIT* uptr, int32 val, CONST char* desc)
{
return vid_show_video (st, uptr, val, desc);
}

#if defined(USE_SIM_VIDEO) && defined(HAVE_LIBSDL)
100
101
102
103
104
105
106

107
108
109
110
111
112
113
 * SDL_SavePNG -- libpng-based SDL_Surface writer.
 *
 * This code is free software, available under zlib/libpng license.
 * http://www.libpng.org/pub/png/src/libpng-LICENSE.txt
 */
#include <SDL.h>
#include <png.h>


#define SUCCESS 0
#define ERROR -1

#define USE_ROW_POINTERS

#if SDL_BYTEORDER == SDL_BIG_ENDIAN







>







139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
 * SDL_SavePNG -- libpng-based SDL_Surface writer.
 *
 * This code is free software, available under zlib/libpng license.
 * http://www.libpng.org/pub/png/src/libpng-LICENSE.txt
 */
#include <SDL.h>
#include <png.h>
#include <zlib.h>

#define SUCCESS 0
#define ERROR -1

#define USE_ROW_POINTERS

#if SDL_BYTEORDER == SDL_BIG_ENDIAN
504
505
506
507
508
509
510































































511
512
513
514
515
516
517
if (!vid_ready) {
    vid_close ();
    return SCPE_OPENERR;
    }
return SCPE_OK;
}
#endif
































































t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags)
{
if (!vid_active) {
    int wait_count = 0;
    t_stat stat;








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







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
if (!vid_ready) {
    vid_close ();
    return SCPE_OPENERR;
    }
return SCPE_OK;
}
#endif

static t_stat vid_init_controllers (void)
{
    SDL_Joystick *y;
    SDL_version ver;
    int i, n;

    if (vid_gamepad_inited)
        return SCPE_OK;

    /* Chech that the SDL_GameControllerFromInstanceID function is
       available at run time. */
    SDL_GetVersion(&ver);
    vid_gamepad_ok = (ver.major > 2 ||
                      (ver.major == 2 && (ver.minor > 0 || ver.patch >= 4)));

    if (vid_gamepad_ok)
        SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
    else
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);

    if (SDL_JoystickEventState (SDL_ENABLE) < 0) {
        if (vid_gamepad_ok)
            SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
        else
            SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
        return SCPE_IOERR;
        }

    if (vid_gamepad_ok && SDL_GameControllerEventState (SDL_ENABLE) < 0) {
        if (vid_gamepad_ok)
            SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
        else
            SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
        return SCPE_IOERR;
        }

    n = SDL_NumJoysticks();

    for (i = 0; i < n; i++) {
        if (vid_gamepad_ok && SDL_IsGameController (i)) {
            SDL_GameController *x = SDL_GameControllerOpen (i);
            if (x != NULL) {
                sim_debug (SIM_VID_DBG_VIDEO, vid_dev,
                "Game controller: %s\n", SDL_GameControllerNameForIndex(i));
                }
            }
        else {
            y = SDL_JoystickOpen (i);
            if (y != NULL) {
                sim_debug (SIM_VID_DBG_VIDEO, vid_dev,
                "Joystick: %s\n", SDL_JoystickNameForIndex(i));
                sim_debug (SIM_VID_DBG_VIDEO, vid_dev,
                "Number of axes: %d, buttons: %d\n",
                SDL_JoystickNumAxes(y),
                SDL_JoystickNumButtons(y));
                }
            }
        }

    vid_gamepad_inited = 1;
    return SCPE_OK;
}

t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags)
{
if (!vid_active) {
    int wait_count = 0;
    t_stat stat;

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
    vid_mouse_events.head = 0;
    vid_mouse_events.tail = 0;
    vid_mouse_events.count = 0;
    vid_mouse_events.sem = SDL_CreateSemaphore (1);

    vid_dev = dptr;




    stat = vid_create_window ();
    if (stat != SCPE_OK)
        return stat;






    sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_open() - Success\n");
    }
return SCPE_OK;
}

t_stat vid_close (void)
{
if (vid_active) {
    SDL_Event user_event;
    int status;









    vid_active = FALSE;
    if (vid_ready) {
        sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_close()\n");
        user_event.type = SDL_USEREVENT;
        user_event.user.code = EVENT_CLOSE;
        user_event.user.data1 = NULL;
        user_event.user.data2 = NULL;







>
>
>



>
>
>
>
>












>
>
>
>
>
>
>
>







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
    vid_mouse_events.head = 0;
    vid_mouse_events.tail = 0;
    vid_mouse_events.count = 0;
    vid_mouse_events.sem = SDL_CreateSemaphore (1);

    vid_dev = dptr;

    memset (motion_callback, 0, sizeof motion_callback);
    memset (button_callback, 0, sizeof button_callback);

    stat = vid_create_window ();
    if (stat != SCPE_OK)
        return stat;

    if (vid_init_controllers () != SCPE_OK) {
        sim_debug (SIM_VID_DBG_VIDEO, vid_dev,
                   "vid_open() - Failed initializing game controllers\n");
        }

    sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_open() - Success\n");
    }
return SCPE_OK;
}

t_stat vid_close (void)
{
if (vid_active) {
    SDL_Event user_event;
    int status;

    vid_gamepad_inited = 0;
    memset (motion_callback, 0, sizeof motion_callback);
    memset (button_callback, 0, sizeof button_callback);
    if (vid_gamepad_ok)
        SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
    else
        SDL_QuitSubSystem(SDL_INIT_JOYSTICK);

    vid_active = FALSE;
    if (vid_ready) {
        sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE, vid_dev, "vid_close()\n");
        user_event.type = SDL_USEREVENT;
        user_event.user.code = EVENT_CLOSE;
        user_event.user.data1 = NULL;
        user_event.user.data2 = NULL;
1143
1144
1145
1146
1147
1148
1149























































1150
1151
1152
1153
1154
1155
1156
    case SDLK_MENU:
        return SIM_KEY_MENU;

    default:
        return SIM_KEY_UNKNOWN;
        }
}
























































void vid_key (SDL_KeyboardEvent *event)
{
SIM_KEY_EVENT ev;

if (vid_mouse_captured) {
    static const Uint8 *KeyStates = NULL;







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







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
    case SDLK_MENU:
        return SIM_KEY_MENU;

    default:
        return SIM_KEY_UNKNOWN;
        }
}

void vid_joy_motion (SDL_JoyAxisEvent *event)
{
    int n = sizeof motion_callback / sizeof (VID_GAMEPAD_CALLBACK);
    int i;

    for (i = 0; i < n; i++) {
        if (motion_callback[i]) {
            motion_callback[i](event->which, event->axis, event->value);
            }
        }
}

void vid_joy_button (SDL_JoyButtonEvent *event)
{
    int n = sizeof button_callback / sizeof (VID_GAMEPAD_CALLBACK);
    int i;

    for (i = 0; i < n; i++) {
        if (button_callback[i]) {
            button_callback[i](event->which, event->button, event->state);
            }
        }
}

void vid_controller_motion (SDL_ControllerAxisEvent *event)
{
    SDL_JoyAxisEvent e;
    e.which = event->which;
    e.axis = event->axis;
    e.value = event->value;
    vid_joy_motion (&e);
}

void vid_controller_button (SDL_ControllerButtonEvent *event)
{
    /* SDL_GameControllerFromInstanceID is only available from SDL
       version 2.0.4, so check the version at compile time.  The
       version is also checked at run time. */
#if (SDL_MAJOR_VERSION > 2) || (SDL_MAJOR_VERSION == 2 && \
    (SDL_MINOR_VERSION > 0) || (SDL_PATCHLEVEL >= 4))

    SDL_JoyButtonEvent e;
    SDL_GameControllerButtonBind b;
    SDL_GameController *c;
    SDL_GameControllerButton button = (SDL_GameControllerButton)event->button;

    c = SDL_GameControllerFromInstanceID (event->which);
    b = SDL_GameControllerGetBindForButton (c, button);
    e.which = event->which;
    e.button = b.value.button;
    e.state = event->state;
    vid_joy_button (&e);
#endif
}

void vid_key (SDL_KeyboardEvent *event)
{
SIM_KEY_EVENT ev;

if (vid_mouse_captured) {
    static const Uint8 *KeyStates = NULL;
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
while (vid_active) {
    int status = SDL_WaitEvent (&event);
    if (status == 1) {
        switch (event.type) {

            case SDL_KEYDOWN:
            case SDL_KEYUP:
                vid_key ((SDL_KeyboardEvent*)&event);
                break;

            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
                vid_mouse_button ((SDL_MouseButtonEvent*)&event);
                break;

            case SDL_MOUSEMOTION:
                vid_mouse_move ((SDL_MouseMotionEvent*)&event);
                break;



















#if SDL_MAJOR_VERSION != 1
            case SDL_WINDOWEVENT:
                if (event.window.windowID == vid_windowID) {
                    sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE|SIM_VID_DBG_CURSOR, vid_dev, "vid_thread() - Window Event: %d - %s\n", event.window.event, windoweventtypes[event.window.event]);
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_ENTER:
                             if (vid_flags & SIM_VID_INPUTCAPTURED)







|




|



|

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







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
while (vid_active) {
    int status = SDL_WaitEvent (&event);
    if (status == 1) {
        switch (event.type) {

            case SDL_KEYDOWN:
            case SDL_KEYUP:
                vid_key (&event.key);
                break;

            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP:
                vid_mouse_button (&event.button);
                break;

            case SDL_MOUSEMOTION:
                vid_mouse_move (&event.motion);
                break;

            case SDL_JOYAXISMOTION:
                vid_joy_motion (&event.jaxis);
                break;

            case SDL_JOYBUTTONUP:
            case SDL_JOYBUTTONDOWN:
                vid_joy_button (&event.jbutton);
                break;

            case SDL_CONTROLLERAXISMOTION:
                vid_controller_motion (&event.caxis);
                break;

            case SDL_CONTROLLERBUTTONUP:
            case SDL_CONTROLLERBUTTONDOWN:
                vid_controller_button (&event.cbutton);
                break;

#if SDL_MAJOR_VERSION != 1
            case SDL_WINDOWEVENT:
                if (event.window.windowID == vid_windowID) {
                    sim_debug (SIM_VID_DBG_VIDEO|SIM_VID_DBG_KEY|SIM_VID_DBG_MOUSE|SIM_VID_DBG_CURSOR, vid_dev, "vid_thread() - Window Event: %d - %s\n", event.window.event, windoweventtypes[event.window.event]);
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_ENTER:
                             if (vid_flags & SIM_VID_INPUTCAPTURED)
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
vid_beep_cleanup ();
SDL_Quit ();
return 0;
}

const char *vid_version(void)
{
static char SDLVersion[80];
SDL_version compiled, running;

#if SDL_MAJOR_VERSION == 1
const SDL_version *ver = SDL_Linked_Version();
running.major = ver->major;
running.minor = ver->minor;
running.patch = ver->patch;
#else
SDL_GetVersion(&running);
#endif
SDL_VERSION(&compiled);


if ((compiled.major == running.major) &&
    (compiled.minor == running.minor) &&
    (compiled.patch == running.patch))
    sprintf(SDLVersion, "SDL Version %d.%d.%d", 
                        compiled.major, compiled.minor, compiled.patch);
else
    sprintf(SDLVersion, "SDL Version (Compiled: %d.%d.%d, Runtime: %d.%d.%d)", 
                        compiled.major, compiled.minor, compiled.patch,
                        running.major, running.minor, running.patch);






















return (const char *)SDLVersion;
}

t_stat vid_set_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc)
{
return SCPE_NOFNC;
}







|












>



|


|


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







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
vid_beep_cleanup ();
SDL_Quit ();
return 0;
}

const char *vid_version(void)
{
static char SDLVersion[160];
SDL_version compiled, running;

#if SDL_MAJOR_VERSION == 1
const SDL_version *ver = SDL_Linked_Version();
running.major = ver->major;
running.minor = ver->minor;
running.patch = ver->patch;
#else
SDL_GetVersion(&running);
#endif
SDL_VERSION(&compiled);

SDLVersion[sizeof (SDLVersion) - 1] = '\0';
if ((compiled.major == running.major) &&
    (compiled.minor == running.minor) &&
    (compiled.patch == running.patch))
    snprintf(SDLVersion, sizeof (SDLVersion) - 1, "SDL Version %d.%d.%d", 
                        compiled.major, compiled.minor, compiled.patch);
else
    snprintf(SDLVersion, sizeof (SDLVersion) - 1, "SDL Version (Compiled: %d.%d.%d, Runtime: %d.%d.%d)", 
                        compiled.major, compiled.minor, compiled.patch,
                        running.major, running.minor, running.patch);
#if defined (HAVE_LIBPNG)
if (1) {
    png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (strcmp (PNG_LIBPNG_VER_STRING, png_get_libpng_ver (png)))
        snprintf(&SDLVersion[strlen (SDLVersion)], sizeof (SDLVersion) - (strlen (SDLVersion) + 1), 
                            ", PNG Version (Compiled: %s, Runtime: %s)", 
                            PNG_LIBPNG_VER_STRING, png_get_libpng_ver (png));
    else
        snprintf(&SDLVersion[strlen (SDLVersion)], sizeof (SDLVersion) - (strlen (SDLVersion) + 1), 
                            ", PNG Version %s", PNG_LIBPNG_VER_STRING);
    png_destroy_read_struct(&png, NULL, NULL);
#if defined (ZLIB_VERSION)
    if (strcmp (ZLIB_VERSION, zlibVersion ()))
        snprintf(&SDLVersion[strlen (SDLVersion)], sizeof (SDLVersion) - (strlen (SDLVersion) + 1), 
                            ", zlib: (Compiled: %s, Runtime: %s)", ZLIB_VERSION, zlibVersion ());
    else
        snprintf(&SDLVersion[strlen (SDLVersion)], sizeof (SDLVersion) - (strlen (SDLVersion) + 1), 
                            ", zlib: %s", ZLIB_VERSION);
#endif
    }
#endif
return (const char *)SDLVersion;
}

t_stat vid_set_release_key (FILE* st, UNIT* uptr, int32 val, CONST void* desc)
{
return SCPE_NOFNC;
}
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
char *fullname = NULL;

if (!vid_active) {
    sim_printf ("No video display is active\n");
    return SCPE_UDIS | SCPE_NOMESSAGE;
    }
fullname = (char *)malloc (strlen(filename) + 5);
if (!filename)
    return SCPE_MEM;
#if SDL_MAJOR_VERSION == 1
#if defined(HAVE_LIBPNG)
if (!match_ext (filename, "bmp")) {
    sprintf (fullname, "%s%s", filename, match_ext (filename, "png") ? "" : ".png");
    stat = SDL_SavePNG(vid_image, fullname);
    }







|







2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
char *fullname = NULL;

if (!vid_active) {
    sim_printf ("No video display is active\n");
    return SCPE_UDIS | SCPE_NOMESSAGE;
    }
fullname = (char *)malloc (strlen(filename) + 5);
if (!fullname)
    return SCPE_MEM;
#if SDL_MAJOR_VERSION == 1
#if defined(HAVE_LIBPNG)
if (!match_ext (filename, "bmp")) {
    sprintf (fullname, "%s%s", filename, match_ext (filename, "png") ? "" : ".png");
    stat = SDL_SavePNG(vid_image, fullname);
    }

Changes to src/SIMH/sim_video.h.

176
177
178
179
180
181
182



183
184
185
186
187
188
189
typedef struct key_event SIM_KEY_EVENT;

t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags);
#define SIM_VID_INPUTCAPTURED       1                       /* Mouse and Keyboard input captured (calling */
                                                            /* code responsible for cursor display in video) */
typedef void (*VID_QUIT_CALLBACK)(void);
t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback);



t_stat vid_close (void);
t_stat vid_poll_kb (SIM_KEY_EVENT *ev);
t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev);
uint32 vid_map_rgb (uint8 r, uint8 g, uint8 b);
void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf);
void vid_beep (void);
void vid_refresh (void);







>
>
>







176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
typedef struct key_event SIM_KEY_EVENT;

t_stat vid_open (DEVICE *dptr, const char *title, uint32 width, uint32 height, int flags);
#define SIM_VID_INPUTCAPTURED       1                       /* Mouse and Keyboard input captured (calling */
                                                            /* code responsible for cursor display in video) */
typedef void (*VID_QUIT_CALLBACK)(void);
t_stat vid_register_quit_callback (VID_QUIT_CALLBACK callback);
typedef void (*VID_GAMEPAD_CALLBACK)(int, int, int);
t_stat vid_register_gamepad_motion_callback (VID_GAMEPAD_CALLBACK);
t_stat vid_register_gamepad_button_callback (VID_GAMEPAD_CALLBACK);
t_stat vid_close (void);
t_stat vid_poll_kb (SIM_KEY_EVENT *ev);
t_stat vid_poll_mouse (SIM_MOUSE_EVENT *ev);
uint32 vid_map_rgb (uint8 r, uint8 g, uint8 b);
void vid_draw (int32 x, int32 y, int32 w, int32 h, uint32 *buf);
void vid_beep (void);
void vid_refresh (void);