root/src/dps8/dps8_cpu.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. cpu_show_config
  2. cpu_set_config
  3. cpu_show_nunits
  4. cpu_set_nunits
  5. cpu_show_kips
  6. cpu_set_kips
  7. cpu_show_stall
  8. cpu_set_stall
  9. setCPUConfigL68
  10. setCPUConfigDPS8M
  11. cycle_str
  12. set_cpu_cycle
  13. set_cpu_idx
  14. cpu_reset_unit_idx
  15. simh_cpu_reset_and_clear_unit
  16. simh_cpu_reset_unit
  17. str_SDW0
  18. cpu_boot
  19. scu_phys_bank
  20. setup_scbank_map_tandd
  21. sc_port_for_addr
  22. tandd_scu_for_addr
  23. consume_parity_bits
  24. ia_priority
  25. sdpap_store_tandd
  26. sc_command_parity
  27. tanddUpdateAnyOn
  28. fullModelUpdate
  29. bad_parity_mark
  30. bad_parity_clear
  31. bad_parity_marked
  32. bad_parity_read
  33. tandd_read_hook
  34. tandd_read_lock_hook
  35. tandd_write_hook
  36. sc_map_addr_tandd
  37. sc_lockout_wait
  38. sc_fine_map
  39. sc_fine_interlaced
  40. sc_fine_unmap
  41. tandd_set_nea_port
  42. setup_scbank_map
  43. tandd_io_mode
  44. lookup_cpu_mem_map
  45. get_serial_number
  46. do_stats
  47. ev_poll_cb
  48. cpu_init
  49. cpu_stop_poll_timer
  50. cpu_reset
  51. sim_cpu_reset
  52. cpu_ex
  53. cpu_dep
  54. get_highest_intr
  55. disDiagEnabled
  56. disDiagEnter
  57. disDiagInterruptSet
  58. disDiagWake
  59. sample_interrupts
  60. simh_hooks
  61. panel_process_event
  62. sim_instr
  63. cpu_thread_main
  64. do_LUF_fault
  65. set_temporary_absolute_mode
  66. clear_temporary_absolute_mode
  67. becomeClockMaster
  68. giveupClockMaster
  69. tanddTRTick
  70. tanddLufCheck
  71. sim_instr_loop
  72. sim_instr_fast
  73. sim_instr_full
  74. sim_instr_copy
  75. threadz_sim_instr
  76. operand_size
  77. readOperandRead
  78. readOperandRMW
  79. write_operand
  80. set_mem_watch
  81. nem_check
  82. cpu_watch_read
  83. core_read_
  84. core_read
  85. core_read_fast
  86. core_read_lock
  87. core_write_
  88. core_write
  89. core_write_fast
  90. core_write_unlock
  91. core_unlock_all
  92. core_write_zone
  93. core_read2
  94. core_write2
  95. decode_instruction
  96. is_priv_mode
  97. get_bar_mode
  98. get_addr_mode
  99. set_addr_mode
  100. get_BAR_address
  101. add_history
  102. add_history_force
  103. add_dps8m_CU_history
  104. add_dps8m_DU_OU_history
  105. add_dps8m_APU_history
  106. add_dps8m_EAPU_history
  107. add_l68_CU_history_entry
  108. add_l68_CU_history
  109. add_l68_CU_fetch_history
  110. add_l68_DU_history
  111. add_l68_OU_history
  112. add_l68_APU_history
  113. get_dbg_verb
  114. dps8_sim_debug
  115. setupPROM
  116. cpuStats
  117. perfTest

   1 /*
   2  * vim: filetype=c:tabstop=4:ai:expandtab
   3  * SPDX-License-Identifier: ICU
   4  * SPDX-License-Identifier: Multics
   5  * scspell-id: 6e07fe19-f62d-11ec-86f2-80ee73e9b8e7
   6  *
   7  * ---------------------------------------------------------------------------
   8  *
   9  * Copyright (c) 2007-2013 Michael Mondy
  10  * Copyright (c) 2012-2016 Harry Reed
  11  * Copyright (c) 2013-2023 Charles Anthony
  12  * Copyright (c) 2017 Michal Tomek
  13  * Copyright (c) 2026 Eric Swenson
  14  * Copyright (c) 2021-2026 Jeffrey H. Johnson
  15  * Copyright (c) 2021-2026 The DPS8M Development Team
  16  *
  17  * This software is made available under the terms of the ICU License.
  18  * See the LICENSE.md file at the top-level directory of this distribution.
  19  *
  20  * ---------------------------------------------------------------------------
  21  *
  22  * This source file may contain code comments that adapt, include, and/or
  23  * incorporate Multics program code and/or documentation distributed under
  24  * the Multics License.  In the event of any discrepancy between code
  25  * comments herein and the original Multics materials, the original Multics
  26  * materials should be considered authoritative unless otherwise noted.
  27  * For more details and historical background, see the LICENSE.md file at
  28  * the top-level directory of this distribution.
  29  *
  30  * ---------------------------------------------------------------------------
  31  */
  32 
  33 #include <stdio.h>
  34 #include <unistd.h>
  35 #include <ctype.h>
  36 
  37 #if !defined(__MINGW64__) && !defined(__MINGW32__) && !defined(CROSS_MINGW64) && !defined(CROSS_MINGW32)
  38 # include <sys/mman.h>
  39 #endif
  40 
  41 #include "dps8.h"
  42 #include "dps8_sys.h"
  43 #include "dps8_iom.h"
  44 #include "dps8_cable.h"
  45 #include "dps8_cpu.h"
  46 #include "dps8_rt.h"
  47 #include "dps8_priv.h"
  48 #include "dps8_addrmods.h"
  49 #include "dps8_faults.h"
  50 #include "dps8_scu.h"
  51 #include "dps8_append.h"
  52 #include "dps8_ins.h"
  53 #include "dps8_state.h"
  54 #include "dps8_math.h"
  55 #include "dps8_iefp.h"
  56 #include "dps8_console.h"
  57 #include "dps8_fnp2.h"
  58 #include "dps8_socket_dev.h"
  59 #include "dps8_crdrdr.h"
  60 #include "dps8_absi.h"
  61 #include "dps8_mgp.h"
  62 #include "dps8_net.h"
  63 #include "dps8_utils.h"
  64 #include "dps8_memalign.h"
  65 #include "dps8_cache.h"
  66 
  67 #if defined(M_SHARED)
  68 # include "shm.h"
  69 #endif
  70 
  71 #include "dps8_opcodetable.h"
  72 #include "../simh/sim_defs.h"
  73 #include "../simh/sim_os_mem.h"
  74 
  75 #if defined(THREADZ) || defined(LOCKLESS)
  76 # include "threadz.h"
  77 __thread uint current_running_cpu_idx;
  78 #endif
  79 
  80 #include "ver.h"
  81 
  82 #if defined(_AIX) && !defined(__PASE__)
  83 # include <pthread.h>
  84 # include <sys/resource.h>
  85 #endif
  86 
  87 #if defined(NO_LOCALE)
  88 # define xstrerror_l strerror
  89 #endif
  90 
  91 #define DBG_CTR cpu.cycleCnt
  92 
  93 #define ASSUME0 0
  94 
  95 #define FREE(p) do  \
  96   {                 \
  97     free((p));      \
  98     (p) = NULL;     \
  99   } while(0)
 100 
 101 // CPU data structures
 102 
 103 static UNIT cpu_unit [N_CPU_UNITS_MAX] = {
 104 #if defined(NO_C_ELLIPSIS)
 105   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 106   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 107   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 108   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 109   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 110   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 111   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL },
 112   { UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL }
 113 #else
 114   [0 ... N_CPU_UNITS_MAX - 1] = {
 115     UDATA (NULL, UNIT_FIX|UNIT_BINK, MEMSIZE), 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL
 116   }
 117 #endif
 118 };
 119 
 120 #define UNIT_IDX(uptr) ((uptr) - cpu_unit)
 121 
 122 // Assume CPU clock ~ 1MIPS. lockup time is 32 ms
 123 #define LOCKUP_KIPS 1000
 124 static uint64 kips = LOCKUP_KIPS;
 125 // Lockup limit n (0-3 = CMR.luf 2/4/8/16 ms, 4 = 32 ms privileged). In T&D
 126 // mode the lockup is timed in TR decrements (512 kHz: 2 ms = 1024 counts),
 127 // so the TR a page reads after a lockup agrees with it (PM776 08A-08H).
 128 
 129 static uint64 luf_limits[] =
 130   {
 131      2000*LOCKUP_KIPS/1000,
 132      4000*LOCKUP_KIPS/1000,
 133      8000*LOCKUP_KIPS/1000,
 134     16000*LOCKUP_KIPS/1000,
 135     32000*LOCKUP_KIPS/1000
 136   };
 137 
 138 struct stall_point_s stall_points [N_STALL_POINTS];
 139 bool stall_point_active = false;
 140 
 141 #if defined(PANEL68)
 142 static void panel_process_event (void);
 143 #endif /* if defined(PANEL68) */
 144 
 145 static t_stat simh_cpu_reset_and_clear_unit (UNIT * uptr,
 146                                              UNUSED int32 value,
 147                                              UNUSED const char * cptr,
 148                                              UNUSED void * desc);
 149 char * cycle_str (cycles_e cycle);
 150 
 151 static t_stat cpu_show_config (UNUSED FILE * st, UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
 152                                UNUSED int val, UNUSED const void * desc)
 153   {
 154     long cpu_unit_idx = UNIT_IDX (uptr);
 155     if (cpu_unit_idx < 0 || cpu_unit_idx >= N_CPU_UNITS_MAX)
 156       {
 157         sim_warn ("error: Invalid unit number %ld\r\n", (long) cpu_unit_idx);
 158         return SCPE_ARG;
 159       }
 160 
 161 #define PFC_INT8 "%c%c%c%c%c%c%c%c"
 162 
 163 #define PBI_8(i)                     \
 164     ( ((i) & 0x80ll) ? '1' : '0' ),  \
 165     ( ((i) & 0x40ll) ? '1' : '0' ),  \
 166     ( ((i) & 0x20ll) ? '1' : '0' ),  \
 167     ( ((i) & 0x10ll) ? '1' : '0' ),  \
 168     ( ((i) & 0x08ll) ? '1' : '0' ),  \
 169     ( ((i) & 0x04ll) ? '1' : '0' ),  \
 170     ( ((i) & 0x02ll) ? '1' : '0' ),  \
 171     ( ((i) & 0x01ll) ? '1' : '0' )
 172 
 173 #define PFC_INT16 PFC_INT8  PFC_INT8
 174 #define PFC_INT32 PFC_INT16 PFC_INT16
 175 #define PFC_INT64 PFC_INT32 PFC_INT32
 176 
 177 #define PBI_16(i) PBI_8((i)  >>  8), PBI_8(i)
 178 #define PBI_32(i) PBI_16((i) >> 16), PBI_16(i)
 179 #define PBI_64(i) PBI_32((i) >> 32), PBI_32(i)
 180 
 181     char dsbin[66], adbin[34];
 182 
 183     sim_msg ("CPU unit number %ld\r\n", (long) cpu_unit_idx);
 184 
 185     sim_msg ("Fault base:                   %03o(8)\r\n",
 186                 cpus[cpu_unit_idx].switches.FLT_BASE);
 187     sim_msg ("CPU number:                   %01o(8)\r\n",
 188                 cpus[cpu_unit_idx].switches.cpu_num);
 189     sim_msg ("Data switches:                %012llo(8)\r\n",
 190                 (unsigned long long)cpus[cpu_unit_idx].switches.data_switches);
 191     (void)snprintf (dsbin, 65, PFC_INT64,
 192                     PBI_64((unsigned long long)cpus[cpu_unit_idx].switches.data_switches));
 193     sim_msg ("                              %36s(2)\r\n",
 194                 dsbin + strlen(dsbin) - 36);
 195     sim_msg ("Address switches:             %06o(8)\r\n",
 196                 cpus[cpu_unit_idx].switches.addr_switches);
 197     (void)snprintf (adbin, 33, PFC_INT32,
 198                     PBI_32(cpus[cpu_unit_idx].switches.addr_switches));
 199     sim_msg ("                              %18s(2)\r\n",
 200                 adbin + strlen(adbin) - 18);
 201     for (int i = 0; i < (cpus[cpu_unit_idx].tweaks.l68_mode ? N_L68_CPU_PORTS : N_DPS8M_CPU_PORTS); i ++)
 202       {
 203         sim_msg ("Port%c enable:                 %01o(8)\r\n",
 204                     'A' + i, cpus[cpu_unit_idx].switches.enable [i]);
 205         sim_msg ("Port%c init enable:            %01o(8)\r\n",
 206                     'A' + i, cpus[cpu_unit_idx].switches.init_enable [i]);
 207         sim_msg ("Port%c assignment:             %01o(8)\r\n",
 208                     'A' + i, cpus[cpu_unit_idx].switches.assignment [i]);
 209         sim_msg ("Port%c interlace:              %01o(8)\r\n",
 210                     'A' + i, cpus[cpu_unit_idx].switches.interlace [i]);
 211         sim_msg ("Port%c store size:             %01o(8)\r\n",
 212                     'A' + i, cpus[cpu_unit_idx].switches.store_size [i]);
 213       }
 214     sim_msg ("Processor mode:               %s [%o]\r\n",
 215                 cpus[cpu_unit_idx].switches.procMode == \
 216                     procModeMultics ? "Multics" : cpus[cpu_unit_idx].switches.procMode == procModeGCOS ? "GCOS" : "???",
 217                 cpus[cpu_unit_idx].switches.procMode);
 218     sim_msg ("8K Cache:                     %s\r\n",
 219                 cpus[cpu_unit_idx].switches.enable_cache ? "Enabled" : "Disabled");
 220     sim_msg ("SDWAM:                        %s\r\n",
 221                 cpus[cpu_unit_idx].switches.sdwam_enable ? "Enabled" : "Disabled");
 222     sim_msg ("PTWAM:                        %s\r\n",
 223                 cpus[cpu_unit_idx].switches.ptwam_enable ? "Enabled" : "Disabled");
 224 
 225     sim_msg ("Processor speed:              %02o(8)\r\n",
 226                 cpus[cpu_unit_idx].options.proc_speed);
 227     sim_msg ("DIS enable:                   %01o(8)\r\n",
 228                 cpus[cpu_unit_idx].tweaks.dis_enable);
 229     sim_msg ("Steady clock:                 %01o(8)\r\n",
 230                 scu [0].steady_clock);
 231     sim_msg ("Halt on unimplemented:        %01o(8)\r\n",
 232                 cpus[cpu_unit_idx].tweaks.halt_on_unimp);
 233     sim_msg ("Enable simulated SDWAM/PTWAM: %01o(8)\r\n",
 234                 cpus[cpu_unit_idx].tweaks.enable_wam);
 235     sim_msg ("Report faults:                %01o(8)\r\n",
 236                 cpus[cpu_unit_idx].tweaks.report_faults);
 237     sim_msg ("TRO faults enabled:           %01o(8)\r\n",
 238                 cpus[cpu_unit_idx].tweaks.tro_enable);
 239     sim_msg ("drl fatal enabled:            %01o(8)\r\n",
 240                 cpus[cpu_unit_idx].tweaks.drl_fatal);
 241     sim_msg ("useMap:                       %d\r\n",
 242                 cpus[cpu_unit_idx].tweaks.useMap);
 243     sim_msg ("PROM installed:               %01o(8)\r\n",
 244                 cpus[cpu_unit_idx].options.prom_installed);
 245     sim_msg ("Hex mode installed:           %01o(8)\r\n",
 246                 cpus[cpu_unit_idx].options.hex_mode_installed);
 247     sim_msg ("8K cache installed:           %01o(8)\r\n",
 248                 cpus[cpu_unit_idx].options.cache_installed);
 249     sim_msg ("Clock slave installed:        %01o(8)\r\n",
 250                 cpus[cpu_unit_idx].options.clock_slave_installed);
 251 #if defined(AFFINITY)
 252     if (cpus[cpu_unit_idx].set_affinity)
 253       sim_msg ("CPU affinity:                 %d\r\n", cpus[cpu_unit_idx].affinity);
 254     else
 255       sim_msg ("CPU affinity:                 not set\r\n");
 256 #endif
 257     sim_msg ("ISOLTS mode:                  %01o(8)\r\n", cpus[cpu_unit_idx].tweaks.isolts_mode);
 258     sim_msg ("T&D mode:                     %01o(8)\r\n", cpus[cpu_unit_idx].tweaks.tandd_mode);
 259     sim_msg ("NODIS mode:                   %01o(8)\r\n", cpus[cpu_unit_idx].tweaks.nodis);
 260     sim_msg ("6180 mode:                    %01o(8) [%s]\r\n",
 261              cpus[cpu_unit_idx].tweaks.l68_mode, cpus[cpu_unit_idx].tweaks.l68_mode ? "6180" : "DPS8/M");
 262     return SCPE_OK;
 263   }
 264 
 265 //
 266 // set cpu0 config=<blah> [;<blah>]
 267 //
 268 //    blah =
 269 //           faultbase = n
 270 //           num = n
 271 //           data = n
 272 //           portenable = n
 273 //           portconfig = n
 274 //           portinterlace = n
 275 //           mode = n
 276 //           speed = n
 277 //    Hacks:
 278 //           dis_enable = n
 279 //           steadyclock = on|off
 280 //           halt_on_unimplemented = n
 281 //           enable_wam = n
 282 //           report_faults = n
 283 //               n = 0 don't
 284 //               n = 1 report
 285 //               n = 2 report overflow
 286 //           tro_enable = n
 287 //           drl_fatal
 288 
 289 static config_value_list_t cfg_multics_fault_base [] =
 290   {
 291     { "multics", 2 },
 292     { NULL,      0 }
 293   };
 294 
 295 static config_value_list_t cfg_on_off [] =
 296   {
 297     { "off",     0 },
 298     { "on",      1 },
 299     { "disable", 0 },
 300     { "enable",  1 },
 301     { NULL,      0 }
 302   };
 303 
 304 static config_value_list_t cfg_l68_mode [] = {
 305   { "dps8/m", 0 },
 306   { "dps8m",  0 },
 307   { "dps8",   0 },
 308   { "l68",    1 },
 309   { "l6180",  1 },
 310   { "6180",   1 },
 311 };
 312 
 313 static config_value_list_t cfg_cpu_mode [] =
 314   {
 315     { "gcos",    0 },
 316     { "multics", 1 },
 317     { NULL,      0 }
 318   };
 319 
 320 static config_value_list_t cfg_port_letter [] =
 321   {
 322     { "a",  0 },
 323     { "b",  1 },
 324     { "c",  2 },
 325     { "d",  3 },
 326     { "e",  4 },
 327     { "f",  5 },
 328     { "g",  6 },
 329     { "h",  7 },
 330     { NULL, 0 }
 331   };
 332 
 333 static config_value_list_t cfg_interlace [] =
 334   {
 335     { "off", 0 },
 336     { "2",   2 },
 337     { "4",   4 },
 338     { NULL,  0 }
 339   };
 340 
 341 #if defined(AFFINITY)
 342 static config_value_list_t cfg_affinity [] =
 343   {
 344     { "off", -1 },
 345     { NULL,  0  }
 346   };
 347 #endif
 348 
 349 static config_value_list_t cfg_size_list [] =
 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     { "32",     8 },    //   32768
 414     { "32K",    8 },    //   32768
 415     { "64",     9 },    //   65536
 416     { "64K",    9 },    //   65536
 417     { "128",   10 },    //  131072
 418     { "128K",  10 },    //  131072
 419     { "256",   11 },    //  262144
 420     { "256K",  11 },    //  262144
 421     { "512",   12 },    //  524288
 422     { "512K",  12 },    //  524288
 423     { "1024",  13 },    // 1048576
 424     { "1024K", 13 },    // 1048576
 425     { "1M",    13 },
 426     { "2048",  14 },    // 2097152
 427     { "2048K", 14 },    // 2097152
 428     { "2M",    14 },
 429     { "4096",  15 },    // 4194304
 430     { "4096K", 15 },    // 4194304
 431     { "4M",    15 },
 432     { NULL,    0  }
 433   };
 434 
 435 static config_list_t cpu_config_list [] =
 436   {
 437     { "faultbase",             0,  0177,            cfg_multics_fault_base },
 438     { "num",                   0,  07,              NULL                   },
 439     { "data",                  0,  0777777777777,   NULL                   },
 440     { "stopnum",               0,  999999,          NULL                   },
 441     { "mode",                  0,  01,              cfg_cpu_mode           },
 442     { "speed",                 0,  017,             NULL                   },  // XXX use keywords
 443     { "port",                  0,  N_CPU_PORTS - 1, cfg_port_letter        },
 444     { "assignment",            0,  7,               NULL                   },
 445     { "interlace",             0,  1,               cfg_interlace          },
 446     { "enable",                0,  1,               cfg_on_off             },
 447     { "init_enable",           0,  1,               cfg_on_off             },
 448     { "store_size",            0,  7,               cfg_size_list          },
 449     { "enable_cache",          0,  1,               cfg_on_off             },
 450     { "sdwam",                 0,  1,               cfg_on_off             },
 451     { "ptwam",                 0,  1,               cfg_on_off             },
 452 
 453     // Hacks
 454     { "dis_enable",            0,  1,               cfg_on_off             },
 455     // steady_clock was moved to SCU; keep here for script compatibility
 456     { "steady_clock",          0,  1,               cfg_on_off             },
 457     { "halt_on_unimplemented", 0,  1,               cfg_on_off             },
 458     { "enable_wam",            0,  1,               cfg_on_off             },
 459     { "report_faults",         0,  1,               cfg_on_off             },
 460     { "tro_enable",            0,  1,               cfg_on_off             },
 461     { "drl_fatal",             0,  1,               cfg_on_off             },
 462     { "useMap",                0,  1,               cfg_on_off             },
 463     { "address",               0,  0777777,         NULL                   },
 464     { "prom_installed",        0,  1,               cfg_on_off             },
 465     { "hex_mode_installed",    0,  1,               cfg_on_off             },
 466     { "cache_installed",       0,  1,               cfg_on_off             },
 467     { "clock_slave_installed", 0,  1,               cfg_on_off             },
 468     { "enable_emcall",         0,  1,               cfg_on_off             },
 469 
 470     // Tuning
 471 #if defined(AFFINITY)
 472     { "affinity",              -1, 32767,           cfg_affinity           },
 473 #endif
 474     { "isolts_mode",           0,  1,               cfg_on_off             },
 475     { "tandd_mode",            0,  1,               cfg_on_off             },
 476     { "nodis",                 0,  1,               cfg_on_off             },
 477     { "l68_mode",              0,  1,               cfg_l68_mode           },
 478     { NULL,                    0,  0,               NULL                   }
 479   };
 480 
 481 static t_stat cpu_set_config (UNIT * uptr, UNUSED int32 value,
     /* [previous][next][first][last][top][bottom][index][help] */
 482                               const char * cptr, UNUSED void * desc)
 483   {
 484     long cpu_unit_idx = UNIT_IDX (uptr);
 485     if (cpu_unit_idx < 0 || cpu_unit_idx >= N_CPU_UNITS_MAX)
 486       {
 487         sim_warn ("error: cpu_set_config: Invalid unit number %ld\r\n",
 488                     (long) cpu_unit_idx);
 489         return SCPE_ARG;
 490       }
 491 
 492     static int port_num = 0;
 493 
 494     config_state_t cfg_state = { NULL, NULL };
 495 
 496     for (;;)
 497       {
 498         int64_t v;
 499         int rc = cfg_parse (__func__, cptr, cpu_config_list,
 500                            & cfg_state, & v);
 501         if (rc == -1) // done
 502           {
 503             break;
 504           }
 505         if (rc == -2) // error
 506           {
 507             cfg_parse_done (& cfg_state);
 508             return SCPE_ARG;
 509           }
 510 
 511         const char * p = cpu_config_list [rc] . name;
 512         if (strcmp (p, "faultbase") == 0)
 513           cpus[cpu_unit_idx].switches.FLT_BASE = (uint) v;
 514         else if (strcmp (p, "num") == 0)
 515           cpus[cpu_unit_idx].switches.cpu_num = (uint) v;
 516         else if (strcmp (p, "data") == 0)
 517           cpus[cpu_unit_idx].switches.data_switches = (word36) v;
 518         else if (strcmp (p, "stopnum") == 0)
 519           {
 520             // set up for check stop
 521             // convert stopnum to bcd
 522             int64_t d1 = (v / 1000) % 10;
 523             int64_t d2 = (v /  100) % 10;
 524             int64_t d3 = (v /   10) % 10;
 525             int64_t d4 = (v /    1) % 10;
 526             word36 d = 0123000000000;
 527             putbits36_6 (& d,  9, (word4) d1);
 528             putbits36_6 (& d, 15, (word4) d2);
 529             putbits36_6 (& d, 21, (word4) d3);
 530             putbits36_6 (& d, 27, (word4) d4);
 531             cpus[cpu_unit_idx].switches.data_switches = d;
 532           }
 533         else if (strcmp (p, "address") == 0)
 534           cpus[cpu_unit_idx].switches.addr_switches = (word18) v;
 535         else if (strcmp (p, "mode") == 0)
 536           cpus[cpu_unit_idx].switches.procMode = v ? procModeMultics : procModeGCOS;
 537         else if (strcmp (p, "speed") == 0)
 538           cpus[cpu_unit_idx].options.proc_speed = (uint) v;
 539         else if (strcmp (p, "port") == 0) {
 540           if ((! cpus[cpu_unit_idx].tweaks.l68_mode) && (int) v > 3) {
 541             cfg_parse_done (& cfg_state);
 542             return SCPE_ARG;
 543           }
 544           port_num = (int) v;
 545         }
 546         else if (strcmp (p, "assignment") == 0)
 547           cpus[cpu_unit_idx].switches.assignment [port_num] = (uint) v;
 548         else if (strcmp (p, "interlace") == 0)
 549           cpus[cpu_unit_idx].switches.interlace [port_num] = (uint) v;
 550         else if (strcmp (p, "enable") == 0)
 551           cpus[cpu_unit_idx].switches.enable [port_num] = (uint) v;
 552         else if (strcmp (p, "init_enable") == 0)
 553           cpus[cpu_unit_idx].switches.init_enable [port_num] = (uint) v;
 554         else if (strcmp (p, "store_size") == 0) {
 555           if (v > 7) {
 556             if (cpus[cpu_unit_idx].tweaks.l68_mode) {
 557               switch (v) {
 558                 case  8:  v = 0;   break; // 32K
 559                 case  9:  v = 1;   break; // 64K
 560                 case 10:  v = 3;   break; // 128K
 561                 case 11:  v = 7;   break; // 256K
 562                 case 12:  v = 4;   break; // 512K
 563                 case 13:  v = 5;   break; // 1024K
 564                 case 14:  v = 6;   break; // 2048K
 565                 case 15:  v = 2;   break; // 4096K
 566               }
 567             } else {
 568               switch (v) {
 569                 case  8:  v = 0;   break; // 32K
 570                 case  9:  v = 1;   break; // 64K
 571                 case 10:  v = 2;   break; // 128K
 572                 case 11:  v = 3;   break; // 256K
 573                 case 12:  v = 4;   break; // 512K
 574                 case 13:  v = 5;   break; // 1024K
 575                 case 14:  v = 6;   break; // 2048K
 576                 case 15:  v = 7;   break; // 4096K
 577               }
 578             }
 579           }
 580           cpus[cpu_unit_idx].switches.store_size [port_num] = (uint) v;
 581         }
 582         else if (strcmp (p, "enable_cache") == 0)
 583           {
 584             bool was = cacheConfigured (cpus + cpu_unit_idx);
 585             cpus[cpu_unit_idx].switches.enable_cache = (uint) v ? true : false;
 586             cacheConfigChanged (cpus + cpu_unit_idx, was);
 587           }
 588         else if (strcmp (p, "sdwam") == 0)
 589           cpus[cpu_unit_idx].switches.sdwam_enable = (uint) v ? true : false;
 590         else if (strcmp (p, "ptwam") == 0)
 591           cpus[cpu_unit_idx].switches.ptwam_enable = (uint) v ? true : false;
 592         else if (strcmp (p, "dis_enable") == 0)
 593           cpus[cpu_unit_idx].tweaks.dis_enable = (uint) v;
 594         else if (strcmp (p, "steady_clock") == 0)
 595           scu [0].steady_clock = (uint) v;
 596         else if (strcmp (p, "halt_on_unimplemented") == 0)
 597           cpus[cpu_unit_idx].tweaks.halt_on_unimp = (uint) v;
 598         else if (strcmp (p, "enable_wam") == 0)
 599           {
 600             bool was = cacheConfigured (cpus + cpu_unit_idx);
 601             cpus[cpu_unit_idx].tweaks.enable_wam = (uint) v;
 602             cacheConfigChanged (cpus + cpu_unit_idx, was);
 603           }
 604         else if (strcmp (p, "report_faults") == 0)
 605           cpus[cpu_unit_idx].tweaks.report_faults = (uint) v;
 606         else if (strcmp (p, "tro_enable") == 0)
 607           cpus[cpu_unit_idx].tweaks.tro_enable = (uint) v;
 608         else if (strcmp (p, "drl_fatal") == 0)
 609           cpus[cpu_unit_idx].tweaks.drl_fatal = (uint) v;
 610         else if (strcmp (p, "useMap") == 0)
 611           cpus[cpu_unit_idx].tweaks.useMap = v;
 612         else if (strcmp (p, "prom_installed") == 0)
 613           cpus[cpu_unit_idx].options.prom_installed = v;
 614         else if (strcmp (p, "hex_mode_installed") == 0)
 615           cpus[cpu_unit_idx].options.hex_mode_installed = v;
 616         else if (strcmp (p, "cache_installed") == 0)
 617           cpus[cpu_unit_idx].options.cache_installed = v;
 618         else if (strcmp (p, "clock_slave_installed") == 0)
 619           cpus[cpu_unit_idx].options.clock_slave_installed = v;
 620         else if (strcmp (p, "enable_emcall") == 0)
 621           cpus[cpu_unit_idx].tweaks.enable_emcall = v;
 622 #if defined(AFFINITY)
 623         else if (strcmp (p, "affinity") == 0)
 624           if (v < 0)
 625             {
 626               cpus[cpu_unit_idx].set_affinity = false;
 627             }
 628           else
 629             {
 630               cpus[cpu_unit_idx].set_affinity = true;
 631               cpus[cpu_unit_idx].affinity = (uint) v;
 632             }
 633 #endif
 634         else if (strcmp (p, "tandd_mode") == 0)
 635           {
 636             cpus[cpu_unit_idx].tweaks.tandd_mode = v ? true : false;
 637             cpus[cpu_unit_idx].disEnded = false;
 638           }
 639         else if (strcmp (p, "isolts_mode") == 0)
 640           {
 641             bool was = cpus[cpu_unit_idx].tweaks.isolts_mode;
 642             cpus[cpu_unit_idx].tweaks.isolts_mode = v;
 643             if (v && ! was) {
 644               uint store_sz;
 645               if (cpus[cpu_unit_idx].tweaks.l68_mode) // L68
 646                 store_sz = 3;
 647               else // DPS8M
 648                 store_sz = 2;
 649               cpus[cpu_unit_idx].isolts_switches_save     = cpus[cpu_unit_idx].switches;
 650 
 651               cpus[cpu_unit_idx].switches.data_switches   = 00000030714000;
 652               cpus[cpu_unit_idx].switches.addr_switches   = 0100150;
 653               cpus[cpu_unit_idx].tweaks.useMap            = true;
 654               cpus[cpu_unit_idx].tweaks.enable_wam        = true;
 655               cpus[cpu_unit_idx].switches.assignment  [0] = 0;
 656               cpus[cpu_unit_idx].switches.interlace   [0] = false;
 657               cpus[cpu_unit_idx].switches.enable      [0] = false;
 658               cpus[cpu_unit_idx].switches.init_enable [0] = false;
 659               cpus[cpu_unit_idx].switches.store_size  [0] = store_sz;
 660 
 661               cpus[cpu_unit_idx].switches.assignment  [1] = 0;
 662               cpus[cpu_unit_idx].switches.interlace   [1] = false;
 663               cpus[cpu_unit_idx].switches.enable      [1] = true;
 664               cpus[cpu_unit_idx].switches.init_enable [1] = false;
 665               cpus[cpu_unit_idx].switches.store_size  [1] = store_sz;
 666 
 667               cpus[cpu_unit_idx].switches.assignment  [2] = 0;
 668               cpus[cpu_unit_idx].switches.interlace   [2] = false;
 669               cpus[cpu_unit_idx].switches.enable      [2] = false;
 670               cpus[cpu_unit_idx].switches.init_enable [2] = false;
 671               cpus[cpu_unit_idx].switches.store_size  [2] = store_sz;
 672 
 673               cpus[cpu_unit_idx].switches.assignment  [3] = 0;
 674               cpus[cpu_unit_idx].switches.interlace   [3] = false;
 675               cpus[cpu_unit_idx].switches.enable      [3] = false;
 676               cpus[cpu_unit_idx].switches.init_enable [3] = false;
 677               cpus[cpu_unit_idx].switches.store_size  [3] = store_sz;
 678 
 679               if (cpus[cpu_unit_idx].tweaks.l68_mode) { // L68
 680                 cpus[cpu_unit_idx].switches.assignment  [4] = 0;
 681                 cpus[cpu_unit_idx].switches.interlace   [4] = false;
 682                 cpus[cpu_unit_idx].switches.enable      [4] = false;
 683                 cpus[cpu_unit_idx].switches.init_enable [4] = false;
 684                 cpus[cpu_unit_idx].switches.store_size  [4] = 3;
 685 
 686                 cpus[cpu_unit_idx].switches.assignment  [5] = 0;
 687                 cpus[cpu_unit_idx].switches.interlace   [5] = false;
 688                 cpus[cpu_unit_idx].switches.enable      [5] = false;
 689                 cpus[cpu_unit_idx].switches.init_enable [5] = false;
 690                 cpus[cpu_unit_idx].switches.store_size  [5] = 3;
 691 
 692                 cpus[cpu_unit_idx].switches.assignment  [6] = 0;
 693                 cpus[cpu_unit_idx].switches.interlace   [6] = false;
 694                 cpus[cpu_unit_idx].switches.enable      [6] = false;
 695                 cpus[cpu_unit_idx].switches.init_enable [6] = false;
 696                 cpus[cpu_unit_idx].switches.store_size  [6] = 3;
 697 
 698                 cpus[cpu_unit_idx].switches.assignment  [7] = 0;
 699                 cpus[cpu_unit_idx].switches.interlace   [7] = false;
 700                 cpus[cpu_unit_idx].switches.enable      [7] = false;
 701                 cpus[cpu_unit_idx].switches.init_enable [7] = false;
 702                 cpus[cpu_unit_idx].switches.store_size  [7] = 3;
 703               }
 704               cpus[cpu_unit_idx].switches.enable      [1] = true; //-V1048
 705 
 706 #if defined(THREADZ) || defined(LOCKLESS)
 707               if (cpus[cpu_unit_idx].executing) {
 708                 cpus[cpu_unit_idx].forceRestart = true;
 709                 wakeCPU (cpu_unit_idx);
 710               } else {
 711                 cpu_reset_unit_idx ((uint) cpu_unit_idx, false);
 712                 //simh_cpu_reset_and_clear_unit (cpuUnits + cpu_unit_idx, 0, NULL, NULL);
 713               }
 714 #else /* defined(THREADZ) || defined(LOCKLESS) */
 715               cpu_reset_unit_idx ((uint) cpu_unit_idx, false);
 716               simh_cpu_reset_and_clear_unit (cpu_unit + cpu_unit_idx, 0, NULL, NULL);
 717 #endif /* defined(THREADZ) || defined(LOCKLESS) */
 718 
 719             } else if (was && !v) {
 720               cpus[cpu_unit_idx].switches = cpus[cpu_unit_idx].isolts_switches_save;
 721 
 722 #if defined(THREADZ) || defined(LOCKLESS)
 723               if (cpus[cpu_unit_idx].executing) {
 724                 cpus[cpu_unit_idx].forceRestart = true;
 725                 wakeCPU (cpu_unit_idx);
 726               } else {
 727                 cpu_reset_unit_idx ((uint) cpu_unit_idx, false);
 728                 //simh_cpu_reset_and_clear_unit (cpuUnits + cpu_unit_idx, 0, NULL, NULL);
 729               }
 730 #else /* defined(THREADZ) || defined(LOCKLESS) */
 731             cpu_reset_unit_idx ((uint) cpu_unit_idx, false);
 732             simh_cpu_reset_and_clear_unit (cpu_unit + cpu_unit_idx, 0, NULL, NULL);
 733 #endif /* defined(THREADZ) || defined(LOCKLESS) */
 734 
 735             }
 736           }
 737         else if (strcmp (p, "nodis") == 0)
 738           cpus[cpu_unit_idx].tweaks.nodis = v;
 739         else if (strcmp (p, "l68_mode") == 0)
 740           cpus[cpu_unit_idx].tweaks.l68_mode = v;
 741         else
 742           {
 743             sim_warn ("error: cpu_set_config: Invalid cfg_parse rc <%ld>\r\n",
 744                         (long) rc);
 745             cfg_parse_done (& cfg_state);
 746             return SCPE_ARG;
 747           }
 748       } // process statements
 749     cfg_parse_done (& cfg_state);
 750     // enable_cache, enable_wam, isolts_mode can change whether a cache is on
 751     cacheUpdateAnyOn ();
 752     tanddUpdateAnyOn ();
 753     // enable_wam decides what the micro-cache may hold (ucCacheSave)
 754     ucInvalidate (& cpus[cpu_unit_idx]);
 755 
 756     return SCPE_OK;
 757   }
 758 
 759 static t_stat cpu_show_nunits (UNUSED FILE * st, UNUSED UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
 760                                UNUSED int val, UNUSED const void * desc)
 761   {
 762     sim_msg ("Number of CPUs in system is %d\r\n", cpu_dev.numunits);
 763     return SCPE_OK;
 764   }
 765 
 766 static t_stat cpu_set_nunits (UNUSED UNIT * uptr, UNUSED int32 value,
     /* [previous][next][first][last][top][bottom][index][help] */
 767                               const char * cptr, UNUSED void * desc)
 768   {
 769     if (! cptr)
 770       return SCPE_ARG;
 771     int n = atoi (cptr);
 772     if (n < 1 || n > N_CPU_UNITS_MAX)
 773       return SCPE_ARG;
 774     cpu_dev.numunits = (uint32) n;
 775     return SCPE_OK;
 776   }
 777 
 778 static t_stat cpu_show_kips (UNUSED FILE * st, UNUSED UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
 779                              UNUSED int val, UNUSED const void * desc)
 780   {
 781     sim_msg ("CPU KIPS %lu\r\n", (unsigned long)kips);
 782     return SCPE_OK;
 783   }
 784 
 785 static t_stat cpu_set_kips (UNUSED UNIT * uptr, UNUSED int32 value,
     /* [previous][next][first][last][top][bottom][index][help] */
 786                             const char * cptr, UNUSED void * desc)
 787   {
 788     if (! cptr)
 789       return SCPE_ARG;
 790     long n = atol (cptr);
 791     if (n < 1 || n > 4000000)
 792       return SCPE_ARG;
 793     kips = (uint64) n;
 794     luf_limits[0] =  2000*kips/1000;
 795     luf_limits[1] =  4000*kips/1000;
 796     luf_limits[2] =  8000*kips/1000;
 797     luf_limits[3] = 16000*kips/1000;
 798     luf_limits[4] = 32000*kips/1000;
 799     return SCPE_OK;
 800   }
 801 
 802 static t_stat cpu_show_stall (UNUSED FILE * st, UNUSED UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
 803                              UNUSED int val, UNUSED const void * desc)
 804   {
 805     if (! stall_point_active)
 806       {
 807         sim_printf ("No stall points\r\n");
 808         return SCPE_OK;
 809       }
 810 
 811     sim_printf ("Stall points\r\n");
 812     for (int i = 0; i < N_STALL_POINTS; i ++)
 813       if (stall_points[i].segno || stall_points[i].offset)
 814         {
 815 #if defined(WIN_STDIO)
 816           sim_printf ("%2ld %05o:%06o %10lu\r\n",
 817 #else
 818           sim_printf ("%2ld %05o:%06o %'10lu\r\n",
 819 #endif
 820                  (long)i, stall_points[i].segno, stall_points[i].offset,
 821                  (unsigned long)stall_points[i].time);
 822         }
 823     return SCPE_OK;
 824   }
 825 
 826 // set cpu stall=n=s:o=t
 827 //   n stall point number
 828 //   s segment number (octal)
 829 //   o offset (octal)
 830 //   t time in microseconds (decimal)
 831 
 832 static t_stat cpu_set_stall (UNUSED UNIT * uptr, UNUSED int32 value,
     /* [previous][next][first][last][top][bottom][index][help] */
 833                              const char * cptr, UNUSED void * desc)
 834   {
 835     if (! cptr)
 836       return SCPE_ARG;
 837 
 838     long n, s, o, t;
 839 
 840     char * end;
 841     n = strtol (cptr, & end, 0);
 842     if (* end != '=')
 843       return SCPE_ARG;
 844     if (n < 0 || n >= N_STALL_POINTS)
 845       return SCPE_ARG;
 846 
 847     s = strtol (end + 1, & end, 8);
 848     if (* end != ':')
 849       return SCPE_ARG;
 850     if (s < 0 || s > MASK15)
 851       return SCPE_ARG;
 852 
 853     o = strtol (end + 1, & end, 8);
 854     if (* end != '=')
 855       return SCPE_ARG;
 856     if (o < 0 || o > MASK18)
 857       return SCPE_ARG;
 858 
 859     t = strtol (end + 1, & end, 0);
 860     if (* end != 0)
 861       return SCPE_ARG;
 862     if (t < 0 || t > 30000000)
 863       return SCPE_ARG;
 864 
 865     stall_points[n].segno  = (word15) s;
 866     stall_points[n].offset = (word18) o;
 867     stall_points[n].time   = (unsigned int) t;
 868     stall_point_active     = false;
 869 
 870     for (int i = 0; i < N_STALL_POINTS; i ++)
 871       if (stall_points[n].segno && stall_points[n].offset)
 872         stall_point_active = true;
 873 
 874     return SCPE_OK;
 875   }
 876 
 877 static t_stat setCPUConfigL68 (UNIT * uptr, UNUSED int32 value, UNUSED const char * cptr, UNUSED void * desc) {
     /* [previous][next][first][last][top][bottom][index][help] */
 878   long cpuUnitIdx = UNIT_IDX (uptr);
 879   if (cpuUnitIdx < 0 || cpuUnitIdx >= N_CPU_UNITS_MAX)
 880     return SCPE_ARG;
 881   cpu_state_t * cpun = cpus + cpuUnitIdx;
 882 
 883   cpun->tweaks.l68_mode = 1;
 884   fullModelUpdate ();   // see FULL_MODEL_ON
 885   cpun->options.hex_mode_installed = 0;
 886   for (uint port_num = 0; port_num < N_DPS8M_CPU_PORTS; port_num ++) {
 887     cpun->switches.assignment[port_num] = port_num;
 888     cpun->switches.interlace[port_num] = 0;
 889     cpun->switches.store_size[port_num] = 2;
 890     cpun->switches.enable[port_num] = 1;
 891     cpun->switches.init_enable[port_num] = 1;
 892   }
 893   for (uint port_num = N_DPS8M_CPU_PORTS; port_num < N_L68_CPU_PORTS; port_num ++) {
 894     cpun->switches.assignment[port_num] = 0;
 895     cpun->switches.interlace[port_num] = 0;
 896     cpun->switches.store_size[port_num] = 0;
 897     cpun->switches.enable[port_num] = 0;
 898     cpun->switches.init_enable[port_num] = 0;
 899   }
 900   return SCPE_OK;
 901 }
 902 
 903 static t_stat setCPUConfigDPS8M (UNIT * uptr, UNUSED int32 value, UNUSED const char * cptr, UNUSED void * desc) {
     /* [previous][next][first][last][top][bottom][index][help] */
 904   long cpuUnitIdx = UNIT_IDX (uptr);
 905   if (cpuUnitIdx < 0 || cpuUnitIdx >= N_CPU_UNITS_MAX)
 906     return SCPE_ARG;
 907   cpu_state_t * cpun = cpus + cpuUnitIdx;
 908 
 909   cpun->tweaks.l68_mode = 0;
 910   fullModelUpdate ();   // see FULL_MODEL_ON
 911   cpun->options.hex_mode_installed = 0;
 912   for (uint port_num = 0; port_num < N_DPS8M_CPU_PORTS; port_num ++) {
 913     cpun->switches.assignment[port_num] = port_num;
 914     cpun->switches.interlace[port_num] = 0;
 915     cpun->switches.store_size[port_num] = 7;
 916     cpun->switches.enable[port_num] = 1;
 917     cpun->switches.init_enable[port_num] = 1;
 918   }
 919   for (uint port_num = N_DPS8M_CPU_PORTS; port_num < N_L68_CPU_PORTS; port_num ++) {
 920     cpun->switches.assignment[port_num] = 0;
 921     cpun->switches.interlace[port_num] = 0;
 922     cpun->switches.store_size[port_num] = 0;
 923     cpun->switches.enable[port_num] = 0;
 924     cpun->switches.init_enable[port_num] = 0;
 925   }
 926   return SCPE_OK;
 927 }
 928 
 929 char * cycle_str (cycles_e cycle)
     /* [previous][next][first][last][top][bottom][index][help] */
 930   {
 931     switch (cycle)
 932       {
 933         //case ABORT_cycle:
 934           //return "ABORT_cycle";
 935         case FAULT_cycle:
 936           return "FAULT_cycle";
 937         case EXEC_cycle:
 938           return "EXEC_cycle";
 939         case FAULT_EXEC_cycle:
 940           return "FAULT_EXEC_cycle";
 941         case INTERRUPT_cycle:
 942           return "INTERRUPT_cycle";
 943         case INTERRUPT_EXEC_cycle:
 944           return "INTERRUPT_EXEC_cycle";
 945         case FETCH_cycle:
 946           return "FETCH_cycle";
 947         case PSEUDO_FETCH_cycle:
 948           return "PSEUDO_FETCH_cycle";
 949         case SYNC_FAULT_RTN_cycle:
 950           return "SYNC_FAULT_RTN_cycle";
 951         default:
 952           return "unknown cycle";
 953       }
 954   }
 955 
 956 static void set_cpu_cycle (cpu_state_t * cpup, cycles_e cycle)
     /* [previous][next][first][last][top][bottom][index][help] */
 957   {
 958     sim_debug (DBG_CYCLE, & cpu_dev, "Setting cycle to %s\r\n",
 959                cycle_str (cycle));
 960     cpu.cycle = cycle;
 961   }
 962 
 963 // DPS8M Memory of 36 bit words is implemented as an array of 64 bit words.
 964 // Put state information into the unused high order bits.
 965 #define MEM_UNINITIALIZED (1LLU<<62)
 966 
 967 uint set_cpu_idx (UNUSED uint cpu_idx)
     /* [previous][next][first][last][top][bottom][index][help] */
 968   {
 969     uint prev = current_running_cpu_idx;
 970 #if defined(THREADZ) || defined(LOCKLESS)
 971     current_running_cpu_idx = cpu_idx;
 972 #endif
 973     _cpup = & cpus [current_running_cpu_idx];
 974     return prev;
 975   }
 976 
 977 void cpu_reset_unit_idx (UNUSED uint cpun, bool clear_mem)
     /* [previous][next][first][last][top][bottom][index][help] */
 978   {
 979     uint save = set_cpu_idx (cpun);
 980     cpu_state_t * cpup = _cpup;
 981     if (clear_mem)
 982       {
 983         for (uint i = 0; i < MEMSIZE; i ++)
 984           {
 985             // Clear lock bits and data field; set uninitialized
 986 #if defined(LOCKLESS)
 987             M[i] = (M[i] & ~(MASK36 | MEM_LOCKED)) | MEM_UNINITIALIZED;
 988 #else
 989             M[i] = (M[i] & ~(MASK36)) | MEM_UNINITIALIZED;
 990 #endif
 991           }
 992       }
 993     cpu.rA = 0;
 994     cpu.rQ = 0;
 995 
 996     cpu.PPR.IC   = 0;
 997     cpu.PPR.PRR  = 0;
 998     cpu.PPR.PSR  = 0;
 999     cpu.PPR.P    = 1;
1000     cpu.RSDWH_R1 = 0;
1001     cpu.rTR      = MASK27;
1002 
1003     if (cpu.tweaks.isolts_mode)
1004       {
1005         cpu.shadowTR = 0;
1006         cpu.rTRlsb   = 0;
1007       }
1008     cpu.rTRticks = 0;
1009 
1010     set_addr_mode (cpup, ABSOLUTE_mode);
1011     SET_I_NBAR;
1012 
1013     cpu.CMR.luf  = 3;    // default of 16 mS
1014     cpu.cu.SD_ON = cpu.switches.sdwam_enable ? 1 : 0;
1015     cpu.cu.PT_ON = cpu.switches.ptwam_enable ? 1 : 0;
1016     ucInvalidate (cpup); // see ucCacheSave
1017 
1018     if (cpu.tweaks.nodis) {
1019       set_cpu_cycle (cpup, FETCH_cycle);
1020     } else {
1021       set_cpu_cycle (cpup, EXEC_cycle);
1022       cpu.cu.IWB = 0000000616200; //-V536  // Stuff DIS w/interrupt inhibit  in instruction buffer
1023     }
1024 #if defined(PERF_STRIP)
1025     set_cpu_cycle (cpup, FETCH_cycle);
1026 #endif
1027     cpu.wasXfer        = false;
1028     cpu.wasInhibited   = false;
1029     cpu.disEnded       = false;
1030 
1031     cpu.interrupt_flag = false;
1032     cpu.g7_flag        = false;
1033 
1034     cpu.faultRegister [0] = 0;
1035     cpu.faultRegister [1] = 0;
1036 
1037 #if defined(RAPRx)
1038     cpu.apu.lastCycle = UNKNOWN_CYCLE;
1039 #endif
1040 
1041     (void)memset (& cpu.PPR, 0, sizeof (struct ppr_s));
1042 
1043     cacheCpuReset (cpup);
1044     setup_scbank_map (cpup);
1045 
1046     tidy_cu (cpup);
1047     set_cpu_idx (save);
1048   }
1049 
1050 static t_stat simh_cpu_reset_and_clear_unit (UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
1051                                              UNUSED int32 value,
1052                                              UNUSED const char * cptr,
1053                                              UNUSED void * desc)
1054   {
1055     long cpu_unit_idx = UNIT_IDX (uptr);
1056     cpu_state_t * cpun = cpus + cpu_unit_idx;
1057     if (cpun->tweaks.isolts_mode)
1058       {
1059         // Currently isolts_mode requires useMap, so this is redundant
1060         if (cpun->tweaks.useMap)
1061           {
1062             for (uint pgnum = 0; pgnum < N_SCBANKS; pgnum ++)
1063               {
1064                 int base = cpun->sc_addr_map [pgnum];
1065                 if (base < 0)
1066                   continue;
1067                 for (uint addr = 0; addr < SCBANK_SZ; addr ++)
1068                   M [addr + (uint) base] = MEM_UNINITIALIZED;
1069               }
1070             // The clear went straight to M, past write notification:
1071             // empty every CPU's cache (this CPU's is also emptied by the
1072             // reset below)
1073             for (uint i = 0; i < cpu_dev.numunits && i < N_CPU_UNITS_MAX; i ++)
1074               cacheReset (cpus + i);
1075           }
1076       }
1077     // Crashes console?
1078     cpu_reset_unit_idx ((uint) cpu_unit_idx, false);
1079     return SCPE_OK;
1080   }
1081 
1082 static t_stat simh_cpu_reset_unit (UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
1083                                    UNUSED int32 value,
1084                                    UNUSED const char * cptr,
1085                                    UNUSED void * desc)
1086   {
1087     long cpu_unit_idx = UNIT_IDX (uptr);
1088     cpu_reset_unit_idx ((uint) cpu_unit_idx, false); // no clear memory
1089     return SCPE_OK;
1090   }
1091 
1092 #if !defined(PERF_STRIP)
1093 static uv_loop_t * ev_poll_loop;
1094 static uv_timer_t ev_poll_handle;
1095 #endif /* if !defined(PERF_STRIP) */
1096 
1097 static MTAB cpu_mod[] =
1098   {
1099     {
1100       MTAB_unit_value,                /* Mask               */
1101       0,                              /* Match              */
1102       "CONFIG",                       /* Print string       */
1103       "CONFIG",                       /* Match string       */
1104       cpu_set_config,                 /* Validation routine */
1105       cpu_show_config,                /* Display routine    */
1106       NULL,                           /* Value descriptor   */
1107       NULL                            /* Help               */
1108     },
1109 
1110 // RESET (INITIALIZE) -- reset CPU
1111 
1112     {
1113       MTAB_unit_value,                /* Mask               */
1114       0,                              /* Match              */
1115       "RESET",                        /* Print string       */
1116       "RESET",                        /* Match string       */
1117       simh_cpu_reset_unit,            /* Validation routine */
1118       NULL,                           /* Display routine    */
1119       NULL,                           /* Value descriptor   */
1120       NULL                            /* Help               */
1121     },
1122 
1123     {
1124       MTAB_unit_value,                /* Mask               */
1125       0,                              /* Match              */
1126       "INITIALIZE",                   /* Print string       */
1127       "INITIALIZE",                   /* Match string       */
1128       simh_cpu_reset_unit,            /* Validation routine */
1129       NULL,                           /* Display routine    */
1130       NULL,                           /* Value descriptor   */
1131       NULL                            /* Help               */
1132     },
1133 
1134 // INITAILIZEANDCLEAR (IAC) -- reset CPU, clear Memory
1135 
1136     {
1137       MTAB_unit_value,                /* Mask               */
1138       0,                              /* Match              */
1139       "INITIALIZEANDCLEAR",           /* Print string       */
1140       "INITIALIZEANDCLEAR",           /* Match string       */
1141       simh_cpu_reset_and_clear_unit,  /* Validation routine */
1142       NULL,                           /* Display routine    */
1143       NULL,                           /* Value descriptor   */
1144       NULL                            /* Help               */
1145     },
1146 
1147     {
1148       MTAB_unit_value,                /* Mask               */
1149       0,                              /* Match              */
1150       "IAC",                          /* Print string       */
1151       "IAC",                          /* Match string       */
1152       simh_cpu_reset_and_clear_unit,  /* Validation routine */
1153       NULL,                           /* Display routine    */
1154       NULL,                           /* Value descriptor   */
1155       NULL                            /* Help               */
1156     },
1157 
1158     {
1159       MTAB_dev_value,                 /* Mask               */
1160       0,                              /* Match              */
1161       "NUNITS",                       /* Print string       */
1162       "NUNITS",                       /* Match string       */
1163       cpu_set_nunits,                 /* Validation routine */
1164       cpu_show_nunits,                /* Display routine    */
1165       NULL,                           /* Value descriptor   */
1166       NULL                            /* Help               */
1167     },
1168 
1169     {
1170       MTAB_dev_value,                 /* Mask               */
1171       0,                              /* Match              */
1172       "KIPS",                         /* Print string       */
1173       "KIPS",                         /* Match string       */
1174       cpu_set_kips,                   /* Validation routine */
1175       cpu_show_kips,                  /* Display routine    */
1176       NULL,                           /* Value descriptor   */
1177       NULL                            /* Help               */
1178     },
1179 
1180     {
1181       MTAB_dev_value,                 /* Mask               */
1182       0,                              /* Match              */
1183       "STALL",                        /* Print string       */
1184       "STALL",                        /* Match string       */
1185       cpu_set_stall,                  /* Validation routine */
1186       cpu_show_stall,                 /* Display routine    */
1187       NULL,                           /* Value descriptor   */
1188       NULL                            /* Help               */
1189     },
1190 
1191     {
1192       MTAB_unit_value,                /* Mask               */
1193       0,                              /* Match              */
1194       "DPS8M",                        /* Print string       */
1195       "DPS8M",                        /* Match string       */
1196       setCPUConfigDPS8M,              /* Validation routine */
1197       NULL,                           /* Display routine    */
1198       NULL,                           /* Value descriptor   */
1199       NULL                            /* Help               */
1200     },
1201 
1202     {
1203       MTAB_unit_value,                /* Mask               */
1204       0,                              /* Match              */
1205       "L68",                          /* Print string       */
1206       "L68",                          /* Match string       */
1207       setCPUConfigL68,                /* Validation routine */
1208       NULL,                           /* Display routine    */
1209       NULL,                           /* Value descriptor   */
1210       NULL                            /* Help               */
1211     },
1212 
1213     { 0, 0, NULL, NULL, NULL, NULL, NULL, NULL }
1214   };
1215 
1216 static DEBTAB cpu_dt[] =
1217   {
1218     { "TRACE",       DBG_TRACE,       NULL },
1219     { "TRACEEXT",    DBG_TRACEEXT,    NULL },
1220     { "MESSAGES",    DBG_MSG,         NULL },
1221 
1222     { "REGDUMPAQI",  DBG_REGDUMPAQI,  NULL },
1223     { "REGDUMPIDX",  DBG_REGDUMPIDX,  NULL },
1224     { "REGDUMPPR",   DBG_REGDUMPPR,   NULL },
1225     { "REGDUMPPPR",  DBG_REGDUMPPPR,  NULL },
1226     { "REGDUMPDSBR", DBG_REGDUMPDSBR, NULL },
1227     { "REGDUMPFLT",  DBG_REGDUMPFLT,  NULL }, // Don't move as it messes up DBG message
1228     { "REGDUMP",     DBG_REGDUMP,     NULL },
1229 
1230     { "ADDRMOD",     DBG_ADDRMOD,     NULL },
1231     { "APPENDING",   DBG_APPENDING,   NULL },
1232 
1233     { "NOTIFY",      DBG_NOTIFY,      NULL },
1234     { "INFO",        DBG_INFO,        NULL },
1235     { "ERR",         DBG_ERR,         NULL },
1236     { "WARN",        DBG_WARN,        NULL },
1237     { "DEBUG",       DBG_DEBUG,       NULL }, // Don't move as it messes up DBG message
1238     { "ALL",         DBG_ALL,         NULL },
1239 
1240     { "FAULT",       DBG_FAULT,       NULL },
1241     { "INTR",        DBG_INTR,        NULL },
1242     { "CORE",        DBG_CORE,        NULL },
1243     { "CYCLE",       DBG_CYCLE,       NULL },
1244     { "CAC",         DBG_CAC,         NULL },
1245     { "FINAL",       DBG_FINAL,       NULL },
1246     { "AVC",         DBG_AVC,         NULL },
1247     { NULL,          0,               NULL }
1248   };
1249 
1250 // This is part of the scp interface
1251 const char *sim_stop_messages[] =
1252   {
1253     "Unknown error",           // SCPE_OK
1254     "Simulation stop",         // STOP_STOP
1255     "Breakpoint",              // STOP_BKPT
1256   };
1257 
1258 /* End of scp interface */
1259 
1260 /* Processor configuration switches
1261  *
1262  * From AM81-04 Multics System Maintenance Procedures
1263  *
1264  * "A Level 68 IOM system may contain a maximum of 7 CPUs, 4 IOMs, 8 SCUs,
1265  * and 16MW of memory ...
1266  * [CAC]: ... but AN87 says Multics only supports two IOMs
1267  *
1268  * ASSIGNMENT: 3 toggle switches determine the base address of the SCU
1269  * connected to the port. The base address (in KW) is the product of this
1270  * number and the value defined by the STORE SIZE patch plug for the port.
1271  *
1272  * ADDRESS RANGE: toggle FULL/HALF. Determines the size of the SCU as full or
1273  * half of the STORE SIZE patch.
1274  *
1275  * PORT ENABLE: (4? toggles)
1276  *
1277  * INITIALIZE ENABLE: (4? toggles) These switches enable the receipt of an
1278  * initialize signal from the SCU connected to the ports. This signal is used
1279  * during the first part of bootload to set all CPUs to a known (idle) state.
1280  * The switch for each port connected to an SCU should be ON, otherwise off.
1281  *
1282  * INTERLACE: ... All INTERLACE switches should be OFF for Multics operation.
1283  *
1284  */
1285 
1286 #if !defined(SPEED)
1287 static bool watch_bits [MEMSIZE];
1288 #endif /* if !defined(SPEED) */
1289 
1290 char * str_SDW0 (char * buf, sdw0_s * SDW)
     /* [previous][next][first][last][top][bottom][index][help] */
1291   {
1292     (void)sprintf (buf, "ADDR=%06o R1=%o R2=%o R3=%o F=%o FC=%o BOUND=%o R=%o "
1293                         "E=%o W=%o P=%o U=%o G=%o C=%o EB=%o",
1294                    SDW->ADDR, SDW->R1,    SDW->R2, SDW->R3, SDW->DF,
1295                    SDW->FC,   SDW->BOUND, SDW->R,  SDW->E,  SDW->W,
1296                    SDW->P,    SDW->U,     SDW->G,  SDW->C,  SDW->EB);
1297     return buf;
1298   }
1299 
1300 static t_stat cpu_boot (UNUSED int32 cpu_unit_idx, UNUSED DEVICE * dptr)
     /* [previous][next][first][last][top][bottom][index][help] */
1301   {
1302     sim_warn ("Try 'BOOT IOMn'\r\n");
1303     return SCPE_ARG;
1304   }
1305 
1306 // The original h/w had one to four (DPS8/M) or eight (Level 68) SCUs;
1307 // each SCU held memory.
1308 // Memory accesses were sent to the SCU that held the region of memory
1309 // being addressed.
1310 //
1311 // eg, SCU 0 has 1 MW of memory and SCU 1 has 2 MW
1312 // Address
1313 //      0M +------------------+
1314 //         |                  |  SCU 0
1315 //      1M +------------------+
1316 //         |                  |  SCU 1
1317 //         |                  |
1318 //      3M +------------------+
1319 //
1320 // So SCU 0 has the first MW of addresses, and SCU1 has the second and third
1321 // MWs.
1322 //
1323 // The simulator has a single 16MW array of memory. This code walks the SCUs
1324 // allocates memory regions out of that array to the SCUs based on their
1325 // individual configurations. The 16MW is divided into 4 zones, one for each
1326 // SCU. (SCU0 uses the first 4MW, SCU1 the second 4MW, etc.
1327 //
1328 #define ZONE_SZ (MEM_SIZE_MAX / 4)
1329 //
1330 // The minimum SCU memory size increment is 64KW, which I will refer to as
1331 // a 'bank'. To map a CPU address to the simulated array, the CPU address is
1332 // divided into a bank number and an offset into that bank
1333 //
1334 //    bank_num    = addr / SCBANK_SZ
1335 //    bank_offset = addr % SCBANK_SZ
1336 //
1337 // sc_addr_map[] maps bank numbers to offset in the simulated memory array
1338 //
1339 //    real_addr = sc_addr_map[bank_num] + bank_offset
1340 //
1341 
1342 // T&D mode: map each CPU port's addresses through its SCU's configuration
1343 // register (lower store size, stores A/A1/B/B1 online, LWR, NEA), as the
1344 // T&D SCU tests (SM781 13A, 17A) and dps8m4 do. Memory stays in the
1345 // port's zone of M. Limited to the port's window (port assignment and
1346 // store size switches).
1347 
1348 // T&D: where SCU bank scu_bank (of the SCU's 4M address space; offset:
1349 // the store A/B swap for LWR) is kept in the CPU port's zone of M:
1350 // relative to the port window's first SCU bank, mod 4M, so that without
1351 // LWR the window is kept from the start of the zone, as in
1352 // setup_scbank_map.
1353 static int scu_phys_bank (uint scu_bank, int offset, uint scu_base_bks)
     /* [previous][next][first][last][top][bottom][index][help] */
1354   {
1355     int n_bks = (int) ((4u << 20) / SCBANK_SZ);
1356     int b = ((int) scu_bank + offset - (int) scu_base_bks) % n_bks;
1357     return b < 0 ? b + n_bks : b;
1358   }
1359 
1360 static void setup_scbank_map_tandd (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
1361   {
1362     for (uint pg = 0; pg < N_SCBANKS; pg ++)
1363       {
1364         cpu.sc_addr_map [pg] = -1;
1365         cpu.sc_scu_map  [pg] = -1;
1366       }
1367     for (uint u = 0; u < N_SCU_UNITS_MAX; u ++)
1368       cpu.sc_num_banks[u] = 0;
1369     for (uint p = 0; p < N_SCU_PORTS; p ++)
1370       cpu.sc_fine_port[p] = false;
1371     cpu.sc_fine = false;
1372 
1373     uint dps8m_store_table [8] =
1374       { 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304 };
1375     uint l68_store_table [8] =
1376       { 32768, 65536, 4194304, 131072, 524288, 1048576, 2097152, 262144 };
1377 
1378     int n_ports = cpu.tweaks.l68_mode ? N_L68_CPU_PORTS : N_DPS8M_CPU_PORTS;
1379     for (int port_num = 0; port_num < n_ports; port_num ++)
1380       {
1381         if (! cpu.switches.enable [port_num])
1382           continue;
1383         if (! cables->cpu_to_scu[current_running_cpu_idx][port_num].in_use)
1384           continue;
1385 
1386         uint store_size = cpu.switches.store_size [port_num];
1387         // ISOLTS on an L68: size code 3 means 64K (the "cpu test"
1388         // free-edge connector), as in setup_scbank_map's
1389         // l68_isolts_store_table; configure_test_cpu checks that an LDA
1390         // at 64K takes a store fault.
1391         uint sz_wds = cpu.tweaks.l68_mode ?
1392                         (cpu.tweaks.isolts_mode && store_size == 3 ?
1393                            65536 : l68_store_table [store_size]) :
1394                         dps8m_store_table [store_size];
1395         uint base_addr_bks = (sz_wds * cpu.switches.assignment[port_num]) / SCBANK_SZ;
1396         uint port_banks    = sz_wds / SCBANK_SZ;
1397 
1398         uint scu_unit_idx = cables->cpu_to_scu[current_running_cpu_idx][port_num].scu_unit_idx;
1399         scu_t * up = scu + scu_unit_idx;
1400 
1401         // Store units. The lower store is A (B with LWR) and A1 (B1): A1
1402         // (B1) is its upper half (WSCU66LA 3.2.3: the second unit of a
1403         // pair is selected by the address bit just below the pair-size
1404         // boundary; the smallest pair is 64K, two 32K units). A 32K store
1405         // is one unit, A (B). The upper store, if present, is as big as
1406         // the lower one.
1407         uint lower_wds = (1u << up->lower_store_size) * 32768u;
1408         uint half_wds  = lower_wds >= 65536u ? lower_wds / 2 : lower_wds;
1409         bool a_on  = (up->onl >> 3) & 1;
1410         bool a1_on = (up->onl >> 2) & 1;
1411         bool b_on  = (up->onl >> 1) & 1;
1412         bool b1_on = (up->onl >> 0) & 1;
1413         // sub_enable [slot * 2 + half]: slot 0 = lower store, 1 = upper
1414         bool sub_enable[4];
1415         if (up->lwr)   // store B is lower
1416           {
1417             sub_enable[0] = b_on; sub_enable[1] = b1_on;
1418             sub_enable[2] = a_on; sub_enable[3] = a1_on;
1419           }
1420         else
1421           {
1422             sub_enable[0] = a_on; sub_enable[1] = a1_on;
1423             sub_enable[2] = b_on; sub_enable[3] = b1_on;
1424           }
1425         // The upper store is present when its first unit (B, or A with
1426         // LWR) is online; its second unit (B1/A1) is not used without it
1427         // (taken as a hardware rule: B1 is not online while B is offline).
1428         uint upper_wds = (up->lwr ? a_on : b_on) ? lower_wds : 0;
1429         // NEA (bit 0200 enables; 7 bits, 1 = 32K): addresses within the
1430         // SCU at or above it don't exist (AN70).
1431         bool nea_enabled = (up->nea >> 7) & 1;
1432         uint nea_wds     = nea_enabled ? (up->nea & 0177u) << 15 : (4u << 20);
1433 
1434         // The SCU decodes the address it receives, the absolute address
1435         // mod 4M (a 4MW SCU), not the offset from the CPU port's base:
1436         // Multics' scr_util computes the upper store size as
1437         // NEA - mod (base, 4M) - lower store size. The two differ only
1438         // when a port's base is not a multiple of 4M, i.e. on an L68 with
1439         // port size switches below 4M. SM781 13A on such an L68 (256K
1440         // ports) sets SC 1's NEA to its port base + 32K and expects a store
1441         // fault at that address. Stores A/A1/B/B1, NEA and the word kept
1442         // are all chosen by this SCU address.
1443         uint base_wds     = sz_wds * cpu.switches.assignment[port_num];
1444         uint scu_base_wds = base_wds % (4u << 20);
1445 
1446         // Where each store unit is kept in the port's zone of M: its home
1447         // SCU address, store A at 0 and store B at the lower store size
1448         // (stride, below), whatever LWR says, so that LWR moves A and B
1449         // without moving their contents. Kept relative to the port
1450         // window's first SCU address, mod 4M, so that without LWR the
1451         // window is kept from the start of the zone, as setup_scbank_map
1452         // does (ISOLTS: Multics' CPU and the CPU under test share memory).
1453         // Interlaced, the SCU address is below 4M and its 2 bit selects
1454         // the store, so a store's local word address is below
1455         // min (lower store size, 2M), and store B is kept at that stride:
1456         // the same place as without interlace when the lower store is 2M
1457         // or less; with a 4M lower store, A's reachable words are its
1458         // first 2M and B's go in the second 2M (the zone has room for
1459         // 4M, not the 8M of two 4M stores).
1460         uint stride_wds = lower_wds;
1461         if (up->interlace && stride_wds > (2u << 20))
1462           stride_wds = 2u << 20;
1463 
1464         // Mapped word by word if the bank map (64K banks) can't express
1465         // the configuration.
1466         bool fine = up->interlace ||
1467                     lower_wds < 2 * SCBANK_SZ ||   // A/A1 not on a bank boundary
1468                     nea_wds % SCBANK_SZ != 0 ||
1469                     sz_wds % SCBANK_SZ != 0 ||
1470                     base_wds % SCBANK_SZ != 0;
1471 
1472         cpu.sc_num_banks[port_num] = (lower_wds + upper_wds) / SCBANK_SZ;
1473         if (cpu.sc_num_banks[port_num] > port_banks)
1474           cpu.sc_num_banks[port_num] = port_banks;
1475 
1476         if (fine)
1477           {
1478             cpu.sc_fine_port[port_num]      = true;
1479             cpu.sc_fine_interlace[port_num] = up->interlace != 0;
1480             cpu.sc_fine_base[port_num]      = base_wds;
1481             cpu.sc_fine_window[port_num]    = sz_wds;
1482             cpu.sc_fine_scu_base[port_num]  = scu_base_wds;
1483             cpu.sc_fine_lower_wds[port_num] = lower_wds;
1484             cpu.sc_fine_upper_wds[port_num] = upper_wds;
1485             cpu.sc_fine_nea_wds[port_num]   = nea_wds;
1486             cpu.sc_fine = true;
1487             for (uint slot = 0; slot < 2; slot ++)
1488               for (uint unit = 0; unit < SC_FINE_UNITS; unit ++)
1489                 {
1490                   cpu.sc_fine_phys[port_num][slot][unit] = -1;
1491                   uint local_wd = unit * SC_FINE_UNIT;
1492                   if (local_wd >= (slot ? upper_wds : lower_wds))
1493                     continue;
1494                   if (! sub_enable[slot * 2 + (local_wd >= half_wds ? 1 : 0)])
1495                     continue;
1496                   uint home_store = up->lwr ? 1 - slot : slot;  // 0 = A, 1 = B
1497                   uint home = home_store * stride_wds + local_wd;
1498                   uint rel  = (home + (4u << 20) - scu_base_wds) % (4u << 20);
1499                   cpu.sc_fine_phys[port_num][slot][unit] =
1500                     (int) port_num * (int) ZONE_SZ + (int) rel;
1501                 }
1502             // sc_addr_map and sc_scu_map stay -1 for the window: a 64K
1503             // bank can't describe a 32K window. sc_fine_map maps every
1504             // address of the window, and sc_port_for_addr finds its port.
1505             continue;
1506           }
1507 
1508         // By bank: every unit, the NEA boundary and the window are whole
1509         // banks here.
1510         uint scu_base_bks = scu_base_wds / SCBANK_SZ;
1511         for (uint n_bank = 0; n_bank < port_banks; n_bank ++)
1512           {
1513             uint scu_wd = scu_base_wds + n_bank * SCBANK_SZ;
1514             if (scu_wd >= lower_wds + upper_wds || scu_wd >= nea_wds)
1515               continue;
1516             uint slot = scu_wd >= lower_wds ? 1 : 0;
1517             uint local_wd = scu_wd - slot * lower_wds;
1518             if (! sub_enable[slot * 2 + (local_wd >= half_wds ? 1 : 0)])
1519               continue;
1520             uint addr_bks = base_addr_bks + n_bank;
1521             if (addr_bks >= N_SCBANKS)
1522               continue;
1523             if (cpu.sc_addr_map [addr_bks] != -1)
1524               continue;
1525             uint home_store = up->lwr ? 1 - slot : slot;
1526             uint home_bks = (home_store * stride_wds + local_wd) / SCBANK_SZ;
1527             int phys_bank = scu_phys_bank (home_bks, 0, scu_base_bks);
1528             cpu.sc_addr_map[addr_bks] = (int) port_num * (int) ZONE_SZ + phys_bank * (int) SCBANK_SZ;
1529             cpu.sc_scu_map[addr_bks]  = port_num;
1530           }
1531       }
1532   }
1533 
1534 // The CPU port whose memory holds absolute address addr, or -1: a port
1535 // mapped word by word (sc_fine_port, T&D) if addr is in its window, else
1536 // the bank map's port. The port of a word-mapped window is returned for
1537 // every address of the window, as the SCU is there even where a store
1538 // unit is offline or beyond NEA (sc_fine_map decides those).
1539 int sc_port_for_addr (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1540   {
1541     if (cpu.sc_fine)
1542       for (uint port_num = 0; port_num < N_SCU_PORTS; port_num ++)
1543         {
1544           if (! cpu.sc_fine_port[port_num])
1545             continue;
1546           uint base = cpu.sc_fine_base[port_num];
1547           if (addr >= base && addr - base < cpu.sc_fine_window[port_num])
1548             return (int) port_num;
1549         }
1550     uint pg = addr / SCBANK_SZ;
1551     if (pg >= N_SCBANKS)
1552       return -1;
1553     return cpu.sc_scu_map[pg];
1554   }
1555 
1556 // T&D: the SCU holding absolute address addr (via the CPU port that the
1557 // bank map assigns it to), or -1.
1558 int tandd_scu_for_addr (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1559   {
1560     int port = sc_port_for_addr (cpup, addr);
1561     if (port < 0)
1562       return -1;
1563     return (int) cables->cpu_to_scu[current_running_cpu_idx][port].scu_unit_idx;
1564   }
1565 
1566 // The mode register's sdpap (data) and separ (ZAC) bits are for the next
1567 // store instruction, which consumes both (AL39: the processor resets bit
1568 // 20/21; SM784 08 sets both). True if separ was set: ZAC has the higher
1569 // illegal action priority (2, data parity 6).
1570 static bool consume_parity_bits (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
1571   {
1572     bool zac = cpu.MR.separ;
1573     cpu.MR.separ = 0;
1574     cpu.MR.sdpap = 0;
1575     putbits36_1 (& cpu.MR.r, 20, 0);
1576     putbits36_1 (& cpu.MR.r, 21, 0);
1577     return zac;
1578   }
1579 
1580 // AL39 table 3-2 priority of a system controller illegal action code
1581 // (lower is reported first).
1582 static int ia_priority (uint ia)
     /* [previous][next][first][last][top][bottom][index][help] */
1583   {
1584     static const int prio [16] = { 99, 99, 5, 1, 99, 12, 11, 10, 4, 13, 3, 7, 2, 6, 8, 9 };
1585     return prio [ia & 017];
1586   }
1587 
1588 // T&D: a store instruction with sdpap/separ pending or to a store unit
1589 // that is not ready. The system controller's mode register decides
1590 // whether it is stored and which illegal action is signalled; an illegal
1591 // action gives a parity fault (store fault for not ready) unless the
1592 // parity mask is on (SM782-SM784). Called by every store path; true if it
1593 // did (or suppressed) the store.
1594 COLD bool sdpap_store_tandd (cpu_state_t * cpup, word24 addr, word36 * data, uint nWords)
     /* [previous][next][first][last][top][bottom][index][help] */
1595   {
1596     if (! cpu.tweaks.tandd_mode)
1597       return false;
1598     bool notReady = scuGoInhibitMask && scuStoreNotReady (cpup, addr);
1599     bool parity = cpu.MR.separ || cpu.MR.sdpap;
1600     if (! (notReady || parity))
1601       return false;
1602     bool zac = false, doStore = ! notReady, keepBadParity = false;
1603     uint ia = 0;
1604     if (parity)
1605       {
1606         // separ applies to every memory cycle of the next store
1607         zac = consume_parity_bits (cpup);
1608         bool parityStore;
1609         ia = scuStoreParityIA (cpup, addr, zac, & parityStore, & keepBadParity);
1610         doStore = doStore && parityStore;
1611       }
1612     // Both: the SC reports the higher priority one (SM784 08)
1613     if (notReady && (! ia || ia_priority (013) < ia_priority (ia))) //-V536
1614       {
1615         tandd_set_nea_port (cpup, addr);
1616         doFault (FAULT_STR, (_fault_subtype) {.fault_str_subtype=flt_str_nrdy}, "store unit not ready");
1617       }
1618     if (doStore)
1619       {
1620         // Through the cache, like any other store: a block the CPU has
1621         // cached must see the new data (SM783 02 reads it back).
1622         if (cpu.useZone)
1623           cache_write_zone (cpup, addr, * data, "PARITY_STORE");
1624         else
1625           cache_writeN (cpup, addr, data, nWords, "PARITY_STORE");
1626         if (keepBadParity && ! zac)
1627           for (uint i = 0; i < nWords; i ++)
1628             {
1629               bad_parity_mark (addr + i);
1630               cacheStoreBadParity (cpup, addr + i);
1631             }
1632       }
1633     if (ia)
1634       {
1635         tandd_set_nea_port (cpup, addr);
1636         SETF (cpu.cu.IR, I_PERR);
1637         if (! TST_I_PMASK)   // the parity mask inhibits the fault
1638           doFault (FAULT_PAR, (_fault_subtype) {.bits=ia}, zac ? "separ" : "sdpap");
1639       }
1640     return true;
1641   }
1642 
1643 // T&D: a system controller command (smic, sscr, smcm) sent with
1644 // sdpap/separ pending: refused with IA 14 (ZAC) / 15 (data) unless the SC
1645 // mode register has parity_disable (SM783 ZAC-PARITY). True if the command
1646 // must not be done.
1647 bool sc_command_parity (cpu_state_t * cpup, uint scuUnitIdx, uint cpuPortNum)
     /* [previous][next][first][last][top][bottom][index][help] */
1648   {
1649     if (! cpu.tweaks.tandd_mode || ! (cpu.MR.separ || cpu.MR.sdpap))
1650       return false;
1651     bool zac = consume_parity_bits (cpup);
1652     uint ia = scuCommandParityIA (scuUnitIdx, zac);
1653     if (! ia)
1654       return false;
1655     cpu.neaPort = (word3) cpuPortNum;
1656     SETF (cpu.cu.IR, I_PERR);
1657     if (! TST_I_PMASK)
1658       doFault (FAULT_PAR, (_fault_subtype) {.bits=ia}, zac ? "separ command" : "sdpap command");
1659     return true;
1660   }
1661 
1662 // T&D: words stored with incorrect parity kept by the store unit (SC mode
1663 // register parity_disable + parity_override). Reading one faults; a normal
1664 // store clears it.
1665 #define N_BAD_PARITY 16
1666 uint nBadParity = 0;
1667 static word24 badParity[N_BAD_PARITY];
1668 
1669 // See dps8_cpu.h
1670 #if defined(THREADZ) || defined(LOCKLESS)
1671 atomic_bool tanddAnyOn = false;
1672 #else
1673 bool tanddAnyOn = false;
1674 #endif
1675 
1676 void tanddUpdateAnyOn (void)
     /* [previous][next][first][last][top][bottom][index][help] */
1677   {
1678     bool on = false;
1679     for (uint i = 0; i < N_CPU_UNITS_MAX; i ++)
1680       {
1681         if (cpus[i].tweaks.tandd_mode)
1682           on = true;
1683         else
1684           cpus[i].tanddFetched = false;
1685         cpus[i].lufXferTrack = (cpus[i].tweaks.tandd_mode ||
1686                                 cpus[i].tweaks.isolts_mode) &&
1687                                ! cpus[i].tweaks.l68_mode;
1688         if (! cpus[i].lufXferTrack)
1689           cpus[i].lufAfterXfer = false;
1690       }
1691 #if defined(THREADZ) || defined(LOCKLESS)
1692     atomic_store_explicit (& tanddAnyOn, on, memory_order_relaxed);
1693 #else
1694     tanddAnyOn = on;
1695 #endif
1696     fullModelUpdate ();
1697   }
1698 
1699 // See dps8_cpu.h
1700 #if defined(THREADZ) || defined(LOCKLESS)
1701 atomic_bool fullModelOn = false;
1702 #else
1703 bool fullModelOn = false;
1704 #endif
1705 
1706 void fullModelUpdate (void)
     /* [previous][next][first][last][top][bottom][index][help] */
1707   {
1708     // The L68's own behaviour (instruction pair tracking for the SCU data
1709     // of a fault in an odd instruction, fetch history, PI-AP, ADR TRAP) is
1710     // only in the full copy, so an L68 CPU selects it too
1711     bool on = TANDD_ANY_ON () || CACHE_ANY_ON ();
1712     for (uint i = 0; i < N_CPU_UNITS_MAX; i ++)
1713       if (cpus[i].tweaks.isolts_mode || cpus[i].tweaks.l68_mode)
1714         on = true;
1715     if (on == FULL_MODEL_LOAD ())
1716       return;
1717 #if defined(THREADZ) || defined(LOCKLESS)
1718     atomic_store_explicit (& fullModelOn, on, memory_order_relaxed);
1719 #else
1720     fullModelOn = on;
1721 #endif
1722     // a running CPU changes copies of the instruction loop at its next fetch
1723     for (uint i = 0; i < N_CPU_UNITS_MAX; i ++)
1724       setFetchAttention (& cpus[i]);
1725   }
1726 
1727 void bad_parity_mark (word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1728   {
1729     for (uint i = 0; i < nBadParity; i ++)
1730       if (badParity[i] == addr)
1731         return;
1732     if (nBadParity < N_BAD_PARITY)
1733       badParity[nBadParity ++] = addr;
1734   }
1735 
1736 void bad_parity_clear (word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1737   {
1738     for (uint i = 0; i < nBadParity; i ++)
1739       if (badParity[i] == addr)
1740         {
1741           badParity[i] = badParity[-- nBadParity];
1742           return;
1743         }
1744   }
1745 
1746 bool bad_parity_marked (word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1747   {
1748     for (uint i = 0; i < nBadParity; i ++)
1749       if (badParity[i] == addr)
1750         return true;
1751     return false;
1752   }
1753 
1754 // A read at an even address faults if either word of the double word has
1755 // bad parity, with PARU/PARL for the even/odd word (subtype bits 0100,
1756 // 0200); a read at an odd address faults only if that word does, and then
1757 // sets both. Fits SM782 11/13 and SM783 02/03. The illegal action code
1758 // depends on the SC mode register (scuReadParityIA); the parity mask
1759 // inhibits the fault.
1760 void bad_parity_read (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1761   {
1762     if (! cpu.tweaks.tandd_mode)
1763       return;
1764     bool upper = bad_parity_marked (addr & ~1u);
1765     bool lower = bad_parity_marked (addr | 1u);
1766     if (addr & 1)
1767       {
1768         if (! lower)
1769           return;
1770         upper = true;
1771       }
1772     else if (! (upper || lower))
1773       return;
1774     word24 badAddr = (addr & 1) ? addr : (bad_parity_marked (addr) ? addr : (addr | 1u));
1775     uint ia = scuReadParityIA (cpup, badAddr);
1776     SETF (cpu.cu.IR, I_PERR);
1777     if (TST_I_PMASK)
1778       return;
1779     tandd_set_nea_port (cpup, badAddr);
1780     doFault (FAULT_PAR,
1781              (_fault_subtype) {.bits=(upper ? 0100u : 0u) | (lower ? 0200u : 0u) | ia},
1782              "bad parity read");
1783   }
1784 
1785 // The T&D parts of the memory routines (see TANDD_ANY_ON in dps8_cpu.h).
1786 // They are out of line so that, with T&D mode off, core_read and the rest
1787 // stay small enough for the compiler to inline them.
1788 
1789 // A read: wait out a lockout, and fault on a word stored with bad parity
1790 COLD void tandd_read_hook (cpu_state_t * cpup, word24 addr, uint nWords)
     /* [previous][next][first][last][top][bottom][index][help] */
1791   {
1792     SC_LOCKOUT_WAIT ();
1793     for (uint i = 0; i < nWords; i ++)
1794       BAD_PARITY_READ (addr + i);
1795   }
1796 
1797 // A locked read (the read of a read-alter-rewrite) of a word with bad
1798 // parity locks out the next access
1799 COLD void tandd_read_lock_hook (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1800   {
1801     if (nBadParity && cpu.tweaks.tandd_mode && bad_parity_marked (addr))
1802       cpu.scLockedOut = true;
1803     BAD_PARITY_READ (addr);
1804   }
1805 
1806 // A store (WAIT: unless it completes a locked read-alter-rewrite): the
1807 // words stored have good parity again
1808 COLD void tandd_write_hook (cpu_state_t * cpup, word24 addr, uint nWords, bool wait)
     /* [previous][next][first][last][top][bottom][index][help] */
1809   {
1810     if (wait)
1811       SC_LOCKOUT_WAIT ();
1812     for (uint i = 0; i < nWords; i ++)
1813       BAD_PARITY_WRITE (addr + i);
1814   }
1815 
1816 // SC_MAP_ADDR in T&D mode: the word by word map, and the port of a
1817 // nonexistent address for the illegal action
1818 COLD word24 sc_map_addr_tandd (cpu_state_t * cpup, word24 addr, const char * func)
     /* [previous][next][first][last][top][bottom][index][help] */
1819   {
1820     uint fine_real;
1821     if (cpu.sc_fine && sc_fine_map (cpup, addr, & fine_real))
1822       return fine_real;
1823     uint pgnum = addr / SCBANK_SZ;
1824     uint os = addr % SCBANK_SZ;
1825     int base = cpu.sc_addr_map[pgnum];
1826     if (base < 0)
1827       {
1828         if (cpu.tweaks.tandd_mode)
1829           tandd_set_nea_port (cpup, addr);
1830         doFault (FAULT_STR, fst_str_nea, func);
1831       }
1832     return (word24) base + os;
1833   }
1834 
1835 // T&D: a locked read (RMW) of a bad parity word leaves the SC locked; the
1836 // next operand access waits 16 TR counts (SM784 15 needs more than 7;
1837 // inferred length), charged to the TR and the T&D clock. Only an access
1838 // that reaches the SC waits: an operand read that hits in the CPU cache
1839 // does not, and the wait falls on the next access that goes to the SC.
1840 void sc_lockout_wait (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
1841   {
1842     if (cpu.cycle == FETCH_cycle)
1843       return;
1844     cpu.scLockedOut = false;
1845     cpu.rTR = (cpu.rTR - 16u) & MASK27;
1846     cpu.lufTicks += 16;
1847     cpu.tanddTRTicks += 16;
1848   }
1849 
1850 // T&D: map addr if it is in the window of a port that
1851 // setup_scbank_map_tandd maps word by word (sc_fine_port): set *realp to
1852 // where the word is kept in M, or take the store fault, and return true.
1853 // The SCU address (absolute address mod 4M) selects the store and the
1854 // word within it. Without interlace the lower store holds the SCU
1855 // addresses below its size and the upper store the next ones. With SCU
1856 // internal interlace the stores alternate double words: the 2 bit selects
1857 // the store, and the store word is the address with that bit removed.
1858 // (The double word granularity is inferred from SM781 17A, which probes
1859 // location 2; as dps8m4.)
1860 bool sc_fine_map (cpu_state_t * cpup, word24 addr, uint * realp)
     /* [previous][next][first][last][top][bottom][index][help] */
1861   {
1862     for (uint port_num = 0; port_num < N_SCU_PORTS; port_num ++)
1863       {
1864         if (! cpu.sc_fine_port[port_num])
1865           continue;
1866         uint base = cpu.sc_fine_base[port_num];
1867         if (addr < base || addr - base >= cpu.sc_fine_window[port_num])
1868           continue;
1869         uint scu   = cpu.sc_fine_scu_base[port_num] + (addr - base);
1870         uint lower = cpu.sc_fine_lower_wds[port_num];
1871         uint upper = cpu.sc_fine_upper_wds[port_num];
1872         uint store, word;
1873         bool present = true;
1874         if (cpu.sc_fine_interlace[port_num])
1875           {
1876             if (scu >= 2 * lower)
1877               present = false;
1878             store = (scu >> 1) & 1;
1879             word  = ((scu >> 2) << 1) | (scu & 1);
1880             // With only one store present the double words that would be
1881             // in the other store don't exist (SM781 17A: location 2 gives
1882             // a store fault), reported as store not ready (IA 13), not NEA.
1883             if (present && store && ! upper)
1884               {
1885                 tandd_set_nea_port (cpup, addr);
1886                 doFault (FAULT_STR, (_fault_subtype) {.fault_str_subtype=flt_str_nrdy},
1887                          "interlace: store not present");
1888               }
1889           }
1890         else
1891           {
1892             store = scu >= lower ? 1 : 0;
1893             word  = scu - store * lower;
1894             if (word >= (store ? upper : lower))
1895               present = false;
1896           }
1897         // NEA applies to the address the SCU receives, not to the word
1898         // within the selected store.
1899         int phys = -1;
1900         if (present && scu < cpu.sc_fine_nea_wds[port_num] && word < (4u << 20))
1901           phys = cpu.sc_fine_phys[port_num][store][word / SC_FINE_UNIT];
1902         if (phys < 0)
1903           {
1904             tandd_set_nea_port (cpup, addr);
1905             doFault (FAULT_STR, fst_str_nea, "nonexistent address");
1906           }
1907         * realp = (uint) phys + word % SC_FINE_UNIT;
1908         return true;
1909       }
1910     return false;
1911   }
1912 
1913 // T&D: is addr in the window of a port whose SCU interlaces its stores?
1914 bool sc_fine_interlaced (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1915   {
1916     for (uint port_num = 0; port_num < N_SCU_PORTS; port_num ++)
1917       if (cpu.sc_fine_port[port_num] && cpu.sc_fine_interlace[port_num] &&
1918           addr >= cpu.sc_fine_base[port_num] &&
1919           addr - cpu.sc_fine_base[port_num] < cpu.sc_fine_window[port_num])
1920         return true;
1921     return false;
1922   }
1923 
1924 // T&D: sc_fine_map backwards, for the ports whose SCU interlaces its
1925 // stores: if the word at REAL in M is one of those, set *addrp to its
1926 // absolute address and return true.
1927 bool sc_fine_unmap (cpu_state_t * cpup, uint real, word24 * addrp)
     /* [previous][next][first][last][top][bottom][index][help] */
1928   {
1929     for (uint port_num = 0; port_num < N_SCU_PORTS; port_num ++)
1930       {
1931         if (! cpu.sc_fine_port[port_num] || ! cpu.sc_fine_interlace[port_num] ||
1932             real / ZONE_SZ != port_num)
1933           continue;
1934         for (uint store = 0; store < 2; store ++)
1935           for (uint unit = 0; unit < SC_FINE_UNITS; unit ++)
1936             {
1937               int phys = cpu.sc_fine_phys[port_num][store][unit];
1938               if (phys < 0 || real < (uint) phys || real - (uint) phys >= SC_FINE_UNIT)
1939                 continue;
1940               uint word = unit * SC_FINE_UNIT + (real - (uint) phys);
1941               uint scu  = ((word >> 1) << 2) | (store << 1) | (word & 1);
1942               if (scu < cpu.sc_fine_scu_base[port_num] ||
1943                   scu - cpu.sc_fine_scu_base[port_num] >= cpu.sc_fine_window[port_num])
1944                 return false;
1945               * addrp = (word24) (cpu.sc_fine_base[port_num] + scu - cpu.sc_fine_scu_base[port_num]);
1946               return true;
1947             }
1948       }
1949     return false;
1950   }
1951 
1952 // T&D: the CPU port whose window (port assignment and store size
1953 // switches) holds addr; SCU word 1 IACHN of an NEA store fault.
1954 void tandd_set_nea_port (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
1955   {
1956     uint dps8m_store_table [8] =
1957       { 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304 };
1958     uint l68_store_table [8] =
1959       { 32768, 65536, 4194304, 131072, 524288, 1048576, 2097152, 262144 };
1960     cpu.neaPort = 0;
1961     cpu.neaNoPort = true;
1962     int n_ports = cpu.tweaks.l68_mode ? N_L68_CPU_PORTS : N_DPS8M_CPU_PORTS;
1963     for (int port_num = 0; port_num < n_ports; port_num ++)
1964       {
1965         if (! cpu.switches.enable [port_num])
1966           continue;
1967         uint store_size = cpu.switches.store_size [port_num];
1968         // ISOLTS on an L68: size code 3 means 64K (the "cpu test"
1969         // free-edge connector), as in setup_scbank_map's
1970         // l68_isolts_store_table; configure_test_cpu checks that an LDA
1971         // at 64K takes a store fault.
1972         uint sz_wds = cpu.tweaks.l68_mode ?
1973                         (cpu.tweaks.isolts_mode && store_size == 3 ?
1974                            65536 : l68_store_table [store_size]) :
1975                         dps8m_store_table [store_size];
1976         uint base = sz_wds * cpu.switches.assignment[port_num];
1977         if (addr >= base && addr - base < sz_wds)
1978           {
1979             cpu.neaPort = (word3) port_num;
1980             cpu.neaNoPort = false;
1981             return;
1982           }
1983       }
1984   }
1985 
1986 void setup_scbank_map (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
1987   {
1988     // The word-by-word map is T&D only, so the normal map must not leave
1989     // a previous T&D map's ports active (tandd_mode turned off, then a
1990     // CPU reset). setup_scbank_map_tandd sets them again.
1991     cpu.sc_fine = false;
1992     for (uint p = 0; p < N_SCU_PORTS; p ++)
1993       cpu.sc_fine_port[p] = false;
1994 
1995     if (cpu.tweaks.tandd_mode)
1996       {
1997         setup_scbank_map_tandd (cpup);
1998         return;
1999       }
2000 
2001     // Initialize to unmapped
2002     for (uint pg = 0; pg < N_SCBANKS; pg ++)
2003       {
2004         cpu.sc_addr_map [pg] = -1;
2005         cpu.sc_scu_map  [pg] = -1;
2006       }
2007     for (uint u = 0; u < N_SCU_UNITS_MAX; u ++)
2008       cpu.sc_num_banks[u] = 0;
2009 
2010     // For each port
2011     for (int port_num = 0; port_num < (cpu.tweaks.l68_mode ? N_L68_CPU_PORTS : N_DPS8M_CPU_PORTS); port_num ++)
2012       {
2013         // Ignore disabled ports
2014         if (! cpu.switches.enable [port_num])
2015           continue;
2016 
2017         // Ignore disconnected ports
2018         // This will happen during early initialization,
2019         // before any cables are run.
2020         if (! cables->cpu_to_scu[current_running_cpu_idx][port_num].in_use)
2021           {
2022             continue;
2023           }
2024 
2025         // Calculate the amount of memory in the SCU in words
2026         uint store_size = cpu.switches.store_size [port_num];
2027         uint dps8m_store_table [8] =
2028           { 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304 };
2029 // ISOLTS sez:
2030 // for DPS88:
2031 //   3. set store size switches to 2222.
2032 // for L68:
2033 //   3. remove the right free-edge connector on the 645pq wwb at slot ab28.
2034 //
2035 // During ISOLTS initialization, it requires that the memory switch be set to
2036 // '3' for all eight ports; this corresponds to '2' for the DPS8M (131072)
2037 // Then:
2038 // isolts: a "lda 65536" (64k) failed to produce a store fault
2039 //
2040 // So it seems that the memory size is expected to be 64K, not 128K as per
2041 // the switches; presumably step 3 causes this. Fake it by tweaking store table:
2042 //
2043         uint l68_store_table [8] =
2044           { 32768, 65536, 4194304, 131072, 524288, 1048576, 2097152, 262144 };
2045         uint l68_isolts_store_table [8] =
2046           { 32768, 65536, 4194304, 65536, 524288, 1048576, 2097152, 262144 };
2047 
2048         uint sz_wds =
2049           cpu.tweaks.l68_mode ?
2050             cpu.tweaks.isolts_mode ?
2051               l68_isolts_store_table [store_size] :
2052                 l68_store_table [store_size] :
2053           dps8m_store_table [store_size];
2054 
2055         // Calculate the base address that will be assigned to the SCU
2056         uint base_addr_wds = sz_wds * cpu.switches.assignment[port_num];
2057 
2058         // Now convert to SCBANK_SZ (number of banks)
2059         uint num_banks             = sz_wds / SCBANK_SZ;
2060         cpu.sc_num_banks[port_num] = num_banks;
2061         uint base_addr_bks         = base_addr_wds / SCBANK_SZ;
2062 
2063         // For each page handled by the SCU
2064         for (uint pg = 0; pg < num_banks; pg ++)
2065           {
2066             // What is the address of this bank?
2067             uint addr_bks = base_addr_bks + pg;
2068             // Past the end of memory?
2069             if (addr_bks < N_SCBANKS)
2070               {
2071                 // Has this address been already assigned?
2072                 if (cpu.sc_addr_map [addr_bks] != -1)
2073                   {
2074                     sim_warn ("scbank overlap addr_bks %d (%o) old port %d "
2075                                 "newport %d\r\n",
2076                                 addr_bks, addr_bks, cpu.sc_addr_map [addr_bks], port_num);
2077                   }
2078                 else
2079                   {
2080                     // Assign it
2081                     cpu.sc_addr_map[addr_bks] = (int)((int)port_num * (int)ZONE_SZ + (int)pg * (int)SCBANK_SZ);
2082                     cpu.sc_scu_map[addr_bks]  = port_num;
2083                   }
2084               }
2085             else
2086               {
2087                 sim_warn ("addr_bks too big port %d addr_bks %d (%o), "
2088                             "limit %d (%o)\r\n",
2089                             port_num, addr_bks, addr_bks, N_SCBANKS, N_SCBANKS);
2090               }
2091           }
2092 
2093       } // for port_num
2094 
2095     //for (uint pg = 0; pg < N_SCBANKS; pg ++)
2096      //sim_printf ("pg %o map: %08o\r\n", pg, cpu.sc_addr_map[pg]);
2097   } // sc_bank_map
2098 
2099 // True when the devices are to behave as the T&D tape expects (set sys
2100 // config=tandd_io=on); for device code, which has no CPU context. This is
2101 // separate from the CPUs' tandd_mode: ISOLTS needs tandd_mode on the CPU
2102 // under test while Multics goes on using the I/O system, so a CPU in T&D
2103 // mode must not change device behaviour (e.g. poll_mpc's EURC commands).
2104 
2105 bool tandd_io_mode (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2106   {
2107     return sys_opts.tandd_io;
2108   }
2109 
2110 int lookup_cpu_mem_map (cpu_state_t * cpup, word24 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
2111   {
2112     return sc_port_for_addr (cpup, addr);
2113   }
2114 
2115 //
2116 // serial.txt format
2117 //
2118 //      sn:  number[,number]
2119 //
2120 //  Additional numbers will be for multi-cpu systems.
2121 //  XXX: Other fields to be added.
2122 
2123 #if !defined(PERF_STRIP)
2124 static void get_serial_number (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2125   {
2126       bool havesn = false;
2127       FILE * fp = fopen ("./serial.txt", "r");
2128     while (fp && ! feof (fp))
2129       {
2130         char buffer [81] = "";
2131 # if !defined(__clang_analyzer__)
2132         char * checksn = fgets (buffer, sizeof (buffer), fp);
2133         (void)checksn;
2134 # endif
2135         uint cpun, sn;
2136         if (sscanf (buffer, "sn: %u", & sn) == 1)
2137           {
2138             if (cpu.switches.serno)
2139               sim_msg ("\r\nReplacing CPU serial number:\r\n");
2140             cpu.switches.serno = sn;
2141             if (!sim_quiet)
2142               {
2143                 sim_msg ("%s CPU serial number: %u\r\n", sim_name, cpu.switches.serno);
2144               }
2145             havesn = true;
2146           }
2147         else if (sscanf (buffer, "sn%u: %u", & cpun, & sn) == 2)
2148           {
2149             if (cpun < N_CPU_UNITS_MAX)
2150               {
2151                 if (cpus[cpun].switches.serno)
2152                   sim_msg ("\r\nReplacing CPU %u serial number:\r\n", cpun);
2153                 cpus[cpun].switches.serno = sn;
2154                 if (!sim_quiet)
2155                   {
2156                     sim_msg ("%s CPU %u serial number: %u\r\n",
2157                     sim_name, cpun, cpus[cpun].switches.serno);
2158                   }
2159                 havesn = true;
2160               }
2161           }
2162       }
2163     if (!havesn)
2164       {
2165         if (!sim_quiet)
2166           {
2167             sim_msg ("\r\nPlease register your system at https://dps8m.gitlab.io/register/\r\n");
2168             sim_msg ("or create the file 'serial.txt' containing the line 'sn: 0'.\r\n\r\n");
2169           }
2170       }
2171     if (fp)
2172       fclose (fp);
2173   }
2174 #endif /* if !defined(PERF_STRIP) */
2175 
2176 #if defined(STATS)
2177 static void do_stats (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2178   {
2179     static struct timespec stats_time;
2180     static bool first = true;
2181     if (first)
2182       {
2183         first = false;
2184         clock_gettime (CLOCK_BOOTTIME, & stats_time);
2185         sim_msg ("stats started\r\n");
2186       }
2187     else
2188       {
2189         struct timespec now, delta;
2190         clock_gettime (CLOCK_BOOTTIME, & now);
2191         timespec_diff (& stats_time, & now, & delta);
2192         stats_time = now;
2193         sim_msg ("stats %6ld.%02ld\r\n", delta.tv_sec,
2194                     delta.tv_nsec / 10000000);
2195 
2196         sim_msg ("Instruction counts\r\n");
2197         for (uint i = 0; i < 8; i ++)
2198           {
2199 # if defined(WIN_STDIO)
2200             sim_msg (" %9lld\r\n", (long long int) cpus[i].instrCnt);
2201 # else
2202             sim_msg (" %'9lld\r\n", (long long int) cpus[i].instrCnt);
2203 # endif /* if defined(WIN_STDIO) */
2204             cpus[i].instrCnt = 0;
2205           }
2206         sim_msg ("\r\n");
2207       }
2208   }
2209 #endif
2210 
2211 // The 100Hz timer has expired; poll I/O
2212 
2213 #if !defined(PERF_STRIP)
2214 static void ev_poll_cb (UNUSED uv_timer_t * handle)
     /* [previous][next][first][last][top][bottom][index][help] */
2215   {
2216     cpu_state_t * cpup = _cpup;
2217 
2218     // Call the one hertz stuff every 100 loops
2219     static uint oneHz = 0;
2220     if (oneHz ++ >= sys_opts.sys_slow_poll_interval) // ~ 1Hz
2221       {
2222         oneHz = 0;
2223         rdrProcessEvent ();
2224 # if defined(STATS)
2225         do_stats ();
2226 # endif
2227         cpu.instrCntT0 = cpu.instrCntT1;
2228         cpu.instrCntT1 = cpu.instrCnt;
2229       }
2230     fnpProcessEvent ();
2231 # if defined(WITH_SOCKET_DEV)
2232 #  if !defined(__MINGW64__) && !defined(__MINGW32__) && !defined(CROSS_MINGW32) && !defined(CROSS_MINGW64)
2233     sk_process_event ();
2234 #  endif /* if !defined(__MINGW64__) && !defined(__MINGW32__) && !defined(CROSS_MINGW32) && !defined(CROSS_MINGW64) */
2235 # endif /* if defined(WITH_SOCKET_DEV) */
2236     consoleProcess ();
2237 # if defined(IO_ASYNC_PAYLOAD_CHAN)
2238     iomProcess ();
2239 # endif
2240 # if defined(WITH_ABSI_DEV)
2241 #  if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(CROSS_MINGW32) && !defined(CROSS_MINGW64)
2242     absi_process_event ();
2243 #  endif /* if !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(CROSS_MINGW32) && !defined(CROSS_MINGW64) */
2244 # endif /* if defined(WITH_ABSI_DEV) */
2245 # if defined(WITH_MGP_DEV)
2246     mgp_process_event ();
2247 # endif /* if defined(WITH_MGP_DEV) */
2248 # if defined(WITH_NET_DEV)
2249     net_process_event ();
2250 # endif /* if defined(WITH_NET_DEV) */
2251     PNL (panel_process_event ());
2252   }
2253 #endif /* if !defined(PERF_STRIP) */
2254 
2255 // called once initialization
2256 
2257 void cpu_init (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2258   {
2259 // !!!! Do not use 'cpu' in this routine; usage of 'cpus' violates 'restrict'
2260 // !!!! attribute
2261 
2262     M = system_state->M;
2263 #if defined(M_SHARED)
2264     cpus = system_state->cpus;
2265 #endif /* if defined(M_SHARED) */
2266 
2267 #if !defined(SPEED)
2268     (void)memset (& watch_bits, 0, sizeof (watch_bits));
2269 #endif /* if !defined(SPEED) */
2270 
2271     set_cpu_idx (0);
2272 
2273     (void)memset (cpus, 0, sizeof (cpu_state_t) * N_CPU_UNITS_MAX);
2274 
2275 #if !defined(PERF_STRIP)
2276     get_serial_number (_cpup);
2277 
2278     ev_poll_loop = uv_default_loop ();
2279     uv_timer_init (ev_poll_loop, & ev_poll_handle);
2280     // 10 ms == 100Hz
2281     unsigned int poll_interval = sys_opts.sys_poll_interval;
2282     uv_timer_start (& ev_poll_handle, ev_poll_cb, poll_interval, poll_interval);
2283 #endif /* if !defined(PERF_STRIP) */
2284     // TODO: reset *all* other structures to zero
2285 
2286     cpu_state_t * cpup = _cpup;
2287 
2288     cpu.instrCnt = 0;
2289     cpu.cycleCnt = 0;
2290     for (int i = 0; i < N_FAULTS; i ++)
2291       cpu.faultCnt [i] = 0;
2292 
2293 #if defined(MATRIX)
2294     initializeTheMatrix ();
2295 #endif /* if defined(MATRIX) */
2296   }
2297 
2298 void cpu_stop_poll_timer (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2299   {
2300 #if !defined(PERF_STRIP)
2301     if (ev_poll_loop && !uv_is_closing ((uv_handle_t *) & ev_poll_handle))
2302       {
2303         (void)uv_timer_stop (& ev_poll_handle);
2304         uv_close ((uv_handle_t *) & ev_poll_handle, NULL);
2305       }
2306 #endif /* if !defined(PERF_STRIP) */
2307   }
2308 
2309 static void cpu_reset (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2310   {
2311     for (uint i = 0; i < N_CPU_UNITS_MAX; i ++)
2312       {
2313         cpu_reset_unit_idx (i, true);
2314       }
2315 
2316     set_cpu_idx (0);
2317 
2318 #if defined(TESTING)
2319     cpu_state_t * cpup = _cpup;
2320     sim_debug (DBG_INFO, & cpu_dev, "CPU reset: Running\r\n");
2321 #endif
2322   }
2323 
2324 static t_stat sim_cpu_reset (UNUSED DEVICE *dptr)
     /* [previous][next][first][last][top][bottom][index][help] */
2325   {
2326     //(void)memset (M, -1, MEMSIZE * sizeof (word36));
2327 
2328     // Fill DPS8M memory with zeros, plus a flag only visible to the emulator
2329     // marking the memory as uninitialized.
2330 
2331     cpu_reset ();
2332     return SCPE_OK;
2333   }
2334 
2335 /* Memory examine */
2336 //  t_stat examine_routine (t_val *eval_array, t_addr addr, UNIT *uptr, int32
2337 //  switches)
2338 //  Copy  sim_emax consecutive addresses for unit uptr, starting
2339 //  at addr, into eval_array. The switch variable has bit<n> set if the n'th
2340 //  letter was specified as a switch to the examine command.
2341 // Not true...
2342 
2343 static t_stat cpu_ex (t_value *vptr, t_addr addr, UNUSED UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
2344                       UNUSED int32 sw)
2345   {
2346     if (addr>= MEMSIZE)
2347         return SCPE_NXM;
2348     if (vptr != NULL)
2349       {
2350         *vptr = M[addr] & DMASK;
2351       }
2352     return SCPE_OK;
2353   }
2354 
2355 /* Memory deposit */
2356 
2357 static t_stat cpu_dep (t_value val, t_addr addr, UNUSED UNIT * uptr,
     /* [previous][next][first][last][top][bottom][index][help] */
2358                        UNUSED int32 sw)
2359   {
2360     if (addr >= MEMSIZE) return SCPE_NXM;
2361     M[addr] = val & DMASK;
2362     cachePurgeAll ((word24) addr);
2363     return SCPE_OK;
2364   }
2365 
2366 /*
2367  * register stuff ...
2368  */
2369 
2370 #if defined(M_SHARED)
2371 // scp has to have a statically allocated IC to refer to.
2372 static word18 dummy_IC;
2373 #endif
2374 
2375 static REG cpu_reg[] =
2376   {
2377     // IC must be the first; see sim_PC.
2378 #if defined(M_SHARED)
2379     { ORDATA (IC, dummy_IC,       VASIZE), 0, 0, 0 },
2380 #else
2381     { ORDATA (IC, cpus[0].PPR.IC, VASIZE), 0, 0, 0 },
2382 #endif
2383     { NULL, NULL, 0, 0, 0, 0,  NULL, NULL, 0, 0, 0 }
2384   };
2385 
2386 /*
2387  * scp interface
2388  */
2389 
2390 REG *sim_PC = & cpu_reg[0];
2391 
2392 /* CPU device descriptor */
2393 
2394 DEVICE cpu_dev =
2395   {
2396     "CPU",          // name
2397     cpu_unit,       // units
2398     cpu_reg,        // registers
2399     cpu_mod,        // modifiers
2400     N_CPU_UNITS,    // #units
2401     8,              // address radix
2402     PASIZE,         // address width
2403     1,              // addr increment
2404     8,              // data radix
2405     36,             // data width
2406     & cpu_ex,       // examine routine
2407     & cpu_dep,      // deposit routine
2408     & sim_cpu_reset,// reset routine
2409     & cpu_boot,     // boot routine
2410     NULL,           // attach routine
2411     NULL,           // detach routine
2412     NULL,           // context
2413     DEV_DEBUG,      // device flags
2414     0,              // debug control flags
2415     cpu_dt,         // debug flag names
2416     NULL,           // memory size change
2417     NULL,           // logical name
2418     NULL,           // help
2419     NULL,           // attach help
2420     NULL,           // help context
2421     NULL,           // description
2422     NULL
2423   };
2424 
2425 #if defined(M_SHARED)
2426 cpu_state_t * cpus = NULL;
2427 #else
2428 cpu_state_t cpus [N_CPU_UNITS_MAX];
2429 #endif
2430 #if defined(THREADZ) || defined(LOCKLESS)
2431 __thread cpu_state_t * restrict _cpup;
2432 #else
2433 cpu_state_t * restrict _cpup;
2434 #endif
2435 
2436 // Scan the SCUs; it one has an interrupt present, return the fault pair
2437 // address for the highest numbered interrupt on that SCU. If no interrupts
2438 // are found, return 1.
2439 
2440 // Called with SCU lock set
2441 
2442 static uint get_highest_intr (cpu_state_t *cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2443   {
2444     uint fp = 1;
2445     for (uint scu_unit_idx = 0; scu_unit_idx < N_SCU_UNITS_MAX; scu_unit_idx ++)
2446       {
2447         if (cpu.events.XIP [scu_unit_idx])
2448           {
2449             fp = scu_get_highest_intr (scu_unit_idx); // CALLED WITH SCU LOCK
2450             if (fp != 1)
2451               break;
2452           }
2453       }
2454     return fp;
2455   }
2456 
2457 // Diagnostic for slow DIS wakeups of a CPU not in Multics (the ISOLTS
2458 // test CPU): with DPS8_DIS_DIAG set in the environment, report every DIS
2459 // wait longer than 3 s, split into the time until an interrupt was set for
2460 // the CPU and the time from then until the CPU noticed it.
2461 static int disDiagOn = -1;
2462 static uint32 disDiagStart[N_CPU_UNITS_MAX];
2463 static uint32 disDiagXip[N_CPU_UNITS_MAX];
2464 
2465 static bool disDiagEnabled (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2466   {
2467     if (disDiagOn < 0)
2468       disDiagOn = getenv ("DPS8_DIS_DIAG") != NULL;
2469     return disDiagOn;
2470   }
2471 
2472 void disDiagEnter (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2473   {
2474     uint i = (uint) current_running_cpu_idx;
2475 #if defined(THREADZ) || defined(LOCKLESS)
2476     if (cpu.inMultics)
2477       return;
2478 #else
2479     (void) cpup;  // only inMultics (threaded builds) needs it
2480 #endif
2481     if (! disDiagEnabled () || i >= N_CPU_UNITS_MAX)
2482       return;
2483     if (disDiagStart[i] == 0)
2484       {
2485         disDiagStart[i] = sim_os_msec () | 1;
2486         disDiagXip[i] = 0;
2487       }
2488   }
2489 
2490 void disDiagInterruptSet (uint i)
     /* [previous][next][first][last][top][bottom][index][help] */
2491   {
2492     if (! disDiagEnabled () || i >= N_CPU_UNITS_MAX)
2493       return;
2494     if (disDiagStart[i] != 0 && disDiagXip[i] == 0)
2495       disDiagXip[i] = sim_os_msec () | 1;
2496   }
2497 
2498 void disDiagWake (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2499   {
2500     uint i = (uint) current_running_cpu_idx;
2501     if (! disDiagEnabled () || i >= N_CPU_UNITS_MAX || disDiagStart[i] == 0)
2502       return;
2503     uint32 now = sim_os_msec ();
2504     // (the "| 1" marking a set time can put it 1 ms after now)
2505     uint32 total = now > disDiagStart[i] ? now - disDiagStart[i] : 0;
2506     if (total > 3000)
2507       {
2508         if (disDiagXip[i])
2509           sim_printf ("DISDIAG CPU %c DIS at %06o: %u ms; interrupt set after %u ms, "
2510                       "noticed %u ms later\r\n", 'A' + i, cpu.PPR.IC, total,
2511                       disDiagXip[i] > disDiagStart[i] ? disDiagXip[i] - disDiagStart[i] : 0,
2512                       now > disDiagXip[i] ? now - disDiagXip[i] : 0);
2513         else
2514           sim_printf ("DISDIAG CPU %c DIS at %06o: %u ms; no interrupt seen being set\r\n",
2515                       'A' + i, cpu.PPR.IC, total);
2516       }
2517     disDiagStart[i] = 0;
2518     disDiagXip[i] = 0;
2519   }
2520 
2521 bool sample_interrupts (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2522   {
2523     cpu.lufCounter = 0;
2524     cpu.lufTicks   = 0;
2525     for (uint scu_unit_idx = 0; scu_unit_idx < N_SCU_UNITS_MAX; scu_unit_idx ++)
2526       {
2527         if (cpu.events.XIP [scu_unit_idx])
2528           {
2529             return true;
2530           }
2531       }
2532     return false;
2533   }
2534 
2535 t_stat simh_hooks (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2536   {
2537     int reason = 0;
2538 
2539     if (breakEnable && stop_cpu)
2540       return STOP_STOP;
2541 
2542     if (cpu.tweaks.isolts_mode == 0)
2543       {
2544         // check clock queue
2545         if (sim_interval <= 0)
2546           {
2547             reason = sim_process_event ();
2548             if ((! breakEnable) && reason == SCPE_STOP)
2549               reason = SCPE_OK;
2550             if (reason)
2551               return reason;
2552           }
2553       }
2554 
2555     sim_interval --;
2556 
2557 #if !defined(THREADZ) && !defined(LOCKLESS)
2558 // This is needed for BCE_TRAP in install scripts
2559     // sim_brk_test expects a 32 bit address; PPR.IC into the low 18, and
2560     // PPR.PSR into the high 12
2561     if (sim_brk_summ &&
2562         sim_brk_test ((cpu.PPR.IC & 0777777) |
2563                       ((((t_addr) cpu.PPR.PSR) & 037777) << 18),
2564                       SWMASK ('E')))  /* breakpoint? */
2565       return STOP_BKPT; /* stop simulation */
2566 # if !defined(SPEED)
2567     if (sim_deb_break && cpu.cycleCnt >= sim_deb_break)
2568       return STOP_BKPT; /* stop simulation */
2569 # endif /* if !defined(SPEED) */
2570 #endif /* if !defined(THREADZ) && !defined(LOCKLESS) */
2571 
2572     return reason;
2573   }
2574 
2575 #if defined(PANEL68)
2576 static void panel_process_event (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2577   {
2578     cpu_state_t * cpup = _cpup;
2579     // INITIALIZE pressed; treat at as a BOOT.
2580     if (cpu.panelInitialize && cpu.DATA_panel_s_trig_sw == 0)
2581       {
2582          // Wait for release
2583          while (cpu.panelInitialize)
2584            ;
2585          if (cpu.DATA_panel_init_sw)
2586            cpu_reset_unit_idx (ASSUME0, true); // INITIALIZE & CLEAR
2587          else
2588            cpu_reset_unit_idx (ASSUME0, false); // INITIALIZE
2589          // XXX Until a boot switch is wired up
2590          do_boot ();
2591       }
2592     // EXECUTE pressed; EXECUTE PB set, EXECUTE FAULT set
2593     if (cpu.DATA_panel_s_trig_sw == 0 &&
2594         cpu.DATA_panel_execute_sw &&  // EXECUTE button
2595         cpu.DATA_panel_scope_sw &&    // 'EXECUTE PB/SCOPE REPEAT' set to PB
2596         cpu.DATA_panel_exec_sw == 0)  // 'EXECUTE SWITCH/EXECUTE FAULT'
2597                                       //  set to FAULT
2598       {
2599         // Wait for release
2600         while (cpu.DATA_panel_execute_sw)
2601           ;
2602 
2603         if (cpu.DATA_panel_exec_sw) // EXECUTE SWITCH
2604           {
2605             cpu_reset_unit_idx (ASSUME0, false);
2606             cpu.cu.IWB = cpu.switches.data_switches;
2607             set_cpu_cycle (cpup, EXEC_cycle);
2608           }
2609          else // EXECUTE FAULT
2610           {
2611             setG7fault (current_running_cpu_idx, FAULT_EXF);
2612           }
2613       }
2614   }
2615 #endif
2616 
2617 #if defined(THREADZ) || defined(LOCKLESS)
2618 bool bce_dis_called = false;
2619 
2620 // The hypervisor CPU for the threadz model
2621 t_stat sim_instr (void)
     /* [previous][next][first][last][top][bottom][index][help] */
2622   {
2623     cpu_state_t * cpup = _cpup;
2624     t_stat reason = 0;
2625 
2626     cacheUpdateAnyOn (); // see dps8_cache.h
2627     tanddUpdateAnyOn (); // see dps8_cpu.h
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     if (cpuThreadz[0].run == false)
2674           createCPUThread (0);
2675     do
2676       {
2677         // Process deferred events and breakpoints
2678         reason = simh_hooks (cpup);
2679         if (reason)
2680           {
2681             break;
2682           }
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         if (bce_dis_called) {
2711           //return STOP_STOP;
2712           reason = STOP_STOP;
2713           break;
2714         }
2715 
2716 # if !defined(PERF_STRIP)
2717 // Loop runs at 1000 Hz
2718 
2719 #  if defined(LOCKLESS)
2720         lock_iom();
2721 #  endif
2722         lock_libuv ();
2723         uv_run (ev_poll_loop, UV_RUN_NOWAIT);
2724         unlock_libuv ();
2725 #  if defined(LOCKLESS)
2726         unlock_iom();
2727 #  endif
2728         PNL (panel_process_event ());
2729 
2730         int con_unit_idx = check_attn_key ();
2731         if (con_unit_idx != -1)
2732           console_attn_idx (con_unit_idx);
2733 # endif
2734 
2735 # if defined(IO_ASYNC_PAYLOAD_CHAN_THREAD)
2736         struct timespec next_time;
2737         clock_gettime (CLOCK_REALTIME, & next_time);
2738         next_time.tv_nsec += 1000l * 1000l;
2739         if (next_time.tv_nsec >= 1000l * 1000l *1000l)
2740           {
2741             next_time.tv_nsec -= 1000l * 1000l *1000l;
2742             next_time.tv_sec  += (time_t) 1;
2743           }
2744         struct timespec new_time;
2745         do
2746           {
2747             pthread_mutex_lock (& iom_start_lock);
2748             pthread_cond_timedwait (& iomCond,
2749                                     & iom_start_lock,
2750                                     & next_time);
2751             pthread_mutex_unlock (& iom_start_lock);
2752             lock_iom();
2753             lock_libuv ();
2754 
2755             iomProcess ();
2756 
2757             unlock_libuv ();
2758             unlock_iom ();
2759 
2760             clock_gettime (CLOCK_REALTIME, & new_time);
2761           }
2762         while ((next_time.tv_sec == new_time.tv_sec) ? (next_time.tv_nsec > new_time.tv_nsec) : \
2763                                                        (next_time.tv_sec  > new_time.tv_sec));
2764 # else
2765         sim_usleep (1000); // 1000 us == 1 ms == 1/1000 sec.
2766 # endif
2767       }
2768     while (reason == 0); //-V654
2769 
2770     for (uint cpuNo = 0; cpuNo < N_CPU_UNITS_MAX; cpuNo ++) {
2771       cpuStats (cpuNo);
2772     }
2773 
2774 # if defined(TESTING)
2775     HDBGPrint ();
2776 # endif
2777     return reason;
2778   }
2779 #endif
2780 
2781 #if !defined(THREADZ) && !defined(LOCKLESS)
2782 static uint fast_queue_subsample = 0;
2783 #endif
2784 
2785 //
2786 // Okay, let's treat this as a state machine
2787 //
2788 //  INTERRUPT_cycle
2789 //     clear interrupt, load interrupt pair into instruction buffer
2790 //     set INTERRUPT_EXEC_cycle
2791 //  INTERRUPT_EXEC_cycle
2792 //     execute instruction in instruction buffer
2793 //     if (! transfer) set INTERUPT_EXEC2_cycle
2794 //     else set FETCH_cycle
2795 //  INTERRUPT_EXEC2_cycle
2796 //     execute odd instruction in instruction buffer
2797 //     set INTERUPT_EXEC2_cycle
2798 //
2799 //  FAULT_cycle
2800 //     fetch fault pair into instruction buffer
2801 //     set FAULT_EXEC_cycle
2802 //  FAULT_EXEC_cycle
2803 //     execute instructions in instruction buffer
2804 //     if (! transfer) set FAULT_EXE2_cycle
2805 //     else set FETCH_cycle
2806 //  FAULT_EXEC2_cycle
2807 //     execute odd instruction in instruction buffer
2808 //     set FETCH_cycle
2809 //
2810 //  FETCH_cycle
2811 //     fetch instruction into instruction buffer
2812 //     set EXEC_cycle
2813 //
2814 //  EXEC_cycle
2815 //     execute instruction in instruction buffer
2816 //     if (repeat conditions) keep cycling
2817 //     if (pair) set EXEC2_cycle
2818 //     else set FETCH_cycle
2819 //  EXEC2_cycle
2820 //     execute odd instruction in instruction buffer
2821 //
2822 //  XEC_cycle
2823 //     load instruction into instruction buffer
2824 //     set EXEC_cycle
2825 //
2826 //  XED_cycle
2827 //     load instruction pair into instruction buffer
2828 //     set EXEC_cycle
2829 //
2830 // other extant cycles:
2831 //  ABORT_cycle
2832 
2833 #if defined(THREADZ) || defined(LOCKLESS)
2834 void * cpu_thread_main (void * arg)
     /* [previous][next][first][last][top][bottom][index][help] */
2835   {
2836     int myid = * (int *) arg;
2837     set_cpu_idx ((uint) myid);
2838     unsigned char umyid = (unsigned char)toupper('a' + (int)myid);
2839     char thread_name[SIR_MAXPID] = {0};
2840     char temp_thread_name[SIR_MAXPID] = {0};
2841 
2842     _cpup->thread_id = pthread_self();
2843 
2844     if (realtime_ok) {
2845       set_realtime_priority (pthread_self(), realtime_max_priority() - 1);
2846       check_realtime_priority (pthread_self(), realtime_max_priority() - 1);
2847     } else {
2848 # if !defined(__QNX__)
2849       (void)sim_os_set_thread_priority (PRIORITY_ABOVE_NORMAL);
2850 # endif
2851     }
2852     _sir_snprintf_trunc(thread_name, SIR_MAXPID, "CPU %c", (unsigned int)umyid);
2853     if (!_sir_setthreadname(thread_name) || !_sir_getthreadname(temp_thread_name))
2854       (void)sir_info ("%s thread created (TID " SIR_TIDFORMAT ")",
2855         thread_name, PID_CAST _sir_gettid());
2856     else
2857       (void)sir_info ("Thread created (TID " SIR_TIDFORMAT ")",
2858         PID_CAST _sir_gettid());
2859 # if defined(TESTING) && defined(__APPLE__) && defined(__MACH__)
2860     (void)sir_info ("Mach thread ID: 0x%x", pthread_mach_thread_np(pthread_self()));
2861 # endif /* if defined(TESTING) && defined(__APPLE__) && defined(__MACH__) */
2862     bool warned = false;
2863     if (realtime_ok) {
2864       if (myid + 2 > nprocs) {
2865         (void)sir_warn ("Total number of supervisor and CPU threads (%lu) exceeds available host parallelism (%lu)!",
2866                         (unsigned long)(myid) + 2, (unsigned long)nprocs);
2867         warned = true;
2868       }
2869       if (!warned && nprocs >= 2 && ncores >= 1 && nprocs >= ncores && myid + 2 > ncores) {
2870         (void)sir_warn ("Total number of supervisor and CPU threads (%lu) exceeds physical host core count (%lu)!",
2871                         (unsigned long)(myid) + 2, (unsigned long)ncores);
2872       }
2873     } else {
2874       if (myid + 1 > nprocs) {
2875         (void)sir_warn ("Total number of CPU threads (%lu) exceeds available host parallelism (%lu)!",
2876                         (unsigned long)(myid) + 1, (unsigned long)nprocs);
2877         warned = true;
2878       }
2879       if (!warned && ncores >= 1 && nprocs >= ncores && myid + 1 > ncores) {
2880         (void)sir_warn ("Total number of CPU threads (%lu) exceeds physical host core count (%lu)!",
2881                         (unsigned long)(myid) + 1, (unsigned long)ncores);
2882       }
2883     }
2884     setSignals ();
2885     threadz_sim_instr ();
2886     return NULL;
2887   }
2888 #endif // THREADZ
2889 
2890 NO_RETURN
2891 static void do_LUF_fault (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2892   {
2893     // DPS8/M T&D/ISOLTS: a lockup that ends a loop is taken on the transfer
2894     // that closes it, which is restarted (RFI). PM776 08I (TRA * in master
2895     // mode) expects the fault at the TRA itself, which the PAS executive
2896     // only reports when RFI is on; 08A (SBA/TNZ *-1) gets the TNZ either
2897     // way. (Inferred from the page's expected values, from dps8m4.)
2898     if ((cpu.tweaks.tandd_mode || cpu.tweaks.isolts_mode) &&
2899         ! cpu.tweaks.l68_mode &&
2900         cpu.cycle == PSEUDO_FETCH_cycle && cpu.lufAfterXfer)
2901       {
2902         cpu.PPR.IC = cpu.lufXferIC;
2903         cpu.lufRFI = true;
2904       }
2905     CPT (cpt1U, 16); // LUF
2906     cpu.lufTicks    = 0;
2907     cpu.lufCounter  = 0;
2908     cpu.lufOccurred = false;
2909 // This is a hack to fix ISOLTS 776. ISOLTS checks that the TR has
2910 // decremented by the LUF timeout value. To implement this, we set
2911 // the TR to the expected value.
2912 
2913 // LUF  time
2914 //  0    2ms
2915 //  1    4ms
2916 //  2    8ms
2917 //  3   16ms
2918 // units
2919 // you have: 2ms
2920 // units
2921 // You have: 512000Hz
2922 // You want: 1/2ms
2923 //    * 1024
2924 //    / 0.0009765625
2925 //
2926 //  TR = 1024 << LUF
2927     // Not in T&D mode: there the TR counts with execution and the lockup is
2928     // timed by it (lufTicks), so the TR is already right (PM776, and PM785
2929     // 05A below, which this fudge gets wrong).
2930     if (cpu.tweaks.isolts_mode && ! cpu.tweaks.tandd_mode)
2931       cpu.shadowTR = (word27) cpu.TR0 - (1024u << (is_priv_mode (cpup) ? 4 : cpu.CMR.luf));
2932 
2933 // The logic fails for test 785:
2934 // set slave mode, LUF time 16ms.
2935 // loop for 15.9 ms.
2936 // set master mode.
2937 // loop for 15.9 ms. The LUF should be noticed, and lufOccurred set.
2938 // return to slave mode. The LUF should fire, with the timer register
2939 // being set for 31.1 ms.
2940 
2941 // XXX: Without accurate cycle timing or simply fudging the results,
2942 // I don't see how to fix this one.
2943 
2944     doFault (FAULT_LUF, fst_zero, "instruction cycle lockup");
2945   }
2946 
2947 #if !defined(THREADZ) && !defined(LOCKLESS)
2948 # define threadz_sim_instr sim_instr
2949 #endif
2950 
2951 /*
2952  * addr_modes_e get_addr_mode()
2953  *
2954  * Report what mode the CPU is in.
2955  * This is determined by examining a couple of IR flags.
2956  *
2957  * TODO: get_addr_mode() probably belongs in the CPU source file.
2958  *
2959  */
2960 
2961 static void set_temporary_absolute_mode (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2962   {
2963     CPT (cpt1L, 20); // set temp. abs. mode
2964     cpu.secret_addressing_mode = true;
2965     cpu.cu.XSF = false;
2966 sim_debug (DBG_TRACEEXT, & cpu_dev, "set_temporary_absolute_mode bit 29 sets XSF to 0\r\n");
2967     //cpu.went_appending = false;
2968   }
2969 
2970 static bool clear_temporary_absolute_mode (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
2971   {
2972     CPT (cpt1L, 21); // clear temp. abs. mode
2973     cpu.secret_addressing_mode = false;
2974     return cpu.cu.XSF;
2975     //return cpu.went_appending;
2976   }
2977 
2978 #if defined(THREADZ) || defined(LOCKLESS)
2979 static const int workAllocationQuantum = 64;
2980 static const int syncClockModePollRate = 64;
2981 static const int masterCycleCntlimit = 2048;
2982 // A slave hands its work back only through the master, which doles out
2983 // allocations from its own sync poll in the EXEC cycle. A master that stops
2984 // reaching that poll (a fault loop, e.g. an ISOLTS CPU whose memory map
2985 // makes every read fault) would leave the slaves waiting forever, so the
2986 // slaves' waits are bounded. The limits are wall-clock milliseconds, well
2987 // above the master's own wait for its slaves (100000 x sim_usleep (1)).
2988 static const uint32 slaveWaitLimitMs = 10000;   // waiting for an allocation
2989 static const uint32 slaveStartLimitMs = 10;     // waiting for syncClockMode
2990 
2991 void becomeClockMaster (uint cpuNum) {
     /* [previous][next][first][last][top][bottom][index][help] */
2992   //HDBGNote (cpup, __func__, "entry%s.", "");
2993 # ifdef SYNCTEST
2994   sim_printf ("CPU%c %s entry\r\n", cpuNum + 'A', __func__);
2995   allocCount = 0;
2996 # endif
2997 
2998   //lockSync ();  // Only one CPU can manage the sync at a time; if more then one CPU is started
2999   // at once, the second will hang here until the first is finished. If this proves to be
3000   // a problem, then we need a mechanism for the second one to join the sync parade.
3001   if (syncClockMode) {
3002     // Someone else is already clock master; let them rule
3003     //sim_printf ("%s: someone else beat us here.\r\n", __func__);
3004     //HDBGNote (cpup, __func__, "someone else beat us here.%s", "");
3005     return;
3006   }
3007 
3008   syncClockModeMasterIdx = cpuNum;
3009   cpu_state_t * cpup = & cpus[cpuNum];
3010   cpu.syncClockModeMaster = true; // This CPU is the clock master
3011   cpu.masterCycleCnt = 0;
3012   cpu.syncClockModeCache = true;
3013   for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
3014     if (i != cpuNum) { // not the new master
3015       cpus[i].workAllocation = 0;
3016       __asm volatile ("");
3017       atomic_thread_fence (memory_order_seq_cst); //-V779
3018       if (cpus[i].inMultics && ! cpus[i].isSlave) { // it is up but not yet a slave
3019         cpus[i].syncClockModePoll = 0;
3020         __asm volatile ("");
3021         atomic_thread_fence (memory_order_seq_cst);
3022         cpus[i].becomeSlave = true;
3023         __asm volatile ("");
3024         atomic_thread_fence (memory_order_seq_cst);
3025       } // candidate
3026     } // not target CPU
3027   } // every CPU
3028 
3029   __asm volatile ("");
3030   atomic_thread_fence (memory_order_seq_cst);
3031   syncClockMode = true;
3032 
3033   __asm volatile ("");
3034   atomic_thread_fence (memory_order_seq_cst);
3035   //HDBGNote (cpup, __func__, "becomes clock master%s", "");
3036 } // becomeClockMaster
3037 
3038 void giveupClockMaster (cpu_state_t * cpup) {
     /* [previous][next][first][last][top][bottom][index][help] */
3039   //HDBGNote (cpup, __func__, "entry%s", "");
3040 # ifdef SYNCTEST
3041   //HDBGNote (cpup, __func__, "alloc count %d", allocCount);
3042   sim_printf ("CPU%c %s entry\r\n", cpu.cpuIdx + 'A', __func__);
3043   sim_printf ("CPU%c Alloc count %d\r\n", cpu.cpuIdx + 'A', allocCount);
3044 # endif
3045   __asm volatile ("");
3046   cpu.syncClockModeMaster = false; //-V779
3047   __asm volatile ("");
3048   syncClockMode = false; // Free the other processors
3049   __asm volatile ("");
3050   for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
3051     cpus[i].syncClockModeCache = false;
3052   }
3053   __asm volatile ("");
3054   atomic_thread_fence (memory_order_seq_cst);
3055   //unlockSync (); // And let someone else grab sync mode
3056 }
3057 #endif
3058 
3059 // T&D: the TR counts down with execution, one count per four cycles, and
3060 // the lockup timer and the T&D calendar clock count with it (dps8m4
3061 // FAUX_TR). PM776/SM784 compare them.
3062 static COLD void tanddTRTick (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
3063   {
3064     cpu.rTRticks = 0;
3065     if (++ cpu.rTRlsb >= 4)
3066       {
3067         cpu.rTRlsb = 0;
3068         cpu.rTR --;
3069         cpu.lufTicks ++;
3070         cpu.tanddTRTicks ++;
3071       }
3072   }
3073 
3074 // T&D: the lockup limit (CMR.luf 0-3 = 2/4/8/16 ms, 32 ms privileged) is
3075 // timed in TR decrements (512 kHz: 2 ms = 1024 counts), so the TR a page
3076 // reads after a lockup agrees with it (PM776 08A-08H). Otherwise as the
3077 // check in threadz_sim_instr.
3078 static COLD void tanddLufCheck (cpu_state_t * cpup, bool priv_mode)
     /* [previous][next][first][last][top][bottom][index][help] */
3079   {
3080     if (cpu.lufTicks >= (1024u << cpu.CMR.luf))
3081       {
3082         if (priv_mode)
3083           cpu.lufOccurred = true; // noted but not executed
3084         else
3085           do_LUF_fault (cpup);
3086       }
3087     if (cpu.lufTicks >= (1024u << 4))
3088       do_LUF_fault (cpup);
3089   }
3090 
3091 // The instruction loop. It is compiled twice (see FULL_MODEL_ON): FULL is
3092 // a constant in each copy, and the T&D, ISOLTS and cache model work done
3093 // for every instruction is left out of the fast copy (FULL false). VAL is
3094 // the setjmp value, or JMP_CHANGE_COPY when threadz_sim_instr changes
3095 // copies; the loop returns SIM_INSTR_CHANGE_COPY to ask for that.
3096 #define SIM_INSTR_CHANGE_COPY (-1)
3097 
3098 static ALWAYS_INLINE t_stat sim_instr_loop (cpu_state_t * cpup, int val, const bool full)
     /* [previous][next][first][last][top][bottom][index][help] */
3099   {
3100     cpu.fullCopy = full;  // for the append cycles and scu2words
3101   //cpu.have_tst_lock = false;
3102 
3103 #if !defined(SCHED_NEVER_YIELD)
3104     unsigned long long lockYieldAll     = 0;
3105 #endif /* if !defined(SCHED_NEVER_YIELD) */
3106     unsigned long long lockWaitMaxAll   = 0;
3107     unsigned long long lockWaitAll      = 0;
3108     unsigned long long lockImmediateAll = 0;
3109     unsigned long long lockCntAll       = 0;
3110     unsigned long long instrCntAll      = 0;
3111     unsigned long long cycleCntAll      = 0;
3112 
3113     t_stat reason = 0;
3114 
3115     switch (val)
3116       {
3117         case JMP_CHANGE_COPY:
3118             // continue at the fetch, where the other copy stopped
3119             break;
3120         case JMP_ENTRY:
3121         case JMP_REENTRY:
3122             reason = 0;
3123             break;
3124         case JMP_SYNC_FAULT_RETURN:
3125             set_cpu_cycle (cpup, SYNC_FAULT_RTN_cycle);
3126             break;
3127         case JMP_STOP:
3128             reason = STOP_STOP;
3129             goto leave;
3130         case JMP_REFETCH:
3131 
3132             // Not necessarily so, but the only times
3133             // this path is taken is after an RCU returning
3134             // from an interrupt, which could only happen if
3135             // was xfer was false; or in a DIS cycle, in
3136             // which case we want it false so interrupts
3137             // can happen.
3138             cpu.wasXfer = false;
3139 
3140             set_cpu_cycle (cpup, FETCH_cycle);
3141             break;
3142         case JMP_RESTART:
3143             set_cpu_cycle (cpup, EXEC_cycle);
3144             break;
3145         case JMP_FORCE_RESTART:
3146           // The configuration has been changed on a CPU that
3147           // has been started and in DIS idle. DIS sees the
3148           // forceRestart flag and longjmps here.
3149           // cpu_reset_unit_idx will update the CPU state to
3150           // match the new configuration and set the
3151           // state to enter DIS.
3152           cpu_reset_unit_idx (current_running_cpu_idx, false);
3153 #if defined(THREADZ) || defined(LOCKLESS)
3154           // Were we a clock master?
3155           if (syncClockMode && syncClockModeMasterIdx == current_running_cpu_idx)
3156             giveupClockMaster (cpup);
3157 #endif
3158           break;
3159         default:
3160           sim_warn ("longjmp value of %d unhandled\r\n", val);
3161             goto leave;
3162       }
3163 
3164     // Main instruction fetch/decode loop
3165 
3166     DCDstruct * ci = & cpu.currentInstruction;
3167 
3168     if (cpu.restart && val != JMP_CHANGE_COPY)
3169       {
3170         set_cpu_cycle (cpup, FAULT_cycle);
3171       }
3172 
3173 #if defined(THREADZ) || defined(LOCKLESS)
3174     // These are used to signal createCPUThread that the "round
3175     // up the slaves" code above has run; they must be set
3176     // after that. This line will prevent the compiler from
3177     // hoisting them.
3178     __asm volatile ("");
3179     cpu.executing = true; //-V779
3180     if (cpu.tweaks.isolts_mode) {
3181       ;
3182     } else {
3183       cpu.inMultics = true;
3184     }
3185 #endif
3186 
3187     do
3188       {
3189 
3190         reason = 0;
3191 
3192 #if !defined(THREADZ) && !defined(LOCKLESS)
3193         // Process deferred events and breakpoints
3194         reason = simh_hooks (cpup);
3195         if (reason)
3196           {
3197             break;
3198           }
3199 
3200 // The event poll is consuming 40% of the CPU according to pprof.
3201 // We only want to process at 100Hz; yet we are testing at ~1MHz.
3202 // If we only test every 1000 cycles, we shouldn't miss by more then
3203 // 10%...
3204 
3205         //if ((! cpu.wasInhibited) && fast_queue_subsample ++ > 1024) // ~ 1KHz
3206         //static uint fastQueueSubsample = 0;
3207         if (fast_queue_subsample ++ > sys_opts.sys_poll_check_rate) // ~ 1KHz
3208           {
3209             fast_queue_subsample = 0;
3210 # if defined(CONSOLE_FIX)
3211 #  if defined(THREADZ) || defined(LOCKLESS)
3212             lock_libuv ();
3213 #  endif
3214 # endif
3215             uv_run (ev_poll_loop, UV_RUN_NOWAIT);
3216 # if defined(CONSOLE_FIX)
3217 #  if defined(THREADZ) || defined(LOCKLESS)
3218             unlock_libuv ();
3219 #  endif
3220 # endif
3221             PNL (panel_process_event ());
3222           }
3223 #endif // ! THREADZ
3224 
3225         cpu.cycleCnt ++;
3226 
3227 #if defined(THREADZ)
3228         // If we faulted somewhere with the memory lock set, clear it.
3229         unlock_mem_force ();
3230 
3231         // wait on run/switch
3232         cpuRunningWait ();
3233 #endif // THREADZ
3234 #if defined(LOCKLESS)
3235         core_unlock_all (cpup); // NO_CACHE
3236 #endif // LOCKLESS
3237 
3238 #if !defined(LOCKLESS)
3239         int con_unit_idx = check_attn_key ();
3240         if (con_unit_idx != -1)
3241           console_attn_idx (con_unit_idx);
3242 #endif
3243 
3244 #if !defined(THREADZ) && !defined(LOCKLESS)
3245         if (cpu.tweaks.isolts_mode)
3246           {
3247             if (cpu.cycle != FETCH_cycle)
3248               {
3249                 // Sync. the TR with the emulator clock.
3250                 cpu.rTRlsb ++;
3251                 if (cpu.rTRlsb >= 4)
3252                   {
3253                     cpu.rTRlsb   = 0;
3254                     cpu.shadowTR = (cpu.shadowTR - 1) & MASK27;
3255                     if (cpu.shadowTR == 0) // passing through 0...
3256                       {
3257                         if (cpu.tweaks.tro_enable)
3258                           setG7fault (current_running_cpu_idx, FAULT_TRO);
3259                       }
3260                   }
3261               }
3262           }
3263 #endif
3264 
3265 // Check for TR underflow. The TR is stored in a uint32_t, but is 27 bits wide.
3266 // The TR update code decrements the TR; if it passes through 0, the high bits
3267 // will be set.
3268 
3269 // If we assume a 1 MIPS reference platform, the TR would be decremented every
3270 // two instructions (1/2 MHz)
3271 
3272         if (full && UNLIKELY (cpu.tweaks.tandd_mode))
3273           tanddTRTick (cpup);
3274         else
3275           {
3276 
3277 
3278 
3279 
3280 
3281 # define TR_RATE 2
3282 
3283         //cpu.rTR      -= cpu.rTRticks / TR_RATE;
3284         // ubsan
3285         cpu.rTR = (word27) (((word27s) cpu.rTR) - (word27s) (cpu.rTRticks / TR_RATE));
3286         cpu.rTRticks %= TR_RATE;
3287 
3288 
3289           }
3290 
3291         if (cpu.rTR & ~MASK27)
3292           {
3293             cpu.rTR &= MASK27;
3294             if (cpu.tweaks.tro_enable) {
3295               setG7fault (current_running_cpu_idx, FAULT_TRO);
3296             }
3297           }
3298 
3299         sim_debug (DBG_CYCLE, & cpu_dev, "Cycle is %s\r\n",
3300                    cycle_str (cpu.cycle));
3301 
3302         switch (cpu.cycle)
3303           {
3304             case INTERRUPT_cycle:
3305               {
3306                 CPT (cpt1U, 0); // Interrupt cycle
3307                 // In the INTERRUPT CYCLE, the processor safe-stores
3308                 // the Control Unit Data (see Section 3) into
3309                 // program-invisible holding registers in preparation
3310                 // for a Store Control Unit (scu) instruction, enters
3311                 // temporary absolute mode, and forces the current
3312                 // ring of execution C(PPR.PRR) to
3313                 // 0. It then issues an XEC system controller command
3314                 // to the system controller on the highest priority
3315                 // port for which there is a bit set in the interrupt
3316                 // present register.
3317 
3318                 uint intr_pair_addr = get_highest_intr (cpup);
3319                 cpu.tanddIntrIC = false;
3320 #if defined(TESTING)
3321                 HDBGIntr (intr_pair_addr, "");
3322 #endif
3323                 cpu.cu.FI_ADDR = (word5) (intr_pair_addr / 2);
3324                 cu_safe_store (cpup);
3325                 // T&D: an interrupt recognized at a fetch: the previous odd
3326                 // instruction, XSF off, RFI and FIF on (PA865 03B)
3327                 if (cpu.tanddFetchIntr)
3328                   {
3329                     cpu.scu_data[7] = cpu.tanddIRODD;
3330                     putbits36_1 (& cpu.scu_data[0], 19, 0);
3331                     putbits36_1 (& cpu.scu_data[5], 27, 1);
3332                     putbits36_1 (& cpu.scu_data[5], 29, 1);
3333                   }
3334                 // XXX the whole interrupt cycle should be rewritten as an xed
3335                 // instruction pushed to IWB and executed
3336 
3337                 CPT (cpt1U, 1); // safe store complete
3338                 // Temporary absolute mode
3339                 set_temporary_absolute_mode (cpup);
3340 
3341                 // Set to ring 0
3342                 cpu.PPR.PRR = 0;
3343                 cpu.TPR.TRR = 0;
3344 
3345                 sim_debug (DBG_INTR, & cpu_dev, "intr_pair_addr %u flag %d\r\n",
3346                            intr_pair_addr, cpu.interrupt_flag);
3347 #if !defined(SPEED)
3348                 if_sim_debug (DBG_INTR, & cpu_dev)
3349                     traceInstruction (DBG_INTR);
3350 #endif /* if !defined(SPEED) */
3351                 // Check that an interrupt is actually pending
3352                 if (cpu.interrupt_flag)
3353                   {
3354                     CPT (cpt1U, 2); // interrupt pending
3355                     // clear interrupt, load interrupt pair into instruction
3356                     // buffer; set INTERRUPT_EXEC_cycle.
3357 
3358                     // In the h/w this is done later, but doing it now allows
3359                     // us to avoid clean up for no interrupt pending.
3360 
3361                     if (intr_pair_addr != 1) // no interrupts
3362                       {
3363                         CPT (cpt1U, 3); // interrupt identified
3364 
3365                         // get interrupt pair
3366                         if (CACHE_ANY_ON ())
3367                           cpu.cacheFetch = true;
3368                         cache_read2 (cpup, intr_pair_addr,
3369                                     & cpu.cu.IWB, & cpu.cu.IRODD, __func__);
3370 #if defined(TESTING)
3371                         HDBGMRead (intr_pair_addr, cpu.cu.IWB, "intr even");
3372                         HDBGMRead (intr_pair_addr + 1, cpu.cu.IRODD, "intr odd");
3373 #endif
3374                         cpu.cu.xde = 1;
3375                         cpu.cu.xdo = 1;
3376                         cpu.isExec = true;
3377                         cpu.isXED  = true;
3378 
3379                         CPT (cpt1U, 4); // interrupt pair fetched
3380                         cpu.interrupt_flag = false;
3381                         // T&D: an interrupt recognized at a fetch comes
3382                         // after the previous (odd) instruction, before the
3383                         // new pair: the pair runs with the IC on that odd
3384                         // instruction (an stc1 in it stores the address of
3385                         // the new pair; PM893 07E). The SCU data keeps the
3386                         // new pair's address; a pair that does not
3387                         // transfer resumes there.
3388                         if (cpu.tanddFetchIntr)
3389                           {
3390                             cpu.PPR.IC      = (cpu.PPR.IC - 1) & MASK18;
3391                             cpu.tanddIntrIC = true;
3392                           }
3393                         cpu.tanddFetchIntr = false;
3394                         set_cpu_cycle (cpup, INTERRUPT_EXEC_cycle);
3395                         break;
3396                       } // int_pair != 1
3397                   } // interrupt_flag
3398 
3399                 // If we get here, there was no interrupt
3400 
3401                 CPT (cpt1U, 5); // interrupt pair spurious
3402                 cpu.interrupt_flag = false;
3403                 clear_temporary_absolute_mode (cpup);
3404                 // Restores addressing mode
3405                 cu_safe_restore (cpup);
3406                 if (cpu.tanddFetchIntr)   // undo the T&D SCU data patch
3407                   {
3408                     cpu.cu.rfi = 0;
3409                     cpu.cu.FIF = 0;
3410                     cpu.tanddFetchIntr = false;
3411                   }
3412                 // We can only get here if wasXfer was
3413                 // false, so we can assume it still is.
3414                 cpu.wasXfer = false;
3415 // The only place cycle is set to INTERRUPT_cycle in FETCH_cycle; therefore
3416 // we can safely assume that is the state that should be restored.
3417                 set_cpu_cycle (cpup, FETCH_cycle);
3418               }
3419               break;
3420 
3421             case FETCH_cycle:
3422 #if defined(PANEL68)
3423                 (void)memset (cpu.cpt, 0, sizeof (cpu.cpt));
3424 #endif
3425                 CPT (cpt1U, 13); // fetch cycle
3426 
3427                 // EXECUTE DATA SWITCHES (press_execute_switches): the
3428                 // switches' instruction runs like a fault pair, in
3429                 // temporary absolute mode, with the CU data safe-stored
3430                 // (one test for that and anything else to be done here:
3431                 // see fetchAttention)
3432 #if defined(THREADZ) || defined(LOCKLESS)
3433                 if (UNLIKELY (atomic_load_explicit (& cpu.fetchAttention, memory_order_relaxed)))
3434 #else
3435                 if (UNLIKELY (cpu.fetchAttention))
3436 #endif
3437                   {
3438 #if defined(THREADZ) || defined(LOCKLESS)
3439                     atomic_thread_fence (memory_order_acquire); // see setFetchAttention
3440 #endif
3441                     // T&D, ISOLTS or the cache model turned on or off:
3442                     // continue in the other copy of this loop (see
3443                     // FULL_MODEL_ON), which will see the attention flag
3444                     // still set
3445                     if (FULL_MODEL_LOAD () != full)
3446                       return SIM_INSTR_CHANGE_COPY;
3447                     cpu.fetchAttention = false;
3448                     if (cpu.execSwitchesReq)
3449                       {
3450                         cpu.execSwitchesReq = false;
3451                         cpu.execSwitches    = true;
3452                         cpu.faultNumber     = FAULT_EXF;
3453                         set_cpu_cycle (cpup, FAULT_cycle);
3454                         break;
3455                       }
3456                   }
3457 
3458                 PNL (L68_ (cpu.INS_FETCH = false;))
3459 
3460 // "If the interrupt inhibit bit is not set in the current instruction
3461 // word at the point of the next sequential instruction pair virtual
3462 // address formation, the processor samples the [group 7 and interrupts]."
3463 
3464 // Since XEx/RPx may overwrite IWB, we must remember
3465 // the inhibit bits (cpu.wasInhibited).
3466 
3467 // If the instruction pair virtual address being formed is the result of a
3468 // transfer of control condition or if the current instruction is
3469 // Execute (xec), Execute Double (xed), Repeat (rpt), Repeat Double (rpd),
3470 // or Repeat Link (rpl), the group 7 faults and interrupt present lines are
3471 // not sampled.
3472 
3473 // Group 7 Faults
3474 //
3475 // Shutdown
3476 //
3477 // An external power shutdown condition has been detected. DC POWER shutdown
3478 // will occur in approximately one millisecond.
3479 //
3480 // Timer Runout
3481 //
3482 // The timer register has decremented to or through the value zero. If the
3483 // processor is in privileged mode or absolute mode, recognition of this fault
3484 // is delayed until a return to normal mode or BAR mode. Counting in the timer
3485 // register continues.
3486 //
3487 // Connect
3488 //
3489 // A connect signal ($CON strobe) has been received from a system controller.
3490 // This event is to be distinguished from a Connect Input/Output Channel (cioc)
3491 // instruction encountered in the program sequence.
3492 
3493                 // check BAR bound and raise store fault if above
3494                 // pft 04d 10070, ISOLTS-776 06ad
3495                 if (get_bar_mode (cpup))
3496                     get_BAR_address (cpup, cpu.PPR.IC);
3497 
3498                 // T&D: fetch the next pair first and use its inhibit bit
3499                 // when deciding whether to sample ("the interrupt inhibit
3500                 // bit ... in the current instruction word at the point of
3501                 // the next sequential instruction pair virtual address
3502                 // formation"); dps8m4 FETCH_REWORK, SM781 07A. Multics and
3503                 // ISOLTS keep sampling before the fetch.
3504                 // The fetch is the one below (at fetch_instruction), which
3505                 // comes back to tandd_fetched: with only one call of
3506                 // fetchInstruction in this loop, the compiler can inline it.
3507                 if (full)   // (4), see FULL_MODEL_ON
3508                   cpu.g7FetchFault = false;
3509                 if (full && UNLIKELY (cpu.tweaks.tandd_mode))
3510                   {
3511                     cpu.tanddFetched = false;
3512                     cpu.tanddIRODD   = cpu.cu.IRODD; // before the fetch
3513                     goto fetch_instruction;
3514                   }
3515               tandd_fetched:;
3516 
3517                 // Don't check timer runout if privileged
3518                 // ISOLTS-776 04bcf, 785 02c
3519                 // (but do if in a DIS instruction with bit28 clear)
3520                 bool tmp_priv_mode = is_priv_mode (cpup);
3521                 // T&D: IWB now holds the next pair, so a DIS that has just
3522                 // ended (on an interrupt or a timer runout) is remembered
3523                 // by the DIS itself; otherwise the runout that woke it
3524                 // would be resampled without TRO (privileged, not a DIS)
3525                 // and lost (PM894 06D)
3526                 // (Only DIS in T&D mode sets the flag: this runs for every
3527                 // instruction.)
3528                 bool is_dis;
3529                 word1 dis_inhibit;
3530                 if (full && UNLIKELY (cpu.tanddFetched))
3531                   {
3532                     bool dis_ended = cpu.disEnded;
3533                     if (dis_ended)
3534                       cpu.disEnded = false;
3535                     is_dis      = dis_ended ||
3536                                   (IWB_IRODD & 0000000777400) == 0000000616000;
3537                     dis_inhibit = dis_ended ? cpu.disInhibit : GET_I (cpu.cu.IWB);
3538                   }
3539                 else
3540                   {
3541                     is_dis      = cpu.currentInstruction.opcode  == 0616 &&
3542                                   cpu.currentInstruction.opcodeX == 0;
3543                     dis_inhibit = GET_I (cpu.cu.IWB);
3544                   }
3545                 bool noCheckTR     = tmp_priv_mode &&
3546                                      !(is_dis && dis_inhibit == 0);
3547 
3548                 if (is_dis)
3549                   {
3550                     // take interrupts and g7 faults as long as
3551                     // last instruction is DIS (??)
3552                     cpu.interrupt_flag = sample_interrupts (cpup);
3553                     cpu.g7_flag =
3554                               noCheckTR ? bG7PendingNoTRO (cpup) : bG7Pending (cpup);
3555                   }
3556                 else if (! (cpu.cu.xde | cpu.cu.xdo |
3557                        cpu.cu.rpt | cpu.cu.rd | cpu.cu.rl))
3558                   {
3559                     if ((!cpu.wasInhibited) &&
3560                         ! (full && cpu.tanddFetched && GET_I (IWB_IRODD)) &&
3561                         (cpu.PPR.IC & 1) == 0 &&
3562                         (! cpu.wasXfer))
3563                       {
3564                         CPT (cpt1U, 14); // sampling interrupts
3565                         cpu.interrupt_flag = sample_interrupts (cpup);
3566                         cpu.g7_flag =
3567                           noCheckTR ? bG7PendingNoTRO (cpup) : bG7Pending (cpup);
3568                       }
3569                     cpu.wasInhibited = false;
3570                   }
3571                 else
3572                   {
3573                     // XEx at an odd location disables interrupt sampling
3574                     // also for the next instruction pair. ISOLTS-785 02g,
3575                     // 776 04g
3576                     // Set the inhibit flag
3577                     // (I assume RPx behaves in the same way)
3578                     if ((cpu.PPR.IC & 1) == 1)
3579                       {
3580                         cpu.wasInhibited = true;
3581                       }
3582                   }
3583 
3584 // Multics executes a CPU connect instruction (which should eventually cause a
3585 // connect fault) while interrupts are inhibited and an IOM interrupt is
3586 // pending. Multics then executes a DIS instruction (Delay Until Interrupt
3587 // Set). This should cause the processor to "sleep" until an interrupt is
3588 // signaled. The DIS instruction sees that an interrupt is pending, sets
3589 // cpu.interrupt_flag to signal that the CPU to service the interrupt and
3590 // resumes the CPU.
3591 //
3592 // The CPU state machine sets up to fetch the next instruction. If checks to
3593 // see if this instruction should check for interrupts or faults according to
3594 // the complex rules (interrupts inhibited, even address, not RPT or XEC,
3595 // etc.); it this case, the test fails as the next instruction is at an odd
3596 // address. If the test had passed, the cpu.interrupt_flag would be set or
3597 // cleared depending on the pending interrupt state data, AND the cpu.g7_flag
3598 // would be set or cleared depending on the faults pending data (in this case,
3599 // the connect fault).
3600 //
3601 // Because the flags were not updated, after the test, cpu.interrupt_flag is
3602 // set (since the DIS instruction set it) and cpu.g7_flag is not set.
3603 //
3604 // Next, the CPU sees the that cpu.interrupt flag is set, and starts the
3605 // interrupt cycle despite the fact that a higher priority g7 fault is pending.
3606 
3607 // To fix this, check (or recheck) g7 if an interrupt is going to be faulted.
3608 // Either DIS set interrupt_flag and FETCH_cycle didn't so g7 needs to be
3609 // checked, or FETCH_cycle did check it when it set interrupt_flag in which
3610 // case it is being rechecked here. It is [locally] idempotent and light
3611 // weight, so this should be okay.
3612 
3613 // not necessary any more because of is_dis logic
3614 
3615 
3616 
3617 
3618                 if (cpu.g7_flag)
3619                   {
3620                       cpu.g7_flag        = false;
3621                       cpu.interrupt_flag = false;
3622                       // T&D: the fault is recognized as the next pair's
3623                       // address is formed: the SCU data has the new even
3624                       // instruction, the previous odd one, XSF off and
3625                       // RFI on (refetch) (PA865 03A)
3626                       if (full && cpu.tanddFetched)
3627                         {
3628                           cpu.cu.IRODD = cpu.tanddIRODD;
3629                           cpu.cu.XSF   = 0;
3630                           cpu.lufRFI   = true;
3631                           cpu.tanddFetchFault = true;
3632                         }
3633                       // The fault comes between instructions: a fault
3634                       // pair that does not transfer resumes at the IC, the
3635                       // instruction not yet executed (PS702 03A, CU-HR
3636                       // overflow trap to an STC1/STC1 pair); not for DIS
3637                       if (full)   // (4), see FULL_MODEL_ON
3638                         cpu.g7FetchFault = ! is_dis;
3639                       sim_debug (DBG_CYCLE, & cpu_dev,
3640                                  "call doG7Fault (%d)\r\n", !noCheckTR);
3641                       doG7Fault (cpup, !noCheckTR);
3642                   }
3643                 if (cpu.interrupt_flag)
3644                   {
3645 // This is the only place cycle is set to INTERRUPT_cycle; therefore
3646 // return from interrupt can safely assume the it should set the cycle
3647 // to FETCH_cycle.
3648                     CPT (cpt1U, 15); // interrupt
3649                     // T&D: as for a g7 fault above (PA865 03B)
3650                     cpu.tanddFetchIntr = full && cpu.tanddFetched;
3651                     set_cpu_cycle (cpup, INTERRUPT_cycle);
3652                     break;
3653                   }
3654 
3655 // "While in absolute mode or privileged mode the lockup fault is signalled at
3656 // the end of the time limit set in the lockup timer but is not recognized
3657 // until the 32 millisecond limit. If the processor returns to normal mode or
3658 // BAR mode after the fault has been signalled but before the 32 millisecond
3659 // limit, the fault is recognized before any instruction in the new mode is
3660 // executed."
3661 
3662           /*FALLTHRU*/ /* fall through */ /* fallthrough */
3663           case PSEUDO_FETCH_cycle:
3664 
3665             tmp_priv_mode = is_priv_mode (cpup);
3666             if (! (luf_flag && tmp_priv_mode))
3667               cpu.lufCounter ++;
3668 
3669             if (full && UNLIKELY (cpu.tweaks.tandd_mode))
3670               tanddLufCheck (cpup, tmp_priv_mode);
3671             else
3672               {
3673               if (cpu.lufCounter > luf_limits[cpu.CMR.luf])
3674                 {
3675                   if (tmp_priv_mode)
3676                     {
3677                       // In priv. mode the LUF is noted but not executed
3678                       cpu.lufOccurred = true;
3679                     }
3680                   else
3681                     {
3682                       do_LUF_fault (cpup);
3683                     }
3684                 } // lufCounter > luf_limit
3685 
3686               // After 32ms, the LUF fires regardless of priv.
3687               if (cpu.lufCounter > luf_limits[4])
3688                 {
3689                   do_LUF_fault (cpup);
3690                 }
3691               }
3692 
3693             // If the LUF occurred in priv. mode and we left priv. mode,
3694             // fault.
3695             if (! tmp_priv_mode && cpu.lufOccurred)
3696               {
3697                 do_LUF_fault (cpup);
3698               }
3699 
3700 
3701 
3702 
3703 
3704 
3705 
3706 
3707 
3708 
3709 
3710 
3711 
3712 
3713 
3714 
3715 
3716 
3717 
3718 
3719 
3720 
3721 
3722 
3723 
3724 
3725 
3726 
3727 
3728 
3729 
3730 
3731             if (cpu.cycle == PSEUDO_FETCH_cycle)
3732               {
3733                 cpu.apu.lastCycle    = INSTRUCTION_FETCH;
3734                 cpu.cu.XSF           = 0;
3735                 cpu.cu.TSN_VALID [0] = 0;
3736                 cpu.TPR.TSR          = cpu.PPR.PSR;
3737                 cpu.TPR.TRR          = cpu.PPR.PRR;
3738                 cpu.wasInhibited     = false;
3739               }
3740             else if (full && UNLIKELY (cpu.tanddFetched))
3741               {
3742                 cpu.tanddFetched = false;   // fetched at the start (T&D)
3743               }
3744             else
3745               {
3746               fetch_instruction:; // also the T&D fetch before sampling
3747                 CPT (cpt1U, 20); // not XEC or RPx
3748                 cpu.isExec               = false;
3749                 cpu.isXED                = false;
3750                 // fetch next instruction into current instruction struct
3751                 //clr_went_appending (); // XXX not sure this is the right
3752                                          //  place
3753                 cpu.cu.XSF               = 0;
3754 sim_debug (DBG_TRACEEXT, & cpu_dev, "fetchCycle bit 29 sets XSF to 0\r\n");
3755                 cpu.cu.TSN_VALID [0]     = 0;
3756                 cpu.TPR.TSR              = cpu.PPR.PSR;
3757                 cpu.TPR.TRR              = cpu.PPR.PRR;
3758                 PNL (cpu.prepare_state   = ps_PIA);
3759                 PNL (L68_ (cpu.INS_FETCH = true;))
3760                 if (full)
3761                   fetchInstructionFull (cpup, cpu.PPR.IC);
3762                 else
3763                   fetchInstructionFast (cpup, cpu.PPR.IC);
3764                 // T&D: that was the fetch before sampling (see above)
3765                 if (full && UNLIKELY (cpu.tweaks.tandd_mode && ! cpu.tanddFetched))
3766                   {
3767                     cpu.tanddFetched = true;
3768                     goto tandd_fetched;
3769                   }
3770               }
3771 
3772             CPT (cpt1U, 21); // go to exec cycle
3773             advanceG7Faults (cpup);
3774             set_cpu_cycle (cpup, EXEC_cycle);
3775             break;
3776 
3777           case EXEC_cycle:
3778           case FAULT_EXEC_cycle:
3779           case INTERRUPT_EXEC_cycle:
3780             {
3781 #if defined(THREADZ) || defined(LOCKLESS)
3782 
3783               // Have we been told to becomes a slave?
3784               if (UNLIKELY (cpu.becomeSlave)) {
3785                 cpu.becomeSlave = false;
3786                 // Wait for the master to wake up. becomeClockMaster sets
3787                 // syncClockMode just after becomeSlave, so this is a short
3788                 // wait; but the master may already have given up (DIS, cycle
3789                 // limit) before this CPU got here, and then syncClockMode
3790                 // stays false: don't wait for it forever.
3791                 uint32 startMs = sim_os_msec ();
3792                 while (! syncClockMode &&
3793                        sim_os_msec () - startMs < slaveStartLimitMs) {
3794                   sim_usleep (1);
3795                 }
3796                 // Force the poll below
3797                 cpu.syncClockModePoll = 0;
3798               }
3799 
3800               // Ready to check sync clock mode?
3801               if (cpu.syncClockModeCache || --cpu.syncClockModePoll <= 0) {
3802 
3803                 cpu.syncClockModePoll = cpu.tweaks.isolts_mode ? 1 : syncClockModePollRate;
3804 
3805                 // Are the clocks synchronized?
3806                 if (syncClockMode) {
3807 
3808                   // Remember that this thread is synchronized
3809                   cpu.syncClockModeCache = true;
3810 
3811                   // Are we the master?
3812                   if (syncClockModeMasterIdx == current_running_cpu_idx) {
3813 
3814                     // Master
3815                     cpu.masterCycleCnt ++;
3816                     if (cpu.masterCycleCnt > masterCycleCntlimit) {
3817 # ifdef SYNCTEST
3818                       sim_printf ("too many cycles\r\n");
3819 # endif
3820                       giveupClockMaster (cpup);
3821                       goto bail;
3822                     }
3823 
3824                     // Have we used up our allocation?
3825                     if (cpu.workAllocation <= 0) {
3826 # ifdef SYNCTEST
3827                       allocCount ++;
3828 # endif
3829 
3830                       // If sim_usleep(1) actually takes only 1 us, then this
3831                       // will be at least 2 seconds.
3832                       //int64_t waitTimeout = 2000000;
3833                       // Quick testing shows it is closer to 2 minutes...
3834                       int64_t waitTimeout = 100000;
3835 
3836                       // Has everyone used up their allocation?
3837                       while (1) {  // while others still have work to do
3838                         bool alldone = true;
3839                         for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
3840                           if (cpus[i].inMultics && cpus[i].workAllocation > 0) {
3841                             wakeCPU (i);
3842                             alldone = false;
3843                             //break;
3844                           } // up and working
3845                         } // cpus
3846                         if (alldone) {
3847                           // Everyone has used up there allocations; dole out some more work
3848                           for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
3849                             if (cpus[i].inMultics) {
3850                               cpus[i].workAllocation += cpu.tweaks.isolts_mode ? 1 : workAllocationQuantum;
3851                               wakeCPU (i);
3852                             }
3853                           }
3854                           break; // while (1)
3855                         } // alldone
3856                         if (waitTimeout-- < 0) {
3857                           // timed out waiting for everyone to finish their
3858                           // work allocation; assume something is fouled.
3859                           sim_printf ("Clock master CPU %c timed out\r\n", "ABCDEFGH"[current_running_cpu_idx]);
3860                           for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
3861                             if (cpus[i].inMultics && cpus[i].workAllocation > 0) {
3862                               sim_printf ("CPU %c remaining allocation: %ld\r\n", "ABCDEFGH"[i], cpus[i].workAllocation);
3863                             }
3864                           }
3865                           sim_printf ("Conceding clock mastery...\r\n");
3866                           cpu.syncClockModeCache = false;
3867                           giveupClockMaster (cpup);
3868                           goto bail;
3869                         }
3870                         sim_usleep (1);
3871                       } // while (1) -- while others still have work to do
3872                     } // have we used up our allocation
3873                     // We are master and have work allocated; fall through
3874                     // and do some work
3875 
3876                   } else { // Master/slave?
3877 
3878                     // We are not the master; must be a slave
3879 
3880                     // Have we just become a slave?
3881                     if (! cpu.isSlave) {
3882                       //HDBGNote (NULL, __func__, "CPU%c Becoming slave", cpu.cpuIdx + 'A');
3883 # ifdef SYNCTEST
3884                      sim_printf ("CPU%c becoming slave\r\n", cpu.cpuIdx + 'A');
3885 # endif
3886                     }
3887                     cpu.isSlave = true;
3888 
3889                     // Wait for allocation, but not forever (see slaveWaitLimitMs)
3890                     uint32 waitStartMs = sim_os_msec ();
3891                     while (syncClockMode && cpu.workAllocation <= 0) {
3892                       if (sim_os_msec () - waitStartMs >= slaveWaitLimitMs) {
3893                         uint masterIdx = syncClockModeMasterIdx;
3894                         sim_printf ("Clock slave CPU %c: no work allocation from clock master CPU %c "
3895                                     "for %u s; ending clock sync\r\n",
3896                                     "ABCDEFGH"[current_running_cpu_idx], "ABCDEFGH"[masterIdx],
3897                                     (unsigned) (slaveWaitLimitMs / 1000));
3898                         if (syncClockMode && masterIdx < N_CPU_UNITS_MAX)
3899                           giveupClockMaster (& cpus[masterIdx]);
3900                         break;
3901                       }
3902                       sim_usleep (1);
3903                     }
3904 
3905                     // We are slave and have work allocated; fall through
3906                     // and do some work
3907 
3908                   } // master/slave
3909 
3910                 } else { // ! syncClockMode
3911                   // Forget that this thread is synchronized
3912                   cpu.syncClockModeCache = false;
3913                   if (cpu.isSlave) {
3914                     //HDBGNote (cpup, __func__, "Free; free at last%s", "");
3915 # ifdef SYNCTEST
3916                     sim_printf ("CPU%c free; free at last\r\n", cpu.cpuIdx + 'A');
3917 # endif
3918                     cpu.isSlave = false;
3919                   }
3920                 } // ! syncClockMode
3921               } // polling
3922           bail:
3923 
3924 #endif
3925 
3926 #if defined(THREADZ) || defined(LOCKLESS)
3927               if (LIKELY (! cpu.tweaks.isolts_mode) &&
3928                   UNLIKELY (! cpu.inMultics)) {
3929                 cpu.inMultics = true;
3930               }
3931 #endif /* defined(THREADZ) || defined(LOCKLESS) */
3932 
3933               CPT (cpt1U, 22); // exec cycle
3934 
3935 #if defined(LOCKLESS)
3936                 if (stall_point_active)
3937                   {
3938                     for (int i = 0; i < N_STALL_POINTS; i ++)
3939                       if (stall_points[i].segno  && stall_points[i].segno  == cpu.PPR.PSR &&
3940                           stall_points[i].offset && stall_points[i].offset == cpu.PPR.IC)
3941                         {
3942 # if defined(CTRACE)
3943                           (void)fprintf (stderr, "%10lu %s stall %d\r\n", seqno (), cpunstr[current_running_cpu_idx], i);
3944 # endif
3945                           //sim_printf ("stall %2d %05o:%06o\r\n", i, stall_points[i].segno, stall_points[i].offset);
3946                           sim_usleep(stall_points[i].time);
3947                           break;
3948                         }
3949                   }
3950 #endif
3951 
3952               // The only time we are going to execute out of IRODD is
3953               // during RPD, at which time interrupts are automatically
3954               // inhibited; so the following can ignore RPD harmlessly
3955               if (GET_I (cpu.cu.IWB))
3956                 cpu.wasInhibited = true;
3957 
3958               if (full)
3959                 {
3960                   // (1), see FULL_MODEL_ON and scu2words
3961                   cpu.xsfScu = false;
3962                   if (UNLIKELY (cpu.lufXferTrack))
3963                     {
3964                       cpu.lufExecIC    = cpu.PPR.IC;
3965                       cpu.lufAfterXfer = false;
3966                     }
3967                 }
3968               t_stat ret = full ? executeInstructionFull (cpup) :
3969                                   executeInstructionFast (cpup);
3970               DO_WORK_EXEC;
3971               CPT (cpt1U, 23); // execution complete
3972               if (full)   // (2), see FULL_MODEL_ON and scu2words
3973                 cpu.lastTag = ci->tag;
3974               cpu.rptXnSaved = false;
3975 
3976               if (cpu.tweaks.l68_mode)
3977                 {
3978                   add_l68_CU_history (cpup);
3979                   if (cpu.adr_trap_lock)
3980                     {
3981                       cpu.adr_trap_lock = false;
3982                       if (cpu.MR.ihrrs)
3983                         cpu.MR.ihr = 0;
3984                     }
3985                 }
3986               else
3987                 add_dps8m_CU_history (cpup);
3988 
3989               if (ret > 0)
3990                 {
3991                    reason = ret;
3992                    break;
3993                 }
3994 
3995               if (ret == CONT_XEC)
3996                 {
3997                   CPT (cpt1U, 27); // XEx instruction
3998                   cpu.wasXfer = false;
3999                   cpu.isExec  = true;
4000                   if (cpu.cu.xdo)
4001                     cpu.isXED = true;
4002 
4003                   cpu.cu.XSF           = 0;
4004                   cpu.cu.TSN_VALID [0] = 0;
4005                   cpu.TPR.TSR          = cpu.PPR.PSR;
4006                   cpu.TPR.TRR          = cpu.PPR.PRR;
4007                   break;
4008                 }
4009 
4010               if (ret == CONT_TRA || ret == CONT_RET)
4011                 {
4012                   CPT (cpt1U, 24); // transfer instruction
4013                   cpu.cu.xde  = cpu.cu.xdo = 0;
4014                   cpu.isExec  = false;
4015                   cpu.isXED   = false;
4016                   // even for CONT_RET else isolts 886 fails
4017                   cpu.wasXfer = true;
4018 
4019                   if (cpu.cycle != EXEC_cycle) // fault or interrupt
4020                     {
4021                       clearFaultCycle (cpup);
4022 
4023 // BAR mode:  [NBAR] is set ON (taking the processor
4024 // out of BAR mode) by the execution of any transfer instruction
4025 // other than tss during a fault or interrupt trap.
4026 
4027                       if (! (cpu.currentInstruction.opcode == 0715 &&
4028                          cpu.currentInstruction.opcodeX == 0))
4029                         {
4030                           CPT (cpt1U, 9); // nbar set
4031                           SET_I_NBAR;
4032                         }
4033 
4034                       if (!clear_temporary_absolute_mode (cpup))
4035                         {
4036                           // didn't go appending
4037                           sim_debug (DBG_TRACEEXT, & cpu_dev,
4038                                      "setting ABS mode\r\n");
4039                           CPT (cpt1U, 10); // temporary absolute mode
4040                           set_addr_mode (cpup, ABSOLUTE_mode);
4041                         }
4042                       else
4043                         {
4044                           // went appending
4045                           sim_debug (DBG_TRACEEXT, & cpu_dev,
4046                                      "not setting ABS mode\r\n");
4047                         }
4048 
4049                     } // fault or interrupt
4050 
4051                   //if (TST_I_ABS && get_went_appending ())
4052                   if (TST_I_ABS && cpu.cu.XSF)
4053                     {
4054                       set_addr_mode (cpup, APPEND_mode);
4055                     }
4056 
4057                   if (ret == CONT_TRA)
4058                     {
4059                       // PSEUDO_FETCH_cycle does not check interrupts/g7faults
4060                       cpu.wasXfer = false;
4061                       if (full && UNLIKELY (cpu.lufXferTrack))
4062                         {
4063                           cpu.lufXferIC    = cpu.lufExecIC;
4064                           cpu.lufAfterXfer = true;
4065                         }
4066                       set_cpu_cycle (cpup, PSEUDO_FETCH_cycle);
4067                     }
4068                   else
4069                     set_cpu_cycle (cpup, FETCH_cycle);
4070                   break;   // Don't bump PPR.IC, instruction already did it
4071                 }
4072 
4073               if (ret == CONT_DIS)
4074                 {
4075                   CPT (cpt1U, 25); // DIS instruction
4076 
4077 #if defined(THREADZ) || defined(LOCKLESS)
4078                   // If we do a DIS is clock sync, skip the sleep
4079                   if (cpu.syncClockModeCache) {
4080                     break;
4081                 }
4082 #endif
4083 
4084 // If we get here, we have encountered a DIS instruction in EXEC_cycle.
4085 //
4086 // We need to idle the CPU until one of the following conditions:
4087 //
4088 //  An external interrupt occurs.
4089 //  The Timer Register underflows.
4090 //  The emulator polled devices need polling.
4091 //
4092 // The external interrupt will only be posted to the CPU engine if the
4093 // device poll posts an interrupt. This means that we do not need to
4094 // detect the interrupts here; if we wake up and poll the devices, the
4095 // interrupt will be detected by the DIS instruction when it is re-executed.
4096 //
4097 // The Timer Register is a fast, high-precision timer but Multics uses it
4098 // in only two ways: detecting I/O lockup during early boot, and process
4099 // quantum scheduling (1/4 second for Multics).
4100 //
4101 // Neither of these require high resolution or high accuracy.
4102 //
4103 // The goal of the polling code is sample at about 100Hz; updating the timer
4104 // register at that rate should suffice.
4105 //
4106 //    sleep for 1/100 of a second
4107 //    update the polling state to trigger a poll
4108 //    update the timer register by 1/100 of a second
4109 //    force the scp queues to process
4110 //    continue processing
4111 //
4112 
4113 // The sim_usleep logic is not smart enough w.r.t. ISOLTS.
4114 // The sleep should only happen if all running processors are in DIS mode.
4115                   // 1/100 is .01 secs.
4116                   // *1000 is 10  milliseconds
4117                   // *1000 is 10000 microseconds
4118                   // in uSec;
4119 #if defined(THREADZ) || defined(LOCKLESS)
4120 
4121 // XXX If interrupt inhibit set, then sleep forever instead of TRO
4122                   // rTR is 512KHz; sleepCPU is in 1Mhz
4123                   //   rTR * 1,000,000 / 512,000
4124                   //   rTR * 1000 / 512
4125                   //   rTR * 500 / 256
4126                   //   rTR * 250 / 128
4127                   //   rTR * 125 / 64
4128 
4129 # if defined(NO_TIMEWAIT)
4130                   //sim_usleep (sys_opts.sys_poll_interval * 1000 /*10000*/ );
4131                   struct timespec req, rem;
4132                   uint ms        = sys_opts.sys_poll_interval;
4133                   long int nsec  = (long int) ms * 1000L * 1000L;
4134                   req.tv_nsec    = nsec;
4135                   req.tv_sec    += req.tv_nsec / 1000000000L;
4136                   req.tv_nsec   %= 1000000000L;
4137                   int rc         = nanosleep (& req, & rem); // XXX Does this work on Windows ???
4138                   // Awakened early?
4139                   if (rc == -1)
4140                     {
4141                        ms = (uint) (rem.tv_nsec / 1000 + req.tv_sec * 1000);
4142                     }
4143                   word27 ticks = ms * 512;
4144                   if (cpu.rTR <= ticks)
4145                     {
4146                       if (cpu.tweaks.tro_enable) {
4147                         setG7fault (current_running_cpu_idx, FAULT_TRO);
4148                       }
4149                       cpu.rTR = (cpu.rTR - ticks) & MASK27;
4150                     }
4151                   else
4152                     cpu.rTR = (cpu.rTR - ticks) & MASK27;
4153 
4154                   if (cpu.rTR == 0)
4155                     cpu.rTR = MASK27;
4156 # else // !NO_TIMEWAIT
4157                   // unsigned long left = cpu.rTR * 125u / 64u;
4158                   // ubsan
4159                   unsigned long left = (unsigned long) ((uint64) (cpu.rTR) * 125u / 64u);
4160 
4161 
4162 
4163 
4164 
4165 
4166 
4167 
4168                   unsigned long nowLeft = left;
4169                   if (!sample_interrupts (cpup))
4170                     {
4171                       nowLeft = sleepCPU (left);
4172                     }
4173                   if (nowLeft)
4174                     {
4175                       // sleepCPU uses a clock that is not guaranteed to be monotonic, and occasionally returns nowLeft > left.
4176                       // Don't run rTR backwards if that happens
4177                       if (nowLeft <= left) {
4178                         cpu.rTR = (word27) (left * 64 / 125);
4179                       }
4180                     }
4181                   else
4182                     {
4183                       // We slept until timer runout
4184                       if (cpu.tweaks.tro_enable)
4185                         {
4186                           lock_scu ();
4187                           setG7fault (current_running_cpu_idx, FAULT_TRO);
4188                           unlock_scu ();
4189                         }
4190                       cpu.rTR = MASK27;
4191                     }
4192 # endif // !NO_TIMEWAIT
4193                   cpu.rTRticks = 0;
4194                   break;
4195 #else // ! (THREADZ || LOCKLESS)
4196                   //sim_sleep (10000);
4197                   sim_usleep (sys_opts.sys_poll_interval * 1000/*10000*/);
4198                   // Trigger I/O polling
4199 # if defined(CONSOLE_FIX)
4200 #  if defined(THREADZ) || defined(LOCKLESS)
4201                   lock_libuv ();
4202 #  endif
4203 # endif
4204                   uv_run (ev_poll_loop, UV_RUN_NOWAIT);
4205 # if defined(CONSOLE_FIX)
4206 #  if defined(THREADZ) || defined(LOCKLESS)
4207                   unlock_libuv ();
4208 #  endif
4209 # endif
4210                   fast_queue_subsample = 0;
4211 
4212                   sim_interval = 0;
4213                   // Timer register runs at 512 KHz
4214                   // 512000 is 1 second
4215                   // 512000/100 -> 5120  is .01 second
4216 
4217                   cpu.rTRticks = 0;
4218                   // Would we have underflowed while sleeping?
4219                   //if ((cpu.rTR & ~ MASK27) || cpu.rTR <= 5120)
4220                   //if (cpu.rTR <= 5120)
4221 
4222                   // Timer register runs at 512 KHz
4223                   // 512Khz / 512 is millisecods
4224                   if (cpu.rTR <= sys_opts.sys_poll_interval * 512)
4225                     {
4226                       if (cpu.tweaks.tro_enable) {
4227                         setG7fault (current_running_cpu_idx, FAULT_TRO);
4228                       }
4229                       cpu.rTR = (cpu.rTR - sys_opts.sys_poll_interval * 512) & MASK27;
4230                     }
4231                   else
4232                     cpu.rTR = (cpu.rTR - sys_opts.sys_poll_interval * 512) & MASK27;
4233                   if (cpu.rTR == 0)
4234                     cpu.rTR = MASK27;
4235 #endif // ! (THREADZ || LOCKLESS)
4236                   /*NOTREACHED*/ /* unreachable */
4237                   break;
4238                 }
4239 
4240               cpu.wasXfer = false;
4241 
4242               if (ret < 0)
4243                 {
4244                   sim_warn ("executeInstruction returned %d?\r\n", ret);
4245                   break;
4246                 }
4247 
4248               if ((! cpu.cu.repeat_first) &&
4249                   (cpu.cu.rpt ||
4250                    (cpu.cu.rd && (cpu.PPR.IC & 1)) ||
4251                    cpu.cu.rl))
4252                 {
4253                   CPT (cpt1U, 26); // RPx instruction
4254                   if (cpu.cu.rd)
4255                     -- cpu.PPR.IC;
4256                   cpu.wasXfer = false;
4257                   set_cpu_cycle (cpup, FETCH_cycle);
4258                   break;
4259                 }
4260 
4261               // If we just did the odd word of a fault pair
4262               if (cpu.cycle == FAULT_EXEC_cycle &&
4263                   !cpu.cu.xde && cpu.cu.xdo)
4264                 {
4265                   clear_temporary_absolute_mode (cpup);
4266                   cu_safe_restore (cpup);
4267                   CPT (cpt1U, 12); // cu restored
4268                   clearFaultCycle (cpup);
4269                   // cu_safe_restore calls decode_instruction ()
4270                   // we can determine the instruction length.
4271                   // decode_instruction() restores ci->info->ndes
4272                   cpu.wasXfer  = false;
4273                   cpu.isExec   = false;
4274                   cpu.isXED    = false;
4275 
4276                   if (full && cpu.g7FetchFault)   // (4), see FULL_MODEL_ON
4277                     cpu.g7FetchFault = false;
4278                   else
4279                     {
4280                       cpu.PPR.IC  += ci->info->ndes;
4281                       cpu.PPR.IC ++;
4282                     }
4283 
4284                   set_cpu_cycle (cpup, FETCH_cycle);
4285                   break;
4286                 }
4287 
4288               // If we just did the odd word of a interrupt pair
4289               if (cpu.cycle == INTERRUPT_EXEC_cycle &&
4290                   !cpu.cu.xde && cpu.cu.xdo)
4291                 {
4292                   clear_temporary_absolute_mode (cpup);
4293                   cu_safe_restore (cpup);
4294                   // cpu.cu.xdo = 0;
4295                   if (cpu.tanddIntrIC)
4296                     {
4297                       cpu.PPR.IC      = (cpu.PPR.IC + 1) & MASK18;
4298                       cpu.tanddIntrIC = false;
4299                     }
4300 // The only place cycle is set to INTERRUPT_cycle in FETCH_cycle; therefore
4301 // we can safely assume that is the state that should be restored.
4302                   CPT (cpt1U, 12); // cu restored
4303                   cpu.wasXfer = false;
4304                   cpu.isExec  = false;
4305                   cpu.isXED   = false;
4306 
4307                   set_cpu_cycle (cpup, FETCH_cycle);
4308                   break;
4309                 }
4310 
4311               // Even word of fault or interrupt pair or xed
4312               if (cpu.cu.xde && cpu.cu.xdo)
4313                 {
4314                   // Get the odd
4315                   cpu.cu.IWB           = cpu.cu.IRODD;
4316                   cpu.cu.xde           = 0;
4317                   cpu.isExec           = true;
4318                   cpu.isXED            = true;
4319                   cpu.cu.XSF           = 0;
4320                   cpu.cu.TSN_VALID [0] = 0;
4321                   cpu.TPR.TSR          = cpu.PPR.PSR;
4322                   cpu.TPR.TRR          = cpu.PPR.PRR;
4323                   break; // go do the odd word
4324                 }
4325 
4326               if (cpu.cu.xde || cpu.cu.xdo)  // we are in an XEC/XED
4327                 {
4328                   cpu.cu.xde        = cpu.cu.xdo = 0;
4329                   cpu.isExec        = false;
4330                   cpu.isXED         = false;
4331                   CPT (cpt1U, 27);           // XEx instruction
4332                   cpu.wasXfer       = false;
4333                   cpu.PPR.IC ++;
4334                   if (ci->info->ndes > 0)
4335                     cpu.PPR.IC     += ci->info->ndes;
4336                   cpu.wasInhibited  = true;
4337                   set_cpu_cycle (cpup, FETCH_cycle);
4338                   break;
4339                 }
4340 
4341               //ASSURE (cpu.cycle == EXEC_cycle);
4342               if (cpu.cycle != EXEC_cycle)
4343                 sim_warn ("expected EXEC_cycle (%d)\r\n", cpu.cycle);
4344 
4345               cpu.cu.xde = cpu.cu.xdo = 0;
4346               cpu.isExec = false;
4347               cpu.isXED  = false;
4348 
4349               // use prefetched instruction from cpu.cu.IRODD
4350               // we must have finished an instruction at an even location
4351               // skip multiword EIS instructions
4352               // skip repeat instructions for now
4353               // skip dis - we may need to take interrupts/g7faults
4354               // skip if (last instruction) wrote to current instruction range
4355               //  the hardware really does this and isolts tests it
4356               //  Multics Differences Manual DPS8 70/M
4357               //  should take segment number into account?
4358               if ((cpu.PPR.IC & 1) == 0 &&
4359                   ci->info->ndes == 0 &&
4360                   !cpu.cu.repeat_first && !cpu.cu.rpt && !cpu.cu.rd && !cpu.cu.rl &&
4361                   !(cpu.currentInstruction.opcode == 0616 && cpu.currentInstruction.opcodeX == 0) &&
4362                   (cpu.PPR.IC & ~3u) != (cpu.last_write  & ~3u))
4363                 {
4364                   cpu.PPR.IC ++;
4365                   cpu.wasXfer = false;
4366                   cpu.cu.IWB  = cpu.cu.IRODD;
4367                   set_cpu_cycle (cpup, PSEUDO_FETCH_cycle);
4368                   break;
4369                 }
4370 
4371               cpu.PPR.IC ++;
4372               if (ci->info->ndes > 0)
4373                 cpu.PPR.IC += ci->info->ndes;
4374 
4375               CPT (cpt1U, 28); // enter fetch cycle
4376               cpu.wasXfer = false;
4377               set_cpu_cycle (cpup, FETCH_cycle);
4378             }
4379             break;
4380 
4381           case SYNC_FAULT_RTN_cycle:
4382             {
4383               CPT (cpt1U, 29); // sync. fault return
4384               // cu_safe_restore should have restored CU.IWB, so
4385               // we can determine the instruction length.
4386               // decode_instruction() restores ci->info->ndes
4387 
4388               cpu.PPR.IC += ci->info->ndes;
4389               cpu.PPR.IC ++;
4390               cpu.wasXfer = false;
4391               set_cpu_cycle (cpup, FETCH_cycle);
4392             }
4393             break;
4394 
4395           case FAULT_cycle:
4396             {
4397               CPT (cpt1U, 30); // fault cycle
4398               // In the FAULT CYCLE, the processor safe-stores the Control
4399               // Unit Data (see Section 3) into program-invisible holding
4400               // registers in preparation for a Store Control Unit ( scu)
4401               // instruction, then enters temporary absolute mode, forces the
4402               // current ring of execution C(PPR.PRR) to 0, and generates a
4403               // computed address for the fault trap pair by concatenating
4404               // the setting of the FAULT BASE switches on the processor
4405               // configuration panel with twice the fault number (see Table
4406               // 7-1).  This computed address and the operation code for the
4407               // Execute Double (xed) instruction are forced into the
4408               // instruction register and executed as an instruction. Note
4409               // that the execution of the instruction is not done in a
4410               // normal EXECUTE CYCLE but in the FAULT CYCLE with the
4411               // processor in temporary absolute mode.
4412 
4413               // F(A)NP should never be stored when faulting.
4414               // ISOLTS-865 01a,870 02d
4415               // Unconditional reset of APU status to FABS breaks boot.
4416               // Checking for F(A)NP here is equivalent to checking that the
4417               // last append cycle has made it as far as H/I without a fault.
4418               // Also reset it on TRB fault. ISOLTS-870 05a
4419               // T&D: not for a group 7 fault recognized at a fetch, which
4420               // keeps the fetch's FANP/FAP (PA865 03A)
4421               // Nor for a store fault, which comes from the final memory
4422               // access itself: the status stays FAP/FANP (PA885 10B)
4423               // L68: the fault keeps the APU status of the last appending
4424               // cycle, e.g. PI-AP and FAP of the instruction fetch (PA865
4425               // 01A, PA885 01A-10A expect it in SCU word 0)
4426               if (((cpu.cu.APUCycleBits & 060) || cpu.secret_addressing_mode) &&
4427                   ! cpu.tanddFetchFault && cpu.faultNumber != FAULT_STR &&
4428                   ! cpu.tweaks.l68_mode)
4429                   set_apu_status (cpup, apuStatus_FABS);
4430               cpu.tanddFetchFault = false;
4431 
4432               // XXX the whole fault cycle should be rewritten as an xed
4433               // instruction pushed to IWB and executed
4434 
4435               // AL39: TRB fault doesn't safestore CUD - the original fault
4436               // CUD should be stored
4437 
4438               // ISOLTS-870 05a: CUD[5] and IWB are safe stored, possibly
4439               //  due to CU overlap
4440 
4441               // keep IRODD untouched if TRB occurred in an even location
4442               if (cpu.faultNumber != FAULT_TRB || cpu.cu.xde == 0)
4443                 {
4444                   cu_safe_store (cpup);
4445                 }
4446               else
4447                 {
4448                   word36 tmpIRODD = cpu.scu_data[7];
4449                   cu_safe_store (cpup);
4450                   cpu.scu_data[7] = tmpIRODD;
4451                 }
4452               if (cpu.scuRFI)   // see doFault
4453                 putbits36_1 (& cpu.scu_data[5], 27, 1);
4454               cpu.scuRFI = false;
4455               // see doFault; only when the next pair is in the same page
4456               if (cpu.l68OddFault && (cpu.l68PairAddr & 01777) <= 01775)
4457                 cache_read (cpup, cpu.l68PairAddr + 3, & cpu.scu_data[7], __func__);
4458               cpu.l68OddFault = false;
4459               CPT (cpt1U, 31); // safe store complete
4460 
4461               // Temporary absolute mode
4462               set_temporary_absolute_mode (cpup);
4463 
4464               // Set to ring 0
4465               cpu.PPR.PRR = 0;
4466               cpu.TPR.TRR = 0;
4467 
4468               // (12-bits of which the top-most 7-bits are used)
4469               uint fltAddress = (cpu.switches.FLT_BASE << 5) & 07740;
4470               L68_ (
4471                 if (cpu.is_FFV)
4472                   {
4473                     cpu.is_FFV = false;
4474                     CPTUR (cptUseMR);
4475                     // The high 15 bits
4476                     fltAddress = (cpu.MR.FFV & MASK15) << 3;
4477                   }
4478               )
4479 
4480               // absolute address of fault YPair
4481               word24 addr = fltAddress + 2 * cpu.faultNumber;
4482 
4483               if (cpu.restart)
4484                 {
4485                   cpu.restart = false;
4486                   addr = cpu.restart_address;
4487                 }
4488 
4489               // EXECUTE DATA SWITCHES: XED Y runs the pair at Y; any other
4490               // instruction runs as the even word, with a NOP after it
4491               bool switches = cpu.execSwitches;
4492               word36 sw = cpu.switches.data_switches;
4493               cpu.execSwitches = false;
4494               if (switches && ((sw >> 8) & 01777) == (0717u << 1))
4495                 {
4496                   addr     = (word24) GETHI (sw);
4497                   switches = false;
4498                 }
4499               if (switches)
4500                 {
4501                   cpu.cu.IWB   = sw;
4502                   cpu.cu.IRODD = 0000000011000; // nop
4503                 }
4504               else
4505                 {
4506                   if (CACHE_ANY_ON ())
4507                     cpu.cacheFetch = true;
4508                   cache_read2 (cpup, addr, & cpu.cu.IWB, & cpu.cu.IRODD, __func__);
4509                 }
4510 #if defined(TESTING)
4511               HDBGMRead (addr, cpu.cu.IWB, "fault even");
4512               HDBGMRead (addr + 1, cpu.cu.IRODD, "fault odd");
4513 #endif
4514               cpu.cu.xde = 1;
4515               cpu.cu.xdo = 1;
4516               cpu.isExec = true;
4517               cpu.isXED  = true;
4518 
4519               CPT (cpt1U, 33); // set fault exec cycle
4520               set_cpu_cycle (cpup, FAULT_EXEC_cycle);
4521 
4522               break;
4523             }
4524 
4525           }  // switch (cpu.cycle)
4526       }
4527     while (reason == 0);
4528 
4529 leave:
4530 #if defined(THREADZ) || defined(LOCKLESS)
4531     cpu.executing = false;
4532     cpu.inMultics = false;
4533 #endif /* defined(THREADZ) || defined(LOCKLESS) */
4534 #if defined(TESTING)
4535     HDBGPrint ();
4536 #endif
4537 
4538     for (unsigned short n = 0; n < N_CPU_UNITS_MAX; n++)
4539       {
4540 #if !defined(SCHED_NEVER_YIELD)
4541         lockYieldAll     = lockYieldAll     + (unsigned long long)cpus[n].coreLockState.lockYield;
4542 #endif /* if !defined(SCHED_NEVER_YIELD) */
4543         lockWaitMaxAll   = lockWaitMaxAll   + (unsigned long long)cpus[n].coreLockState.lockWaitMax;
4544         lockWaitAll      = lockWaitAll      + (unsigned long long)cpus[n].coreLockState.lockWait;
4545         lockImmediateAll = lockImmediateAll + (unsigned long long)cpus[n].coreLockState.lockImmediate;
4546         lockCntAll       = lockCntAll       + (unsigned long long)cpus[n].coreLockState.lockCnt;
4547         instrCntAll      = instrCntAll      + (unsigned long long)cpus[n].instrCnt;
4548         cycleCntAll      = cycleCntAll      + (unsigned long long)cpus[n].cycleCnt;
4549       }
4550 
4551     (void)fflush(stderr);
4552     (void)fflush(stdout);
4553 
4554 # if !defined(PERF_STRIP)
4555     if (cycleCntAll > (unsigned long long)cpu.cycleCnt)
4556       {
4557 # endif /*if !defined(PERF_STRIP) */
4558         sim_msg ("\r\n");
4559         sim_msg ("\r+---------------------------------+\r\n");
4560         sim_msg ("\r|     Aggregate CPU Statistics    |\r\n");
4561         sim_msg ("\r+---------------------------------+\r\n");
4562         (void)fflush(stderr);
4563         (void)fflush(stdout);
4564 # if defined(WIN_STDIO)
4565         sim_msg ("\r|  cycles        %15llu  |\r\n", cycleCntAll);
4566         sim_msg ("\r|  instructions  %15llu  |\r\n", instrCntAll);
4567         (void)fflush(stderr);
4568         (void)fflush(stdout);
4569         sim_msg ("\r+---------------------------------+\r\n");
4570         sim_msg ("\r|  lockCnt       %15llu  |\r\n", lockCntAll);
4571         sim_msg ("\r|  lockImmediate %15llu  |\r\n", lockImmediateAll);
4572         (void)fflush(stderr);
4573         (void)fflush(stdout);
4574         sim_msg ("\r+---------------------------------+\r\n");
4575         sim_msg ("\r|  lockWait      %15llu  |\r\n", lockWaitAll);
4576         sim_msg ("\r|  lockWaitMax   %15llu  |\r\n", lockWaitMaxAll);
4577         (void)fflush(stderr);
4578         (void)fflush(stdout);
4579 #  if !defined(SCHED_NEVER_YIELD)
4580         sim_msg ("\r|  lockYield     %15llu  |\r\n", lockYieldAll);
4581 #  else
4582         sim_msg ("\r|  lockYield                ----  |\r\n");
4583 #  endif /* if !defined(SCHED_NEVER_YIELD) */
4584         sim_msg ("\r+---------------------------------+\r\n");
4585         (void)fflush(stderr);
4586         (void)fflush(stdout);
4587 # else
4588         sim_msg ("\r|  cycles        %'15llu  |\r\n", cycleCntAll);
4589         sim_msg ("\r|  instructions  %'15llu  |\r\n", instrCntAll);
4590         (void)fflush(stderr);
4591         (void)fflush(stdout);
4592         sim_msg ("\r+---------------------------------+\r\n");
4593         sim_msg ("\r|  lockCnt       %'15llu  |\r\n", lockCntAll);
4594         sim_msg ("\r|  lockImmediate %'15llu  |\r\n", lockImmediateAll);
4595         (void)fflush(stderr);
4596         (void)fflush(stdout);
4597         sim_msg ("\r+---------------------------------+\r\n");
4598         sim_msg ("\r|  lockWait      %'15llu  |\r\n", lockWaitAll);
4599         sim_msg ("\r|  lockWaitMax   %'15llu  |\r\n", lockWaitMaxAll);
4600         (void)fflush(stderr);
4601         (void)fflush(stdout);
4602 #  if !defined(SCHED_NEVER_YIELD)
4603         sim_msg ("\r|  lockYield     %'15llu  |\r\n", lockYieldAll);
4604 #  else
4605         sim_msg ("\r|  lockYield                ----  |\r\n");
4606 #  endif /* if !defined(SCHED_NEVER_YIELD) */
4607         sim_msg ("\r+---------------------------------+\r\n");
4608         (void)fflush(stderr);
4609         (void)fflush(stdout);
4610 # endif /* if defined(WIN_STDIO) */
4611 # if !defined(PERF_STRIP)
4612       }
4613 # else
4614     sim_msg("\r\n");
4615 # endif /* if !defined(PERF_STRIP) */
4616 
4617 
4618 
4619 
4620 
4621 
4622 
4623 
4624 
4625 
4626 
4627 #if defined(THREADZ) || defined(LOCKLESS)
4628     if (running_perf_test == false)
4629       sim_usleep(2000000); // Delay (up to 2s) to allow for stats gathering
4630     stopCPUThread();
4631 #endif
4632 
4633 #if defined(M_SHARED)
4634 // scp needs to have the IC statically allocated, so a placeholder
4635 // was created. Update the placeholder so the IC can be seen via scp
4636 // and restarting sim_instr won't lose the place.
4637 
4638     set_cpu_idx (0); //-V779
4639     dummy_IC = cpu.PPR.IC;
4640 #endif
4641 
4642     return reason;
4643   }
4644 
4645 static NO_INLINE t_stat sim_instr_fast (cpu_state_t * cpup, int val)
     /* [previous][next][first][last][top][bottom][index][help] */
4646   {
4647     return sim_instr_loop (cpup, val, false);
4648   }
4649 
4650 static NO_INLINE t_stat sim_instr_full (cpu_state_t * cpup, int val)
     /* [previous][next][first][last][top][bottom][index][help] */
4651   {
4652     return sim_instr_loop (cpup, val, true);
4653   }
4654 
4655 static inline t_stat sim_instr_copy (cpu_state_t * cpup, int val)
     /* [previous][next][first][last][top][bottom][index][help] */
4656   {
4657     return FULL_MODEL_ON () ? sim_instr_full (cpup, val) : sim_instr_fast (cpup, val);
4658   }
4659 
4660 t_stat threadz_sim_instr (void)
     /* [previous][next][first][last][top][bottom][index][help] */
4661   {
4662     cpu_state_t * cpup = _cpup;
4663 
4664 #if !defined(THREADZ) && !defined(LOCKLESS)
4665     set_cpu_idx (0);
4666 # if defined(M_SHARED)
4667 // scp needs to have the IC statically allocated, so a placeholder was
4668 // created.
4669 
4670     // Copy the placeholder so the IC can be set
4671     cpus [0].PPR.IC = dummy_IC;
4672 # endif
4673 
4674 #endif
4675 
4676     // This allows long jumping to the top of the state machine
4677     int val = setjmp (cpu.jmpMain);
4678 
4679     t_stat reason = sim_instr_copy (cpup, val);
4680     while (reason == SIM_INSTR_CHANGE_COPY)
4681       reason = sim_instr_copy (cpup, JMP_CHANGE_COPY);
4682     return reason;
4683   }
4684 
4685 /*
4686  * cd@libertyhaven.com - sez ...
4687  *  If the instruction addresses a block of four words, the target of the
4688  * instruction is supposed to be an address that is aligned on a four-word
4689  * boundary (0 mod 4). If not, the processor will grab the four-word block
4690  * containing that address that begins on a four-word boundary, even if it
4691  * has to go back 1 to 3 words. Analogous explanation for 8, 16, and 32 cases.
4692  *
4693  * olin@olinsibert.com - sez ...
4694  *  It means that the appropriate low bits of the address are forced to zero.
4695  * So it's the previous words, not the succeeding words, that are used to
4696  * satisfy the request. -- Olin
4697  */
4698 
4699 int operand_size (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
4700   {
4701     DCDstruct * i = & cpu.currentInstruction;
4702     if (i->info->flags & (READ_OPERAND | STORE_OPERAND))
4703         return 1;
4704     else if (i->info->flags & (READ_YPAIR | STORE_YPAIR))
4705         return 2;
4706     else if (i->info->flags & (READ_YBLOCK8 | STORE_YBLOCK8))
4707         return 8;
4708     else if (i->info->flags & (READ_YBLOCK16 | STORE_YBLOCK16))
4709         return 16;
4710     else if (i->info->flags & (READ_YBLOCK32 | STORE_YBLOCK32))
4711         return 32;
4712     return 0;
4713   }
4714 
4715 // read instruction operands
4716 
4717 void readOperandRead (cpu_state_t * cpup, word18 addr) {
     /* [previous][next][first][last][top][bottom][index][help] */
4718   CPT (cpt1L, 6); // read_operand
4719 
4720 #if defined(THREADZ)
4721   DCDstruct * i = & cpu.currentInstruction;
4722   if (RMWOP (i)) // ldac, ldqc, stac, stacq, snzc
4723     lock_rmw ();
4724 #endif
4725 
4726   switch (operand_size (cpup)) {
4727     case 1:
4728       CPT (cpt1L, 7); // word
4729       ReadOperandRead (cpup, addr, & cpu.CY);
4730       break;
4731     case 2:
4732       CPT (cpt1L, 8); // double word
4733       addr &= 0777776;   // make even
4734       Read2OperandRead (cpup, addr, cpu.Ypair);
4735       break;
4736     case 8:
4737       CPT (cpt1L, 9); // oct word
4738       addr &= 0777770;   // make on 8-word boundary
4739       Read8 (cpup, addr, cpu.Yblock8, cpu.currentInstruction.b29);
4740       break;
4741     case 16:
4742       CPT (cpt1L, 10); // 16 words
4743       addr &= 0777770;   // make on 8-word boundary
4744       Read16 (cpup, addr, cpu.Yblock16);
4745       break;
4746     case 32:
4747       CPT (cpt1L, 11); // 32 words
4748       addr &= 0777740;   // make on 32-word boundary
4749       for (uint j = 0 ; j < 32 ; j += 1)
4750         ReadOperandRead (cpup, addr + j, cpu.Yblock32 + j);
4751       break;
4752   }
4753 }
4754 
4755 void readOperandRMW (cpu_state_t * cpup, word18 addr) {
     /* [previous][next][first][last][top][bottom][index][help] */
4756   CPT (cpt1L, 6); // read_operand
4757   switch (operand_size (cpup)) {
4758     case 1:
4759       CPT (cpt1L, 7); // word
4760       ReadOperandRMW (cpup, addr, & cpu.CY);
4761       break;
4762     case 2:
4763       CPT (cpt1L, 8); // double word
4764       addr &= 0777776;   // make even
4765       Read2OperandRead (cpup, addr, cpu.Ypair);
4766       break;
4767     case 8:
4768       CPT (cpt1L, 9); // oct word
4769       addr &= 0777770;   // make on 8-word boundary
4770       Read8 (cpup, addr, cpu.Yblock8, cpu.currentInstruction.b29);
4771       break;
4772     case 16:
4773       CPT (cpt1L, 10); // 16 words
4774       addr &= 0777770;   // make on 8-word boundary
4775       Read16 (cpup, addr, cpu.Yblock16);
4776       break;
4777     case 32:
4778       CPT (cpt1L, 11); // 32 words
4779       addr &= 0777740;   // make on 32-word boundary
4780       for (uint j = 0 ; j < 32 ; j += 1)
4781         ReadOperandRMW (cpup, addr + j, cpu.Yblock32 + j);
4782       break;
4783   }
4784 }
4785 
4786 // write instruction operands
4787 
4788 t_stat write_operand (cpu_state_t * cpup, word18 addr, UNUSED processor_cycle_type cyctyp)
     /* [previous][next][first][last][top][bottom][index][help] */
4789   {
4790     switch (operand_size (cpup))
4791       {
4792         case 1:
4793             CPT (cpt1L, 12); // word
4794             WriteOperandStore (cpup, addr, cpu.CY);
4795             break;
4796         case 2:
4797             CPT (cpt1L, 13); // double word
4798             addr &= 0777776;   // make even
4799             Write2OperandStore (cpup, addr + 0, cpu.Ypair);
4800             break;
4801         case 8:
4802             CPT (cpt1L, 14); // 8 words
4803             addr &= 0777770;   // make on 8-word boundary
4804             Write8 (cpup, addr, cpu.Yblock8, cpu.currentInstruction.b29);
4805             break;
4806         case 16:
4807             CPT (cpt1L, 15); // 16 words
4808             addr &= 0777770;   // make on 8-word boundary
4809             Write16 (cpup, addr, cpu.Yblock16);
4810             break;
4811         case 32:
4812             CPT (cpt1L, 16); // 32 words
4813             addr &= 0777740;   // make on 32-word boundary
4814             //for (uint j = 0 ; j < 32 ; j += 1)
4815                 //Write (addr + j, cpu.Yblock32[j], OPERAND_STORE);
4816             Write32 (cpup, addr, cpu.Yblock32);
4817             break;
4818       }
4819 
4820 #if defined(THREADZ)
4821     if (cyctyp == OPERAND_STORE)
4822       {
4823         DCDstruct * i = & cpu.currentInstruction;
4824         if (RMWOP (i))
4825           unlock_mem ();
4826       }
4827 #endif
4828     return SCPE_OK;
4829 
4830   }
4831 
4832 #if !defined(SPEED)
4833 t_stat set_mem_watch (int32 arg, const char * buf)
     /* [previous][next][first][last][top][bottom][index][help] */
4834   {
4835     if (strlen (buf) == 0)
4836       {
4837         if (arg)
4838           {
4839             sim_warn ("no argument to watch?\r\n");
4840             return SCPE_ARG;
4841           }
4842         sim_msg ("Clearing all watch points\r\n");
4843         (void)memset (& watch_bits, 0, sizeof (watch_bits));
4844         return SCPE_OK;
4845       }
4846     char * end;
4847     long int n = strtol (buf, & end, 0);
4848     if (* end || n < 0 || n >= MEMSIZE)
4849       {
4850         sim_warn ("Invalid argument to watch? %ld\r\n", (long) n);
4851         return SCPE_ARG;
4852       }
4853     watch_bits [n] = arg != 0;
4854     return SCPE_OK;
4855   }
4856 #endif /* if !defined(SPEED) */
4857 
4858 /*!
4859  * "Raw" core interface ....
4860  */
4861 
4862 #if !defined(SPEED)
4863 void nem_check (word24 addr, const char * context)
     /* [previous][next][first][last][top][bottom][index][help] */
4864   {
4865     cpu_state_t * cpup = _cpup;
4866     if (lookup_cpu_mem_map (cpup, addr) < 0)
4867       {
4868         doFault (FAULT_STR, fst_str_nea,  context);
4869       }
4870   }
4871 #endif /* if !defined(SPEED) */
4872 
4873 // static uint get_scu_unit_idx (word24 addr, word24 * offset)
4874 //   {
4875 //     int cpu_port_num = lookup_cpu_mem_map (addr, offset);
4876 //     if (cpu_port_num < 0) // Can't happen, we passed nem_check above
4877 //       {
4878 //         sim_warn ("cpu_port_num < 0");
4879 //         doFault (FAULT_STR, fst_str_nea,  __func__);
4880 //       }
4881 //     return cables->cpu_to_scu [current_running_cpu_idx][cpu_port_num].scu_unit_idx;
4882 //   }
4883 
4884 #if !defined(SPEED)
4885 // A read watch on REAL (an address in M), for a read that core_read does
4886 // not make: a hit in the CPU cache (DATA, the cached word)
4887 void cpu_watch_read (cpu_state_t * cpup, word24 real, word36 data, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
4888   {
4889     if (watch_bits [real])
4890       {
4891         sim_msg ("WATCH [%llu] %05o:%06o read   %08o %012llo (%s, cache)\r\n",
4892                  (long long unsigned int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC, real,
4893                  (long long unsigned int)data, ctx);
4894         traceInstruction (0);
4895       }
4896   }
4897 #endif
4898 
4899 #if !defined(SPEED) || !defined(INLINE_CORE)
4900 // core_read and core_write are compiled twice: core_read_fast and
4901 // core_write_fast, for the fast copies of the append cycles (see
4902 // FULL_MODEL_ON), leave out the T&D hooks and the cache model
4903 static ALWAYS_INLINE int core_read_ (cpu_state_t * cpup, word24 addr, word36 *data, const char * ctx, const bool full)
     /* [previous][next][first][last][top][bottom][index][help] */
4904   {
4905     if (full)
4906       TANDD_HOOK (tandd_read_hook (cpup, addr, 1));
4907     PNL (cpu.portBusy = true;)
4908     SC_MAP_ADDR (addr, addr);
4909 # if !defined(LOCKLESS)
4910     if (M[addr] & MEM_UNINITIALIZED)
4911       {
4912         sim_debug (DBG_WARN, & cpu_dev,
4913                    "Uninitialized memory accessed at address %08o; "
4914                    "IC is 0%06o:0%06o (%s(\r\n",
4915                    addr, cpu.PPR.PSR, cpu.PPR.IC, ctx);
4916       }
4917 # endif /* if !defined(LOCKLESS) */
4918 # if !defined(SPEED)
4919     if (watch_bits [addr])
4920       {
4921         sim_msg ("WATCH [%llu] %05o:%06o read   %08o %012llo (%s)\r\n",
4922                     (long long unsigned int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC, addr,
4923                     (long long unsigned int)M [addr], ctx);
4924         traceInstruction (0);
4925       }
4926 # endif /* if !defined(SPEED) */
4927 # if defined(LOCKLESS)
4928 #  if !defined(SUNLINT)
4929     word36 v;
4930     LOAD_ACQ_CORE_WORD(v, addr);
4931     *data = v & DMASK;
4932 #  endif /* if !defined(SUNLINT) */
4933 # else
4934     *data = M[addr] & DMASK;
4935 # endif /* if defined(LOCKLESS) */
4936 
4937     DO_WORK_MEM;
4938     sim_debug (DBG_CORE, & cpu_dev,
4939                "core_read  %08o %012"PRIo64" (%s)\r\n",
4940                 addr, * data, ctx);
4941     PNL (trackport (addr, * data));
4942     return 0;
4943   }
4944 
4945 int core_read (cpu_state_t * cpup, word24 addr, word36 *data, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
4946   {
4947     return core_read_ (cpup, addr, data, ctx, true);
4948   }
4949 
4950 int core_read_fast (cpu_state_t * cpup, word24 addr, word36 *data, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
4951   {
4952     return core_read_ (cpup, addr, data, ctx, false);
4953   }
4954 #endif
4955 
4956 #if defined(LOCKLESS)
4957 int core_read_lock (cpu_state_t * cpup, word24 addr, word36 *data, UNUSED const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
4958 {
4959     TANDD_HOOK (tandd_read_lock_hook (cpup, addr));
4960     SC_MAP_ADDR (addr, addr);
4961     LOCK_CORE_WORD(addr, & cpu.coreLockState);
4962     if (cpu.coreLockState.locked_addr != 0) {
4963       sim_warn ("core_read_lock: locked %08o locked_addr %08o %c %05o:%06o\r\n",
4964                 addr, cpu.coreLockState.locked_addr, current_running_cpu_idx + 'A',
4965                 cpu.PPR.PSR, cpu.PPR.IC);
4966       core_unlock_all (cpup);
4967     }
4968     cpu.coreLockState.locked_addr = addr;
4969 # if !defined(SUNLINT)
4970     word36 v;
4971     LOAD_ACQ_CORE_WORD(v, addr);
4972     * data = v & DMASK;
4973 # endif /* if !defined(SUNLINT) */
4974     return 0;
4975 }
4976 #endif
4977 
4978 #if !defined(SPEED) || !defined(INLINE_CORE)
4979 // (see core_read_)
4980 static ALWAYS_INLINE int core_write_ (cpu_state_t * cpup, word24 addr, word36 data, const char * ctx, const bool full)
     /* [previous][next][first][last][top][bottom][index][help] */
4981   {
4982     if (full)
4983       TANDD_HOOK (tandd_write_hook (cpup, addr, 1, true));
4984     PNL (cpu.portBusy = true;)
4985     SC_MAP_ADDR (addr, addr);
4986     if (cpu.tweaks.isolts_mode)
4987       {
4988         if (cpu.MR.sdpap)
4989           {
4990             sim_warn ("failing to implement sdpap\r\n");
4991             cpu.MR.sdpap = 0;
4992           }
4993         if (cpu.MR.separ)
4994           {
4995             sim_warn ("failing to implement separ\r\n");
4996                 cpu.MR.separ = 0;
4997           }
4998       }
4999 # if defined(LOCKLESS)
5000     LOCK_CORE_WORD(addr, & cpu.coreLockState);
5001 #  if !defined(SUNLINT)
5002     STORE_REL_CORE_WORD(addr, data);
5003 #  endif /* if !defined(SUNLINT) */
5004 # else
5005     M[addr] = data & DMASK;
5006 # endif /* if defined(LOCKLESS) */
5007     // this CPU's cache is store through; SCU write notification to the others
5008     if (full)
5009       cacheStoreNotify (cpup, addr, data & DMASK);
5010 # if !defined(SPEED)
5011     if (watch_bits [addr])
5012       {
5013         sim_msg ("WATCH [%llu] %05o:%06o write  %08llo %012llo (%s)\r\n",
5014                  (long long unsigned int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5015                  (long long unsigned int)addr, (unsigned long long int)M [addr], ctx);
5016         traceInstruction (0);
5017       }
5018 # endif /* if !defined(SPEED) */
5019     DO_WORK_MEM;
5020     sim_debug (DBG_CORE, & cpu_dev,
5021                "core_write %08o %012"PRIo64" (%s)\r\n",
5022                 addr, data, ctx);
5023     PNL (trackport (addr, data));
5024     return 0;
5025   }
5026 
5027 int core_write (cpu_state_t * cpup, word24 addr, word36 data, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
5028   {
5029     return core_write_ (cpup, addr, data, ctx, true);
5030   }
5031 
5032 int core_write_fast (cpu_state_t * cpup, word24 addr, word36 data, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
5033   {
5034     return core_write_ (cpup, addr, data, ctx, false);
5035   }
5036 #endif /* if !defined(SPEED) || !defined(INLINE_CORE) */
5037 
5038 #if defined(LOCKLESS)
5039 int core_write_unlock (cpu_state_t * cpup, word24 addr, word36 data, UNUSED const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
5040 {
5041     TANDD_HOOK (tandd_write_hook (cpup, addr, 1, false));
5042     SC_MAP_ADDR (addr, addr);
5043     if (cpu.coreLockState.locked_addr != addr)
5044       {
5045         sim_warn ("core_write_unlock: locked %08o locked_addr %08o %c %05o:%06o\r\n",
5046                   addr,        cpu.coreLockState.locked_addr, current_running_cpu_idx + 'A',
5047                   cpu.PPR.PSR, cpu.PPR.IC);
5048        core_unlock_all (cpup);
5049       }
5050 
5051 # if !defined(SUNLINT)
5052     STORE_REL_CORE_WORD(addr, data);
5053 # endif /* if !defined(SUNLINT) */
5054     cpu.coreLockState.locked_addr = 0;
5055     // this CPU's cache is store through; SCU write notification to the others
5056     cacheStoreNotify (cpup, addr, data);
5057     return 0;
5058 }
5059 
5060 int core_unlock_all (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5061 {
5062   if (cpu.coreLockState.locked_addr != 0) {
5063       sim_warn ("core_unlock_all: locked %08o %c %05o:%06o\r\n",
5064                 cpu.coreLockState.locked_addr, current_running_cpu_idx + 'A',
5065                 cpu.PPR.PSR,     cpu.PPR.IC);
5066 # if !defined(SUNLINT)
5067       STORE_REL_CORE_WORD(cpu.coreLockState.locked_addr, M[cpu.coreLockState.locked_addr]);
5068 # endif /* if !defined(SUNLINT) */
5069       cpu.coreLockState.locked_addr = 0;
5070   }
5071   return 0;
5072 }
5073 #endif
5074 
5075 #if !defined(SPEED) || !defined(INLINE_CORE)
5076 int core_write_zone (cpu_state_t * cpup, word24 addr, word36 data, word36 * final, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
5077   {
5078     TANDD_HOOK (tandd_write_hook (cpup, addr, 1, true));
5079     PNL (cpu.portBusy = true;)
5080     if (cpu.tweaks.isolts_mode)
5081       {
5082         if (cpu.MR.sdpap)
5083           {
5084             sim_warn ("failing to implement sdpap\r\n");
5085             cpu.MR.sdpap = 0;
5086           }
5087         if (cpu.MR.separ)
5088           {
5089             sim_warn ("failing to implement separ\r\n");
5090             cpu.MR.separ = 0;
5091           }
5092       }
5093     word24 mapAddr = 0;
5094     SC_MAP_ADDR (addr, mapAddr);
5095 # if defined(LOCKLESS)
5096     word36 v;
5097     core_read_lock(cpup, addr,  &v, ctx);
5098     v = (v & ~cpu.zone) | (data & cpu.zone);
5099     core_write_unlock(cpup, addr, v, ctx);
5100     if (final)
5101       * final = v;
5102 # else
5103     M[mapAddr] = (M[mapAddr] & ~cpu.zone) | (data & cpu.zone);
5104     if (final)
5105       * final = M[mapAddr];
5106     // this CPU's cache is store through; SCU write notification to the others
5107     cacheStoreNotify (cpup, mapAddr, M[mapAddr]);
5108 # endif
5109     cpu.useZone = false; // Safety
5110 # if !defined(SPEED)
5111     if (watch_bits [mapAddr])
5112       {
5113         sim_msg ("WATCH [%llu] %05o:%06o writez %08llo %012llo (%s)\r\n",
5114                 (unsigned long long int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5115                 (unsigned long long int)mapAddr, (unsigned long long int)M [mapAddr], ctx);
5116         traceInstruction (0);
5117       }
5118 # endif
5119     DO_WORK_MEM;
5120     sim_debug (DBG_CORE, & cpu_dev,
5121                "core_write_zone %08o %012"PRIo64" (%s)\r\n",
5122                 mapAddr, data, ctx);
5123     PNL (trackport (mapAddr, data));
5124     return 0;
5125   }
5126 #endif
5127 
5128 #if !defined(SPEED) || !defined(INLINE_CORE)
5129 int core_read2 (cpu_state_t * cpup, word24 addr, word36 *even, word36 *odd, const char * ctx)
     /* [previous][next][first][last][top][bottom][index][help] */
5130   {
5131     TANDD_HOOK (tandd_read_hook (cpup, addr & ~1u, 2));
5132     PNL (cpu.portBusy = true;)
5133 # if defined(LOCKLESS)
5134     /*LINTED E_FUNC_VAR_UNUSED*/ /* Appease SUNLINT */
5135     word36 v;
5136 # endif
5137     if (addr & 1)
5138       {
5139         sim_debug (DBG_MSG, & cpu_dev,
5140                    "warning: subtracting 1 from pair at %o in "
5141                    "core_read2 (%s)\r\n", addr, ctx);
5142         addr &= (word24)~1; /* make it an even address */
5143       }
5144     SC_MAP_ADDR (addr, addr);
5145 # if !defined(LOCKLESS)
5146     if (M[addr] & MEM_UNINITIALIZED)
5147       {
5148         sim_debug (DBG_WARN, & cpu_dev,
5149                    "Uninitialized memory accessed at address %08o; "
5150                    "IC is 0%06o:0%06o (%s)\r\n",
5151                    addr, cpu.PPR.PSR, cpu.PPR.IC, ctx);
5152       }
5153 # endif
5154 # if !defined(SPEED)
5155     if (watch_bits [addr])
5156       {
5157         sim_msg ("WATCH [%llu] %05o:%06o read2  %08llo %012llo (%s)\r\n",
5158                  (unsigned long long int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5159                  (unsigned long long int)addr, (unsigned long long int)M [addr], ctx);
5160         traceInstruction (0);
5161       }
5162 # endif
5163 # if defined(LOCKLESS)
5164 #  if !defined(SUNLINT)
5165     LOAD_ACQ_CORE_WORD(v, addr);
5166     if (v & MEM_LOCKED)
5167       sim_warn ("core_read2: even locked %08o locked_addr %08o %c %05o:%06o\r\n",
5168                 addr,        cpu.coreLockState.locked_addr, current_running_cpu_idx + 'A',
5169                 cpu.PPR.PSR, cpu.PPR.IC);
5170     *even = v & DMASK;
5171     addr++;
5172 #  endif /* if !defined(SUNLINT) */
5173 # else
5174     *even = M[addr++] & DMASK;
5175 # endif
5176     sim_debug (DBG_CORE, & cpu_dev,
5177                "core_read2 %08o %012"PRIo64" (%s)\r\n",
5178                 addr - 1, * even, ctx);
5179 
5180     // if the even address is OK, the odd will be
5181     //nem_check (addr,  "core_read2 nem");
5182 # if !defined(LOCKLESS)
5183     if (M[addr] & MEM_UNINITIALIZED)
5184       {
5185         sim_debug (DBG_WARN, & cpu_dev,
5186                    "Uninitialized memory accessed at address %08o; "
5187                    "IC is 0%06o:0%06o (%s)\r\n",
5188                     addr, cpu.PPR.PSR, cpu.PPR.IC, ctx);
5189       }
5190 # endif
5191 # if !defined(SPEED)
5192     if (watch_bits [addr])
5193       {
5194         sim_msg ("WATCH [%llu] %05o:%06o read2  %08llo %012llo (%s)\r\n",
5195                  (unsigned long long int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5196                  (unsigned long long int)addr, (unsigned long long int)M [addr], ctx);
5197         traceInstruction (0);
5198       }
5199 # endif
5200 # if defined(LOCKLESS)
5201 #  if !defined(SUNLINT)
5202     LOAD_ACQ_CORE_WORD(v, addr);
5203     if (v & MEM_LOCKED)
5204       sim_warn ("core_read2: odd locked %08o locked_addr %08o %c %05o:%06o\r\n",
5205                 addr,        cpu.coreLockState.locked_addr, current_running_cpu_idx + 'A',
5206                 cpu.PPR.PSR, cpu.PPR.IC);
5207     *odd = v & DMASK;
5208 #  endif /* if !defined(SUNLINT) */
5209 # else
5210     *odd = M[addr] & DMASK;
5211 # endif
5212     sim_debug (DBG_CORE, & cpu_dev,
5213                "core_read2 %08o %012"PRIo64" (%s)\r\n",
5214                 addr, * odd, ctx);
5215     DO_WORK_MEM;
5216     PNL (trackport (addr - 1, * even));
5217     return 0;
5218   }
5219 #endif
5220 
5221 #if !defined(SPEED) || !defined(INLINE_CORE)
5222 int core_write2 (cpu_state_t * cpup, word24 addr, word36 even, word36 odd, const char * ctx) {
     /* [previous][next][first][last][top][bottom][index][help] */
5223   TANDD_HOOK (tandd_write_hook (cpup, addr & ~1u, 2, true));
5224   PNL (cpu.portBusy = true;)
5225   if (addr & 1) {
5226     sim_debug (DBG_MSG, & cpu_dev,
5227                "warning: subtracting 1 from pair at %o in core_write2 " "(%s)\r\n",
5228                addr, ctx);
5229     addr &= (word24)~1; /* make it even a dress, or iron a skirt ;) */
5230   }
5231   SC_MAP_ADDR (addr, addr);
5232   if (cpu.tweaks.isolts_mode) {
5233     if (cpu.MR.sdpap) {
5234       sim_warn ("failing to implement sdpap\r\n");
5235       cpu.MR.sdpap = 0;
5236     }
5237     if (cpu.MR.separ) {
5238       sim_warn ("failing to implement separ\r\n");
5239       cpu.MR.separ = 0;
5240     }
5241   }
5242 
5243 # if !defined(SPEED)
5244   if (watch_bits [addr]) {
5245     sim_msg ("WATCH [%llu] %05o:%06o write2 %08llo %012llo (%s)\r\n",
5246              (unsigned long long int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5247              (unsigned long long int)addr, (unsigned long long int)even, ctx);
5248     traceInstruction (0);
5249   }
5250 # endif
5251 # if defined(LOCKLESS)
5252   LOCK_CORE_WORD(addr, & cpu.coreLockState);
5253 #  if !defined(SUNLINT)
5254   STORE_REL_CORE_WORD(addr, even);
5255 #  endif /* if !defined(SUNLINT) */
5256   addr++;
5257 # else
5258   M[addr++] = even & DMASK;
5259 # endif
5260   sim_debug (DBG_CORE, & cpu_dev, "core_write2 %08o %012llo (%s)\r\n", addr - 1,
5261           (long long unsigned int)even, ctx);
5262 
5263   // If the even address is OK, the odd will be
5264   //mem_check (addr,  "core_write2 nem");
5265 
5266 # if !defined(SPEED)
5267   if (watch_bits [addr]) {
5268     sim_msg ("WATCH [%llu] %05o:%06o write2 %08llo %012llo (%s)\r\n",
5269              (long long unsigned int)cpu.cycleCnt, cpu.PPR.PSR, cpu.PPR.IC,
5270              (long long unsigned int)addr, (long long unsigned int)odd, ctx);
5271     traceInstruction (0);
5272   }
5273 # endif
5274 # if defined(LOCKLESS)
5275   LOCK_CORE_WORD(addr, & cpu.coreLockState);
5276 #  if !defined(SUNLINT)
5277   STORE_REL_CORE_WORD(addr, odd);
5278 #  endif /* if !defined(SUNLINT) */
5279 # else
5280   M[addr] = odd & DMASK;
5281 # endif
5282   // this CPU's cache is store through; SCU write notification to the others
5283   cacheStoreNotify (cpup, addr - 1, even & DMASK);
5284   cacheStoreNotify (cpup, addr, odd & DMASK);
5285   DO_WORK_MEM;
5286   PNL (trackport (addr - 1, even));
5287   sim_debug (DBG_CORE, & cpu_dev, "core_write2 %08o %012"PRIo64" (%s)\r\n", addr, odd, ctx);
5288   return 0;
5289 }
5290 #endif
5291 
5292 /*
5293  * Instruction fetcher ...
5294  * Fetch + decode instruction at 18-bit address 'addr'
5295  */
5296 
5297 /*
5298  * Instruction decoder .....
5299  */
5300 
5301 void decode_instruction (cpu_state_t * cpup, word36 inst, DCDstruct * p)
     /* [previous][next][first][last][top][bottom][index][help] */
5302   {
5303     CPT (cpt1L, 17); // instruction decoder
5304     //(void)memset (p, 0, sizeof (DCDstruct));
5305     // only these two flags need explicit clearing before the new instruction is decoded.
5306     // Every other field is explicitly assigned below.
5307     p->stiTally = false;
5308     p->restart  = false;
5309 
5310     p->opcode   = GET_OP (inst);   // get opcode
5311     p->opcodeX  = GET_OPX(inst);   // opcode extension
5312     p->opcode10 = p->opcode | (p->opcodeX ? 01000 : 0); //-V536
5313     p->address  = GET_ADDR (inst); // address field from instruction
5314     p->b29      = GET_A (inst);    // "A" the indirect via pointer register flag
5315     p->i        = GET_I (inst);    // "I" inhibit interrupt flag
5316     p->tag      = GET_TAG (inst);  // instruction tag
5317 
5318     p->info     = get_iwb_info  (p);     // get info for IWB instruction
5319 
5320     if (p->info->flags & IGN_B29)
5321         p->b29 = 0;   // make certain 'a' bit is valid always
5322 
5323     if (p->info->ndes > 0)
5324       {
5325         p->b29 = 0;
5326         p->tag = 0;
5327         if (p->info->ndes > 1)
5328           {
5329             (void)memset (& cpu.currentEISinstruction, 0,
5330                           sizeof (cpu.currentEISinstruction));
5331           }
5332       }
5333   }
5334 
5335 // MM stuff ...
5336 
5337 //
5338 // is_priv_mode()
5339 //
5340 // Report whether or or not the CPU is in privileged mode.
5341 // True if in absolute mode or if priv bit is on in segment TPR.TSR
5342 // The processor executes instructions in privileged mode when forming
5343 // addresses in absolute mode or when forming addresses in append mode and the
5344 // segment descriptor word (SDW) for the segment in execution specifies a
5345 // privileged procedure and the execution ring is equal to zero.
5346 //
5347 // PPR.P A flag controlling execution of privileged instructions.
5348 //
5349 // Its value is 1 (permitting execution of privileged instructions) if PPR.PRR
5350 // is 0 and the privileged bit in the segment descriptor word (SDW.P) for the
5351 // procedure is 1; otherwise, its value is 0.
5352 //
5353 
5354 int is_priv_mode (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5355   {
5356 // Back when it was ABS/APP/BAR, this test was right; now that
5357 // it is ABS/APP,BAR/NBAR, check bar mode.
5358 // Fixes ISOLTS 890 05a.
5359     if (get_bar_mode (cpup))
5360       return 0;
5361 
5362 // PPR.P is only relevant if we're in APPEND mode. ABSOLUTE mode ignores it.
5363     if (get_addr_mode (cpup) == ABSOLUTE_mode)
5364       return 1;
5365     else if (cpu.PPR.P)
5366       return 1;
5367 
5368     return 0;
5369   }
5370 
5371 /*
5372  * get_bar_mode: During fault processing, we do not want to fetch and execute
5373  * the fault vector instructions in BAR mode. We leverage the
5374  * secret_addressing_mode flag that is set in set_TEMPORARY_ABSOLUTE_MODE to
5375  * direct us to ignore the I_NBAR indicator register.
5376  */
5377 
5378 bool get_bar_mode (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5379   {
5380     return ! (cpu.secret_addressing_mode || TST_I_NBAR);
5381   }
5382 
5383 addr_modes_e get_addr_mode (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5384   {
5385     if (cpu.secret_addressing_mode)
5386         return ABSOLUTE_mode; // This is not the mode you are looking for
5387 
5388     // went_appending does not alter privileged state (only enables appending)
5389     // the went_appending check is only required by ABSA, AFAICT
5390     // pft 02b 013255, ISOLTS-860
5391     //if (cpu.went_appending)
5392     //    return APPEND_mode;
5393 
5394     if (TST_I_ABS)
5395       {
5396           return ABSOLUTE_mode;
5397       }
5398     else
5399       {
5400           return APPEND_mode;
5401       }
5402   }
5403 
5404 /*
5405  * set_addr_mode()
5406  *
5407  * Put the CPU into the specified addressing mode.   This involves
5408  * setting a couple of IR flags and the PPR priv flag.
5409  */
5410 
5411 void set_addr_mode (cpu_state_t * cpup, addr_modes_e mode)
     /* [previous][next][first][last][top][bottom][index][help] */
5412   {
5413 //    cpu.cu.XSF = false;
5414 //sim_debug (DBG_TRACEEXT, & cpu_dev, "set_addr_mode bit 29 sets XSF to 0\r\n");
5415     //cpu.went_appending = false;
5416 // Temporary hack to fix fault/intr pair address mode state tracking
5417 //   1. secret_addressing_mode is only set in fault/intr pair processing.
5418 //   2. Assume that the only set_addr_mode that will occur is the b29 special
5419 //   case or ITx.
5420     //if (secret_addressing_mode && mode == APPEND_mode)
5421       //set_went_appending ();
5422 
5423     cpu.secret_addressing_mode = false;
5424     if (mode == ABSOLUTE_mode)
5425       {
5426         CPT (cpt1L, 22); // set abs mode
5427         sim_debug (DBG_DEBUG, & cpu_dev, "APU: Setting absolute mode.\r\n");
5428 
5429         SET_I_ABS;
5430         cpu.PPR.P = 1;
5431       }
5432     else if (mode == APPEND_mode)
5433       {
5434         CPT (cpt1L, 23); // set append mode
5435         if (! TST_I_ABS && TST_I_NBAR)
5436           sim_debug (DBG_DEBUG, & cpu_dev, "APU: Keeping append mode.\r\n");
5437         else
5438           sim_debug (DBG_DEBUG, & cpu_dev, "APU: Setting append mode.\r\n");
5439 
5440         CLR_I_ABS;
5441       }
5442     else
5443       {
5444         sim_debug (DBG_ERR, & cpu_dev,
5445                   "APU: Unable to determine address mode.\r\n");
5446         sim_warn ("APU: Unable to determine address mode. Can't happen!\r\n");
5447       }
5448   }
5449 
5450 /*
5451  * stuff to handle BAR mode ...
5452  */
5453 
5454 /*
5455  * The Base Address Register provides automatic hardware Address relocation and
5456  * Address range limitation when the processor is in BAR mode.
5457  *
5458  * BAR.BASE: Contains the 9 high-order bits of an 18-bit address relocation
5459  * constant. The low-order bits are generated as zeros.
5460  *
5461  * BAR.BOUND: Contains the 9 high-order bits of the unrelocated address limit.
5462  * The low- order bits are generated as zeros. An attempt to access main memory
5463  * beyond this limit causes a store fault, out of bounds. A value of 0 is truly
5464  * 0, indicating a null memory range.
5465  *
5466  * In BAR mode, the base address register (BAR) is used. The BAR contains an
5467  * address bound and a base address. All computed addresses are relocated by
5468  * adding the base address. The relocated address is combined with the
5469  * procedure pointer register to form the virtual memory address. A program is
5470  * kept within certain limits by subtracting the unrelocated computed address
5471  * from the address bound. If the result is zero or negative, the relocated
5472  * address is out of range, and a store fault occurs.
5473  */
5474 
5475 // CANFAULT
5476 word18 get_BAR_address (cpu_state_t * cpup, word18 addr)
     /* [previous][next][first][last][top][bottom][index][help] */
5477   {
5478     if (cpu . BAR.BOUND == 0)
5479         // store fault, out of bounds.
5480         doFault (FAULT_STR, fst_str_oob, "BAR store fault; out of bounds");
5481 
5482     // A program is kept within certain limits by subtracting the
5483     // unrelocated computed address from the address bound. If the result
5484     // is zero or negative, the relocated address is out of range, and a
5485     // store fault occurs.
5486     //
5487     // BAR.BOUND - CA <= 0
5488     // BAR.BOUND <= CA
5489     // CA >= BAR.BOUND
5490     //
5491     if (addr >= (((word18) cpu . BAR.BOUND) << 9))
5492         // store fault, out of bounds.
5493         doFault (FAULT_STR, fst_str_oob, "BAR store fault; out of bounds");
5494 
5495     word18 barAddr = (addr + (((word18) cpu . BAR.BASE) << 9)) & 0777777;
5496     return barAddr;
5497   }
5498 
5499 //=============================================================================
5500 
5501 static void add_history (cpu_state_t * cpup, uint hset, word36 w0, word36 w1)
     /* [previous][next][first][last][top][bottom][index][help] */
5502   {
5503     //if (cpu.MR.emr)
5504       {
5505         cpu.history [hset] [cpu.history_cyclic[hset]] [0] = w0;
5506         cpu.history [hset] [cpu.history_cyclic[hset]] [1] = w1;
5507         cpu.history_cyclic[hset] = (cpu.history_cyclic[hset] + 1) % N_MODEL_HIST_SIZE;
5508       }
5509   }
5510 
5511 void add_history_force (cpu_state_t * cpup, uint hset, word36 w0, word36 w1)
     /* [previous][next][first][last][top][bottom][index][help] */
5512   {
5513     cpu.history [hset] [cpu.history_cyclic[hset]] [0] = w0;
5514     cpu.history [hset] [cpu.history_cyclic[hset]] [1] = w1;
5515     cpu.history_cyclic[hset] = (cpu.history_cyclic[hset] + 1) % N_MODEL_HIST_SIZE;
5516   }
5517 
5518 // (inline: see fetchInstruction)
5519 inline void add_dps8m_CU_history (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5520   {
5521     if (cpu.skip_cu_hist)
5522       return;
5523     if (! cpu.MR_cache.emr)
5524       return;
5525     if (! cpu.MR_cache.ihr)
5526       return;
5527     if (cpu.MR_cache.hrxfr && ! cpu.wasXfer)
5528       return;
5529 
5530     word36 flags   = 0; // XXX fill out
5531     word5 proccmd  = 0; // XXX fill out
5532     word7 flags2   = 0; // XXX fill out
5533     word36 w0      = 0, w1 = 0;
5534     w0            |= flags & 0777777000000;
5535     w0            |= IWB_IRODD & MASK18;
5536     w1            |= ((word36)(cpu.iefpFinalAddress & MASK24) << 12);
5537     w1            |= (proccmd & MASK5) << 7;
5538     w1            |= flags2 & 0176;
5539     add_history (cpup, CU_HIST_REG, w0, w1);
5540   }
5541 
5542 #if !defined(QUIET_UNUSED)
5543 void add_dps8m_DU_OU_history (cpu_state_t * cpup, word36 flags, word18 ICT, word9 RS_REG, word9 flags2)
     /* [previous][next][first][last][top][bottom][index][help] */
5544   {
5545     word36 w0  = flags, w1 = 0;
5546     w1        |= (ICT & MASK18) << 18;
5547     w1        |= (RS_REG & MASK9) << 9;
5548     w1        |= flags2 & MASK9;
5549     add_history (cpup, DPS8M_DU_OU_HIST_REG, w0, w1);
5550   }
5551 
5552 void add_dps8m_APU_history (cpu_state_t * cpup, word15 ESN, word21 flags, word24 RMA, word3 RTRR, word9 flags2)
     /* [previous][next][first][last][top][bottom][index][help] */
5553   {
5554     word36 w0  = 0, w1 = 0;
5555     w0        |= (ESN & MASK15) << 21;
5556     w0        |= flags & MASK21;
5557     w1        |= (RMA & MASK24) << 12;
5558     w1        |= (RTRR & MASK3) << 9;
5559     w1        |= flags2 & MASK9;
5560     add_history (cpu.tweaks.l68_mode ? L68_APU_HIST_REG : DPS8M_APU_HIST_REG, w0, w1);
5561   }
5562 
5563 void add_dps8m_EAPU_history (word18 ZCA, word18 opcode)
     /* [previous][next][first][last][top][bottom][index][help] */
5564   {
5565     word36 w0  = 0;
5566     w0        |= (ZCA & MASK18) << 18;
5567     w0        |= opcode & MASK18;
5568     add_history (DPS8M_EAPU_HIST_REG, w0, 0);
5569     //cpu.eapu_hist[cpu.eapu_cyclic].ZCA = ZCA;
5570     //cpu.eapu_hist[cpu.eapu_cyclic].opcode = opcode;
5571     //cpu.history_cyclic[DPS8M_EAPU_HIST_REG] =
5572       //(cpu.history_cyclic[DPS8M_EAPU_HIST_REG] + 1) % N_DPS8M_HIST_SIZE;
5573   }
5574 #endif
5575 
5576 // According to ISOLTS
5577 //
5578 //   0 PIA
5579 //   1 POA
5580 //   2 RIW
5581 //   3 SIW
5582 //   4 POT
5583 //   5 PON
5584 //   6 RAW
5585 //   7 SAW
5586 //   8 TRGO
5587 //   9 XDE
5588 //  10 XDO
5589 //  11 IC
5590 //  12 RPTS
5591 //  13 WI
5592 //  14 AR F/E
5593 //  15 XIP
5594 //  16 FLT
5595 //  17 COMPL. ADD BASE
5596 //  18:23 OPCODE/TAG
5597 //  24:29 ADDREG
5598 //  30:34 COMMAND A/B/C/D/E
5599 //  35:38 PORT A/B/C/D
5600 //  39 FB XEC
5601 //  40 INS FETCH
5602 //  41 CU STORE
5603 //  42 OU STORE
5604 //  43 CU LOAD
5605 //  44 OU LOAD
5606 //  45 RB DIRECT
5607 //  46 -PC BUSY
5608 //  47 PORT BUSY
5609 
5610 // The L68 CU history register is strobed on every control unit cycle
5611 // (AL39: "the conditions for the last 16 control unit cycles"), so an
5612 // instruction pair fetch, or a transfer's read of its target pair, makes
5613 // an entry of its own (INS-FETCH); the CU-HR counter overflow trap counts
5614 // these too (PM701 02C).
5615 static void add_l68_CU_history_entry (cpu_state_t * cpup, bool ins_fetch)
     /* [previous][next][first][last][top][bottom][index][help] */
5616   {
5617     CPT (cpt1L, 24); // add cu hist
5618     if (cpu.skip_cu_hist)
5619       return;
5620     if (! cpu.MR_cache.emr)
5621       return;
5622     if (! cpu.MR_cache.ihr)
5623       return;
5624     // O.C$ (bit 29): strobe only the instruction whose opcode matches the
5625     // MR OPCODE field (PM700 02Y)
5626     if (getbits36_1 (cpu.MR_cache.r, 29) &&
5627         (ins_fetch ||
5628          cpu.currentInstruction.opcode != getbits36_9 (cpu.MR_cache.r, 18) ||
5629          (cpu.currentInstruction.opcodeX ? 1u : 0u) != getbits36_1 (cpu.MR_cache.r, 27)))
5630       return;
5631 
5632     word36 w0 = 0, w1 = 0;
5633 
5634     // 0 PIA
5635     // 1 POA
5636     // 2 RIW
5637     // 3 SIW
5638     // 4 POT
5639     // 5 PON
5640     // 6 RAW
5641     // 7 SAW
5642     PNL (putbits36_8 (& w0, 0, cpu.prepare_state);)
5643     // 8 TRG
5644     putbits36_1  (& w0, 8, cpu.wasXfer);
5645     // 9 XDE
5646     putbits36_1  (& w0, 9, cpu.cu.xde);
5647     // 10 XDO
5648     putbits36_1  (& w0, 10, cpu.cu.xdo);
5649     // 11 IC
5650     putbits36_1  (& w0, 11, USE_IRODD?1:0);
5651     // 12 RPT
5652     putbits36_1  (& w0, 12, cpu.cu.rpt);
5653     // 13 WI Wait for instruction fetch XXX Not tracked
5654     // 14 ARF "AR F/E" Address register Full/Empty Address has valid data
5655     PNL (putbits36_1 (& w0, 14, cpu.AR_F_E);)
5656     // 15 !XA/Z "-XIP NOT prepare interrupt address"
5657     putbits36_1  (& w0, 15, cpu.cycle != INTERRUPT_cycle?1:0);
5658     // 16 !FA/Z Not tracked. (cu.-FL?)
5659     putbits36_1  (& w0, 16, cpu.cycle != FAULT_cycle?1:0);
5660     // 17 M/S  (master/slave, cu.-BASE?, NOT BAR MODE)
5661     putbits36_1  (& w0, 17, TSTF (cpu.cu.IR, I_NBAR)?1:0);
5662     // 18:35 IWR (lower half of IWB)
5663     putbits36_18 (& w0, 18, (word18) (IWB_IRODD & MASK18));
5664 
5665     // 36:53 CA
5666     putbits36_18 (& w1, 0, cpu.TPR.CA);
5667     // 54:58 CMD system controller command XXX
5668     // 59:62 SEL port select (XXX ignoring "only valid if port A-D is selected")
5669     PNL (putbits36_1 (& w1, 59-36, (cpu.portSelect == 0)?1:0);)
5670     PNL (putbits36_1 (& w1, 60-36, (cpu.portSelect == 1)?1:0);)
5671     PNL (putbits36_1 (& w1, 61-36, (cpu.portSelect == 2)?1:0);)
5672     PNL (putbits36_1 (& w1, 62-36, (cpu.portSelect == 3)?1:0);)
5673     // 63 XEC-INT An interrupt is present
5674     putbits36_1 (& w1, 63-36, cpu.interrupt_flag?1:0);
5675     // 64 INS-FETCH Perform an instruction fetch
5676     putbits36_1 (& w1, 64-36, ins_fetch?1:0);
5677     // 65 CU-STORE Control unit store cycle XXX
5678     // 66 OU-STORE Operations unit store cycle XXX
5679     // 67 CU-LOAD Control unit load cycle XXX
5680     // 68 OU-LOAD Operations unit load cycle XXX
5681     // 69 DIRECT Direct cycle XXX
5682     // 70 -PC-BUSY Port control logic not busy XXX
5683     // 71 BUSY Port interface busy XXX
5684 
5685     add_history (cpup, CU_HIST_REG, w0, w1);
5686 
5687     // Check for overflow
5688     CPTUR (cptUseMR);
5689     if (cpu.MR.hrhlt && cpu.history_cyclic[CU_HIST_REG] == 0)
5690       {
5691         //cpu.history_cyclic[CU_HIST_REG] = 15;
5692         if (cpu.MR.ihrrs)
5693           {
5694             cpu.MR.ihr = 0;
5695           }
5696         set_FFV_fault (cpup, 4);
5697         return;
5698       }
5699   }
5700 
5701 void add_l68_CU_history (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5702   {
5703     add_l68_CU_history_entry (cpup, false);
5704   }
5705 
5706 void add_l68_CU_fetch_history (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5707   {
5708     add_l68_CU_history_entry (cpup, true);
5709   }
5710 
5711 // du history register inputs(actual names)
5712 // bit 00= fpol-cx;010       bit 36= fdud-dg;112
5713 // bit 01= fpop-cx;010       bit 37= fgdlda-dc;010
5714 // bit 02= need-desc-bd;000  bit 38= fgdldb-dc;010
5715 // bit 03= sel-adr-bd;000    bit 39= fgdldc-dc;010
5716 // bit 04= dlen=direct-bd;000bit 40= fnld1-dp;110
5717 // bit 05= dfrst-bd;021      bit 41= fgldp1-dc;110
5718 // bit 06= fexr-bd;010       bit 42= fnld2-dp;110
5719 // bit 07= dlast-frst-bd;010 bit 43= fgldp2-dc;110
5720 // bit 08= ddu-ldea-bd;000   bit 44= fanld1-dp;110
5721 // bit 09= ddu-stea-bd;000   bit 45= fanld2-dp;110
5722 // bit 10= dredo-bd;030      bit 46= fldwrt1-dp;110
5723 // bit 11= dlvl<wd-sz-bg;000 bit 47= fldwrt2-dp;110
5724 // bit 12= exh-bg;000        bit 48= data-avldu-cm;000
5725 // bit 13= dend-seg-bd;111   bit 49= fwrt1-dp;110
5726 // bit 14= dend-bd;000       bit 50= fgstr-dc;110
5727 // bit 15= du=rd+wrt-bd;010  bit 51= fanstr-dp;110
5728 // bit 16= ptra00-bd;000     bit 52= fstr-op-av-dg;010
5729 // bit 17= ptra01-bd;000     bit 53= fend-seg-dg;010
5730 // bit 18= fa/i1-bd;110      bit 54= flen<128-dg;010
5731 // bit 19= fa/i2-bd;110      bit 55= fgch-dp;110
5732 // bit 20= fa/i3-bd;110      bit 56= fanpk-dp;110
5733 // bit 21= wrd-bd;000        bit 57= fexmop-dl;110
5734 // bit 22= nine-bd;000       bit 58= fblnk-dp;100
5735 // bit 23= six-bd;000        bit 59= unused
5736 // bit 24= four-bd;000       bit 60= dgbd-dc;100
5737 // bit 25= bit-bd;000        bit 61= dgdb-dc;100
5738 // bit 26= unused            bit 62= dgsp-dc;100
5739 // bit 27= unused            bit 63= ffltg-dc;110
5740 // bit 28= unused            bit 64= frnd-dg;120
5741 // bit 29= unused            bit 65= dadd-gate-dc;100
5742 // bit 30= fsampl-bd;111     bit 66= dmp+dv-gate-db;100
5743 // bit 31= dfrst-ct-bd;010   bit 67= dxpn-gate-dg;100
5744 // bit 32= adj-lenint-cx;000 bit 68= unused
5745 // bit 33= fintrptd-cx;010   bit 69= unused
5746 // bit 34= finhib-stc1-cx;010bit 70= unused
5747 // bit 35= unused            bit 71= unused
5748 
5749 void add_l68_DU_history (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5750   {
5751     CPT (cpt1L, 25); // add du hist
5752     PNL (add_history (cpup, L68_DU_HIST_REG, cpu.du.cycle1, cpu.du.cycle2);)
5753   }
5754 
5755 void add_l68_OU_history (cpu_state_t * cpup)
     /* [previous][next][first][last][top][bottom][index][help] */
5756   {
5757     CPT (cpt1L, 26); // add ou hist
5758     word36 w0 = 0, w1 = 0;
5759 
5760     // 0-16 RP
5761     //   0-8 OP CODE
5762     putbits36_9 (& w0,       0,       cpu.ou.RS);
5763 
5764     //   9 CHAR
5765     putbits36_1 (& w0,       9,       cpu.ou.characterOperandSize ? 1 : 0);
5766 
5767     //   10-12 TAG 1/2/3
5768     putbits36_3 (& w0,       10,      cpu.ou.characterOperandOffset);
5769 
5770     //   13 CRFLAG
5771     putbits36_1 (& w0,       13,      cpu.ou.crflag);
5772 
5773     //   14 DRFLAG
5774     putbits36_1 (& w0,       14,      cpu.ou.directOperandFlag ? 1 : 0);
5775 
5776     //   15-16 EAC
5777     putbits36_2 (& w0,       15,      cpu.ou.eac);
5778 
5779     // 17 0
5780     // 18-26 RS REG
5781     putbits36_9 (& w0,       18,      cpu.ou.RS);
5782 
5783     // 27 RB1 FULL
5784     putbits36_1 (& w0,       27,      cpu.ou.RB1_FULL);
5785 
5786     // 28 RP FULL
5787     putbits36_1 (& w0,       28,      cpu.ou.RP_FULL);
5788 
5789     // 29 RS FULL
5790     putbits36_1 (& w0,       29,      cpu.ou.RS_FULL);
5791 
5792     // 30-35 GIN/GOS/GD1/GD2/GOE/GOA
5793     putbits36_6 (& w0,       30,      (word6) (cpu.ou.cycle >> 3));
5794 
5795     // 36-38 GOM/GON/GOF
5796     putbits36_3 (& w1,       36-36,   (word3) cpu.ou.cycle);
5797 
5798     // 39 STR OP
5799     putbits36_1 (& w1,       39-36,   cpu.ou.STR_OP);
5800 
5801     // 40 -DA-AV XXX
5802 
5803     // 41-50 stuvwyyzAB -A-REG -Q-REG -X0-REG .. -X7-REG
5804     putbits36_10 (& w1,      41-36,
5805                   (word10) ~opcodes10 [cpu.ou.RS].reg_use);
5806 
5807     // 51-53 0
5808 
5809     // 54-71 ICT TRACKER
5810     putbits36_18 (& w1,      54 - 36, cpu.PPR.IC);
5811 
5812     add_history (cpup, L68_OU_HIST_REG, w0, w1);
5813   }
5814 
5815 // According to ISOLTS
5816 //  0:2 OPCODE RP
5817 //  3 9 BIT CHAR
5818 //  4:6 TAG 3/4/5
5819 //  7 CR FLAG
5820 //  8 DIR FLAG
5821 //  9 RP15
5822 // 10 RP16
5823 // 11 SPARE
5824 // 12:14 OPCODE RS
5825 // 15 RB1 FULL
5826 // 16 RP FULL
5827 // 17 RS FULL
5828 // 18 GIN
5829 // 19 GOS
5830 // 20 GD1
5831 // 21 GD2
5832 // 22 GOE
5833 // 23 GOA
5834 // 24 GOM
5835 // 25 GON
5836 // 26 GOF
5837 // 27 STORE OP
5838 // 28 DA NOT
5839 // 29:38 COMPLEMENTED REGISTER IN USE FLAG A/Q/0/1/2/3/4/5/6/7
5840 // 39 ?
5841 // 40 ?
5842 // 41 ?
5843 // 42:47 ICT TRACT
5844 
5845 // XXX add_APU_history
5846 
5847 //  0:5 SEGMENT NUMBER
5848 //  6 SNR/ESN
5849 //  7 TSR/ESN
5850 //  8 FSDPTW
5851 //  9 FPTW2
5852 // 10 MPTW
5853 // 11 FANP
5854 // 12 FAP
5855 // 13 AMSDW
5856 // 14:15 AMSDW #
5857 // 16 AMPTW
5858 // 17:18 AMPW #
5859 // 19 ACV/DF
5860 // 20:27 ABSOLUTE MEMORY ADDRESS
5861 // 28 TRR #
5862 // 29 FLT HLD
5863 
5864 void add_l68_APU_history (cpu_state_t * cpup, enum APUH_e op)
     /* [previous][next][first][last][top][bottom][index][help] */
5865   {
5866     CPT (cpt1L, 28); // add apu hist
5867     word36 w0 = 0, w1 = 0;
5868 
5869     w0 = op; // set 17-24 FDSPTW/.../FAP bits
5870 
5871     // 0-14 ESN
5872     putbits36_15 (& w0,      0,  cpu.TPR.TSR);
5873     // 15-16 BSY
5874     PNL (putbits36_1 (& w0,  15, (cpu.apu.state & apu_ESN_SNR) ? 1 : 0);)
5875     PNL (putbits36_1 (& w0,  16, (cpu.apu.state & apu_ESN_TSR) ? 1 : 0);)
5876     // 25 SDWAMM
5877     putbits36_1 (& w0,       25, cpu.cu.SDWAMM);
5878     // 26-29 SDWAMR
5879     putbits36_4 (& w0,       26, (word4) cpu.SDWAMR);
5880     // 30 PTWAMM
5881     putbits36_1 (& w0,       30, cpu.cu.PTWAMM);
5882     // 31-34 PTWAMR
5883     putbits36_4 (& w0,       31, (word4) cpu.PTWAMR);
5884     // 35 FLT
5885     PNL (putbits36_1 (& w0,  35, (cpu.apu.state & apu_FLT) ? 1 : 0);)
5886 
5887     // 36-59 ADD
5888     PNL (putbits36_24 (& w1, 0,  cpu.APUMemAddr);)
5889     // 60-62 TRR
5890     putbits36_3 (& w1,       24, cpu.TPR.TRR);
5891     // 66 XXX Multiple match error in SDWAM
5892     // 70 Segment is encachable
5893     putbits36_1 (& w1,       34, cpu.SDW0.C);
5894     // 71 XXX Multiple match error in PTWAM
5895 
5896     add_history (cpup, L68_APU_HIST_REG, w0, w1);
5897   }
5898 
5899 #if defined(THREADZ) || defined(LOCKLESS)
5900 //static pthread_mutex_t debug_lock = PTHREAD_MUTEX_INITIALIZER;
5901 
5902 static const char * get_dbg_verb (uint32 dbits, DEVICE * dptr)
     /* [previous][next][first][last][top][bottom][index][help] */
5903   {
5904     static const char * debtab_none    = "DEBTAB_ISNULL";
5905     static const char * debtab_nomatch = "DEBTAB_NOMATCH";
5906     const char * some_match            = NULL;
5907     int32 offset                       = 0;
5908 
5909     if (dptr->debflags == 0)
5910       return debtab_none;
5911 
5912     dbits &= dptr->dctrl;     /* Look for just the bits that matched */
5913 
5914     /* Find matching words for bitmask */
5915     while ((offset < 32) && dptr->debflags[offset].name)
5916       {
5917         if (dptr->debflags[offset].mask == dbits)   /* All Bits Match */
5918           return dptr->debflags[offset].name;
5919         if (dptr->debflags[offset].mask & dbits)
5920           some_match = dptr->debflags[offset].name;
5921         offset ++;
5922       }
5923     return some_match ? some_match : debtab_nomatch;
5924   }
5925 
5926 void dps8_sim_debug (uint32 dbits, DEVICE * dptr, unsigned long long cnt, const char* fmt, ...)
     /* [previous][next][first][last][top][bottom][index][help] */
5927   {
5928     //pthread_mutex_lock (& debug_lock);
5929     if (sim_deb && dptr && (dptr->dctrl & dbits))
5930       {
5931         const char * debug_type = get_dbg_verb (dbits, dptr);
5932         char stackbuf[STACKBUFSIZE];
5933         int32 bufsize           = sizeof (stackbuf);
5934         char * buf              = stackbuf;
5935         va_list arglist;
5936         int32 i, j, len;
5937         struct timespec t;
5938         clock_gettime(CLOCK_REALTIME, &t);
5939 
5940         buf [bufsize-1] = '\0';
5941 
5942         while (1)
5943           {                 /* format passed string, args */
5944             va_start (arglist, fmt);
5945             len = vsnprintf (buf, (int)((unsigned long)(bufsize)-1), fmt, arglist);
5946             va_end (arglist);
5947 
5948 /* If the formatted result didn't fit into the buffer, then grow the buffer and try again */
5949 
5950             if ((len < 0) || (len >= bufsize-1))
5951               {
5952                 if (buf != stackbuf)
5953                   FREE (buf);
5954                 if (bufsize >= (INT_MAX / 2))
5955                   return;                                   /* too big */
5956                 bufsize = bufsize * 2;
5957                 if (bufsize < len + 2)
5958                   bufsize = len + 2;
5959                 buf = (char *) malloc ((unsigned long) bufsize);
5960                 if (buf == NULL)                            /* out of memory */
5961                   return;
5962                 buf[bufsize-1] = '\0';
5963                 continue;
5964               }
5965             break;
5966           }
5967 
5968 /* Output the formatted data expanding newlines where they exist */
5969 
5970         for (i = j = 0; i < len; ++i)
5971           {
5972             if ('\n' == buf[i])
5973               {
5974                 if (i >= j)
5975                   {
5976                     if ((i != j) || (i == 0))
5977                       {
5978                           (void)fprintf (sim_deb, "%lld.%06ld: DBG(%lld) %o: %s %s %.*s\r\n",
5979                                          (long long)t.tv_sec, t.tv_nsec/1000, cnt,
5980                                          current_running_cpu_idx, dptr->name, debug_type, i-j, &buf[j]);
5981                       }
5982                   }
5983                 j = i + 1;
5984               }
5985           }
5986 
5987         /* Set unterminated flag for next time */
5988         if (buf != stackbuf)
5989           FREE (buf);
5990       }
5991     //pthread_mutex_unlock (& debug_lock);
5992   }
5993 #endif
5994 
5995 void setupPROM (uint cpuNo, unsigned char * PROM) {
     /* [previous][next][first][last][top][bottom][index][help] */
5996 // 58009997-040 MULTICS Differences Manual DPS 8-70M Aug83
5997 //
5998 // THESE OFFSETS ARE IN OCTAL
5999 //
6000 //  0-13 CPU Model Number
6001 // 13-25 CPU Serial Number
6002 // 26-33 Date-Ship code (YYMMDD)
6003 // 34-40 CPU ID Field (reference RSW 2)
6004 //  Byte 40: Bits 03 (Bits 32-35 of RSW 2 Field
6005 //           Bit 4=1 Hex Option included
6006 //           Bit 5=1 RSCR (Clock) is Slave Mode included
6007 //           Bits 6-7 Reserved for later use.
6008 //       50: Operating System Use
6009 // 51-1777(8) To be defined.
6010 // NOTE: There is the possibility of disagreement between the
6011 //       ID bits of RSW 2 and the ID bits of PROM locations
6012 //       35-40. This condition could result when alterable
6013 //       configuration condition is contained in the PROM.
6014 //       The user is advised to ignore the PROM fields which
6015 //       contain the processor fault vector base (GCOS III)
6016 //       and the processor number and rely on the RSW 2 bits
6017 //       for this purpose. Bits 14-16 of the RSW 2 should be
6018 //       ignored and the bits representing this information in
6019 //       the PROM should be treated as valid.
6020 
6021 // "0-13" disagrees with Multics source (start_pl1); it interprets
6022 // it as "0-12"; most likely a typo in 58009997-040.
6023 
6024 // CAC notes: I interpret the fields as
6025 //  0-12 CPU Model Number                                          //  0-10  11 chars
6026 // 13-25 CPU Serial Number // 13 chars                             // 11-21  11 chars
6027 // 26-33 Date-Ship code (YYMMDD) // 8 chars (enough for YYYYMMDD). // 22-27   6 chars
6028 // 34-40 CPU ID Field (reference RSW 2)                            // 28-32   5 chars
6029 //  Byte 40: Bits 03 (Bits 32-35 of RSW 2 Field                    //    32
6030 //           Bit 4=1 Hex Option included
6031 //           Bit 5=1 RSCR (Clock) is Slave Mode included
6032 //           Bits 6-7 Reserved for later use.
6033 //       50: Operating System Use                                  //    40
6034 
6035   word36 rsw2 = 0;
6036 
6037   // The PROM copy of RSW 2 contains a canonical RSW 2 rather than the actual RSW 2.
6038   //   The port interlace is set to 0
6039   //   The fault base is set to 2 (Multics)
6040   //   Processor mode is set to 0 (Multics)
6041 
6042   //  0 -   3   4   Port interlace = 0000
6043   putbits36_4 (& rsw2,  0,   0);
6044   //  4 -   5   2   CPU type  01 = DPS8
6045   putbits36_2 (& rsw2,  4,  001);
6046   //  6 - 12    7   Fault Base  = 2
6047   putbits36_7 (& rsw2,  6,   2);
6048   // 13 - 13    1   PROM Present = 1
6049   putbits36_1 (& rsw2,  13,  1);
6050   // 14 - 18    5   Pad 00000
6051   putbits36_5 (& rsw2,  14,  0);
6052   // 19 - 19    1   CPU  1 = DPS8
6053   putbits36_1 (& rsw2,  19,  1);
6054   // 20 - 20    1   8K Cache  1 = Present
6055   putbits36_1 (& rsw2,  20,  cpus[cpuNo].options.cache_installed ? 1 : 0);
6056   // 21 - 22    2   Pad
6057   putbits36_2 (& rsw2,  21,  0);
6058   // 23 - 23    1   Always 1 for Multics CPU
6059   putbits36_1 (& rsw2,  23,  1);
6060   // 24 - 24    1   Proc Mode Bit
6061   putbits36_1 (& rsw2,  24,  0);
6062   // 25 - 28    4   Pad
6063   putbits36_4 (& rsw2,  25,  0);
6064   // 29 - 32    4   CPU speed options
6065   putbits36_4 (& rsw2,  29,  cpus[cpuNo].options.proc_speed & 017LL);
6066   // 33 - 35    3   CPU number
6067   putbits36_3 (& rsw2,  33,  cpus[cpuNo].switches.cpu_num & 07LL);
6068 
6069   word4 rsw2Ext = 0;
6070   if (cpus[cpuNo].options.hex_mode_installed)
6071     rsw2Ext |= 010;  // bit 4
6072   if (cpus[cpuNo].options.clock_slave_installed)
6073     rsw2Ext |= 004;  // bit 5
6074   // bits 6,7 reserved for future use
6075 
6076   char serial[12];
6077   (void)sprintf (serial, "%-11u", cpus[cpuNo].switches.serno);
6078 
6079 #if defined(VER_H_PROM_SHIP)
6080   char * ship = VER_H_PROM_SHIP;
6081 #else
6082   char * ship = "200101";
6083 #endif /* VER_H_PROM_SHIP */
6084 
6085 #if !defined(VER_H_PROM_MAJOR_VER)
6086 # define VER_H_PROM_MAJOR_VER "999"
6087 #endif /* VER_H_PROM_MAJOR_VER */
6088 
6089 #if !defined(VER_H_PROM_MINOR_VER)
6090 # define VER_H_PROM_MINOR_VER "999"
6091 #endif /* VER_H_PROM_MINOR_VER */
6092 
6093 #if !defined(VER_H_PROM_PATCH_VER)
6094 # define VER_H_PROM_PATCH_VER "999"
6095 #endif /* VER_H_PROM_PATCH_VER */
6096 
6097 #if !defined(VER_H_PROM_OTHER_VER)
6098 # define VER_H_PROM_OTHER_VER "999"
6099 #endif /* VER_H_PROM_OTHER_VER */
6100 
6101 #if !defined(VER_H_GIT_RELT)
6102 # define VER_H_GIT_RELT "X"
6103 #endif /* VER_H_GIT_RELT */
6104 
6105 #if !defined(VER_H_PROM_VER_TEXT)
6106 # define VER_H_PROM_VER_TEXT "Unknown                      "
6107 #endif /* VER_H_PROM_VER_TEXT */
6108 
6109 #if defined(BUILD_PROM_OSA_TEXT)
6110 # define BURN_PROM_OSA_TEXT BUILD_PROM_OSA_TEXT
6111 #else
6112 # if !defined(VER_H_PROM_OSA_TEXT)
6113 #  define BURN_PROM_OSA_TEXT "Unknown Build Op Sys"
6114 # else
6115 #  define BURN_PROM_OSA_TEXT VER_H_PROM_OSA_TEXT
6116 # endif /* VER_H_PROM_OSA_TEXT */
6117 #endif /* BUILD_PROM_OSA_TEXT */
6118 
6119 #if defined(BUILD_PROM_OSV_TEXT)
6120 # define BURN_PROM_OSV_TEXT BUILD_PROM_OSV_TEXT
6121 #else
6122 # if !defined(VER_H_PROM_OSV_TEXT)
6123 #  define BURN_PROM_OSV_TEXT "Unknown Build Arch. "
6124 # else
6125 #  define BURN_PROM_OSV_TEXT VER_H_PROM_OSV_TEXT
6126 # endif /* VER_H_PROM_OSV_TEXT */
6127 #endif /* BUILD_PROM_OSV_TEXT */
6128 
6129 #if defined(BUILD_PROM_TSA_TEXT)
6130 # define BURN_PROM_TSA_TEXT BUILD_PROM_TSA_TEXT
6131 #else
6132 # if defined(_M_X64) || defined(_M_AMD64) || defined(__amd64__) || defined(__x86_64__) || defined(__AMD64)
6133 #  define VER_H_PROM_TSA_TEXT "Intel x86_64 (AMD64)"
6134 # elif defined(_M_IX86) || defined(__i386) || defined(__i486) || defined(__i586) || defined(__i686) || defined(__ix86)
6135 #  define VER_H_PROM_TSA_TEXT "Intel ix86 (32-bit) "
6136 # elif defined(_M_ARM64) || defined(__aarch64__) || defined(__arm64__)
6137 #  define VER_H_PROM_TSA_TEXT "AArch64/ARM64/64-bit"
6138 # elif defined(_M_ARM) || defined(__arm__)
6139 #  define VER_H_PROM_TSA_TEXT "AArch32/ARM32/32-bit"
6140 # elif defined(__ia64__) || defined(_M_IA64) || defined(__itanium__)
6141 #  define VER_H_PROM_TSA_TEXT "Intel Itanium (IA64)"
6142 # elif defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || defined(__PPC64LE__) || defined(__powerpc64__) || \
6143   defined(__POWERPC64__) || \
6144   defined(_M_PPC64) || \
6145   defined(__PPC64) || \
6146   defined(_ARCH_PPC64)
6147 #  define VER_H_PROM_TSA_TEXT "Power ISA (64-bit)  "
6148 # elif defined(__ppc__) || defined(__PPC__) || defined(__powerpc__) || defined(__POWERPC__) || defined(_M_PPC) || \
6149   defined(__PPC) || \
6150   defined(__ppc32__) || \
6151   defined(__PPC32__) || \
6152   defined(__powerpc32__) || \
6153   defined(__POWERPC32__) || \
6154   defined(_M_PPC32) || \
6155   defined(__PPC32)
6156 #  define VER_H_PROM_TSA_TEXT "PowerPC ISA (32-bit)"
6157 # elif defined(__s390x__)
6158 #  define VER_H_PROM_TSA_TEXT "IBM z/Architecture  "
6159 # elif defined(__s390__)
6160 #  define VER_H_PROM_TSA_TEXT "IBM ESA System/390  "
6161 # elif defined(__J2__) || defined(__J2P__) || defined(__j2__) || defined(__j2p__)
6162 #  define VER_H_PROM_TSA_TEXT "J-Core J2 Open CPU  "
6163 # elif defined(__SH4__) || defined(__sh4__) || defined(__SH4) || defined(__sh4)
6164 #  define VER_H_PROM_TSA_TEXT "Hitachi/Renesas SH-4"
6165 # elif defined(__SH2__) || defined(__sh2__) || defined(__SH2) || defined(__sh2)
6166 #  define VER_H_PROM_TSA_TEXT "Hitachi/Renesas SH-2"
6167 # elif defined(__alpha__)
6168 #  define VER_H_PROM_TSA_TEXT "Alpha AXP           "
6169 # elif defined(__hppa__) || defined(__HPPA__) || defined(__PARISC__) || defined(__parisc__)
6170 #  define VER_H_PROM_TSA_TEXT "HP PA-RISC          "
6171 # elif defined(__ICE9__) || defined(__ice9__) || defined(__ICE9) || defined(__ice9)
6172 #  define VER_H_PROM_TSA_TEXT "SiCortex ICE-9      "
6173 # elif defined(mips64) || defined(__mips64__) || defined(MIPS64) || defined(_MIPS64_) || defined(__mips64)
6174 #  define VER_H_PROM_TSA_TEXT "MIPS64              "
6175 # elif defined(mips) || defined(__mips__) || defined(MIPS) || defined(_MIPS_) || defined(__mips)
6176 #  define VER_H_PROM_TSA_TEXT "MIPS                "
6177 # elif defined(__OpenRISC__) || defined(__OPENRISC__) || defined(__openrisc__) || defined(__OR1K__) || defined(__OPENRISC1K__)
6178 #  define VER_H_PROM_TSA_TEXT "OpenRISC            "
6179 # elif defined(__sparc64) || defined(__SPARC64) || defined(__SPARC64__) || defined(__sparc64__)
6180 #  define VER_H_PROM_TSA_TEXT "SPARC64             "
6181 # elif defined(__sparc) || defined(__SPARC) || defined(__SPARC__) || defined(__sparc__)
6182 #  define VER_H_PROM_TSA_TEXT "SPARC               "
6183 # elif defined(__riscv) || defined(__riscv__)
6184 #  define VER_H_PROM_TSA_TEXT "RISC-V              "
6185 # elif defined(__e2k__) || defined(__E2K__) || defined(__elbrus64__) || defined(__elbrus__) || defined(__ELBRUS__) || defined(__e2k64__)
6186 #  if defined(__iset__)
6187 #   if __iset__ > 0
6188 #    if __iset__ == 1
6189 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v1      "
6190 #    elif __iset__ == 2
6191 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v2      "
6192 #    elif __iset__ == 3
6193 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v3      "
6194 #    elif __iset__ == 4
6195 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v4      "
6196 #    elif __iset__ == 5
6197 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v5      "
6198 #    elif __iset__ == 6
6199 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v6      "
6200 #    elif __iset__ == 7
6201 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v7      "
6202 #    elif __iset__ == 8
6203 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v8      "
6204 #    elif __iset__ == 9
6205 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v9      "
6206 #    elif __iset__ == 10
6207 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus v10     "
6208 #    else
6209 #     define VER_H_PROM_TSA_TEXT "MCST Elbrus         "
6210 #    endif
6211 #   else
6212 #    define VER_H_PROM_TSA_TEXT "MCST Elbrus         "
6213 #   endif
6214 #  else
6215 #   define VER_H_PROM_TSA_TEXT "MCST Elbrus         "
6216 #  endif
6217 # elif defined(__myriad2__)
6218 #  define VER_H_PROM_TSA_TEXT "Myriad2             "
6219 # elif defined(__loongarch64) || defined(__loongarch__)
6220 #  define VER_H_PROM_TSA_TEXT "LoongArch           "
6221 # elif defined(_m68851) || defined(__m68k__) || defined(__m68000__) || defined(__M68K)
6222 #  define VER_H_PROM_TSA_TEXT "Motorola m68k       "
6223 # elif defined(__m88k__) || defined(__m88000__) || defined(__M88K)
6224 #  define VER_H_PROM_TSA_TEXT "Motorola m88k       "
6225 # elif defined(__VAX__) || defined(__vax__)
6226 #  define VER_H_PROM_TSA_TEXT "VAX                 "
6227 # elif defined(__NIOS2__) || defined(__nios2__)
6228 #  define VER_H_PROM_TSA_TEXT "Altera Nios II      "
6229 # elif defined(__MICROBLAZE__) || defined(__microblaze__)
6230 #  define VER_H_PROM_TSA_TEXT "Xilinx MicroBlaze   "
6231 # elif defined(__kvx__) || defined(__KVX__) || defined(__KVX_64__)
6232 #  define VER_H_PROM_TSA_TEXT "Kalray KVX          "
6233 # endif
6234 # if !defined(VER_H_PROM_TSA_TEXT)
6235 #  define BURN_PROM_TSA_TEXT "Unknown Target Arch."
6236 # else
6237 #  define BURN_PROM_TSA_TEXT VER_H_PROM_TSA_TEXT
6238 # endif /* VER_H_PROM_TSA_TEXT */
6239 #endif /* BUILD_PROM_TSA_TEXT */
6240 
6241 #if (defined(__WIN__) || defined(_WIN32) || defined(IS_WINDOWS) || defined(_MSC_VER) || defined(__MINGW32__) || \
6242         defined(__MINGW64__) || defined(CROSS_MINGW32) || defined(CROSS_MINGW64)) && !defined(__CYGWIN__)
6243 # define DC_IS_WINDOWS 1
6244 #else
6245 # define DC_IS_WINDOWS 0
6246 #endif
6247 
6248 #if defined(BUILD_PROM_TSV_TEXT)
6249 # define BURN_PROM_TSV_TEXT BUILD_PROM_TSV_TEXT
6250 #else
6251 # if DC_IS_WINDOWS
6252 #  define VER_H_PROM_TSV_TEXT "Microsoft Windows   "
6253 # elif defined(__CYGWIN__)
6254 #  define VER_H_PROM_TSV_TEXT "Windows/Cygwin      "
6255 # elif (defined(__sunos) || defined(__sun) || defined(__sun__)) && (defined(SYSV) || defined(__SVR4) || defined(__SVR4__) || \
6256         defined(__svr4__))
6257 #  if defined(__illumos__)
6258 #   define VER_H_PROM_TSV_TEXT "illumos             "
6259 #  else
6260 #   define VER_H_PROM_TSV_TEXT "Solaris             "
6261 #  endif
6262 # elif defined(__APPLE__) && defined(__MACH__)
6263 #  define VER_H_PROM_TSV_TEXT "Apple macOS         "
6264 # elif defined(__GNU__) && !defined(__linux__)
6265 #  define VER_H_PROM_TSV_TEXT "GNU/Hurd            "
6266 # elif defined(__ANDROID__) && defined(__ANDROID_API__)
6267 #  if defined(__linux__)
6268 #   define VER_H_PROM_TSV_TEXT "Android/Linux       "
6269 #  else
6270 #   define VER_H_PROM_TSV_TEXT "Android             "
6271 #  endif
6272 # elif defined(__lynxOS__) || defined(__LYNXOS__) || defined(LynxOS) || defined(LYNXOS)
6273 #  define VER_H_PROM_TSV_TEXT "LynxOS              "
6274 # elif defined(__HELENOS__)
6275 #  define VER_H_PROM_TSV_TEXT "HelenOS             "
6276 # elif defined(__linux__)
6277 #  if defined(__BIONIC__)
6278 #   define VER_H_PROM_TSV_TEXT "Linux/Bionic-libc   "
6279 #  elif defined(__UCLIBC__) || defined(UCLIBC)
6280 #   define VER_H_PROM_TSV_TEXT "Linux/uClibc        "
6281 #  elif defined(__NEWLIB__)
6282 #   define VER_H_PROM_TSV_TEXT "Linux/Newlib        "
6283 #  elif defined(__dietlibc__)
6284 #   define VER_H_PROM_TSV_TEXT "Linux/Diet-libc     "
6285 #  elif defined(__GLIBC__)
6286 #   define VER_H_PROM_TSV_TEXT "GNU/Linux           "
6287 #  else
6288 #   define VER_H_PROM_TSV_TEXT "Linux               "
6289 #  endif
6290 # elif defined(__HAIKU__)
6291 #  define VER_H_PROM_TSV_TEXT "Haiku               "
6292 # elif defined(__serenity__)
6293 #  define VER_H_PROM_TSV_TEXT "SerenityOS          "
6294 # elif defined(__FreeBSD__)
6295 #  define VER_H_PROM_TSV_TEXT "FreeBSD             "
6296 # elif defined(__NetBSD__)
6297 #  define VER_H_PROM_TSV_TEXT "NetBSD              "
6298 # elif defined(__OpenBSD__)
6299 #  define VER_H_PROM_TSV_TEXT "OpenBSD             "
6300 # elif defined(__DragonFly__)
6301 #  define VER_H_PROM_TSV_TEXT "DragonFly BSD       "
6302 # elif defined(_AIX)
6303 #  if !defined(__PASE__)
6304 #   define VER_H_PROM_TSV_TEXT "IBM AIX             "
6305 #  else
6306 #   define VER_H_PROM_TSV_TEXT "IBM OS/400 (PASE)   "
6307 #  endif
6308 # elif defined(__VXWORKS__) || defined(__VXWORKS) || defined(__vxworks) || defined(__vxworks__) || defined(_VxWorks)
6309 #  if !defined(__RTP__)
6310 #   define VER_H_PROM_TSV_TEXT "VxWorks             "
6311 #  else
6312 #   define VER_H_PROM_TSV_TEXT "VxWorks RTP         "
6313 #  endif
6314 # elif defined(__rtems__)
6315 #  if defined(__FreeBSD_version)
6316 #   define VER_H_PROM_TSV_TEXT "RTEMS/LibBSD        "
6317 #  else
6318 #   define VER_H_PROM_TSV_TEXT "RTEMS               "
6319 #  endif
6320 # elif defined(__ZEPHYR__)
6321 #  define VER_H_PROM_TSV_TEXT "Zephyr              "
6322 # elif defined(ti_sysbios_BIOS___VERS) || defined(ti_sysbios_BIOS__top__)
6323 #  define VER_H_PROM_TSV_TEXT "TI-RTOS (SYS/BIOS)  "
6324 # elif defined(__OSV__) // -V1040
6325 #  define VER_H_PROM_TSV_TEXT "OSv                 "
6326 # elif defined(MINIX) || defined(MINIX3) || defined(MINIX315) || defined(__minix__) || defined(__minix3__) || defined(__minix315__)
6327 #  define VER_H_PROM_TSV_TEXT "Minix               "
6328 # elif defined(__QNX__)
6329 #  if defined(__QNXNTO__)
6330 #   define VER_H_PROM_TSV_TEXT "QNX Neutrino        "
6331 #  else
6332 #   define VER_H_PROM_TSV_TEXT "QNX                 "
6333 #  endif
6334 # elif defined(__managarm__)
6335 #  define VER_H_PROM_TSV_TEXT "Managarm            "
6336 # endif
6337 # if !defined(VER_H_PROM_TSV_TEXT)
6338 #  define BURN_PROM_TSV_TEXT "Unknown Target OpSys"
6339 # else
6340 #  define BURN_PROM_TSV_TEXT VER_H_PROM_TSV_TEXT
6341 # endif /* VER_H_PROM_TSV_TEXT */
6342 #endif /* BUILD_PROM_TSV_TEXT */
6343 
6344 #if !defined(VER_H_GIT_DATE_SHORT)
6345 # define VER_H_GIT_DATE_SHORT "2021-01-01"
6346 #endif /* if !defined(VER_H_GIT_DATE_SHORT) */
6347 
6348 #if !defined(BURN_PROM_BUILD_NUM)
6349 # define BURN_PROM_BUILD_NUM "        "
6350 #endif /* if !defined(BURN_PROM_BUILD_NUM) */
6351 
6352 #define BURN(offset, length, string) memcpy ((char *) PROM + (offset), string, length)
6353 #define BURN1(offset, byte) PROM[offset] = (char) (byte)
6354 
6355   (void)memset (PROM, 255, 1024);
6356 
6357   //   Offset Length  Data
6358   BURN  ( 00,  11,  "DPS 8/SIM M");                //    0-10  CPU model ("XXXXXXXXXXX")       //-V1086
6359   BURN  (013,  11,  serial);                       //   11-21  CPU serial ("DDDDDDDDDDD")      //-V1086
6360   BURN  (026,   6,  ship);                         //   22-27  CPU ship date ("YYMMDD")        //-V1086
6361   BURN1 (034,       getbits36_8 (rsw2,  0));       //   34     RSW 2 bits  0- 7                //-V1086
6362   BURN1 (035,       getbits36_8 (rsw2,  8));       //   35     RSW 2 bits  8-15                //-V1086
6363   BURN1 (036,       getbits36_8 (rsw2, 16));       //   36     RSW 2 bits 16-23                //-V1086
6364   BURN1 (037,       getbits36_8 (rsw2, 24));       //   37     RSW 2 bits 24-31                //-V1086
6365   BURN1 (040,     ((getbits36_4 (rsw2, 32) << 4) \
6366                                | rsw2Ext));        //   40     RSW 2 bits 32-35, options bits  //-V1086
6367 
6368   /* Begin extended PROM data */
6369   BURN  ( 60,   1,  "2");                          //   60     PROM Layout Version Number      //-V1086
6370   BURN  ( 70,  10,  VER_H_GIT_DATE_SHORT);         //   70     Release Git Commit Date         //-V1086
6371   BURN  ( 80,   3,  VER_H_PROM_MAJOR_VER);         //   80     Major Release Number            //-V1086
6372   BURN  ( 83,   3,  VER_H_PROM_MINOR_VER);         //   83     Minor Release Number            //-V1086
6373   BURN  ( 86,   3,  VER_H_PROM_PATCH_VER);         //   86     Patch Release Number            //-V1086
6374   BURN  ( 89,   3,  VER_H_PROM_OTHER_VER);         //   89     Iteration Release Number        //-V1086
6375   BURN  ( 92,   8,  BURN_PROM_BUILD_NUM);          //   92     Reserved for Build Number       //-V1086
6376   BURN  (100,   1,  VER_H_GIT_RELT);               //  100     Release Type                    //-V1086
6377   BURN  (101,  29,  VER_H_PROM_VER_TEXT);          //  101     Release Text                    //-V1086
6378   BURN  (130,  20,  BURN_PROM_OSA_TEXT);           //  130     Build System Architecture       //-V1086
6379   BURN  (150,  20,  BURN_PROM_OSV_TEXT);           //  150     Build System Operating System   //-V1086
6380   BURN  (170,  20,  BURN_PROM_TSA_TEXT);           //  170     Target System Architecture      //-V1086
6381   BURN  (190,  20,  BURN_PROM_TSV_TEXT);           //  190     Target System Architecture      //-V1086
6382 }
6383 
6384 void cpuStats (uint cpuNo) {
     /* [previous][next][first][last][top][bottom][index][help] */
6385   if (! cpus[cpuNo].cycleCnt)
6386     return;
6387 
6388 /* Detect Haiku pthread_getcpuclockid availability */
6389 #if defined(__HAIKU__)
6390 # if HAS_INCLUDE(<syscall_clock_info.h>)
6391 #  include <syscall_clock_info.h>
6392 # endif
6393 # if !defined(_SYSTEM_SYSCALL_CLOCK_INFO_H)
6394 #  if !defined(HAIKU_NO_PTHREAD_GETCPUCLOCKID)
6395 #   define HAIKU_NO_PTHREAD_GETCPUCLOCKID
6396 #  endif
6397 # endif
6398 #endif
6399 
6400 /* Clang and SunCC may not define __illumos__ but we require it
6401  * here to check for pthread_getcpuclockid availability */
6402 #if defined(__sun) || defined(__sun__)
6403 # if !defined(__illumos__)
6404 #  if HAS_INCLUDE(<sys/sysevent.h>)
6405 #   include <sys/sysevent.h>
6406 #  endif
6407 #  if defined(ILLUMOS_VENDOR) || defined(ILLUMOS_KERN_PUB)
6408 #   define __illumos__
6409 #  endif
6410 # endif
6411 #endif
6412 
6413   double cpu_seconds = 0;
6414   int cpu_millis = 0;
6415   char cpu_ftime[64] = {0};
6416 #if (defined(THREADZ) || defined(LOCKLESS))
6417 # if !defined(HAIKU_NO_PTHREAD_GETCPUCLOCKID) && !defined(__illumos__) && \
6418      !defined(__APPLE__) && !defined(__PASE__) && !defined(__serenity__)
6419   struct timespec cpu_time;
6420   clockid_t clock_id;
6421   if (pthread_getcpuclockid (cpus[cpuNo].thread_id, &clock_id) == 0) {
6422     if (clock_gettime (clock_id, &cpu_time) == 0) {
6423       cpu_seconds = (double)cpu_time.tv_sec + cpu_time.tv_nsec / 1e9;
6424     }
6425   }
6426 # endif
6427 #endif
6428 
6429   if (cpu_seconds > 0 && cpus[cpuNo].instrCnt > 0) {
6430     int cpu_hours = (int)(cpu_seconds / 3600);
6431     int cpu_minutes = (int)((cpu_seconds - cpu_hours * 3600) / 60);
6432     int cpu_secs = (int)(cpu_seconds - (cpu_hours * 3600) - (cpu_minutes * 60));
6433     struct tm cpu_tm = {0};
6434     cpu_tm.tm_hour = cpu_hours;
6435     cpu_tm.tm_min = cpu_minutes;
6436     cpu_tm.tm_sec = cpu_secs;
6437     strftime(cpu_ftime, sizeof(cpu_ftime), "%H:%M:%S", &cpu_tm);
6438     cpu_millis = (int)((cpu_seconds - (cpu_hours * 3600) - (cpu_minutes * 60) - cpu_secs) * 1000);
6439   }
6440 
6441   (void)fflush(stderr);
6442   (void)fflush(stdout);
6443   sim_msg ("\r\n");
6444   (void)fflush(stdout);
6445   (void)fflush(stderr);
6446   sim_msg ("\r+---------------------------------+\r\n");
6447   sim_msg ("\r|         CPU %c Statistics        |\r\n", 'A' + cpuNo);
6448   sim_msg ("\r+---------------------------------+\r\n");
6449   if (cpu_seconds > 0 && cpus[cpuNo].instrCnt > 0) {
6450     sim_msg ("\r|  CPU Time Used %11s.%03d  |\r\n", cpu_ftime, cpu_millis);
6451     sim_msg ("\r+---------------------------------+\r\n");
6452   }
6453   (void)fflush(stdout);
6454   (void)fflush(stderr);
6455 #if defined(_AIX) && !defined(__PASE__)
6456   struct rusage rusage;
6457   if (!pthread_getrusage_np(cpus[cpuNo].thread_id, &rusage, PTHRDSINFO_RUSAGE_COLLECT)) {
6458     sim_msg ("\r|  Volun. CtxtSw %'15llu  |\r\n", (unsigned long long)rusage.ru_nvcsw);
6459     sim_msg ("\r|  Invol. CtxtSw %'15llu  |\r\n", (unsigned long long)rusage.ru_nivcsw);
6460     sim_msg ("\r+---------------------------------+\r\n");
6461   }
6462 #endif
6463 #if defined(WIN_STDIO)
6464   sim_msg ("\r|  cycles        %15llu  |\r\n", (unsigned long long)cpus[cpuNo].cycleCnt);
6465   sim_msg ("\r|  instructions  %15llu  |\r\n", (unsigned long long)cpus[cpuNo].instrCnt);
6466   (void)fflush(stdout);
6467   (void)fflush(stderr);
6468   sim_msg ("\r+---------------------------------+\r\n");
6469   sim_msg ("\r|  lockCnt       %15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockCnt);
6470   sim_msg ("\r|  lockImmediate %15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockImmediate);
6471   (void)fflush(stdout);
6472   (void)fflush(stderr);
6473   sim_msg ("\r+---------------------------------+\r\n");
6474   sim_msg ("\r|  lockWait      %15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockWait);
6475   sim_msg ("\r|  lockWaitMax   %15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockWaitMax);
6476   (void)fflush(stdout);
6477   (void)fflush(stderr);
6478 # if !defined(SCHED_NEVER_YIELD)
6479   sim_msg ("\r|  lockYield     %15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockYield);
6480   (void)fflush(stdout);
6481   (void)fflush(stderr);
6482 # else
6483   sim_msg ("\r|  lockYield                ----  |\r\n");
6484   (void)fflush(stdout);
6485   (void)fflush(stderr);
6486 # endif /* if !defined(SCHED_NEVER_YIELD) */
6487   sim_msg ("\r+---------------------------------+");
6488   (void)fflush(stdout);
6489   (void)fflush(stderr);
6490 # if !defined(UCACHE)
6491 #  if !defined(UCACHE_STATS)
6492   sim_msg ("\r\n");
6493 #  endif
6494 # endif
6495   (void)fflush(stdout);
6496   (void)fflush(stderr);
6497 #else
6498   sim_msg ("\r|  cycles        %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].cycleCnt);
6499   sim_msg ("\r|  instructions  %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].instrCnt);
6500   (void)fflush(stdout);
6501   (void)fflush(stderr);
6502   sim_msg ("\r+---------------------------------+\r\n");
6503   sim_msg ("\r|  lockCnt       %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockCnt);
6504   sim_msg ("\r|  lockImmediate %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockImmediate);
6505   (void)fflush(stdout);
6506   (void)fflush(stderr);
6507   sim_msg ("\r+---------------------------------+\r\n");
6508   sim_msg ("\r|  lockWait      %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockWait);
6509   sim_msg ("\r|  lockWaitMax   %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockWaitMax);
6510   (void)fflush(stdout);
6511   (void)fflush(stderr);
6512 # if !defined(SCHED_NEVER_YIELD)
6513   sim_msg ("\r|  lockYield     %'15llu  |\r\n", (unsigned long long)cpus[cpuNo].coreLockState.lockYield);
6514   (void)fflush(stdout);
6515   (void)fflush(stderr);
6516 # else
6517   sim_msg ("\r|  lockYield                ----  |\r\n");
6518   (void)fflush(stdout);
6519   (void)fflush(stderr);
6520 # endif /* if !defined(SCHED_NEVER_YIELD) */
6521   sim_msg ("\r+---------------------------------+");
6522   (void)fflush(stdout);
6523   (void)fflush(stderr);
6524 # if !defined(UCACHE)
6525 #  if !defined(UCACHE_STATS)
6526   sim_msg ("\r\n");
6527 #  endif
6528 # endif
6529   (void)fflush(stderr);
6530   (void)fflush(stdout);
6531 #endif
6532 
6533   cacheStats (cpuNo);
6534 
6535 #if defined(UCACHE_STATS)
6536   ucacheStats (cpuNo);
6537 #endif
6538 
6539 
6540 
6541 
6542 
6543 
6544 
6545 }
6546 
6547 bool running_perf_test;
6548 
6549 #if defined(THREADZ) || defined(LOCKLESS)
6550 # include <locale.h>
6551 # include "segldr.h"
6552 
6553 void perfTest (char * testName) {
     /* [previous][next][first][last][top][bottom][index][help] */
6554   running_perf_test = true;
6555 
6556   if (testName == NULL)
6557     testName = "strip.mem";
6558 
6559 # if !defined(NO_LOCALE)
6560   (void) setlocale(LC_NUMERIC, "");
6561 # endif
6562 
6563   // dps8m_init_strip
6564 # if !defined(_AIX)
6565   system_state = aligned_malloc (sizeof (struct system_state_s));
6566 # else
6567   system_state = malloc (sizeof (struct system_state_s));
6568 # endif
6569   if (!system_state)
6570     {
6571       (void)fprintf (stderr, "\rFATAL: Out of memory! Aborting at %s[%s:%d]\r\n",
6572                      __func__, __FILE__, __LINE__);
6573 # if defined(USE_BACKTRACE)
6574 #  if defined(SIGUSR2)
6575       (void)raise(SIGUSR2);
6576       /*NOTREACHED*/ /* unreachable */
6577 #  endif /* if defined(SIGUSR2) */
6578 # endif /* if defined(USE_BACKTRACE) */
6579       abort();
6580     }
6581 # if !defined(__MINGW64__) && !defined(__MINGW32__) && !defined(CROSS_MINGW64) && !defined(CROSS_MINGW32) && !defined(__PASE__)
6582   if (0 == sim_free_memory || sim_free_memory >= 192000000) {
6583     if (mlock(system_state, sizeof(struct system_state_s)) == -1) {
6584       mlock_failure = true;
6585     }
6586   } else {
6587 #  if defined(TESTING)
6588     sim_warn ("Low memory - no memory locking attempted.\r\n");
6589 #  else
6590     (void)system_state;
6591 #  endif
6592   }
6593 # endif
6594   M = system_state->M;
6595 # if defined(M_SHARED)
6596   cpus = system_state->cpus;
6597 # endif /* if defined(M_SHARED) */
6598   (void) memset (cpus, 0, sizeof (cpu_state_t) * N_CPU_UNITS_MAX);
6599   for (int i = 0; i < N_CPU_UNITS_MAX; i ++) {
6600     cpus[i].switches.FLT_BASE = 2; // Some of the UnitTests assume this
6601     cpus[i].instrCnt = 0;
6602     cpus[i].cycleCnt = 0;
6603     for (int j = 0; j < N_FAULTS; j ++)
6604       cpus[i].faultCnt [j] = 0;
6605   }
6606 
6607   cpus[0].tweaks.enable_emcall = 1;
6608   opc_dev.numunits = 1;
6609   cpu_reset_unit_idx (0, false);
6610   set_cpu_cycle (& cpus[0], FETCH_cycle);
6611   mrestore (testName);
6612   _cpup = & cpus[0];
6613   threadz_sim_instr ();
6614 }
6615 #endif

/* [previous][next][first][last][top][bottom][index][help] */