Introduce Coco 3 Plus for MiSTer
Add original-firmware Sound & Speech, four configurable Multi-Pak sockets, bounded per-slot ROM allocation and a nine-page menu organized around devices and media. Repair inherited clock/reset/CPU-memory/video paths and add explicit conditional external-I/O timing contracts. Preserve native Main startup-file ordering, saved layouts, stock-core separation and the coco3plus media profile. Provide native Windows tool downloads, pinned ToolShed ROM assembly, fresh Quartus builds, functional and fitted timing checks, reviewed release packaging and passwordless SSH installation with backups. Retain original component notices, document contribution copyright and keep SSC ROM inputs outside Git. Validation: Quartus17.0.2 Build602 seed5, zero errors; 15 functional jobs, 368 both-corner timing scopes and eight tooling-integrity checks pass. The renamed build reaches Disk BASIC, PRINT1+1 returns2 and SSC loads ready. Physical cold power cycling and conditional board-delay assumptions remain separate. Full original upstream histories are preserved before this single consolidated implementation commit.
This commit is contained in:
1 parent
8b8cf72d1f
commit
cb40fed3b9
126 files changed
+12795
-528
No files matched your search
@@ -0,0 +1,35 @@
|
||||
# quartus_sta -t bh_mpi_timing.tcl PROJECT REVISION OUTPUT
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [file normalize [lindex $quartus(args) 0]]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
cd [file dirname $project]
|
||||
project_open [file tail $project] -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
foreach {scope pattern} {
|
||||
config {*mpi_configuration|*}
|
||||
rom {*mpi_program_roms|*}
|
||||
banks {*rom_banks*}
|
||||
restart {*mpi_rom_cold_pending*}
|
||||
} {
|
||||
set nodes [get_keepers $pattern]
|
||||
set count [get_collection_size $nodes]
|
||||
puts "BH_MPI_SCOPE $model $scope $count"
|
||||
if {$count==0} {error "Missing new MPI state scope: $scope"}
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -to $nodes -npaths 20 -detail full_path \
|
||||
-file [file join $output ${scope}-to-${model}-${check}.rpt]
|
||||
report_timing -$check -from $nodes -npaths 20 -detail full_path \
|
||||
-file [file join $output ${scope}-from-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
report_timing -setup -npaths 30 -detail full_path \
|
||||
-file [file join $output global-${model}-setup.rpt]
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Coco 3 Plus deployment paths and native MiSTer remembered-file records."""
|
||||
NAME = 'coco3plus'
|
||||
GAME_DIR = '/media/fat/games/' + NAME
|
||||
ROM_SLOTS = {4: 'pic-7040-510.bin', 5: 'sp0256-al2.bin'}
|
||||
|
||||
|
||||
def startup_records():
|
||||
# Match MiSTer menu.cpp's 1024-byte, NUL-terminated selPath buffer.
|
||||
records = {}
|
||||
for slot, name in ROM_SLOTS.items():
|
||||
path = (GAME_DIR + '/' + name).encode('ascii')
|
||||
if len(path) >= 1024:
|
||||
raise ValueError('Startup path does not fit MiSTer selPath')
|
||||
records[f'config/{NAME}.f{slot}'] = path.ljust(1024, b'\0')
|
||||
return records
|
||||
@@ -0,0 +1,72 @@
|
||||
# Read-only fitted-design audit. Optional last argument is an experimental SDC.
|
||||
# quartus_sta -t SCRIPT PROJECT REVISION OUTPUT [EXTRA_SDC]
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [file normalize [lindex $quartus(args) 0]]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
set extra [lindex $quartus(args) 3]
|
||||
set mode [lindex $quartus(args) 4]
|
||||
file mkdir $output
|
||||
cd [file dirname $project]
|
||||
project_open [file tail $project] -revision $revision
|
||||
if {$mode eq "replace-external"} {
|
||||
# In-memory settings only: retrospective analysis of an identical fitted
|
||||
# netlist with a corrected constraint guard. Never export these assignments.
|
||||
set_global_assignment -remove -name SDC_FILE external-io.sdc
|
||||
set_global_assignment -name SDC_FILE $extra
|
||||
set f [open [file join $output constraint-override.txt] w]
|
||||
puts $f $extra
|
||||
close $f
|
||||
set extra ""
|
||||
}
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
if {$extra ne ""} {read_sdc $extra}
|
||||
update_timing_netlist
|
||||
foreach {name pattern} {
|
||||
sdram_dq {SDRAM_DQ[*]}
|
||||
sdram_command {SDRAM_A[*] SDRAM_BA[*] SDRAM_n* SDRAM_DQM*}
|
||||
hdmi_video {HDMI_TX_D[*] HDMI_TX_DE HDMI_TX_HS HDMI_TX_VS}
|
||||
hdmi_audio {HDMI_I2S HDMI_LRCLK HDMI_SCLK}
|
||||
mcp_i2c {IO_SDA IO_SCL}
|
||||
} {
|
||||
set ports [get_ports $pattern]
|
||||
puts "EXTERNAL_IO_SCOPE $model $name [get_collection_size $ports]"
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -from $ports -npaths 32 -detail full_path -file [file join $output ${name}-in-${model}-${check}.rpt]
|
||||
report_timing -$check -to $ports -npaths 40 -detail full_path -file [file join $output ${name}-out-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
foreach {mode launch latch} {
|
||||
scaled {pll_hdmi|pll_hdmi_inst|altera_pll_i|cyclonev_pll|counter[0].output_counter|divclk} hdmi_scaled_forward
|
||||
direct {emu|pll|pll_inst|altera_pll_i|general[1].gpll~PLL_OUTPUT_COUNTER|divclk} hdmi_direct_forward
|
||||
} {
|
||||
if {[get_collection_size [get_clocks $latch]] == 1} {
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -from_clock [get_clocks $launch] -to_clock [get_clocks $latch] -to [get_ports {HDMI_TX_D[*] HDMI_TX_DE HDMI_TX_HS HDMI_TX_VS}] -npaths 40 -detail full_path -file [file join $output hdmi-${mode}-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
}
|
||||
if {[get_collection_size [get_clocks coco_pixel]] == 1} {
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -from_clock [get_clocks coco_pixel] -npaths 40 -detail full_path -file [file join $output pixel-out-${model}-${check}.rpt]
|
||||
report_timing -$check -to_clock [get_clocks coco_pixel] -npaths 40 -detail full_path -file [file join $output pixel-in-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
foreach check {setup hold recovery removal} {
|
||||
report_timing -$check -npaths 40 -detail full_path -file [file join $output global-${model}-${check}.rpt]
|
||||
}
|
||||
if {$model eq "slow"} {
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_exceptions -file [file join $output exceptions.rpt]
|
||||
report_clock_transfers -setup -file [file join $output transfers.rpt]
|
||||
set f [open [file join $output clock-nodes.txt] w]
|
||||
foreach_in_collection n [get_pins -hierarchical {*divclk* *MISTER_COCOVID*PIX_CLK* *sdramclk_ddr*}] {puts $f [get_node_info -name $n]}
|
||||
close $f
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close -dont_export_assignments
|
||||
@@ -0,0 +1,60 @@
|
||||
# quartus_sta -t nmi_timing_paths.tcl PROJECT REVISION OUTPUT_DIRECTORY
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [lindex $quartus(args) 0]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
project_open $project -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
set nmi [get_registers {*GLBCPU09|NMI*}]
|
||||
if {[get_collection_size $nmi] < 5} {error "Expected complete CPU NMI register scope"}
|
||||
puts "NMI_REGISTERS $model [get_collection_size $nmi]"
|
||||
set cpu [get_registers {*GLBCPU09|*}]
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -from $cpu -to $cpu -npaths 5 -detail full_path \
|
||||
-file [file join $output cpu-internal-${model}-${check}.rpt]
|
||||
}
|
||||
# Register-only endpoints would miss the effective mask/pending view.
|
||||
# Kept combinational nets must also be covered through to CPU consumers.
|
||||
if {[get_collection_size $nmi] > 5} {
|
||||
foreach signal {NMIMask NMILatched} {
|
||||
set through [get_nets *GLBCPU09|$signal]
|
||||
if {[get_collection_size $through] == 0} {error "Missing kept NMI net $signal"}
|
||||
puts "NMI_THROUGH $model $signal [get_collection_size $through]"
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -through $through -npaths 20 -detail full_path \
|
||||
-file [file join $output nmi-through-${signal}-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach check {setup hold recovery removal} {
|
||||
report_timing -$check -to $nmi -npaths 20 -detail full_path \
|
||||
-file [file join $output nmi-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $nmi -npaths 20 -detail full_path \
|
||||
-file [file join $output nmi-out-${model}-${check}.rpt]
|
||||
report_timing -$check -npaths 5 -detail full_path \
|
||||
-file [file join $output global-${model}-${check}.rpt]
|
||||
}
|
||||
if {$model eq "slow"} {
|
||||
set audit [open [file join $output nmi-register-clocks.tsv] w]
|
||||
puts $audit "register\tclock_pin\tclock_driver"
|
||||
foreach_in_collection reg $nmi {
|
||||
foreach edge [get_register_info -clock_edges $reg] {
|
||||
set pin [get_edge_info -src $edge]
|
||||
foreach input_edge [get_node_info -clock_edges $pin] {
|
||||
puts $audit "[get_register_info -name $reg]\t[get_node_info -name $pin]\t[get_node_info -name [get_edge_info -src $input_edge]]"
|
||||
}
|
||||
}
|
||||
}
|
||||
close $audit
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_clock_transfers -file [file join $output clock-transfers.rpt]
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close
|
||||
@@ -0,0 +1,79 @@
|
||||
# quartus_sta -t reset_cpu_timing_paths.tcl PROJECT REVISION OUTPUT_DIRECTORY
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [lindex $quartus(args) 0]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
project_open $project -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
set per_clock [file join $output per-clock-${model}-setup.rpt]
|
||||
set empty [open $per_clock w]
|
||||
close $empty
|
||||
foreach_in_collection clock [get_clocks *] {
|
||||
report_timing -setup -to_clock [get_clocks [list [get_clock_info -name $clock]]] \
|
||||
-npaths 2 -detail full_path -append -file $per_clock
|
||||
}
|
||||
set resets [get_registers {*coco3|RESET_N *coco3|RESET_RAW_N *coco3|CPU_RESET *coco3|reset_*release[*] *coco_fdc|wd_reset_release[*] *coco_sdc_top|wd_reset_release[*]}]
|
||||
if {[get_collection_size $resets] < 4} {error "Incomplete reset sequencer scope"}
|
||||
foreach check {setup hold recovery removal} {
|
||||
report_timing -$check -from $resets -npaths 30 -detail full_path \
|
||||
-file [file join $output reset-${model}-${check}.rpt]
|
||||
report_timing -$check -npaths 30 -detail full_path \
|
||||
-file [file join $output global-${model}-${check}.rpt]
|
||||
}
|
||||
set cpu [get_registers {*GLBCPU09|*}]
|
||||
puts "CPU_REGISTERS $model [get_collection_size $cpu]"
|
||||
set control [get_registers {*coco3|data_ready* *coco3|hold_data* *coco3|hold* *coco3|end_hold *coco3|cpu_cycle_ena *coco3|clear_data_ready *coco3|sdram_cpu_req *coco3|sdram_cpu_rnw *coco3|sdram_cpu_addr_L[*] *coco3|GART_RD *coco3|GART_WR *coco3|AMW_WR *coco3|RAM0_BE0_L *coco3|RAM0_BE1_L *coco3|sdram_BE_0 *coco3|sdram_BE_1 *coco3|last_write *coco3|CLK[*] *coco3|SWITCH_L[*]}]
|
||||
set boot [get_registers {*COCO3_EE_Cold_Bt|*}]
|
||||
set bridge [get_registers {*cpu_memory_boundary|*}]
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -to $cpu -npaths 30 -detail full_path \
|
||||
-file [file join $output cpu-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $cpu -npaths 30 -detail full_path \
|
||||
-file [file join $output cpu-out-${model}-${check}.rpt]
|
||||
report_timing -$check -to $control -npaths 30 -detail full_path \
|
||||
-file [file join $output control-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $control -npaths 30 -detail full_path \
|
||||
-file [file join $output control-out-${model}-${check}.rpt]
|
||||
report_timing -$check -from $cpu -to $cpu -npaths 30 -detail full_path \
|
||||
-file [file join $output cpu-all-${model}-${check}.rpt]
|
||||
if {[info exists cpu_ce]} {
|
||||
report_timing -$check -from $cpu_ce -to $cpu_ce -npaths 30 -detail full_path \
|
||||
-file [file join $output cpu-qualified-${model}-${check}.rpt]
|
||||
}
|
||||
report_timing -$check -to $boot -npaths 20 -detail full_path \
|
||||
-file [file join $output boot-${model}-${check}.rpt]
|
||||
if {[get_collection_size $bridge] > 0} {
|
||||
report_timing -$check -to $bridge -npaths 20 -detail full_path \
|
||||
-file [file join $output bridge-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $bridge -npaths 20 -detail full_path \
|
||||
-file [file join $output bridge-out-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
if {$model eq "slow"} {
|
||||
set f [open [file join $output cpu-clock-audit.tsv] w]
|
||||
puts $f "register\trole\tclock_pin\tclock_driver"
|
||||
foreach_in_collection reg $cpu {
|
||||
set name [get_register_info -name $reg]
|
||||
regexp {GLBCPU09\|([A-Za-z_][A-Za-z_0-9]*)} $name unused base
|
||||
set role single-cycle
|
||||
if {[info exists cpu_ce_bases] && [lsearch -exact $cpu_ce_bases $base] >= 0} {set role qualified-enable}
|
||||
foreach edge [get_register_info -clock_edges $reg] {
|
||||
set pin [get_edge_info -src $edge]
|
||||
foreach input_edge [get_node_info -clock_edges $pin] {
|
||||
puts $f "$name\t$role\t[get_node_info -name $pin]\t[get_node_info -name [get_edge_info -src $input_edge]]"
|
||||
}
|
||||
}
|
||||
}
|
||||
close $f
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_exceptions -file [file join $output exceptions.rpt]
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close
|
||||
@@ -0,0 +1,15 @@
|
||||
import hashlib,zlib
|
||||
ROM_IDENTITIES = {
|
||||
'pic-7040-510.bin': (4096, '0013cd78482cc5f2360fdf584e9ba51d34861e8ccd9d88247f1a54039c16c365',
|
||||
'7c17dcbc21757535ce0b3a9e1ce5ca61319d3606', 'a8e2eb98'),
|
||||
'sp0256-al2.bin': (2048, '98c280fd082169c54081e503dfe7d7d9a6fd46d4ffcc973e199ea0e1d9bc1ac9',
|
||||
'e60fcb5fa16ff3f3b69d36c7a6e955744d3feafc', 'b504ac15'),
|
||||
}
|
||||
|
||||
|
||||
def verified_rom(path, identity):
|
||||
size, sha256, sha1, crc = identity
|
||||
data = path.read_bytes()
|
||||
if len(data) != size or hashlib.sha256(data).hexdigest() != sha256 or hashlib.sha1(data).hexdigest() != sha1 or f'{zlib.crc32(data):08x}' != crc:
|
||||
raise RuntimeError('Original ROM identity mismatch: ' + path.name)
|
||||
return {'path': str(path), 'bytes': size, 'sha256': sha256, 'sha1': sha1, 'crc32': crc}
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run independent MPI and inherited regressions against an isolated source copy.
|
||||
|
||||
This does not compile Quartus, qualify timing, install a core, or test hardware.
|
||||
Each test owns a fresh output folder and its source-hashed evidence.
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path, nargs='?', default=ROOT)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
p.add_argument('--main-reference', type=Path, required=True)
|
||||
p.add_argument('--output',type=Path,default=ROOT/'build/regressions')
|
||||
p.add_argument('--jobs', type=int, default=3, choices=range(1, 5))
|
||||
a = p.parse_args()
|
||||
project = a.project.resolve()
|
||||
if project != ROOT and not project.is_relative_to(ROOT / 'build'):
|
||||
p.error('Use a prepared build/ project')
|
||||
base = a.output.resolve()
|
||||
if not base.is_relative_to(ROOT/'build'):p.error('Use an output under build/')
|
||||
base.mkdir(parents=True)
|
||||
logs = base / 'regression-logs'
|
||||
logs.mkdir() # Preserve any earlier run; never overwrite its evidence.
|
||||
from source_snapshot import original_sources
|
||||
original=original_sources('coco3-mister')
|
||||
jobs = [
|
||||
('test_bh_mpi.py', 'mpi-functional', ['--project', str(project)]),
|
||||
('test_bh_mpi_core.py', 'mpi-core-functional', [str(project)]),
|
||||
('test_ssc_mister_system.py', 'ssc-system-functional', [str(project)]),
|
||||
('test_registered_interfaces.py', 'registered-functional', [str(project)]),
|
||||
('test_reset_domains.py', 'reset-functional', [str(project)]),
|
||||
('test_keyboard_control_phase.py', 'keyboard-functional', [str(project)]),
|
||||
('test_peripheral_phase.py', 'peripheral-functional', [str(project)]),
|
||||
('test_external_sdram_commands.py', 'commands-functional', [str(project)]),
|
||||
('test_external_sdram.py', 'delayed-functional', [str(project)]),
|
||||
('test_external_audio.py', 'audio-functional', [str(project)]),
|
||||
('test_external_pixel.py', 'pixel-functional', [str(project)]),
|
||||
('test_external_i2c.py', 'i2c-functional', [str(project)]),
|
||||
('test_coco3_bh_startup.py', 'startup-functional',
|
||||
[str(project), str(a.main_reference.resolve())]),
|
||||
('test_bh_menu.py', 'menu-functional', [str(project), str(a.main_reference.resolve())]),
|
||||
('test_video_sdram.py', 'video-functional', [str(original),str(project)]),
|
||||
]
|
||||
|
||||
def run(job):
|
||||
script, name, inputs = job
|
||||
command = [sys.executable, '-X', 'utf8', '-B', str(ROOT / 'scripts' / script),
|
||||
*inputs, str(base / name)]
|
||||
if script not in ('test_coco3_bh_startup.py','test_bh_menu.py'):
|
||||
command += ['--suite', str(a.suite.resolve())]
|
||||
if script == 'test_external_sdram.py':
|
||||
command += ['--check-cpu-data']
|
||||
started = time.monotonic()
|
||||
print('START ' + name, flush=True)
|
||||
with (logs / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
result = subprocess.run(command, cwd=ROOT, stdout=log,
|
||||
stderr=subprocess.STDOUT)
|
||||
receipt = dict(name=name, command=command, exit_code=result.returncode,
|
||||
seconds=round(time.monotonic() - started, 2))
|
||||
print(('PASS ' if result.returncode == 0 else 'FAIL ') + name, flush=True)
|
||||
return receipt
|
||||
|
||||
results = []
|
||||
with ThreadPoolExecutor(max_workers=a.jobs) as pool:
|
||||
for future in as_completed([pool.submit(run, job) for job in jobs]):
|
||||
results.append(future.result())
|
||||
passed = all(item['exit_code'] == 0 for item in results)
|
||||
(logs / 'result.json').write_text(json.dumps(dict(
|
||||
passed=passed, scope='Offline functional regressions; no timing/hardware signoff',
|
||||
results=sorted(results, key=lambda x: x['name'])), indent=2) + '\n')
|
||||
if not passed:
|
||||
raise SystemExit('One or more regressions failed; inspect regression-logs')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Restore original comparison sources from the preserved upstream commit."""
|
||||
import hashlib,json,subprocess
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SNAPSHOT='8b8cf72d1fb4de1d05345de8d5b92ec2d500fcd2'
|
||||
def original_sources(name):
|
||||
if name!='coco3-mister':raise ValueError('This repository supports MiSTer only')
|
||||
out=ROOT/'build/source-snapshots'/name
|
||||
entries=subprocess.check_output(['git','ls-tree','-r','-z',SNAPSHOT],cwd=ROOT).split(b'\0')
|
||||
for entry in filter(None,entries):
|
||||
header,name=entry.split(b'\t',1);mode,kind,oid=header.decode().split();name=name.decode()
|
||||
if kind!='blob' or mode not in ('100644','100755'):raise RuntimeError('Unsupported upstream entry')
|
||||
data=subprocess.check_output(['git','show',SNAPSHOT+':'+name],cwd=ROOT)
|
||||
path=out/name
|
||||
if path.exists() and path.read_bytes()!=data:raise RuntimeError('Preserve changed reference cache: '+name)
|
||||
if not path.exists():path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(data)
|
||||
return out
|
||||
@@ -0,0 +1,49 @@
|
||||
# quartus_sta -t ssc_integrated_timing.tcl PROJECT REVISION OUTPUT
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [file normalize [lindex $quartus(args) 0]]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
cd [file dirname $project]
|
||||
project_open [file tail $project] -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
foreach {name pattern minimum} {
|
||||
cartridge {*coco3|ssc|*} 1200
|
||||
bridge {*coco3|ssc_bridge|*} 30
|
||||
controller {*coco3|ssc|controller|*} 400
|
||||
speech {*coco3|ssc|speech|*} 400
|
||||
audio {*coco3|ssc|audio|*} 100
|
||||
ay {*coco3|ssc|ay|*} 100
|
||||
glue {*coco3|ssc|glue|*} 15
|
||||
host {*coco3|ssc|host|*} 10
|
||||
power {*ssc_power_release*} 2
|
||||
} {
|
||||
set nodes [get_keepers $pattern]
|
||||
set count [get_collection_size $nodes]
|
||||
puts "SSC_INTEGRATED_SCOPE $model $name $count"
|
||||
if {$count<$minimum} {error "Incomplete SSC scope: $name"}
|
||||
set audit [open [file join $output keepers-${name}-${model}.txt] w]
|
||||
foreach_in_collection node $nodes {puts $audit [get_node_info -name $node]}
|
||||
close $audit
|
||||
foreach check {setup hold recovery removal} {
|
||||
# Setup/hold must have substantive paths. Recovery/removal may legitimately
|
||||
# be empty for synchronous-only chip helpers; preserve both reports.
|
||||
report_timing -$check -to $nodes -npaths 40 -detail full_path \
|
||||
-file [file join $output ${name}-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $nodes -npaths 40 -detail full_path \
|
||||
-file [file join $output ${name}-out-${model}-${check}.rpt]
|
||||
}
|
||||
}
|
||||
report_clock_transfers -setup -file [file join $output clock-transfers-${model}.rpt]
|
||||
if {$model eq "slow"} {
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_exceptions -file [file join $output exceptions.rpt]
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close -dont_export_assignments
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile pinned Main's real menu prefix/status parsers against Coco 3 Plus rows.
|
||||
|
||||
Filesystem/OSD rendering and hardware transport are outside this host test.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from test_coco3_bh_startup import block
|
||||
from validation_common import ROOT, cpp_environment, digest
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('reference', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if out.exists() or not out.is_relative_to(ROOT / 'build'):
|
||||
p.error('Use a fresh build/ output')
|
||||
out.mkdir(parents=True)
|
||||
top = a.project / 'CoCo3.sv'
|
||||
user = a.reference / 'user_io.cpp'
|
||||
menu = a.reference / 'menu.cpp'
|
||||
provenance = json.loads((a.reference / 'provenance.json').read_text())
|
||||
for source in (user, menu):
|
||||
assert digest(source) == provenance['files'][source.name]['sha256']
|
||||
conf = top.read_text().split('localparam CONF_STR = {', 1)[1].split('};', 1)[0]
|
||||
entries = re.findall(r'"([^"\n]*)"', conf)
|
||||
rows = [x[:-1] for x in entries if x.endswith(';')][1:]
|
||||
user_text = user.read_text()
|
||||
menu_text = menu.read_text()
|
||||
# Action-side parser has no drawing calls; keep it byte-for-byte as source.
|
||||
action = menu_text[menu_text.index('//Hide or Disable flag\n'):]
|
||||
prefix = block(action, "while ((p[0] == 'H'")
|
||||
page = block(action, "if (p[0] == 'P')")
|
||||
definitions = '\n'.join(block(user_text, signature) for signature in (
|
||||
'int user_io_status_bits(', 'uint32_t user_io_status_get(',
|
||||
'uint32_t user_io_status_mask(', 'uint32_t user_io_hd_mask(',
|
||||
'void user_io_status_set('))
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
static unsigned char cur_status[16]={};
|
||||
int user_io_status_bits(const char*,int*,int*,int,int single=0);
|
||||
bool is_st(){return true;} bool is_minimig(){return false;}
|
||||
uint32_t minimig_core_extcfg(){return 0;}
|
||||
void spi_uio_cmd_cont(int){} void spi_w(uint16_t){} void DisableIO(){}
|
||||
const int UIO_SET_STATUS2=0;
|
||||
struct Mgl {bool done=true;}; static Mgl instance; static Mgl *mgl=&instance;
|
||||
'''+definitions+r'''
|
||||
struct Decoded{bool hidden,disabled,inpage;std::string row;};
|
||||
Decoded decode(const char *row,int page,uint32_t hdmask){
|
||||
char buffer[1024];strcpy(buffer,row);char *p=buffer;
|
||||
int h=0,d=0,inpage=!page,flat=0;
|
||||
'''+prefix+'\n'+page+r'''
|
||||
return {bool(h),bool(d),bool(inpage),p};
|
||||
}
|
||||
static const char *rows[]={
|
||||
'''+',\n'.join(json.dumps(row) for row in rows)+r'''};
|
||||
bool visible(const char *label,int page,uint32_t mask,bool *disabled=nullptr){
|
||||
for(const char *r:rows){auto d=decode(r,page,mask);
|
||||
auto comma=d.row.find(',');if(comma==std::string::npos)continue;
|
||||
if(d.row[0]=='F'||d.row[0]=='S')
|
||||
comma=d.row.find(',',comma+1);
|
||||
if(comma==std::string::npos)continue;
|
||||
std::string tail=d.row.substr(comma+1);
|
||||
if(tail==label || tail.rfind(std::string(label)+",",0)==0){
|
||||
if(disabled)*disabled=d.disabled;
|
||||
return d.inpage&&!d.hidden;
|
||||
}
|
||||
}fprintf(stderr,"Missing contract row: %s page=%d mask=%u\n",label,page,mask);
|
||||
assert(!"Missing contract row");return false;
|
||||
}
|
||||
int main(){
|
||||
unsigned options=0;
|
||||
// Every exposed option uses the actual Main bit parser and setter. Verify
|
||||
// all its representable values without changing any unrelated status bit.
|
||||
for(const char *r:rows){auto d=decode(r,1,0);const char *p=d.row.c_str();
|
||||
if(*p!='O'&&*p!='o')continue;
|
||||
int start,end;int ex=*p=='o';int size=user_io_status_bits(p+1,&start,&end,ex,0);
|
||||
assert(size>0 && end<63); // bit63 is exclusively the RTL migration marker.
|
||||
char label[128];const char *first=strchr(p,',');assert(first);
|
||||
const char *last=strchr(first+1,',');assert(last);
|
||||
size_t length=last-first-1;assert(length<sizeof(label));
|
||||
memcpy(label,first+1,length);label[length]=0;
|
||||
if(!strncmp(label,"Slot ",5)){
|
||||
int slot=label[5]-'1';assert(slot>=0&&slot<4);
|
||||
assert(start==43+3*slot && end==45+3*slot);
|
||||
}
|
||||
if(!strcmp(label,"Startup slot"))assert(start==12&&end==13);
|
||||
if(!strcmp(label,"Expansion"))assert(start==42&&end==42);
|
||||
for(unsigned value=0;value<(1u<<size);++value){
|
||||
memset(cur_status,0xa5,sizeof(cur_status));unsigned char before[16];
|
||||
memcpy(before,cur_status,16);user_io_status_set(p+1,value,ex);
|
||||
assert(user_io_status_get(p+1,ex)==value);
|
||||
for(int bit=0;bit<128;++bit)if(bit<start||bit>end)
|
||||
assert(((cur_status[bit/8]^before[bit/8])&(1u<<(bit%8)))==0);
|
||||
}++options;
|
||||
}
|
||||
const char *pages[]={"Cartridges & Multi-Pak","Floppy Disks","CoCo SDC",
|
||||
"Sound & Expansion","Cassette","Machine","Display","Input","Advanced"};
|
||||
for(unsigned mask=0;mask<65536;++mask){
|
||||
for(const char *p:pages)assert(visible(p,0,mask));
|
||||
}
|
||||
bool disabled=false;
|
||||
assert(visible("Drive 0",2,0,&disabled)&&!disabled);
|
||||
assert(visible("Drive 0",2,8,&disabled)&&disabled);
|
||||
assert(visible("SDC Drive 0",3,2,&disabled)&&disabled);
|
||||
assert(visible("Expansion",4,1u<<13,&disabled)&&disabled);
|
||||
assert(!visible("Assign SSC in Multi-Pak",4,0));
|
||||
assert(visible("Assign SSC in Multi-Pak",4,1u<<13));
|
||||
assert(visible("Slot 1 ROM",1,0)&&!visible("Slot 1 ROM",1,1u<<8));
|
||||
assert(visible("Slot 4 ROM",1,0)&&!visible("Slot 4 ROM",1,1u<<11));
|
||||
assert(!visible("Legacy cartridge",0,1));
|
||||
assert(!visible("Load SSC controller (4K)",0,16));
|
||||
assert(!visible("Load SSC voice (2K)",0,16));
|
||||
assert(visible("Sound & Speech ready",4,0));
|
||||
assert(!visible("Sound & Speech ready",4,1u<<6));
|
||||
assert(visible("Sound & Speech error",4,0));
|
||||
assert(!visible("Sound & Speech error",4,1u<<7));
|
||||
assert(visible("Orchestra90 stereo enabled",4,0));
|
||||
assert(!visible("Orchestra90 stereo enabled",4,1u<<15));
|
||||
for(const char *r:rows){auto d=decode(r,1,0);
|
||||
if(d.row.rfind("-,",0)==0)assert(d.row.size()-2<=27);
|
||||
}
|
||||
// Ordinary page membership survives H/D prefixes; unrelated pages stay out.
|
||||
assert(!visible("Drive 0",1,0));assert(!visible("Slot 1 ROM",2,0));
|
||||
printf("PASS native Main menu: 9 stable pages across65536 masks, %u options with isolated status writes, device visibility and disabled controls\n",options);
|
||||
}
|
||||
'''
|
||||
cpp = out / 'menu-contract.cpp'
|
||||
cpp.write_text(harness)
|
||||
compiler, env = cpp_environment(out)
|
||||
exe = out / ('menu-contract.exe' if os.name == 'nt' else 'menu-contract')
|
||||
command = ([compiler, '/nologo', '/std:c++17', '/EHsc', '/O2',
|
||||
'/D_CRT_SECURE_NO_WARNINGS', '/Fe:' + str(exe), str(cpp)]
|
||||
if os.name == 'nt' else [compiler, '-std=c++17', '-O2', str(cpp), '-o', str(exe)])
|
||||
with (out / 'compile.log').open('w') as log:
|
||||
subprocess.run(command, cwd=out, env=env, stdout=log,
|
||||
stderr=subprocess.STDOUT, check=True)
|
||||
result = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
(out / 'run.log').write_text(result.stdout + result.stderr)
|
||||
result.check_returncode()
|
||||
paths = (top, user, menu, cpp, Path(__file__))
|
||||
(out / 'result.json').write_text(json.dumps(dict(passed=True,
|
||||
scope='Pinned native Main parsing; no OSD drawing or FPGA/hardware test',
|
||||
result=result.stdout.strip(), sha256={str(x.resolve()): digest(x) for x in paths}), indent=2)+'\n')
|
||||
print(result.stdout, end='')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise actual four-slot modules and independently detect routing/storage defects."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('output',type=Path)
|
||||
p.add_argument('--suite',type=Path,required=True)
|
||||
p.add_argument('--project',type=Path,default=ROOT)
|
||||
a=p.parse_args();out=a.output.resolve()
|
||||
if out.exists() or not out.is_relative_to(ROOT/'build'):p.error('Use a fresh build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
sources=[a.project/'rtl'/('bh_mpi_'+n+'.sv') for n in ('config','router','rom')]
|
||||
bench=ROOT/'tests/bh_mpi_tb.sv'
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(a.suite/'bin'),str(a.suite/'lib'),env['PATH']])
|
||||
ext='.exe' if os.name=='nt' else ''
|
||||
variants=[('native',None),('rom-route',('router','layout[cts*3+:3]','layout[scs*3+:3]')),
|
||||
('rom-slot-alias',('rom','index==6?0:index==7?1:index==9?3:2','2\'d0')),
|
||||
('singleton',('config','remaining=mask&~used','remaining=mask'))]
|
||||
results=[]
|
||||
for name,change in variants:
|
||||
folder=out/name;folder.mkdir();files=[]
|
||||
for source in sources:
|
||||
text=source.read_text()
|
||||
if change and source.stem=='bh_mpi_'+change[0]:
|
||||
assert text.count(change[1])==1,change
|
||||
text=text.replace(change[1],change[2])
|
||||
dest=folder/source.name;dest.write_text(text,encoding='utf-8',newline='\n');files.append(dest)
|
||||
binary=folder/'test.vvp'
|
||||
run=subprocess.run([str(a.suite/'bin'/('iverilog'+ext)),'-g2012','-s','bh_mpi_tb','-o',str(binary),str(bench),*map(str,files)],env=env,capture_output=True,text=True)
|
||||
(folder/'compile.log').write_text(run.stdout+run.stderr)
|
||||
if run.returncode:raise RuntimeError('Compile failed: '+str(folder))
|
||||
run=subprocess.run([str(a.suite/'bin'/('vvp'+ext)),str(binary)],env=env,capture_output=True,text=True,timeout=180)
|
||||
log=run.stdout+run.stderr;(folder/'rtl.log').write_text(log)
|
||||
if name=='native':assert run.returncode==0 and 'PASS 65536 routing combinations' in log,log
|
||||
else:assert run.returncode!=0 and 'FATAL' in log,(name,log)
|
||||
results.append(dict(name=name,exit_code=run.returncode,result=log.strip()))
|
||||
print(name+': '+log.strip(),flush=True)
|
||||
obj=dict(passed=True,source_sha256={str(x):hashlib.sha256(x.read_bytes()).hexdigest() for x in [*sources,bench,Path(__file__)]},cases=results,hardware_tested=False)
|
||||
(out/'result.json').write_text(json.dumps(obj,indent=2)+'\n')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check actual core ROM/address/bank/IRQ/restart bindings with real slot RAM.
|
||||
|
||||
The CPU bus and system/disk ROM bytes are stimuli. This is not a full-core
|
||||
vendor-IP simulation; exact source snippets are compiled without rewriting them.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project',type=Path);p.add_argument('output',type=Path)
|
||||
p.add_argument('--suite',type=Path,required=True);a=p.parse_args()
|
||||
out=a.output.resolve()
|
||||
if out.exists() or not out.is_relative_to(ROOT/'build'):p.error('Use fresh build/ output')
|
||||
out.mkdir(parents=True);core=a.project/'rtl/coco3fpga.sv';s=core.read_text()
|
||||
def region(start,end):return s[s.index(start):s.index(end,s.index(start))]
|
||||
routing=region('wire [2:0] mpi_rom_kind,mpi_io_kind;','wire [7:0] mpi_orch_right=')
|
||||
routing+=s[s.index('wire [7:0] mpi_orch_right='):s.index("wire [7:0] mpi_orch_right=")+len("wire [7:0] mpi_orch_right=mpi_orchestra_present?ORCH_RIGHT:8'h80;")]
|
||||
bank_declarations=region('reg [2:0] rom_banks[0:3];','integer rom_bank_index;')+'integer rom_bank_index;'
|
||||
bank=region('/*\n$FF40 -','wire [3:0]\tConfig_FLAG')
|
||||
if 'always @(negedge clk_sys or negedge RESET_N)' not in bank:raise RuntimeError('Bank source contract changed')
|
||||
romdecode=region('assign FLASH_DATA =','assign\tVDAC_EN =')
|
||||
addresses=region('assign FLASH_ADDRESS =','// Empty cartridge sockets')
|
||||
irq=region('// A loaded ROM drives','assign CART_INT_N = CART_INT_IN_N;')
|
||||
restart=region('reg mpi_rom_cold_pending=0;','AMW coco_AMW (')
|
||||
trigger=re.search(r'\.Trigger\((AMW_Trigger \|\| \(mpi_rom_cold_pending && AMW_Ready\))\)',s)
|
||||
assert trigger
|
||||
selector=re.search(r"16'hFF7F:\s*begin\s*MPI_SCS <= DATA_OUT\[1:0\];\s*MPI_CTS <= DATA_OUT\[5:4\];\s*end",s)[0]
|
||||
generated='''module actual_mpi_core(input clk_sys,SSC_POWER_RESET,RESET_N,CART_SEL,ROM_SEL,PH_2,RW_N,
|
||||
input [15:0] ADDRESS,input [1:0] ROM,input [9:0] SWITCH,input [7:0] DATA_OUT,
|
||||
input [11:0] MPI_LAYOUT,input MPI_BOOT_LOADING,input ioctl_download,ioctl_wr,input [15:0] ioctl_index,
|
||||
input [24:0] ioctl_addr,input [7:0] ioctl_data,input ext_response,SER_IRQ,
|
||||
input AMW_Trigger,AMW_Ready,AMW_EN,
|
||||
output [7:0] FLASH_DATA,output HDD_EN,SDC_OBSERVE,RS232_EN,SLOT3_HW,
|
||||
output [3:0] MPI_ROM_FAULT,output MPI_ROM_LOADING,MPI_ROM_LOADED,RESTART,
|
||||
output reg [1:0] MPI_SCS,MPI_CTS,output reg CART_INT_IN_N);
|
||||
wire [7:0] COCO3_ROM_DATA=8'haa,COCO3_DISK_ROM_DATA=8'hd4,CART_DATA;
|
||||
wire [7:0] ORCH_LEFT=8'h80,ORCH_RIGHT=8'h80;
|
||||
wire [21:0] FLASH_ADDRESS;
|
||||
wire ENA_DISK2,ENA_PAK,ENA_DSK;
|
||||
wire SSC_MODE=1'b1;
|
||||
'''+routing+'\n'+bank_declarations+'\n'+addresses+'\n'+romdecode+'\n'+bank+'\n'+irq+'\n'+restart+'''
|
||||
always @(negedge clk_sys or negedge RESET_N)begin
|
||||
if(!RESET_N)begin MPI_SCS<=SWITCH[2:1];MPI_CTS<=SWITCH[2:1];end
|
||||
else if(PH_2&&!RW_N)begin case(ADDRESS)
|
||||
'''+selector+'''
|
||||
default:;
|
||||
endcase end
|
||||
end
|
||||
assign RESTART='''+trigger[1]+''';
|
||||
assign SDC_OBSERVE=SDC_EN_CS;
|
||||
endmodule
|
||||
'''
|
||||
wrapper=out/'actual-core.sv';wrapper.write_text(generated,encoding='utf-8',newline='\n')
|
||||
bench=ROOT/'tests/bh_mpi_core_tb.sv'
|
||||
modules=[a.project/'rtl/bh_mpi_router.sv',a.project/'rtl/bh_mpi_rom.sv',a.project/'rtl/bh_mpi_config.sv']
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(a.suite/'bin'),str(a.suite/'lib'),env['PATH']]);ext='.exe' if os.name=='nt' else ''
|
||||
cases=[]
|
||||
for tag,define,mutation in [('ordinary',False,None),('os9-compatibility',True,None),
|
||||
('wrong-bank-route',False,('rom_banks[MPI_SCS] <= DATA_OUT[2:0];','rom_banks[MPI_CTS] <= DATA_OUT[2:0];')),
|
||||
('lost-restart',False,('assign RESTART='+trigger[1], 'assign RESTART=AMW_Trigger || MPI_ROM_LOADED')),
|
||||
('lost-startup-autoload',False,('MPI_BOOT_LOADING||device_kind==1', 'device_kind==1')),
|
||||
('startup-main-order',False,None),('early-init-handshake',False,None)]:
|
||||
startup=tag in ('startup-main-order','early-init-handshake')
|
||||
active_bench=ROOT/'tests/bh_mpi_startup_tb.sv' if startup else bench
|
||||
active_modules=modules.copy()
|
||||
rejected=mutation is not None or tag=='early-init-handshake'
|
||||
if tag=='early-init-handshake':
|
||||
original=modules[-1].read_text()
|
||||
guard='host_started&&!requested[0]&&requested==last_requested&&pending&&!status_set'
|
||||
assert original.count(guard)==1
|
||||
bad=out/'early-init-config.sv'
|
||||
bad.write_text(original.replace(guard,'pending&&!status_set'),encoding='utf-8',newline='\n')
|
||||
active_modules[-1]=bad
|
||||
active_wrapper=wrapper
|
||||
if mutation:
|
||||
assert generated.count(mutation[0])==1
|
||||
active_wrapper=out/(tag+'-core.sv')
|
||||
active_wrapper.write_text(generated.replace(*mutation),encoding='utf-8',newline='\n')
|
||||
binary=out/(tag+'.vvp')
|
||||
cmd=[str(a.suite/'bin'/('iverilog'+ext)),'-g2012','-s',
|
||||
'bh_mpi_startup_tb' if startup else 'bh_mpi_core_tb','-o',str(binary)]
|
||||
if define:cmd+=['-DCoCo3_sdc_fix_os9_driver']
|
||||
run=subprocess.run([*cmd,str(active_wrapper),str(active_bench),*map(str,active_modules)],env=env,capture_output=True,text=True)
|
||||
(out/(tag+'-compile.log')).write_text(run.stdout+run.stderr)
|
||||
if run.returncode:raise RuntimeError('Actual core binding compile failed: '+tag)
|
||||
run=subprocess.run([str(a.suite/'bin'/('vvp'+ext)),str(binary)],env=env,capture_output=True,text=True,timeout=120)
|
||||
log=run.stdout+run.stderr;(out/(tag+'.log')).write_text(log)
|
||||
if rejected:assert run.returncode!=0 and 'FATAL' in log,(tag,log)
|
||||
else:assert run.returncode==0 and 'PASS actual core MPI bindings' in log,log
|
||||
print(tag+': '+log.strip(),flush=True);cases.append(dict(name=tag,result=log.strip()))
|
||||
files=[core,wrapper,bench,ROOT/'tests/bh_mpi_startup_tb.sv',*modules,Path(__file__)]
|
||||
(out/'result.json').write_text(json.dumps(dict(passed=True,hardware_tested=False,cases=cases,source_sha256={str(x):hashlib.sha256(x.read_bytes()).hexdigest() for x in files}),indent=2)+'\n')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the pinned original MiSTer FC parser with BH records and mocked I/O.
|
||||
|
||||
This verifies host parser/record/index behavior, not the installed ARM binary,
|
||||
FPGA configuration, analog timing or physical startup. No Main source is edited.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from validation_common import ROOT, digest, cpp_environment
|
||||
from coco3_bh_profile import NAME, ROM_SLOTS, startup_records
|
||||
|
||||
|
||||
def block(text, anchor):
|
||||
start = text.index(anchor)
|
||||
opening = text.index('{', start)
|
||||
depth = 1
|
||||
end = opening + 1
|
||||
while depth:
|
||||
depth += (text[end] == '{') - (text[end] == '}')
|
||||
end += 1
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('reference', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if out.exists() or not out.is_relative_to(ROOT / 'build'):
|
||||
p.error('Use a fresh build directory')
|
||||
out.mkdir(parents=True)
|
||||
source = a.reference / 'user_io.cpp'
|
||||
provenance = json.loads((a.reference / 'provenance.json').read_text())
|
||||
if digest(source) != provenance['files']['user_io.cpp']['sha256']:
|
||||
raise RuntimeError('Pinned Main parser changed')
|
||||
original = source.read_text()
|
||||
# Main's real initialization order matters to slot-ROM eligibility: FC
|
||||
# parsing precedes saved status restoration while bit0 remains asserted.
|
||||
init_reset = original.index('user_io_status_set("[0]", 1);', original.index('void user_io_init('))
|
||||
parse_call = original.index('parse_config();', init_reset)
|
||||
saved_config = original.index('int config_found = FileLoadConfig(name, cur_status', parse_call)
|
||||
release_reset = original.index('user_io_status_set("[0]", 0);', saved_config)
|
||||
assert init_reset < parse_call < saved_config < release_reset
|
||||
file_tx = block(original, 'int user_io_file_tx(const char* name,')
|
||||
acknowledgement = block(original, 'static void check_status_change()')
|
||||
assert 'check_status_change();' in file_tx
|
||||
assert 'user_io_status_set("[0]", 0);' in acknowledgement
|
||||
parser = block(original, "if (p[0] == 'F')")
|
||||
substring = block(original, 'int substrcpy(')
|
||||
extension = block(original, 'unsigned char user_io_ext_idx(')
|
||||
top = a.project / 'CoCo3.sv'
|
||||
if 'bh_mpi_config mpi_configuration' in top.read_text():
|
||||
assert '.MPI_BOOT_LOADING(status[0])' in top.read_text(), 'Retain FC files until saved layout arrives'
|
||||
conf = top.read_text().split('localparam CONF_STR = {', 1)[1].split('};', 1)[0]
|
||||
lines = re.findall(r'"([^"\n]*)"', conf)
|
||||
if not lines[0].startswith('Coco 3 Plus;'):
|
||||
raise RuntimeError('Fitted source does not have the independent identity')
|
||||
picks = [next(x[:-1] for x in lines if x.startswith(f'H4FC{n},')) for n in ROM_SLOTS]
|
||||
cases = [
|
||||
('default', NAME, picks, [4, 5]),
|
||||
('hidden-independent', NAME, ['H4D0' + x[2:] for x in picks], [4, 5]),
|
||||
('legacy-manual', NAME, [x.replace('FC', 'F', 1) for x in picks], []),
|
||||
('stock-isolated', 'COCO3', picks, []),
|
||||
('missing-voice', NAME, picks, [4]),
|
||||
('rom-extension', NAME, picks, [68, 69]),
|
||||
]
|
||||
slot_picks = [next(x[:-1] for x in lines if re.match(r'H[89AB]P1FC'+str(n)+',', x))
|
||||
for n in range(6, 10)] if any('P1FC6,' in x for x in lines) else []
|
||||
if slot_picks:
|
||||
cases.append(('slot-autoload', NAME, slot_picks, [6, 7, 8, 9]))
|
||||
records = startup_records()
|
||||
if slot_picks:
|
||||
for n in range(6, 10):
|
||||
value = f'/media/fat/games/coco3plus/slot{n-5}.ccc'.encode()
|
||||
records[f'config/{NAME}.f{n}'] = value.ljust(1024, b'\0')
|
||||
for path, data in records.items():
|
||||
target = out / path
|
||||
target.parent.mkdir(exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
harness = r'''
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#ifdef _MSC_VER
|
||||
#define strcasecmp _stricmp
|
||||
#else
|
||||
#include <strings.h>
|
||||
#endif
|
||||
#include <string>
|
||||
#include <vector>
|
||||
static const char *identity, *scenario;
|
||||
static int boot0_loaded=0;
|
||||
static std::vector<int> sent;
|
||||
const char *user_io_get_core_name(){return identity;}
|
||||
bool is_cpc(){return false;}
|
||||
void StoreIdx_F(int,const char*){}
|
||||
int FileLoadConfig(const char *name,void *buffer,int size){
|
||||
std::string path="config/";path+=name;
|
||||
if(!strcmp(scenario,"missing-voice") && path.find(".f5")!=std::string::npos)return 0;
|
||||
FILE *f=fopen(path.c_str(),"rb");if(!f)return 0;
|
||||
int n=fread(buffer,1,size,f);fclose(f);
|
||||
if(!strcmp(scenario,"rom-extension")) {
|
||||
char *s=(char*)buffer;char *e=strrchr(s,'.');assert(e);strcpy(e,".rom");
|
||||
}
|
||||
assert(((char*)buffer)[size-1]==0);return n;
|
||||
}
|
||||
void user_io_file_tx(const char *name,int index,int,int,int,uint32_t address){
|
||||
assert(!strncmp(name,"/media/fat/games/coco3plus/",strlen("/media/fat/games/coco3plus/")));
|
||||
assert(address==0);sent.push_back(index);
|
||||
printf("TX %d %s\n",index,name);
|
||||
}
|
||||
'''
|
||||
generated = harness + '\n' + substring + '\n' + extension + '\nvoid load(char *p){\nchar str[1024]={},ext[256]={};\n'
|
||||
generated += 'while((p[0]==\'H\'||p[0]==\'D\'||p[0]==\'h\'||p[0]==\'d\')&&strlen(p)>=2)p+=2;\n'
|
||||
# Exact page-prefix skip from pinned user_io.cpp's config initialization.
|
||||
page_skip = re.search(r"if \(p\[0\] == 'P'\) p \+= 2;", original)
|
||||
if not page_skip:
|
||||
raise RuntimeError('Pinned Main page-prefix contract changed')
|
||||
generated += page_skip[0] + '\n'
|
||||
# Exercise the exact original Main name reader with the display identity and
|
||||
# native MGL override, including embedded spaces and its real 32-byte fields.
|
||||
name_reader = block(original, 'void user_io_read_core_name()')
|
||||
name_fixture = r'''namespace identity_contract {
|
||||
static char core_name[32]={},orig_name[32]={},ovr_name[32]={};
|
||||
static int is_no_type=0;
|
||||
char *user_io_get_confstr(int){static char n[]="Coco 3 Plus";return n;}
|
||||
'''+name_reader+r'''
|
||||
void run(){
|
||||
user_io_read_core_name();
|
||||
assert(!strcmp(core_name,"Coco 3 Plus") && !strcmp(orig_name,"Coco 3 Plus"));
|
||||
strcpy(ovr_name,"coco3plus");user_io_read_core_name();
|
||||
assert(!strcmp(core_name,"coco3plus") && !strcmp(orig_name,"Coco 3 Plus"));
|
||||
}
|
||||
}
|
||||
'''
|
||||
generated += parser + '\n}\n'+name_fixture+'\nint main(int argc,char **argv){assert(argc==3);identity_contract::run();identity=argv[1];scenario=argv[2];\n'
|
||||
for tag, identity, options, expected in cases:
|
||||
generated += f'if(!strcmp(scenario,{json.dumps(tag)})){{\n'
|
||||
for item in options:
|
||||
generated += f'{{char p[]={json.dumps(item)};load(p);}}\n'
|
||||
generated += 'assert(boot0_loaded==0);assert((sent==std::vector<int>{' + ','.join(map(str, expected)) + '}));}\n'
|
||||
generated += 'puts("PASS native Main FC startup parser");}\n'
|
||||
cpp = out / 'main-fc-probe.cpp'
|
||||
cpp.write_text(generated)
|
||||
compiler, env = cpp_environment(out)
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
exe = out / ('probe' + ext)
|
||||
with (out / 'compile.log').open('w') as log:
|
||||
command = ([compiler, '/nologo', '/std:c++17', '/EHsc', '/O2', '/D_CRT_SECURE_NO_WARNINGS', '/Fe:' + str(exe)]
|
||||
if os.name == 'nt' else [compiler, '-std=c++17', '-O2', '-o', str(exe)])
|
||||
subprocess.run([*command, str(cpp)], cwd=out,
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
results = []
|
||||
for tag, identity, _, expected in cases:
|
||||
result = subprocess.run([str(exe), identity, tag], cwd=out, env=env, capture_output=True, text=True)
|
||||
(out / (tag + '.log')).write_text(result.stdout + result.stderr)
|
||||
if result.returncode or 'PASS native Main FC startup parser' not in result.stdout:
|
||||
raise RuntimeError('Startup parser probe failed: ' + tag)
|
||||
results.append({'case': tag, 'indices': expected, 'log_sha256': digest(out / (tag + '.log'))})
|
||||
data = {'passed': True, 'hardware_tested': False, 'main_reference': provenance,
|
||||
'top_sha256': digest(top), 'records': {k: {'bytes': len(v), 'path': v.split(b'\0')[0].decode()} for k, v in records.items()},
|
||||
'cases': results, 'script_sha256': digest(Path(__file__)),
|
||||
'scope': 'Original native Main FC/extension parser; mocked file I/O and transport; installed binary startup remains a hardware check'}
|
||||
(out / 'result.json').write_text(json.dumps(data, indent=2) + '\n')
|
||||
print(f'PASS {len(cases)} original-Main startup cases, including applicable page-scoped slot ROM records')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check the real platform serializer's timing slots; reject a same-edge defect."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if not out.is_relative_to(ROOT / 'build') or out.exists():
|
||||
p.error('Use a fresh build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
source = a.project / 'sys/audio_out.v'
|
||||
i2s = a.project / 'sys/i2s.v'
|
||||
text = source.read_text()
|
||||
ce = text[text.index('localparam AUDIO_RATE'):text.index('\ni2s i2s')]
|
||||
ce = ce.replace('always @(posedge clk) begin', 'always @(posedge clk) begin : ce_phase', 1)
|
||||
at = ce.index('reg i2s_ce;')
|
||||
ce = ce[:at] + ce[at:].replace('always @(posedge clk) begin', 'always @(posedge clk) begin : divider_phase', 1)
|
||||
wrapper = ('module audio_pin_contract(input clk,reset,sample_rate,output bclk,lrclk,data);\n'
|
||||
'localparam CLK_RATE=24576000;\n' + ce + '\n'
|
||||
'i2s i2s(.reset(reset),.clk(clk),.ce(i2s_ce),.sclk(bclk),.lrclk(lrclk),.sdata(data),'
|
||||
'.left_chan(16\'ha55a),.right_chan(16\'h5aa5));\nendmodule\n')
|
||||
(out / 'wrapper.sv').write_text(wrapper)
|
||||
(out / 'i2s.v').write_bytes(i2s.read_bytes())
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(a.suite / 'bin'), str(a.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
cmd = [str(a.suite / 'bin' / ('iverilog' + ext)), '-g2012', '-s', 'external_audio_tb', '-o', str(out / 'run.vvp'),
|
||||
str(ROOT / 'tests/external_audio_tb.sv'), str(out / 'wrapper.sv'), str(out / 'i2s.v')]
|
||||
for negative in (False, True):
|
||||
tag = 'negative' if negative else 'positive'
|
||||
if negative:
|
||||
# Deliberately invert the forwarded sampling edge.
|
||||
mutant = i2s.read_text().replace('sclk <= msclk;', 'sclk <= ~msclk;')
|
||||
assert mutant != i2s.read_text()
|
||||
(out / 'i2s.v').write_text(mutant)
|
||||
with (out / f'{tag}-compile.log').open('w') as log:
|
||||
subprocess.run(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (out / f'{tag}.log').open('w') as log:
|
||||
result = subprocess.run([str(a.suite / 'bin' / ('vvp' + ext)), str(out / 'run.vvp')],
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT, timeout=60)
|
||||
log_text = (out / f'{tag}.log').read_text()
|
||||
print(log_text, end='')
|
||||
if (not negative and (result.returncode or 'PASS audio pin slots' not in log_text)) or (
|
||||
negative and (not result.returncode or 'I2S receiver setup slot lost' not in log_text)):
|
||||
raise RuntimeError(f'Unexpected {tag} result')
|
||||
(out / 'i2s.v').write_bytes(i2s.read_bytes())
|
||||
(out / 'result.json').write_text(json.dumps({'passed': True, 'wrong_edge_mutant_rejected': True,
|
||||
'setup_min_fabric_cycles': 5, 'hold_min_fabric_cycles': 3, 'modes_hz': [48000, 96000],
|
||||
'scope': 'real CE and I2S RTL; no analog edge/pull-up or external receiver model',
|
||||
'source_sha256': {str(path.relative_to(a.project)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in (source, i2s)}}, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check actual MCP I2C master against fast-mode slots and finite release delay."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if not out.is_relative_to(ROOT / 'build') or out.exists():
|
||||
p.error('Use a new build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
source = a.project / 'sys/i2c.v'
|
||||
wrapper = a.project / 'sys/mcp23009.sv'
|
||||
m = re.search(r'i2c\s*#\(50_000_000,\s*([\d_]+)\)', wrapper.read_text())
|
||||
assert m
|
||||
native_hz = int(m[1].replace('_', ''))
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(a.suite / 'bin'), str(a.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
results = []
|
||||
for hz in sorted({native_hz, 250000, 500000}):
|
||||
# Four independent pin-edge extrema for the accepted profile;
|
||||
# the ideal legacy waveform is the negative frequency/low-time control.
|
||||
corners = range(16) if hz == 250000 else (0, 1)
|
||||
for corner in corners:
|
||||
scl_fall = 300 if corner & 1 else 0
|
||||
scl_release = 300 if corner & 2 else 0
|
||||
sda_fall = 300 if corner & 4 else 0
|
||||
sda_release = 300 if corner & 8 else 0
|
||||
tag = f'{hz}-{corner}'
|
||||
text = source.read_text()
|
||||
# Icarus requires declarations before their use in delayed drivers;
|
||||
# Quartus accepts the original declaration order. No logic changes.
|
||||
declarations = []
|
||||
for name in ('SCLK', 'SDO'):
|
||||
d = re.search(r'^reg\s+(?:\[[^\]]+\]\s*)?' + name + r';', text, re.M)
|
||||
assert d
|
||||
declarations.append(d[0])
|
||||
text = text.replace(d[0], '', 1)
|
||||
text = text.replace('assign I2C_SCL =', '\n'.join(declarations) + '\nassign I2C_SCL =', 1)
|
||||
text = text.replace('assign I2C_SCL =', f'assign #(0,{scl_fall},{scl_release}) I2C_SCL =')
|
||||
text = text.replace('assign I2C_SDA =', f'assign #(0,{sda_fall},{sda_release}) I2C_SDA =')
|
||||
(out / 'i2c.v').write_text(text)
|
||||
cmd = [str(a.suite / 'bin' / ('iverilog' + ext)), '-g2012', f'-DBUS_HZ={hz}',
|
||||
f'-DSDA_FALL_NS={sda_fall}', f'-DSDA_RELEASE_NS={sda_release}', '-s', 'external_i2c_tb',
|
||||
'-o', str(out / 'run.vvp'), str(ROOT / 'tests/external_i2c_tb.sv'), str(out / 'i2c.v')]
|
||||
with (out / f'{tag}-compile.log').open('w') as log:
|
||||
subprocess.run(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (out / f'{tag}.log').open('w') as log:
|
||||
r = subprocess.run([str(a.suite / 'bin' / ('vvp' + ext)), str(out / 'run.vvp')], env=env,
|
||||
stdout=log, stderr=subprocess.STDOUT, timeout=60)
|
||||
text = (out / f'{tag}.log').read_text()
|
||||
print(text, end='')
|
||||
if hz == 500000:
|
||||
assert r.returncode and ('I2C low below 1300ns' in text or 'I2C fast-mode period below 2500ns' in text)
|
||||
else:
|
||||
assert not r.returncode and 'PASS I2C fast-mode slots' in text
|
||||
results.append({'bus_hz': hz, 'scl_fall_ns': scl_fall, 'scl_release_ns': scl_release,
|
||||
'sda_fall_ns': sda_fall, 'sda_release_ns': sda_release, 'exit_code': r.returncode,
|
||||
'log_sha256': hashlib.sha256((out / f'{tag}.log').read_bytes()).hexdigest()})
|
||||
(out / 'result.json').write_text(json.dumps({'native_bus_hz': native_hz, 'fast_profile_passed': native_hz == 250000,
|
||||
'scope': 'actual master, NACK/released FF and maximum-900ns ACK/slave-data cases; independent 0/300ns pin-edge extrema, no physical slave/RC measurement',
|
||||
'source_sha256': {str(f.relative_to(a.project)): hashlib.sha256(f.read_bytes()).hexdigest() for f in (source, wrapper)},
|
||||
'results': results}, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the actual pixel divider's generated-clock edges and reject a defect."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if not out.is_relative_to(ROOT / 'build') or out.exists():
|
||||
p.error('Use a fresh build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
source = a.project / 'rtl/Mister_Video.v'
|
||||
sdc = a.project / 'external-io.sdc'
|
||||
text = source.read_text()
|
||||
divider = re.search(r'always @ \(posedge MASTER_CLK\)\s*begin\s*reg\s*\[1:0\]\s*div;.*?\nend', text, re.S)
|
||||
assert divider is not None
|
||||
assert '-edges {3 7 11}' in sdc.read_text()
|
||||
block = divider[0].replace('begin', 'begin : divider', 1)
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(a.suite / 'bin'), str(a.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
bench = '''`timescale 1ns/1ps
|
||||
module tb;
|
||||
reg clk=0; always #5 clk=~clk;
|
||||
wire pix; generator dut(clk,pix);
|
||||
integer cycles=0, rises=0, last_rise=0, last_fall=0;
|
||||
reg previous=0;
|
||||
always @(posedge clk) cycles=cycles+1;
|
||||
// Observe the registered final value after all nonblocking assignments settle.
|
||||
// The original RTL assigns default low then conditionally high in one process.
|
||||
always @(negedge clk) begin
|
||||
if(pix && !previous) begin
|
||||
if(rises==0 && cycles!=2) $fatal(1,"Pixel first edge %0d",cycles);
|
||||
if(rises>0 && cycles-last_rise!=4) $fatal(1,"Pixel period %0d",cycles-last_rise);
|
||||
if(rises>0 && cycles-last_fall!=2) $fatal(1,"Pixel low width");
|
||||
last_rise=cycles;rises=rises+1;
|
||||
end
|
||||
if(!pix && previous && rises>0) begin
|
||||
if(cycles-last_rise!=2) $fatal(1,"Pixel high width");
|
||||
last_fall=cycles;
|
||||
end
|
||||
previous=pix;
|
||||
end
|
||||
initial begin
|
||||
dut.divider.div=0;
|
||||
repeat(4096) @(negedge clk);
|
||||
if(rises!=1024) $fatal(1,"Pixel count");
|
||||
$display("PASS pixel edges {3 7 11}: 1024 periods, divide four, duty half");
|
||||
$finish;
|
||||
end
|
||||
endmodule
|
||||
'''
|
||||
(out / 'tb.sv').write_text(bench)
|
||||
cmd = [str(a.suite / 'bin' / ('iverilog' + ext)), '-g2012', '-s', 'tb', '-o', str(out / 'run.vvp'), str(out / 'tb.sv'), str(out / 'generator.sv')]
|
||||
for negative in (False, True):
|
||||
tag = 'negative' if negative else 'positive'
|
||||
logic = block.replace("(div == 2'd2)", "(div == 2'd3)") if negative else block
|
||||
(out / 'generator.sv').write_text('module generator(input MASTER_CLK,output reg PIX_CLK);\n' + logic + '\nendmodule\n')
|
||||
with (out / f'{tag}-compile.log').open('w') as log:
|
||||
subprocess.run(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (out / f'{tag}.log').open('w') as log:
|
||||
r = subprocess.run([str(a.suite / 'bin' / ('vvp' + ext)), str(out / 'run.vvp')], env=env, stdout=log, stderr=subprocess.STDOUT, timeout=30)
|
||||
output = (out / f'{tag}.log').read_text()
|
||||
print(output, end='')
|
||||
if (not negative and (r.returncode or 'PASS pixel edges' not in output)) or (negative and (not r.returncode or 'Pixel' not in output)):
|
||||
raise RuntimeError('Unexpected divider result: ' + tag)
|
||||
(out / 'result.json').write_text(json.dumps({'passed': True, 'wrong_duty_mutant_rejected': True,
|
||||
'generated_edges': [3, 7, 11], 'periods': 1024,
|
||||
'scope': 'extracted actual divider; FPGA zero power-up counter assumption; not pixel rendering',
|
||||
'source_sha256': {str(path.relative_to(a.project)): hashlib.sha256(path.read_bytes()).hexdigest() for path in (source, sdc)}}, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Delayed SDRAM read-window experiment using the existing independent line oracle.
|
||||
|
||||
This is a digital corner model, not vendor silicon or signal-integrity simulation.
|
||||
It models the fitted clock skew and return propagation explicitly; source stays
|
||||
unchanged. Generated variants test whether ready strobes select the right beat.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
from test_video_sdram import normalize_controller
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
p.add_argument('--check-cpu-data', action='store_true',
|
||||
help='Also check the competing CPU read payload at the actual positive-edge consumer')
|
||||
p.add_argument('--legacy-extra-launch-cycle', action='store_true',
|
||||
help='Reproduce the rejected model that added tAC after three whole CL3 cycles')
|
||||
args = p.parse_args()
|
||||
out = args.output.resolve()
|
||||
if not out.is_relative_to(ROOT / 'build') or out.exists():
|
||||
p.error('Use a fresh build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(args.suite / 'bin'), str(args.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
source = args.project / 'rtl/sdram/sdram2.sv'
|
||||
fetch = (args.project / 'rtl/coco_mem_fetch.sv').read_text()
|
||||
import re
|
||||
for name in ('SDRAM_VID_REQ', 'BUFF_ADD', 'BUFF_DATA_O', 'BUFFER_WRITE'):
|
||||
fetch, n = re.subn(r'(output\s+)(?!reg)(\[[^\]]+\]\s*)?(' + name + r'\b)', r'\1reg \2\3', fetch, count=1)
|
||||
assert n == 1
|
||||
fetch = re.sub(r'wire(\s+\[2:0\]\s+BUF_HBORDER;)', r'reg\1', fetch, count=1)
|
||||
(out / 'fetch.sv').write_text(fetch)
|
||||
bench_source = (ROOT / 'tests/video_sdram_tb.sv').read_text()
|
||||
if args.check_cpu_data:
|
||||
# The existing video oracle already checks independent addresses. Its
|
||||
# competing CPU channel used to count READY without checking payload.
|
||||
cpu_address = int(re.search(r"sdram_cpu_addr\(25'h([0-9a-fA-F]+)\)", bench_source)[1], 16)
|
||||
word = cpu_address >> 1
|
||||
expected = (word & 0xffff) ^ (((word >> 16) & 255) * 0x101) ^ 0x96a5
|
||||
old = 'if(cpu_ready) cpu_reads<=cpu_reads+1;'
|
||||
assert bench_source.count(old) == 1
|
||||
bench_source = bench_source.replace(old,
|
||||
f'if(cpu_ready) begin cpu_reads<=cpu_reads+1; '
|
||||
f'if(dout!==16\'h{expected:04x}) $fatal(1,"CPU read data mismatch value=%h",dout); end')
|
||||
records = []
|
||||
native_extra_match = re.search(r'localparam READ_CAPTURE_EXTRA\s*=\s*(\d+)', source.read_text())
|
||||
native_extra = int(native_extra_match[1]) if native_extra_match else 0
|
||||
# Clock skew bounds are diagnostic envelopes; latest tAC and earliest tOH
|
||||
# use different stable-data corners. 0/0 is the old logical model control.
|
||||
for corner, clock_skew, return_delay, command_delay in [('logical', 0, 0, 0), ('late', 4.5, 8.245, 5.0), ('early', 1.5, 3.121, 1.0)]:
|
||||
for extra_ready in (0, 1):
|
||||
folder = out / f'{corner}-ready{extra_ready}'
|
||||
folder.mkdir()
|
||||
for name in ('reference', 'candidate'):
|
||||
text = normalize_controller(source.read_text(), 'sdram_' + name)
|
||||
if native_extra_match:
|
||||
text = re.sub(r'localparam READ_CAPTURE_EXTRA\s*=\s*\d+', 'localparam READ_CAPTURE_EXTRA = ' + str(extra_ready), text)
|
||||
elif extra_ready:
|
||||
# Expand the whole ready pipeline by one, preserving ordering.
|
||||
text = text.replace('[CAS_LATENCY+BURST_LENGTH:0]', '[CAS_LATENCY+BURST_LENGTH+1:0]')
|
||||
text = text.replace('[CAS_LATENCY+BURST_LENGTH]', '[CAS_LATENCY+BURST_LENGTH+1]')
|
||||
(folder / (name + '.sv')).write_text(text)
|
||||
bench = bench_source.replace('always #5 clk=~clk;', 'always #4.365079 clk=~clk;')
|
||||
physical_launch_cycles = 3 if corner == 'logical' or args.legacy_extra_launch_cycle else 2
|
||||
if physical_launch_cycles == 2:
|
||||
# Alliance Fig31.2: READ at T4, Ax0 launches after T6 and
|
||||
# is sampled at T7. CL3's third edge is the receive boundary;
|
||||
# adding tAC after T7 incorrectly adds another whole cycle.
|
||||
old = "pipe[2]=contents(word_address);pipe[3]=contents(word_address ^ 24'd1);\n valid[2]=1;valid[3]=1;"
|
||||
new = "pipe[1]=contents(word_address);pipe[2]=contents(word_address ^ 24'd1);\n valid[1]=1;valid[2]=1;"
|
||||
assert bench.count(old) == 1
|
||||
bench = bench.replace(old, new)
|
||||
bench = bench.replace('COMMAND_DELAY_NS=0', 'COMMAND_DELAY_NS=' + str(command_delay))
|
||||
bench = bench.replace('always @(negedge clk) begin\n drive <= #(RETURN_DELAY_NS) (valid[0]?pipe[0]:16\'hzzzz);',
|
||||
# Transport each edge: an inertial continuous delay larger
|
||||
# than half a period incorrectly suppresses the whole clock.
|
||||
f'reg pin_clk; always @(clk) pin_clk <= #{clock_skew} clk;\n'
|
||||
f'always @(negedge pin_clk) begin\n drive <= #{return_delay} (valid[0]?pipe[0]:16\'hzzzz);')
|
||||
assert 'reg pin_clk' in bench
|
||||
(folder / 'tb.sv').write_text(bench)
|
||||
cmd = [str(args.suite / 'bin' / ('iverilog' + ext)), '-g2012', '-s', 'video_sdram_tb', '-o', str(folder / 'run.vvp'),
|
||||
str(folder / 'tb.sv'), str(out / 'fetch.sv'), str(folder / 'reference.sv'), str(folder / 'candidate.sv')]
|
||||
with (folder / 'compile.log').open('w') as log:
|
||||
subprocess.run(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (folder / 'run.log').open('w') as log:
|
||||
r = subprocess.run([str(args.suite / 'bin' / ('vvp' + ext)), str(folder / 'run.vvp')],
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT, timeout=180)
|
||||
result = {'corner': corner, 'extra_ready_cycle': extra_ready, 'clock_skew_ns': clock_skew,
|
||||
'return_delay_ns': return_delay, 'exit_code': r.returncode,
|
||||
'command_delay_ns': command_delay,
|
||||
'physical_launch_cycles': physical_launch_cycles,
|
||||
'native_extra_cycle': native_extra, 'is_ready_mutant': extra_ready != native_extra,
|
||||
'log_tail': (folder / 'run.log').read_text().strip().splitlines()[-2:],
|
||||
'log_sha256': hashlib.sha256((folder / 'run.log').read_bytes()).hexdigest()}
|
||||
expected_pass = ((corner == 'logical') != bool(extra_ready)) if args.legacy_extra_launch_cycle else not extra_ready
|
||||
signatures = ['video data channel='] + (['CPU read data mismatch'] if args.check_cpu_data else [])
|
||||
if (r.returncode == 0) != expected_pass or (r.returncode and not any(s in (folder / 'run.log').read_text() for s in signatures)):
|
||||
raise RuntimeError(f'Unexpected read-window control result: {corner}/{extra_ready}')
|
||||
records.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
(out / 'result.json').write_text(json.dumps({'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
|
||||
'bench_sha256': hashlib.sha256((ROOT / 'tests/video_sdram_tb.sv').read_bytes()).hexdigest(),
|
||||
'controller_normalizer_sha256': hashlib.sha256((ROOT / 'scripts/test_video_sdram.py').read_bytes()).hexdigest(),
|
||||
'generator_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
'scope': 'read bursts / line oracle, no write timing or analog model', 'controls_verified': True,
|
||||
'cpu_data_oracle': args.check_cpu_data,
|
||||
'legacy_extra_launch_cycle': args.legacy_extra_launch_cycle,
|
||||
'native_read_window_passed': all(r['exit_code'] == 0 for r in records if not r['is_ready_mutant']),
|
||||
'results': records}, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check AS4C32M16SB -7 command minima on actual controller pin commands."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from test_video_sdram import normalize_controller
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('project', type=Path)
|
||||
p.add_argument('output', type=Path)
|
||||
p.add_argument('--suite', type=Path, required=True)
|
||||
p.add_argument('--expect-legacy-failures', action='store_true')
|
||||
a = p.parse_args()
|
||||
out = a.output.resolve()
|
||||
if not out.is_relative_to(ROOT / 'build') or out.exists():
|
||||
p.error('Use a new build/ directory')
|
||||
out.mkdir(parents=True)
|
||||
source = a.project / 'rtl/sdram/sdram2.sv'
|
||||
(out / 'controller.sv').write_text(normalize_controller(source.read_text(), 'sdram_probe'))
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(a.suite / 'bin'), str(a.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
cmd = [str(a.suite / 'bin' / ('iverilog' + ext)), '-g2012', '-s', 'external_sdram_commands_tb', '-o', str(out / 'run.vvp'),
|
||||
str(ROOT / 'tests/external_sdram_commands_tb.sv'), str(out / 'controller.sv')]
|
||||
with (out / 'compile.log').open('w') as log:
|
||||
subprocess.run(cmd, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
results = {}
|
||||
for tag, extra, signature in [('startup', [], 'SDRAM startup below 200 us'),
|
||||
('recovery', ['+IGNORE_STARTUP'], 'SDRAM tRC below 63 ns'),
|
||||
('refresh', ['+IGNORE_STARTUP', '+IGNORE_TRC'], 'SDRAM refresh interval above 7812.5 ns')]:
|
||||
with (out / f'{tag}.log').open('w') as log:
|
||||
r = subprocess.run([str(a.suite / 'bin' / ('vvp' + ext)), str(out / 'run.vvp'), *extra], env=env,
|
||||
stdout=log, stderr=subprocess.STDOUT, timeout=60)
|
||||
text = (out / f'{tag}.log').read_text()
|
||||
print(text, end='')
|
||||
if a.expect_legacy_failures:
|
||||
assert r.returncode != 0 and signature in text
|
||||
else:
|
||||
assert r.returncode == 0 and 'PASS SDRAM command intervals' in text
|
||||
results[tag] = {'exit_code': r.returncode, 'log_sha256': hashlib.sha256((out / f'{tag}.log').read_bytes()).hexdigest()}
|
||||
(out / 'result.json').write_text(json.dumps({'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
|
||||
'legacy_failures_reproduced': a.expect_legacy_failures, 'command_checks_passed': not a.expect_legacy_failures,
|
||||
'scope': 'digital pin-command intervals, no physical read data or analog timing', 'results': results}, indent=2) + '\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the exact keyboard row against upstream with the stated control delay."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
from source_snapshot import original_sources
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('project',type=Path)
|
||||
parser.add_argument('output',type=Path)
|
||||
parser.add_argument('--suite',type=Path,required=True)
|
||||
args=parser.parse_args();output=args.output.resolve()
|
||||
if not output.is_relative_to((ROOT/'build').resolve()) or output.exists():parser.error('Use a new build/ output')
|
||||
output.mkdir(parents=True)
|
||||
original=original_sources('coco3-mister')/'rtl/coco3fpga.sv';candidate=args.project/'rtl/coco3fpga.sv'
|
||||
def row(text,start):return text[text.index(start):text.index('assign KEYBOARD_IN[7]')]
|
||||
reference=row(original.read_text(),'assign KEYBOARD_IN[6] =')
|
||||
actual=row(candidate.read_text(),'// Research: phase-match the remaining CPU keyboard control flags.')
|
||||
header='input [3:0] controls,input [72:0] KEY,input [7:0] KEY_COLUMN,output y);\nwire EE_N=controls[3],MUGS=controls[2],SHIFT=controls[1],SHIFT_OVERRIDE=controls[0];\nwire [7:0] KEYBOARD_IN;wire [7:0] BUTTON_N={7\'d0,EE_N};\n'
|
||||
source=output/'actual-keyboard.sv'
|
||||
source.write_text('module actual_keyboard_controls(input clk_sys,'+header+actual+'\nassign y=KEYBOARD_IN[6];endmodule\nmodule reference_keyboard_controls('+header+reference+'\nassign y=KEYBOARD_IN[6];endmodule\n',encoding='utf-8')
|
||||
bench=ROOT/'tests/keyboard_control_phase_tb.sv'
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(args.suite/'bin'),str(args.suite/'lib'),env['PATH']])
|
||||
ext='.exe' if os.name=='nt' else ''
|
||||
with (output/'compile.log').open('w') as log:
|
||||
subprocess.run([str(args.suite/'bin'/('iverilog'+ext)),'-g2012','-s','keyboard_control_phase_tb','-o',str(output/'test.vvp'),str(bench),str(source)],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
with (output/'test.log').open('w') as log:
|
||||
subprocess.run([str(args.suite/'bin'/('vvp'+ext)),str(output/'test.vvp')],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
print((output/'test.log').read_text())
|
||||
(output/'test-result.json').write_text(json.dumps({'passed':True,'hardware_tested':False,'sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [original,candidate,bench,source,Path(__file__),output/'test.log']}},indent=2)+'\n',encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare actual SDC RAM and VDAC write-clock bindings at legal CPU boundaries."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from source_snapshot import original_sources
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('project',type=Path)
|
||||
parser.add_argument('output',type=Path)
|
||||
parser.add_argument('--suite',type=Path,required=True)
|
||||
args=parser.parse_args()
|
||||
output=args.output.resolve()
|
||||
if not output.is_relative_to((ROOT/'build').resolve()) or output.exists():
|
||||
parser.error('Use a new output inside build/')
|
||||
output.mkdir(parents=True)
|
||||
original=original_sources('coco3-mister')/'rtl/sdc.sv'
|
||||
candidate=args.project/'rtl/sdc.sv'
|
||||
core=args.project/'rtl/coco3fpga.sv'
|
||||
reference=original.read_text();reference=reference[reference.index('module sdc_dpram'):]
|
||||
text=candidate.read_text();text=text[text.index('module sdc_dpram'):]
|
||||
# Both CPU RAM address/data/enable expressions must remain identical.
|
||||
for field in ('address_b','data_b','wren_b'):
|
||||
pattern=r'\.'+field+r'\(([^\n]+)\)'
|
||||
if re.search(pattern,original.read_text()).group(1)!=re.search(pattern,candidate.read_text()).group(1):
|
||||
raise RuntimeError('SDC CPU port changed: '+field)
|
||||
instance=core.read_text().split('VDAC\tVDAC_inst (',1)[1].split(');',1)[0]
|
||||
clock=re.search(r'\.wrclock\s*\(\s*([^\)]+)\)',instance).group(1).strip()
|
||||
if clock!='~clk_sys':raise RuntimeError('Unexpected VDAC write phase')
|
||||
for field in ('data','wraddress'):
|
||||
baseline=(original_sources('coco3-mister')/'rtl/coco3fpga.sv').read_text().split('VDAC\tVDAC_inst (',1)[1].split(');',1)[0]
|
||||
pattern=r'\.'+field+r'\s*\(([^\n]+)\)'
|
||||
if re.search(pattern,baseline).group(1)!=re.search(pattern,instance).group(1):raise RuntimeError('VDAC payload changed')
|
||||
wren=re.search(r'\.wren\s*\(([^\n]+)\)',instance).group(1).strip()
|
||||
compact=re.sub(r'\s+','',wren)
|
||||
has_ssc=bool(re.search(r'\bssc_cartridge\s*#',core.read_text()))
|
||||
required='VDAC_EN&PH_2&ssc_palette_owner' if has_ssc else 'VDAC_EN&PH_2'
|
||||
if compact!=required:raise RuntimeError('Unexpected VDAC address ownership qualification')
|
||||
source=output/'actual-memory.sv'
|
||||
source.write_text(reference.replace('module sdc_dpram','module sdc_reference',1)+'\n'+text+
|
||||
'\nmodule actual_vdac_clock(input clk_sys,output q); assign q='+clock+'; endmodule\n'+
|
||||
'\nmodule actual_vdac_write(input PH_2,VDAC_EN,ssc_palette_owner,output q,output supports_ssc); assign q='+wren+
|
||||
"; assign supports_ssc=1'b"+str(int(has_ssc))+'; endmodule\n',encoding='utf-8')
|
||||
bench=ROOT/'tests/peripheral_phase_tb.sv'
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(args.suite/'bin'),str(args.suite/'lib'),env['PATH']])
|
||||
ext='.exe' if os.name=='nt' else ''
|
||||
with (output/'compile.log').open('w') as log:
|
||||
subprocess.run([str(args.suite/'bin'/('iverilog'+ext)),'-g2012','-s','peripheral_phase_tb','-o',str(output/'test.vvp'),str(bench),str(source)],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
with (output/'test.log').open('w') as log:
|
||||
subprocess.run([str(args.suite/'bin'/('vvp'+ext)),str(output/'test.vvp')],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
print((output/'test.log').read_text())
|
||||
paths=[original,candidate,core,source,bench,Path(__file__),output/'test.log']
|
||||
(output/'test-result.json').write_text(json.dumps({'passed':True,'hardware_tested':False,'sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}},indent=2)+'\n',encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test new request boundary with actual SDRAM controller and complete boot logic."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from source_snapshot import original_sources
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def boot_declarations(text):
|
||||
constants=re.findall(r'^localparam\s+inst_\w+\s*=[^;]+;',text,re.M)
|
||||
for declaration in constants:
|
||||
text=text.replace(declaration,'',1)
|
||||
position=re.search(r'localparam\s+EE_PROG',text).start()
|
||||
return text[:position]+'\n'.join(constants)+'\n'+text[position:]
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('project',type=Path)
|
||||
parser.add_argument('output',type=Path)
|
||||
parser.add_argument('--suite',type=Path,required=True)
|
||||
args=parser.parse_args()
|
||||
output=args.output.resolve()
|
||||
if not output.is_relative_to((ROOT/'build').resolve()) or output.exists():
|
||||
parser.error('Use a new output directory inside build/')
|
||||
output.mkdir(parents=True)
|
||||
# Icarus does not accept procedural assignment to Quartus's inout reg.
|
||||
# Model that exact bidirectional driver with an internal reg + continuous wire.
|
||||
controller=args.project/'rtl/sdram/sdram2.sv'
|
||||
text=controller.read_text()
|
||||
text=text.replace('inout reg [15:0] SDRAM_DQ','inout wire [15:0] SDRAM_DQ',1)
|
||||
text=text.replace('assign SDRAM_nCS = 0;', 'reg [15:0] dq_drive;\nassign SDRAM_DQ = dq_drive;\nassign SDRAM_nCS = 0;',1)
|
||||
text=text.replace('SDRAM_DQ <=','dq_drive <=')
|
||||
# Icarus requires these part-select/continuous-assignment operands declared
|
||||
# before use. Move declarations only, retaining width and all behavior.
|
||||
declarations=[]
|
||||
for name in ['command','dq_reg']:
|
||||
declaration=re.search(r'^reg\s+\[[^\]]+\]\s+'+name+r';',text,re.M).group(0)
|
||||
text=text.replace(declaration,'',1)
|
||||
declarations.append(declaration)
|
||||
text=text.replace('reg [15:0] dq_drive;', '\n'.join(declarations)+'\nreg [15:0] dq_drive;',1)
|
||||
# The unused board clock-output DDIO primitive has no effect on controller
|
||||
# state or this bench's constant read bus; model its configured inversion.
|
||||
text=text[:text.index('\naltddio_out')]+ '\nassign SDRAM_CLK = ~clk;\nendmodule\n'
|
||||
normalized=output/'sdram-icarus.sv'
|
||||
normalized.write_text(text,encoding='utf-8')
|
||||
original=original_sources('coco3-mister')/'rtl/EE_Cold_Bt.v'
|
||||
reference=output/'boot-reference.v'
|
||||
reference.write_text(boot_declarations(original.read_text()).replace('module EE_Cold_Bt','module EE_Cold_Bt_reference',1),encoding='utf-8')
|
||||
boot_candidate=output/'boot-candidate.v'
|
||||
boot_candidate.write_text(boot_declarations((args.project/'rtl/EE_Cold_Bt.v').read_text()),encoding='utf-8')
|
||||
env=os.environ.copy()
|
||||
env['PATH']=os.pathsep.join([str(args.suite/'bin'),str(args.suite/'lib'),env['PATH']])
|
||||
ext='.exe' if os.name=='nt' else ''
|
||||
results={}
|
||||
for name,files in [('bridge_protocol_tb',[ROOT/'tests/bridge_protocol_tb.sv',args.project/'rtl/cpu_sdram_bridge.sv']),('cpu_sdram_bridge_tb',[ROOT/'tests/cpu_sdram_bridge_tb.sv',args.project/'rtl/cpu_sdram_bridge.sv',normalized]),('boot_control_tb',[ROOT/'tests/boot_control_tb.sv',boot_candidate,reference])]:
|
||||
with (output/(name+'-compile.log')).open('w') as file:
|
||||
subprocess.run([str(args.suite/'bin'/('iverilog'+ext)),'-g2012','-s',name,'-o',str(output/(name+'.vvp')),*map(str,files)],env=env,stdout=file,stderr=subprocess.STDOUT,check=True)
|
||||
log=output/(name+'.log')
|
||||
with log.open('w') as file:
|
||||
subprocess.run([str(args.suite/'bin'/('vvp'+ext)),str(output/(name+'.vvp'))],env=env,stdout=file,stderr=subprocess.STDOUT,check=True)
|
||||
print(log.read_text(),flush=True)
|
||||
results[name]={'sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [*files,log]}}
|
||||
results['hardware_tested']=False
|
||||
results['sdram_model_limit']='Actual RTL controller; inout-reg driver adaptation and unused clock-output DDIO model; constant read bus, no physical SDRAM array/timing model'
|
||||
(output/'test-result.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test exact consumer reset chains and disk-buffer pipeline cadence contracts."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('project',type=Path)
|
||||
parser.add_argument('output',type=Path)
|
||||
parser.add_argument('--suite',type=Path,required=True)
|
||||
args=parser.parse_args()
|
||||
output=args.output.resolve()
|
||||
if not output.is_relative_to((ROOT/'build').resolve()) or output.exists():parser.error('Use a new output directory inside build/')
|
||||
output.mkdir(parents=True)
|
||||
core=(args.project/'rtl/coco3fpga.sv').read_text()
|
||||
start=core.index('(* preserve *) reg [1:0] reset_main_release')
|
||||
end=core.index('reg\t\t[6:0]\tCPU_RESET_SM;',start)
|
||||
block=core[start:end]
|
||||
for name in ['RESET_N','RESET_POS_N','RESET_FAST_N']:
|
||||
block=block.replace('wire '+name+' =','assign '+name+' =')
|
||||
stages='module actual_reset_domains(input clk_sys,CLK_114,RESET_RAW_N,output RESET_N,RESET_POS_N,RESET_FAST_N);\n'+block+'\nendmodule\n'
|
||||
fdc=(args.project/'rtl/fdc.sv').read_text()
|
||||
start=fdc.index('(* preserve *) reg [1:0] wd_reset_release')
|
||||
end=fdc.index('always@',start)
|
||||
stages+='module actual_wd_release(input CLK,RESET_N,output WD_RESET_N);\n'+fdc[start:end]+'\nassign WD_RESET_N=wd_reset_release[1];\nendmodule\n'
|
||||
if '// Research: matching fast-clock' in core:
|
||||
start=core.index('// Research: matching fast-clock')
|
||||
end=core.index('localparam Sz_512K',start)
|
||||
block=core[start:end].replace('reg data_ready_phase;','').replace('reg [15:0] hold_data_phase;','')
|
||||
stages+='module actual_completion(input CLK_114,clear_data_ready,sdram_cpu_ready,input [15:0] sdram_dout,output reg data_ready_phase,output reg [15:0] hold_data_phase);\nreg data_ready;reg [15:0] hold_data;\n'+block+'\nendmodule\n'
|
||||
sdc=(args.project/'rtl/sdc.sv').read_text()
|
||||
wd=(args.project/'rtl/wd1793.sv').read_text()
|
||||
if '(* preserve *) reg [7:0] cpu_buffer_pipe;' in sdc:
|
||||
start=sdc.index('(* preserve *) reg [7:0] cpu_buffer_pipe;')
|
||||
end=sdc.index('sdc_dpram hd_buff',start)
|
||||
stages+='module actual_sdc_pipeline(input CLK,input [7:0] hd_buff_data_raw,output [7:0] hd_buff_data);\n'+sdc[start:end]+'\nendmodule\n'
|
||||
else:
|
||||
assert '.q_b(hd_buff_data)' in sdc and 'always_ff@(negedge clock)' in sdc
|
||||
stages+='module actual_sdc_pipeline(input CLK,input [7:0] hd_buff_data_raw,output [7:0] hd_buff_data); assign hd_buff_data=hd_buff_data_raw; endmodule\n'
|
||||
if '(* preserve *) reg [7:0] cpu_buffer_pipe;' in wd:
|
||||
start=wd.index('(* preserve *) reg [7:0] cpu_buffer_pipe;')
|
||||
end=wd.index('always @*',start)
|
||||
stages+='module actual_wd_pipeline(input clk_sys,RWMODE,input [7:0] buff_dout,buff_din,output [7:0] q);\n'+wd[start:end]+'\nassign q=cpu_buffer_pipe;\nendmodule\n'
|
||||
else:
|
||||
assert 'buff_rd ? (RWMODE ? buff_dout : buff_din) :' in wd
|
||||
stages+='module actual_wd_pipeline(input clk_sys,RWMODE,input [7:0] buff_dout,buff_din,output [7:0] q); assign q=RWMODE?buff_dout:buff_din; endmodule\n'
|
||||
# Verify the actual wrapper inversion, not just the leaf module clock name.
|
||||
for name,count in [('fdc.sv',4),('sdc_top.sv',2)]:
|
||||
if (args.project/'rtl'/name).read_text().count('.clk_sys(~CLK)')!=count:raise RuntimeError('WD clock binding changed')
|
||||
stages+=sdc[sdc.index('module sdc_dpram'):]+'\n'+wd[wd.index('module wd1793_dpram'):]
|
||||
source=output/'actual-domains-buffers.sv';source.write_text(stages,encoding='utf-8')
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(args.suite/'bin'),str(args.suite/'lib'),env['PATH']])
|
||||
ext='.exe' if os.name=='nt' else '';results={}
|
||||
cases=[('domains','reset_domains_tb',False),('buffers','disk_buffer_pipeline_tb',False),('buffers-negative','disk_buffer_pipeline_tb',True)]
|
||||
if 'module actual_completion' in stages:cases.append(('completion','completion_phase_tb',False))
|
||||
for name,top,negative in cases:
|
||||
bench=ROOT/'tests'/(top+'.sv')
|
||||
with (output/(name+'-compile.log')).open('w') as log:
|
||||
subprocess.run([str(args.suite/'bin'/('iverilog'+ext)),'-g2012',*(['-DNEGATIVE_CONSECUTIVE'] if negative else []),'-s',top,'-o',str(output/(name+'.vvp')),str(bench),str(source)],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
log=output/(name+'.log')
|
||||
with log.open('w') as file:run=subprocess.run([str(args.suite/'bin'/('vvp'+ext)),str(output/(name+'.vvp'))],env=env,stdout=file,stderr=subprocess.STDOUT)
|
||||
text=log.read_text();print(text,flush=True)
|
||||
if negative:
|
||||
if run.returncode==0 or not any(message in text for message in ['CPU observed stale disk buffer','unsupported consecutive CPU disk read']):raise RuntimeError('Unsupported consecutive-enable negative control missing')
|
||||
print('PASS negative control: CPU buffer read phases require the proven nonconsecutive enable contract')
|
||||
elif run.returncode:raise RuntimeError('Regression failed: '+name)
|
||||
results[name]={'exit':run.returncode,'sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in [bench,source,log]}}
|
||||
results['hardware_tested']=False
|
||||
(output/'test-result.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test actual prepared core SSC instantiations, without replacing chip logic."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
from validation_common import ROOT,digest
|
||||
from rom_inputs import ROM_IDENTITIES,verified_rom
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('project',type=Path);parser.add_argument('output',type=Path);parser.add_argument('--suite',type=Path,required=True)
|
||||
args=parser.parse_args();project=args.project.resolve();output=args.output.resolve();suite=args.suite.resolve()
|
||||
if output.exists() or not output.is_relative_to((ROOT / 'build').resolve()):parser.error('Use a fresh build/ output')
|
||||
output.mkdir(parents=True);core=project / 'rtl/coco3fpga.sv';text=core.read_text()
|
||||
top=project / 'CoCo3.sv';top_text=top.read_text()
|
||||
pll=re.search(r'\bpll\s+pll\s*\((.*?)\);',top_text,re.S)
|
||||
lock=re.search(r'\.locked\(\s*(\w+)\s*\)',pll[1]) if pll else None
|
||||
reset_binding=re.search(r'\.SSC_POWER_RESET\(ssc_power_reset\)',top_text)
|
||||
if not lock or not reset_binding or not re.search(r'always\s*@\(posedge clk_sys or negedge '+re.escape(lock[1])+r'\)\s*if\(!'+re.escape(lock[1])+r'\) ssc_power_release <= 2\x27b00;',top_text):
|
||||
raise RuntimeError('SSC power reset is not driven by the actual core PLL lock output')
|
||||
if "else ssc_power_release <= {ssc_power_release[0],1'b1};" not in top_text or 'wire ssc_power_reset = !ssc_power_release[1];' not in top_text:
|
||||
raise RuntimeError('SSC power reset release contract changed')
|
||||
if not re.search(r'\.SSC_MODE\(status\[42\]\)',top_text):raise RuntimeError('SSC menu mode binding changed')
|
||||
if not re.search(r'assign\s+DATA_IN\s*=\s*ssc_read_valid\s*\?\s*ssc_read_data\s*:',text):raise RuntimeError('SSC CPU read-priority binding changed')
|
||||
declarations=text[text.index('wire ssc_palette_owner,'):text.index('wire [15:0] ssc_legacy_left,ssc_legacy_right;')+len('wire [15:0] ssc_legacy_left,ssc_legacy_right;')]
|
||||
body=text[text.index('assign ssc_legacy_left ='):text.index('.debug_pc(ssc_debug_pc));')+len('.debug_pc(ssc_debug_pc));')]
|
||||
routing=''
|
||||
if 'bh_mpi_router mpi_router' in text:
|
||||
start=text.index('wire [2:0] mpi_rom_kind,mpi_io_kind;')
|
||||
end=text.index("wire [7:0] mpi_orch_right=mpi_orchestra_present?ORCH_RIGHT:8'h80;",start)
|
||||
routing="wire MPI_BOOT_LOADING=0;\nwire [1:0] MPI_CTS=0,MPI_SCS=0;\n"+text[start:end+len("wire [7:0] mpi_orch_right=mpi_orchestra_present?ORCH_RIGHT:8'h80;")]
|
||||
generated=output / 'actual-bindings.sv'
|
||||
power_start=top_text.index('(* preserve, altera_attribute',top_text.index('// Cartridge ROM validity'))
|
||||
power_end=top_text.index('wire ssc_power_reset = !ssc_power_release[1];',power_start)+len('wire ssc_power_reset = !ssc_power_release[1];')
|
||||
power_block=top_text[power_start:power_end].replace('wire ssc_power_reset =','assign ssc_power_reset =')
|
||||
generated.write_text('module actual_ssc_power_reset(input clk_sys,'+lock[1]+',output ssc_power_reset);\n'+power_block+'\nendmodule\n'+'''module actual_ssc_mister_system(input clk_sys,SSC_POWER_RESET,RESET_POS_N,SSC_MODE,PH_2,RW_N,
|
||||
input [15:0] ADDRESS,input [7:0] DATA_OUT,input [11:0] MPI_LAYOUT,input ioctl_download,ioctl_wr,input [15:0] ioctl_index,
|
||||
input [24:0] ioctl_addr,input [7:0] ioctl_data,input SOUND_EN,input [1:0] SEL,
|
||||
input [7:0] ORCH_LEFT,ORCH_RIGHT,SOUND,output SSC_READY,SSC_FAULT,
|
||||
output [15:0] SOUND_LEFT,SOUND_RIGHT,output READ_VALID,output [7:0] READ_DATA,output PALETTE_OWNER);
|
||||
'''+routing+'\n'+declarations+'\n'+body+'''
|
||||
assign READ_VALID=ssc_read_valid;assign READ_DATA=ssc_read_data;assign PALETTE_OWNER=ssc_palette_owner;
|
||||
endmodule
|
||||
''',encoding='utf-8',newline='\n')
|
||||
folder=project / 'rtl/ssc';sources=sorted(folder.glob('*.sv'));bench=ROOT / 'tests/ssc_mister_system_tb.sv'
|
||||
if routing:sources.append(project/'rtl/bh_mpi_router.sv')
|
||||
paths=[Path(__file__),ROOT / 'scripts/validation_common.py',ROOT / 'scripts/rom_inputs.py',core,top,generated,bench,*sources,*folder.glob('*.vh')]
|
||||
hashes={str(p):digest(p) for p in paths};roms=ROOT / 'roms/ssc'
|
||||
identities={name:verified_rom(roms / name,value) for name,value in ROM_IDENTITIES.items()}
|
||||
env=os.environ.copy();env['PATH']=os.pathsep.join([str(suite / 'bin'),str(suite / 'lib'),env['PATH']]);ext='.exe' if os.name=='nt' else '';binary=output / 'system.vvp'
|
||||
with (output / 'compile.log').open('w') as log:
|
||||
subprocess.run([str(suite / 'bin' / ('iverilog'+ext)),'-g2012','-I',str(folder),'-s','ssc_mister_system_tb','-o',str(binary),str(bench),str(generated),*map(str,sources)],env=env,stdout=log,stderr=subprocess.STDOUT,check=True)
|
||||
process=subprocess.Popen([str(suite / 'bin' / ('vvp'+ext)),str(binary),'+PIC_PATH='+(roms / 'pic-7040-510.bin').as_posix(),'+SPEECH_PATH='+(roms / 'sp0256-al2.bin').as_posix()],cwd=output,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,bufsize=1)
|
||||
timer=threading.Timer(900,process.kill);timer.start();summary=None
|
||||
try:
|
||||
with (output / 'rtl.log').open('w') as log:
|
||||
for line in process.stdout:
|
||||
print(line.rstrip(),flush=True);log.write(line);log.flush()
|
||||
if line.startswith('RESULT '):summary=json.loads(line[7:])
|
||||
code=process.wait()
|
||||
finally:
|
||||
timer.cancel()
|
||||
if process.poll() is None:process.kill();process.wait()
|
||||
if code or not summary or not summary['passed']:raise RuntimeError('Actual core SSC bindings failed; inspect rtl.log')
|
||||
if any(digest(Path(p))!=h for p,h in hashes.items()):raise RuntimeError('Actual core/test source changed during run')
|
||||
for name,value in ROM_IDENTITIES.items():verified_rom(roms / name,value)
|
||||
hashes.update({str(p):digest(p) for p in output.glob('*.log')})
|
||||
(output / 'test-result.json').write_text(json.dumps({'passed':True,'roms':identities,'summary':summary,'sha256':hashes,
|
||||
'hardware_tested':False,'scope':'Actual extracted prepared-core SSC bindings with real chip RTL; CPU/HPS stimulus, not full CoCo CPU/vendor-IP or physical run'},indent=2)+'\n',encoding='utf-8',newline='\n')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare real video fetch/controller behavior before and after activation staging."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def normalize_controller(text, name):
|
||||
# Same driver/declaration adaptation as test_registered_interfaces.py.
|
||||
text = text.replace('module sdram_32r8w', 'module ' + name, 1)
|
||||
text = text.replace('inout reg [15:0] SDRAM_DQ', 'inout wire [15:0] SDRAM_DQ', 1)
|
||||
declarations = []
|
||||
for register in ('command', 'dq_reg'):
|
||||
declaration = re.search(r'^reg\s+\[[^\]]+\]\s+' + register + r';', text, re.M).group()
|
||||
text = text.replace(declaration, '', 1)
|
||||
declarations.append(declaration)
|
||||
text = text.replace('assign SDRAM_nCS = 0;', '\n'.join(declarations) +
|
||||
'\nreg [15:0] dq_drive;\nassign SDRAM_DQ = dq_drive;\nassign SDRAM_nCS = 0;', 1)
|
||||
text = text.replace('SDRAM_DQ <=', 'dq_drive <=')
|
||||
return text[:text.index('\naltddio_out')] + '\nassign SDRAM_CLK = ~clk;\nendmodule\n'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('reference', type=Path)
|
||||
parser.add_argument('candidate', type=Path)
|
||||
parser.add_argument('output', type=Path)
|
||||
parser.add_argument('--suite', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
if not output.is_relative_to((ROOT / 'build').resolve()) or output.exists():
|
||||
parser.error('Use a fresh output directory inside build/')
|
||||
output.mkdir(parents=True)
|
||||
sources = []
|
||||
for name, project in [('reference', args.reference), ('candidate', args.candidate)]:
|
||||
path = project / 'rtl/sdram/sdram2.sv'
|
||||
sources.append(path)
|
||||
(output / (name + '.sv')).write_text(normalize_controller(path.read_text(), 'sdram_' + name), encoding='utf-8')
|
||||
fetch = args.candidate / 'rtl/coco_mem_fetch.sv'
|
||||
sources.append(fetch)
|
||||
if fetch.read_bytes() != (args.reference / 'rtl/coco_mem_fetch.sv').read_bytes():
|
||||
raise RuntimeError('This comparison expects an unchanged video fetcher')
|
||||
text = fetch.read_text()
|
||||
# Quartus accepts procedural assignment to these implicit output nets;
|
||||
# Icarus needs the explicit variable type. No expression/state edits.
|
||||
for name in ('SDRAM_VID_REQ', 'BUFF_ADD', 'BUFF_DATA_O', 'BUFFER_WRITE'):
|
||||
text, n = re.subn(r'(output\s+)(?!reg)(\[[^\]]+\]\s*)?(' + name + r'\b)', r'\1reg \2\3', text, count=1)
|
||||
if n != 1:
|
||||
raise RuntimeError('Unexpected fetch output declaration: ' + name)
|
||||
text = re.sub(r'wire(\s+\[2:0\]\s+BUF_HBORDER;)', r'reg\1', text, count=1)
|
||||
(output / 'fetch.sv').write_text(text, encoding='utf-8')
|
||||
bench = ROOT / 'tests/video_sdram_tb.sv'
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.pathsep.join([str(args.suite / 'bin'), str(args.suite / 'lib'), env['PATH']])
|
||||
ext = '.exe' if os.name == 'nt' else ''
|
||||
command = [str(args.suite / 'bin' / ('iverilog' + ext)), '-g2012', '-s', 'video_sdram_tb',
|
||||
'-o', str(output / 'test.vvp'), str(bench), *map(str, output.glob('*.sv'))]
|
||||
for name, project in [('REFERENCE', args.reference), ('CANDIDATE', args.candidate)]:
|
||||
extra = re.search(r'localparam READ_CAPTURE_EXTRA\s*=\s*(\d+)', (project / 'rtl/sdram/sdram2.sv').read_text())
|
||||
if extra:
|
||||
# Model a declared extra return cycle, independently of the FSM.
|
||||
command.insert(1, '-D' + name + '_RETURN_DELAY=' + str(10 * int(extra[1])))
|
||||
with (output / 'compile.log').open('w') as log:
|
||||
subprocess.run(command, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (output / 'test.log').open('w') as log:
|
||||
subprocess.run([str(args.suite / 'bin' / ('vvp' + ext)), str(output / 'test.vvp')],
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=180)
|
||||
print((output / 'test.log').read_text())
|
||||
# An actual address error must be caught by the data oracle. Keep the
|
||||
# perturbation solely in this generated simulation copy.
|
||||
negative = output / 'candidate.sv'
|
||||
original = negative.read_text()
|
||||
corrupted, changed = re.subn(r'video_address_snapshot\[24:1\]',
|
||||
r'{video_address_snapshot[24:2],~video_address_snapshot[1]}', original)
|
||||
if changed != 1:
|
||||
raise RuntimeError('Expected exactly one video activation address')
|
||||
negative.write_text(corrupted, encoding='utf-8')
|
||||
try:
|
||||
negative_command = command.copy()
|
||||
negative_command[negative_command.index('-o') + 1] = str(output / 'negative.vvp')
|
||||
with (output / 'negative-compile.log').open('w') as log:
|
||||
subprocess.run(negative_command, env=env, stdout=log, stderr=subprocess.STDOUT, check=True)
|
||||
with (output / 'negative.log').open('w') as log:
|
||||
failed = subprocess.run([str(args.suite / 'bin' / ('vvp' + ext)), str(output / 'negative.vvp')],
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT, timeout=180)
|
||||
if failed.returncode == 0 or 'video data channel=1' not in (output / 'negative.log').read_text():
|
||||
raise RuntimeError('Corrupted video-address negative control did not fail as expected')
|
||||
finally:
|
||||
negative.write_text(original, encoding='utf-8')
|
||||
print('PASS negative control: corrupting the candidate video address fails the data oracle')
|
||||
hashes = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in [*sources, bench, Path(__file__)]}
|
||||
(output / 'test-result.json').write_text(json.dumps({
|
||||
'passed': True, 'negative_control_passed': True, 'hardware_tested': False, 'input_sha256': hashes,
|
||||
'model_limit': 'Logical SDRAM read-command/CL3/two-word burst model; no electrical/device timing or video pixel rendering.',
|
||||
'log': (output / 'test.log').read_text(),
|
||||
}, indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
# Fitted UART diagnostics, both timing corners; no changes to project assignments.
|
||||
# quartus_sta -t uart_timing_paths.tcl PROJECT REVISION OUTPUT_DIRECTORY
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [lindex $quartus(args) 0]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
project_open $project -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
# Include the MiSTer wrapper's enable generator/reset chain, not just RS232.
|
||||
set uart [get_registers {*RS232|* *COM1|* *|CLK_6551* *|uart_tick_release* dw_top_release[*] dw_mode* dw_base_d COM1_CLOCK* COM1_STATE* COM1_CLK*}]
|
||||
if {[get_collection_size $uart] == 0} {error "Expected fitted UART registers"}
|
||||
puts "UART_REGISTERS $model [get_collection_size $uart]"
|
||||
foreach check {setup hold recovery removal} {
|
||||
report_timing -$check -npaths 3 -detail full_path \
|
||||
-file [file join $output global-${model}-${check}.rpt]
|
||||
report_timing -$check -to $uart -npaths 20 -detail full_path \
|
||||
-file [file join $output uart-${model}-${check}.rpt]
|
||||
report_timing -$check -from $uart -npaths 10 -detail full_path \
|
||||
-file [file join $output uart-out-${model}-${check}.rpt]
|
||||
}
|
||||
set cfg [get_registers {*RS232|CTL_REG[*] *RS232|CMD_REG[*] *COM1|CTL_REG[*]}]
|
||||
report_timing -setup -from $cfg -to $uart -npaths 10 -detail full_path \
|
||||
-file [file join $output uart-config-${model}-setup.rpt]
|
||||
report_timing -hold -from $cfg -to $uart -npaths 10 -detail full_path \
|
||||
-file [file join $output uart-config-${model}-hold.rpt]
|
||||
if {$model eq "slow"} {
|
||||
set audit [open [file join $output uart-register-clocks.tsv] w]
|
||||
puts $audit "register\tclock_pin\tclock_driver"
|
||||
foreach_in_collection reg $uart {
|
||||
foreach edge [get_register_info -clock_edges $reg] {
|
||||
set source [get_edge_info -src $edge]
|
||||
foreach input_edge [get_node_info -clock_edges $source] {
|
||||
set driver [get_edge_info -src $input_edge]
|
||||
puts $audit "[get_register_info -name $reg]\t[get_node_info -name $source]\t[get_node_info -name $driver]"
|
||||
}
|
||||
}
|
||||
}
|
||||
close $audit
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_clock_transfers -file [file join $output clock-transfers.rpt]
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close
|
||||
@@ -0,0 +1,25 @@
|
||||
import hashlib, os, shutil, subprocess
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
def cpp_environment(output):
|
||||
env = os.environ.copy()
|
||||
if os.name != 'nt':
|
||||
return os.environ.get('CXX', 'c++'), env
|
||||
finder = Path(os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')) / 'Microsoft Visual Studio/Installer/vswhere.exe'
|
||||
vs = subprocess.check_output([str(finder), '-latest', '-version', '[17.0,18.0)',
|
||||
'-products', '*', '-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
|
||||
'-property', 'installationPath'], text=True).strip()
|
||||
if not vs or any(c in vs for c in '%!"&^<>\r\n'):
|
||||
raise RuntimeError('No usable VS2022 C++ toolchain')
|
||||
batch = output / 'vs-environment.cmd'
|
||||
batch.write_text(f'@echo off\ncall "{vs}/Common7/Tools/VsDevCmd.bat" -arch=x64 -host_arch=x64 >nul\nif errorlevel 1 exit /b %errorlevel%\nset\n', encoding='utf-8')
|
||||
setup = subprocess.check_output([os.environ.get('COMSPEC', 'cmd.exe'), '/d', '/c', str(batch)], text=True, errors='replace')
|
||||
# Developer environment may contain private values; never print or save it.
|
||||
env.update((key.upper(), value) for key, value in
|
||||
(line.split('=', 1) for line in setup.splitlines() if '=' in line and not line.startswith('=')))
|
||||
compiler = shutil.which('cl.exe', path=env['PATH'])
|
||||
if not compiler:
|
||||
raise RuntimeError('VS environment did not provide cl.exe')
|
||||
return compiler, env
|
||||
@@ -0,0 +1,43 @@
|
||||
# quartus_sta -t video_timing_paths.tcl PROJECT REVISION OUTPUT_DIRECTORY
|
||||
package require ::quartus::project
|
||||
package require ::quartus::sta
|
||||
set project [lindex $quartus(args) 0]
|
||||
set revision [lindex $quartus(args) 1]
|
||||
set output [file normalize [lindex $quartus(args) 2]]
|
||||
file mkdir $output
|
||||
project_open $project -revision $revision
|
||||
foreach model {slow fast} {
|
||||
create_timing_netlist -model $model
|
||||
read_sdc
|
||||
update_timing_netlist
|
||||
set snapshot [get_registers {*coco3_sdram|video_address_snapshot[*]*}]
|
||||
set fetch [get_registers {*video_fetch|*}]
|
||||
set controller [get_registers {*coco3_sdram|*}]
|
||||
set source [get_registers {*MISTER_COCOVID|ROW_ADD[*]* *MISTER_COCOVID|SCREEN_START_ADD[*]*}]
|
||||
foreach {name collection minimum} [list snapshot $snapshot 20 fetch $fetch 10 controller $controller 40 source $source 20] {
|
||||
set count [get_collection_size $collection]
|
||||
puts "VIDEO_SCOPE $model $name $count"
|
||||
if {$count < $minimum} {error "Incomplete video timing scope: $name"}
|
||||
}
|
||||
foreach check {setup hold} {
|
||||
report_timing -$check -from $source -to $snapshot -npaths 30 -detail full_path \
|
||||
-file [file join $output address-${model}-${check}.rpt]
|
||||
report_timing -$check -from $snapshot -to $controller -npaths 30 -detail full_path \
|
||||
-file [file join $output activation-${model}-${check}.rpt]
|
||||
report_timing -$check -to $fetch -npaths 30 -detail full_path \
|
||||
-file [file join $output fetch-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $fetch -npaths 30 -detail full_path \
|
||||
-file [file join $output fetch-out-${model}-${check}.rpt]
|
||||
report_timing -$check -to $controller -npaths 30 -detail full_path \
|
||||
-file [file join $output controller-in-${model}-${check}.rpt]
|
||||
report_timing -$check -from $controller -npaths 30 -detail full_path \
|
||||
-file [file join $output controller-out-${model}-${check}.rpt]
|
||||
}
|
||||
if {$model eq "slow"} {
|
||||
report_clocks -file [file join $output clocks.rpt]
|
||||
report_ucp -file [file join $output unconstrained.rpt]
|
||||
report_exceptions -file [file join $output exceptions.rpt]
|
||||
}
|
||||
delete_timing_netlist
|
||||
}
|
||||
project_close
|
||||
Reference in new issue
Block a user