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:
bholman committed 2026-11-18 16:00:45 -07:00
1 parent 8b8cf72d1f
commit cb40fed3b9
126 files changed
+12795 -528

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Audit actual fitted timing paths without treating empty scopes as passes."""
import argparse,hashlib,json,re,subprocess
from pathlib import Path
from timing_coverage import parse_ucp,classify
ROOT=Path(__file__).resolve().parents[1]
AUDITS=('bh_mpi_timing','nmi_timing_paths','uart_timing_paths','reset_cpu_timing_paths','video_timing_paths','ssc_integrated_timing','external_io_timing')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--quartus',type=Path,required=True,help='quartus_sta 17.0.2')
p.add_argument('--build',type=Path,default=ROOT/'build/fpga')
p.add_argument('--output',type=Path,default=ROOT/'build/timing')
p.add_argument('--resume',action='store_true',help='Reuse complete native logs; recheck all report hashes/paths')
a=p.parse_args();a.build=a.build.resolve();a.output=a.output.resolve()
if not a.output.is_relative_to(ROOT/'build'):p.error('Use an output inside build/')
build=json.loads((a.build/'build.json').read_text());project=a.build/'project'
if not build.get('passed'):raise RuntimeError('Full fit with nonnegative summary required')
for n,h in build['inputs'].items():
if sha(project/n)!=h or sha(ROOT/n)!=h:raise RuntimeError('Fitted/current input differs: '+n)
identity=dict(rbf_sha256=build['rbf_sha256'],inputs=build['inputs'],
fitted_sof_sha256=sha(project/'output_files/CoCo3.sof'),
scripts={name:sha(ROOT/'scripts'/(name+'.tcl')) for name in AUDITS})
if a.output.exists() and not a.resume:raise RuntimeError('Preserve earlier diagnostics; choose a fresh output')
a.output.mkdir(parents=True,exist_ok=True)
identity_file=a.output/'audit-input.json'
if a.resume:
if not identity_file.is_file() or json.loads(identity_file.read_text())!=identity:raise RuntimeError('Resumed audit does not match the fitted build and original scripts')
else:identity_file.write_text(json.dumps(identity,indent=2)+'\n')
results={}
for script in AUDITS:
out=a.output/script;log=a.output/(script+'.log')
print('AUDIT '+script,flush=True)
if not a.resume:
if log.exists() or out.exists():raise RuntimeError('Existing partial audit: '+script)
with log.open('w') as f:subprocess.run([str(a.quartus.resolve()),'-t',str(ROOT/'scripts'/(script+'.tcl')),str(project/'CoCo3'),'CoCo3',str(out)],stdout=f,stderr=subprocess.STDOUT,cwd=ROOT,check=True)
text=log.read_text(errors='replace')
if 'Quartus Prime TimeQuest Timing Analyzer was successful. 0 errors' not in text:raise RuntimeError('Incomplete native audit: '+script)
reports={};empty=[]
for path in sorted(out.glob('*.rpt')):
name=path.name
if not re.search(r'-(setup|hold|recovery|removal)\.rpt$',name):continue
if script=='external_io_timing':
expected=['sdram_dq-in','sdram_dq-out','sdram_command-out','hdmi-scaled','hdmi-direct','hdmi_audio-out','mcp_i2c-in','mcp_i2c-out','pixel-in','pixel-out','global']
if not any(name.startswith(n+'-') for n in expected):continue
values=[float(x) for x in re.findall(r'Worst case slack is ([-\d.]+)',path.read_text(errors='replace'))]
if any(x<0 for x in values):raise RuntimeError('Negative fitted timing: '+script+'/'+name)
if not values:
# Only asynchronous checks on synchronous-only subscopes may be empty.
if name.startswith('global-') or not re.search(r'-(recovery|removal)\.rpt$',name):raise RuntimeError('Empty substantive timing scope: '+script+'/'+name)
empty.append(name)
reports[name]=dict(slack_ns=min(values) if values else None,sha256=sha(path))
if script=='bh_mpi_timing' and len(reports)!=34:raise RuntimeError('MPI report inventory incomplete')
if script=='external_io_timing' and len(reports)!=48:raise RuntimeError('External report inventory incomplete')
if script=='ssc_integrated_timing' and len(reports)!=144:raise RuntimeError('SSC report inventory incomplete')
if script=='video_timing_paths' and len(reports)!=24:raise RuntimeError('Video report inventory incomplete')
if not reports:raise RuntimeError('No substantive report inventory: '+script)
results[script]=dict(reports=reports,empty_synchronous_async_checks=empty,log_sha256=sha(log),script_sha256=sha(ROOT/'scripts'/(script+'.tcl')))
if sha(project/'output_files/CoCo3.rbf')!=build['rbf_sha256']:raise RuntimeError('RBF changed during audit')
ucp=a.output/'external_io_timing/unconstrained.rpt'
counts,inventory=parse_ucp(ucp)
contracts={direction:{name:classify(name) for name in pins} for direction,pins in inventory.items()}
if any('UNCLASSIFIED' in value for pins in contracts.values() for value in pins.values()):raise RuntimeError('Unclassified remaining pin contract')
receipt=dict(audit_identity=identity,unconstrained_counts=counts,remaining_pin_contracts=contracts,coverage_sha256=sha(ucp),passed=True,rbf_sha256=build['rbf_sha256'],inputs=build['inputs'],audits=results,
scope='Both-corner fitted path audits under conditional SDRAM/PCB profile; not complete physical-board qualification',whole_board_electrically_qualified=False)
(a.output/'result.json').write_text(json.dumps(receipt,indent=2)+'\n')
print('PASS '+str(sum(len(v['reports']) for v in results.values()))+' fitted report scopes')
if __name__=='__main__':main()
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Download pinned public tools/sources; verify hashes before extraction/use."""
import argparse, hashlib, json, os, shutil, stat, tarfile, urllib.request, zipfile
from pathlib import Path, PurePosixPath
ROOT=Path(__file__).resolve().parents[1]
def sha(p):
h=hashlib.sha256()
with p.open('rb') as f:
for data in iter(lambda:f.read(1024*1024),b''):h.update(data)
return h.hexdigest()
def fetch(url,path,expected):
path.parent.mkdir(parents=True,exist_ok=True)
if path.exists():
if sha(path)!=expected:raise RuntimeError('Preserve invalid cached download: '+str(path))
return path
temporary=path.with_name(path.name+'.partial')
if temporary.exists():raise RuntimeError('Preserve incomplete download: '+str(temporary))
print('DOWNLOAD '+url,flush=True)
request=urllib.request.Request(url,headers={'User-Agent':'Coco3Plus-build/1.0'})
with urllib.request.urlopen(request,timeout=120) as response,temporary.open('xb') as out:
shutil.copyfileobj(response,out)
if sha(temporary)!=expected:raise RuntimeError('Download hash mismatch: '+str(temporary))
temporary.rename(path);return path
def safe_member(name):
p=PurePosixPath(name)
if p.is_absolute() or '..' in p.parts or '\\' in name or ':' in name:
raise RuntimeError('Unsafe archive member: '+name)
return p
def install_simulator(archive,folder,archive_hash):
marker='.coco3plus-install.json'
if folder.exists():
record=folder/marker
if not record.is_file():raise RuntimeError('Incomplete/legacy simulator directory; preserve it and use a fresh --simulator-dir: '+str(folder))
data=json.loads(record.read_text())
if data['archive_sha256']!=archive_hash:raise RuntimeError('Simulator archive identity changed')
for name,item in data['files'].items():
path=folder/safe_member(name)
if not path.is_file() or path.is_symlink() or path.stat().st_size!=item['bytes'] or sha(path)!=item['sha256']:raise RuntimeError('Simulator installation incomplete/changed: '+name)
return
partial=folder.with_name(folder.name+'.partial')
if partial.exists():raise RuntimeError('Preserve incomplete simulator extraction: '+str(partial))
partial.mkdir(parents=True);files={}
with tarfile.open(archive,'r:gz') as tar:
for member in tar.getmembers():
rel=safe_member(member.name);target=partial/rel
if not(member.isfile() or member.isdir()):raise RuntimeError('Unsupported simulator entry: '+member.name)
if member.isdir():target.mkdir(parents=True,exist_ok=True)
else:
if rel.as_posix() in files:raise RuntimeError('Duplicate simulator entry')
target.parent.mkdir(parents=True,exist_ok=True)
with tar.extractfile(member) as source,target.open('xb') as out:shutil.copyfileobj(source,out)
files[rel.as_posix()]={'bytes':target.stat().st_size,'sha256':sha(target)}
for binary in ('iverilog.exe','vvp.exe'):
if 'oss-cad-suite/bin/'+binary not in files:raise RuntimeError('Missing simulator executable: '+binary)
(partial/marker).write_text(json.dumps(dict(archive_sha256=archive_hash,files=files),indent=2)+'\n')
partial.rename(folder)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--cache',type=Path,default=ROOT/'.cache/downloads')
p.add_argument('--simulator-dir',type=Path,default=ROOT/'.tools/oss-cad')
p.add_argument('--only',choices=['lwtools','cocoroms','main','simulator'],nargs='+',default=['lwtools','cocoroms','main'])
a=p.parse_args();lock=json.loads((ROOT/'tools/toolchain.json').read_text())
if 'lwtools' in a.only:
if os.name!='nt':raise RuntimeError('The pinned prebuilt LWTools package is Windows x64. Supply native lwasm to build_roms.py on other systems.')
item=lock['lwtools_windows'];archive=fetch(item['url'],a.cache/item['archive'],item['sha256'])
folder=ROOT/'.tools/lwtools'
if not folder.exists():
folder.mkdir(parents=True)
with zipfile.ZipFile(archive) as z:
for m in z.infolist():
rel=safe_member(m.filename)
if stat.S_ISLNK(m.external_attr>>16):raise RuntimeError('Archive symlink')
target=folder/rel
if m.is_dir():target.mkdir(parents=True,exist_ok=True)
else:target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(z.read(m))
found=list(folder.rglob('lwasm.exe'))
if len(found)!=1 or sha(found[0])!=item['lwasm_sha256']:raise RuntimeError('Pinned LWASM not found or changed')
print('LWASM '+str(found[0]))
if 'cocoroms' in a.only:
item=json.loads((ROOT/'tools/cocoroms.json').read_text())
folder=ROOT/'.deps/cocoroms';folder.mkdir(parents=True,exist_ok=True)
for name,value in item['upstreamFileSHA256'].items():
url=f"https://raw.githubusercontent.com/nitros9project/toolshed/{item['sourceRevision']}/cocoroms/{name}"
cached=fetch(url,a.cache/('cocoroms-'+item['sourceRevision'])/name,value)
target=folder/name
if target.exists() and sha(target)!=value:raise RuntimeError('Prepared assembly changed: '+name)
if not target.exists():shutil.copyfile(cached,target)
print('ToolShed assembly: eight source files verified; no prebuilt ROM input')
if 'main' in a.only:
item=lock['main_reference'];folder=ROOT/'.deps/main';folder.mkdir(parents=True,exist_ok=True)
for name,record in item['files'].items():
cached=fetch(f"https://raw.githubusercontent.com/MiSTer-devel/Main_MiSTer/{item['revision']}/{name}",a.cache/('main-'+item['revision'])/name,record['sha256'])
target=folder/name
if target.exists() and sha(target)!=record['sha256']:raise RuntimeError('Main reference changed: '+name)
if not target.exists():shutil.copyfile(cached,target)
(folder/'provenance.json').write_text(json.dumps(item,indent=2)+'\n')
print('Main parser reference verified (not installed or modified)')
if 'simulator' in a.only:
item=lock['oss_cad_windows'];archive=fetch(item['url'],a.cache/item['archive'],item['sha256'])
folder=a.simulator_dir.resolve()
install_simulator(archive,folder,item['sha256'])
print('Simulator '+str(folder/'oss-cad-suite'))
if __name__=='__main__':main()
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Build in a fresh source copy using pinned Quartus; leave source/IP untouched."""
import argparse, datetime, hashlib, json, re, shutil, subprocess
from pathlib import Path,PurePosixPath
ROOT=Path(__file__).resolve().parents[1]
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--quartus',type=Path,required=True,help='Full path to quartus_sh.exe (17.0.2 Build602)')
p.add_argument('--output',type=Path,default=ROOT/'build/fpga')
p.add_argument('--prepare-only',action='store_true')
a=p.parse_args();a.output=a.output.resolve()
if not a.output.is_relative_to(ROOT/'build') or a.output.exists():raise RuntimeError('Use a fresh repository build/ directory')
version=subprocess.check_output([str(a.quartus.resolve()),'--version'],stderr=subprocess.STDOUT).decode()
if not re.search(r'17\.0\.2\s+Build\s+602',version):raise RuntimeError('Expected Quartus17.0.2 Build602: '+version)
inventory=json.loads((ROOT/'tools/project_inputs.json').read_text())
names=inventory['files']
if len(names)!=len(set(names)):raise RuntimeError('Duplicate project input')
for name in names:
relative=PurePosixPath(name)
if relative.is_absolute() or '..' in relative.parts or '\\' in name or ':' in name:raise RuntimeError('Unsafe project input: '+name)
if not (ROOT/name).is_file() or (ROOT/name).is_symlink():raise RuntimeError('Missing/nonregular project input: '+name)
# New HDL/IP/constraint files must not silently disappear from the build copy.
extensions={'.sv','.v','.vh','.vhd','.qip','.sdc','.mif','.hex','.qsys','.ip','.tcl'}
candidates=[p for folder in (ROOT/'rtl',ROOT/'sys') for p in folder.rglob('*') if p.is_file() and p.suffix.lower() in extensions]
candidates += [p for p in ROOT.iterdir() if p.is_file() and p.suffix.lower() in extensions]
missing=sorted(p.relative_to(ROOT).as_posix() for p in candidates if p.relative_to(ROOT).as_posix() not in names)
if missing:raise RuntimeError('Add new project dependencies to tools/project_inputs.json: '+', '.join(missing))
seeds=re.findall(r'^set_global_assignment\s+-name\s+SEED\s+(\d+)\s*$',(ROOT/'CoCo3.qsf').read_text(),re.M)
if len(seeds)!=1:raise RuntimeError('Require one literal SEED assignment in CoCo3.qsf')
seed=int(seeds[0])
project=a.output/'project';project.mkdir(parents=True)
inputs={}
for name in names:
source=ROOT/name;target=project/name;target.parent.mkdir(parents=True,exist_ok=True)
shutil.copyfile(source,target)
if name not in ('README.md','.gitignore','changes.txt'):inputs[name]=sha(source)
# The unchanged upstream flow generates build_id.v in this copy only.
receipt=dict(source_commit_at_build=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip(),source_state='Working tree with individually hashed project inputs',quartus=version.strip(),seed=seed,project_inventory_sha256=sha(ROOT/'tools/project_inputs.json'),inputs=inputs,prepared_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),scope='Prepared source only')
(a.output/'build.json').write_text(json.dumps(receipt,indent=2)+'\n')
if a.prepare_only:print('Prepared '+str(project));return
command=[str(a.quartus.resolve()),'--flow','compile','CoCo3']
with (a.output/'compile.log').open('w') as log:
result=subprocess.run(command,cwd=project,stdout=log,stderr=subprocess.STDOUT)
receipt['command']=['quartus_sh','--flow','compile','CoCo3'];receipt['exit_code']=result.returncode
rbf=project/'output_files/CoCo3.rbf'
if result.returncode or not rbf.exists():raise RuntimeError('Compilation failed; inspect '+str(a.output/'compile.log'))
summary=project/'output_files/CoCo3.sta.summary'
text=summary.read_text(errors='replace')
slack=[float(x) for x in re.findall(r'Slack\s*:\s*([-+\d.]+)',text,re.I)]
if not slack or min(slack)<0:raise RuntimeError('Missing or negative timing summary; inspect '+str(summary))
if any(sha(ROOT/n)!=h for n,h in inputs.items()):raise RuntimeError('Source changed during compilation')
receipt.update(scope='Full native fit and timing summary; detailed path audits and hardware are separate',rbf_sha256=sha(rbf),rbf_bytes=rbf.stat().st_size,summary_sha256=sha(summary),slack_ns=slack,passed=True)
(a.output/'build.json').write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps({k:v for k,v in receipt.items() if k!='inputs'},indent=2))
if __name__=='__main__':main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Assemble ToolShed CoCo firmware with native LWASM; no make, WSL or binary inputs."""
import argparse, hashlib, json, shutil, subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--source',type=Path,default=ROOT/'.deps/cocoroms')
p.add_argument('--lwasm',type=Path)
p.add_argument('--output',type=Path,default=ROOT/'build/roms')
a=p.parse_args();meta=json.loads((ROOT/'tools/cocoroms.json').read_text())
if a.output.exists():raise RuntimeError('Use a fresh output directory')
for name,h in meta['upstreamFileSHA256'].items():
if sha(a.source/name)!=h:raise RuntimeError('Assembly source mismatch: '+name)
if a.lwasm is None:
found=list((ROOT/'.tools/lwtools').rglob('lwasm.exe'))
if len(found)!=1:raise RuntimeError('Run bootstrap.py or supply --lwasm')
a.lwasm=found[0]
a.lwasm=a.lwasm.resolve();a.output.mkdir(parents=True)
work=a.output/'work';shutil.copytree(a.source,work)
if any(p.suffix.lower() in ('.bin','.rom') for p in work.rglob('*')):raise RuntimeError('Unexpected binary firmware input')
commands=[]
def run(args,stdout=None):
commands.append(args)
result=subprocess.run([str(a.lwasm),*args],cwd=work,capture_output=True,check=True)
if stdout:(work/stdout).write_bytes(result.stdout)
with (a.output/'build.log').open('ab') as log:log.write(result.stderr)
run(['--raw','-o','bas13.rom','equates.asm','bas.asm'])
run(['--symbol-dump','--no-output','equates.asm','bas.asm'],'cb_equates.asm')
run(['--raw','-o','extbas11.rom','cb_equates.asm','extbas.asm'])
run(['--symbol-dump','--no-output','equates.asm','bas.asm','extbas.asm'],'ecb_equates.asm')
run(['--raw','--pragma=noindex0tonone','-o','disk11.rom','ecb_equates.asm','disk.asm'])
run(['--raw','-o','coco3.rom','equates.asm','coco3.asm'])
outputs={}
for name,expected in meta['romOutputs'].items():
actual={'bytes':(work/name).stat().st_size,'sha256':sha(work/name)}
if actual!=expected:raise RuntimeError('Assembled ROM mismatch: '+name)
shutil.copyfile(work/name,a.output/name);outputs[name]=actual
for source,target in [('coco3.rom','boot0.rom'),('disk11.rom','boot1.rom')]:shutil.copyfile(a.output/source,a.output/target)
notice='Rebuilt from ToolShed cocoroms assembly at '+meta['sourceRevision']+'.\nOriginal Tandy/Microsoft/Microware notices remain applicable.\nNo preassembled firmware input. SSC chip ROMs are separate external inputs.\n'
(a.output/'ROM_SOURCE_NOTICE.txt').write_text(notice)
(a.output/'manifest.json').write_text(json.dumps(dict(source_url=meta['sourceURL'],source_revision=meta['sourceRevision'],source_sha256=meta['upstreamFileSHA256'],assembler_sha256=sha(a.lwasm),assembler_version=subprocess.check_output([str(a.lwasm),'--version']).decode().strip(),commands=commands,roms=outputs,preassembled_inputs=False),indent=2)+'\n')
print('PASS: all four reconstructed ROM hashes; boot0/boot1 staged')
if __name__=='__main__':main()
+33
View File
@@ -0,0 +1,33 @@
{
"sourceURL": "https://github.com/nitros9project/toolshed",
"sourceRevision": "3667a41c9605b7fcb150eace29cc7f42d460be1a",
"upstreamFileSHA256": {
"Makefile": "4a29262fc1ba0b6106887425f5b0a4edb8ab81fd343af548cb3a863bda3aea51",
"bas.asm": "ca2e0fba27a1c960f56648ab7be6571a89a4aff6c433b9a2649924e308e8bf24",
"coco3.asm": "01147f426baf1b48fc6d590f18ca5974bedc3dfac486020e694d9f4b890d74f2",
"disk.asm": "735443637ebaddc358f6a12856c495cc92e08f3aaa8bb68cf9a0494d7655faae",
"equates.asm": "099d4ae145ee5151aa1eb7e9805388d338b2613fd53e2ba666ab757734d94442",
"extbas.asm": "75ce20734d0272f636a961b318fb898c555061194da12d9bfc26782fc4b5e42b",
"md5sums.txt": "f0374ad4bdd32f9cd322cfa5eafe04a0b27d2e90698b536aa26c00d1ea7c8eab",
"mugateerspic.asm": "2878b1a9fbf7cc3bde25475f5e256f25910fdb44b1b2f8e6f01883bcf13548a1"
},
"romOutputs": {
"bas13.rom": {
"bytes": 8192,
"sha256": "5375b1caef9df815b781d9cd6df81ecdaddd2642b06a01adac521e40f1329751"
},
"coco3.rom": {
"bytes": 32768,
"sha256": "ad358430568250eb8330a37f85361d9ce67e5ae6d5a28c17b31802cd3953a5d2"
},
"disk11.rom": {
"bytes": 8192,
"sha256": "1c40c5a74e72edaeecc2511fee1aab347eae2c3d5fc6778cb622e3df14d63157"
},
"extbas11.rom": {
"bytes": 8192,
"sha256": "a18f270d3495d82b9f515de049f46253a623a2d9b1bb226c9ad338508344c5ee"
}
},
"license": "File-specific Tandy, Microsoft and Microware notices retained in reconstructed firmware and assembly comments."
}
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Install a verified overlay using existing passwordless OpenSSH access."""
import argparse,datetime,json,re,shlex,subprocess
from pathlib import Path,PurePosixPath
from release import ROOT,make_release,sha
def q(s):return shlex.quote(str(s))
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--host',help='IP or DNS hostname; prompted when omitted')
p.add_argument('--user',default='root')
p.add_argument('--release',type=Path,help='Existing tools/release.py output; otherwise package defaults')
p.add_argument('--without-ssc',action='store_true')
p.add_argument('--load',action='store_true',help='Return to MENU then load the new launcher')
a=p.parse_args();a.host=a.host or input('MiSTer IP address or hostname: ').strip()
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*',a.host) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_-]*',a.user):p.error('Use a plain hostname/IP and Unix username')
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
release=a.release.resolve() if a.release else ROOT/'dist'/('install-'+stamp)
if not a.release:make_release(release,ROOT/'build/fpga',ROOT/'build/roms',ROOT/'roms/ssc',a.without_ssc)
manifest=json.loads((release/'manifest.json').read_text());fat=release/'fat'
if manifest.get('public_package'):raise RuntimeError('Public core/source package omits required ROMs. Build a complete local package with your verified ROM inputs; see docs/INSTALL.md.')
for n,v in manifest['files'].items():
path=PurePosixPath(n)
if path.is_absolute() or '..' in path.parts or '\\' in n:raise RuntimeError('Unsafe manifest path')
file=fat/n
if not file.is_file() or file.stat().st_size!=v['bytes'] or sha(file)!=v['sha256']:raise RuntimeError('Release changed: '+n)
args=['-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=10']
target=a.user+'@'+a.host
def ssh(script):return subprocess.check_output(['ssh',*args,target,'sh -s'],input=script.encode(),stderr=subprocess.STDOUT).decode()
# No target writes before all local hashes and this read-only preflight pass.
print(ssh('set -eu\ntest -d /media/fat\ntest -w /media/fat\ntest -e /dev/MiSTer_cmd\ncommand -v sha256sum\nid\n').strip())
remote='/media/fat/.coco3plus/install-'+stamp;backup=remote+'/backup';stage=remote+'/stage'
ssh('set -eu\nmkdir -p '+q(stage)+' '+q(backup)+'\n')
# Raw argv paths are intentional: OpenSSH SFTP handles spaces without shell quoting.
subprocess.run(['scp',*args,'-r',str(fat),target+':'+stage+'/'],check=True)
lines=['set -eu']
for n,v in manifest['files'].items():lines.append('test "$(sha256sum '+q(stage+'/fat/'+n)+' | cut -d " " -f 1)" = '+q(v['sha256']))
lines.append("printf 'load_core /media/fat/menu.rbf\\n' > /dev/MiSTer_cmd")
lines.append('sleep 2')
for n,v in manifest['files'].items():
src=stage+'/fat/'+n;dest='/media/fat/'+n;old=backup+'/'+n
lines.append('mkdir -p '+q(str(PurePosixPath(dest).parent))+' '+q(str(PurePosixPath(old).parent)))
if v['policy']=='create-if-missing':lines.append('if [ ! -e '+q(dest)+' ]; then cp '+q(src)+' '+q(dest)+'; fi')
else:
lines.append('if [ -e '+q(dest)+' ]; then cp '+q(dest)+' '+q(old)+'; fi')
lines.append('cp '+q(src)+' '+q(dest))
lines.append('test "$(sha256sum '+q(dest)+' | cut -d " " -f 1)" = '+q(v['sha256']))
lines.append('sync')
if a.load:lines.append("printf 'load_core /media/fat/_Computer/Coco 3 Plus.mgl\\n' > /dev/MiSTer_cmd")
result=ssh('\n'.join(lines)+'\n')
receipt=dict(host=a.host,user=a.user,backup=backup,manifest=manifest,loaded=a.load,remote_output=result)
(release/'install-receipt.json').write_text(json.dumps(receipt,indent=2)+'\n')
print('Installed Coco 3 Plus; backup: '+backup+'; RBF '+manifest['rbf_sha256'])
print('Receipt: '+str(release/'install-receipt.json'))
if __name__=='__main__':main()
+179
View File
@@ -0,0 +1,179 @@
{
"description": "Maintained project input inventory. Add dependencies here and HDL assignments to files.qip. Historical provenance remains in validation/source-import.json.",
"files": [
".gitignore",
"AMW.stp",
"COCO3_Comp.xlsx",
"CoCo3.qpf",
"CoCo3.qsf",
"CoCo3.srf",
"CoCo3.sv",
"CoCo3FPGA.sdc",
"HD.stp",
"HD2.stp",
"README.md",
"Serial.stp",
"Video1.stp",
"Video_Explorer.stp",
"Video_Explorer2.stp",
"Vsync.stp",
"build_id_num.v",
"changes.txt",
"docs/Boot.vhd",
"docs/CoCo3FPGA.docx",
"docs/CoCo3FPGA.pdf",
"docs/~$Co3FPGA.docx",
"external-io.sdc",
"files.qip",
"pll.xml",
"releases/CoCo3_20211221.rbf",
"releases/CoCo3_20211229.rbf",
"releases/CoCo3_20220124.rbf",
"releases/CoCo3_20220211.rbf",
"releases/CoCo3_20220219.rbf",
"releases/CoCo3_20220226.rbf",
"releases/CoCo3_20230224.rbf",
"releases/CoCo3_20231023.rbf",
"releases/CoCo3_20240205.rbf",
"releases/CoCo3_20240318.rbf",
"releases/CoCo3_20240514.rbf",
"releases/CoCo3_20260927.rbf",
"releases/Tandy CoCo3 Overview.pdf",
"reset-cpu.sdc",
"reset.stp",
"rom_Exploror.stp1",
"rtl/AMW.v",
"rtl/Auto_Run.sv",
"rtl/CPU09/6809Data.pdf",
"rtl/CPU09/cpu09_119.vhd",
"rtl/CPU09/cpu09_122.vhd",
"rtl/CPU09/cpu09l_126.vhd",
"rtl/CPU09/cpu09l_126x.vhd",
"rtl/CPU09/cpu09l_127.vhd",
"rtl/CPU09/cpu09l_128.vhd",
"rtl/CPU09/cpu09l_128a.vhd",
"rtl/CPU09/cpu09new_B15.vhd",
"rtl/Cassette_Write.sv",
"rtl/CoCo3FPGA.sdc",
"rtl/EE_Cold_Bt.v",
"rtl/Mister_Video.v",
"rtl/OVO.vhd",
"rtl/PS2_Key/ps2_keyboard.v",
"rtl/UART_6551/6551rx.v",
"rtl/UART_6551/6551tx.v",
"rtl/UART_6551/uart_6551.v",
"rtl/VDAC.mif",
"rtl/VDAC.qip",
"rtl/VDAC.v",
"rtl/bh_mpi_config.sv",
"rtl/bh_mpi_rom.sv",
"rtl/bh_mpi_router.sv",
"rtl/cassette.v",
"rtl/coco3fpga.sv",
"rtl/coco_mem_fetch.sv",
"rtl/cocokey.v",
"rtl/config.sv",
"rtl/cpu_sdram_bridge.sv",
"rtl/fdc.sv",
"rtl/mc6809glb/mc6809glb.v",
"rtl/pll.ppf",
"rtl/pll.qip",
"rtl/pll.sip",
"rtl/pll.spd",
"rtl/pll.v",
"rtl/pll/pll_0002.qip",
"rtl/pll/pll_0002.v",
"rtl/ps2_mouse.v",
"rtl/rom/coco3_char_rom.vhd",
"rtl/rom/coco_rom_16.vhd",
"rtl/rom/coco_rom_32K.vhd",
"rtl/rom/coco_rom_8K.vhd",
"rtl/rom/coco_rom_cart.vhd",
"rtl/rtc.sv",
"rtl/sdc.sv",
"rtl/sdc_top.sv",
"rtl/sdram/sdram2.sv",
"rtl/square_gen.v",
"rtl/sram/coco_ram.vhd",
"rtl/sram/coco_vid_ram_buf.vhd",
"rtl/ssc/LICENSE",
"rtl/ssc/ssc_audio.sv",
"rtl/ssc/ssc_ay8913.sv",
"rtl/ssc/ssc_cartridge.sv",
"rtl/ssc/ssc_glue.sv",
"rtl/ssc/ssc_host.sv",
"rtl/ssc/ssc_mister_bridge.sv",
"rtl/ssc/ssc_sp0256.sv",
"rtl/ssc/ssc_sp0256_memory.sv",
"rtl/ssc/ssc_sp0256_tables.vh",
"rtl/ssc/ssc_tms7000.sv",
"rtl/ssc/ssc_tms7000_alu.sv",
"rtl/ssc/ssc_tms7000_bcd.sv",
"rtl/ssc/ssc_tms7000_decode.sv",
"rtl/ssc/ssc_tms7000_defs.vh",
"rtl/ssc/ssc_tms7000_exec.sv",
"rtl/ssc/ssc_tms7000_io.sv",
"rtl/ssc/ssc_tms7000_memory.sv",
"rtl/ssc/ssc_tms7000_pacer.sv",
"rtl/wd1793.sv",
"sys/alsa.sv",
"sys/arcade_video.v",
"sys/ascal.vhd",
"sys/audio_out.v",
"sys/build_id.tcl",
"sys/ddr_svc.sv",
"sys/f2sdram_safe_terminator.sv",
"sys/gamma_corr.sv",
"sys/hps_io.sv",
"sys/hq2x.sv",
"sys/i2c.v",
"sys/i2s.v",
"sys/iir_filter.v",
"sys/ltc2308.sv",
"sys/math.sv",
"sys/mcp23009.sv",
"sys/mt32pi.sv",
"sys/osd.v",
"sys/pll.13.qip",
"sys/pll_audio.13.qip",
"sys/pll_audio.qip",
"sys/pll_audio.v",
"sys/pll_audio/pll_audio_0002.qip",
"sys/pll_audio/pll_audio_0002.v",
"sys/pll_cfg.qip",
"sys/pll_cfg.v",
"sys/pll_cfg/altera_pll_reconfig_core.v",
"sys/pll_cfg/altera_pll_reconfig_top.v",
"sys/pll_cfg/pll_cfg.v",
"sys/pll_cfg/pll_cfg_hdmi.v",
"sys/pll_cfg_hdmi.v",
"sys/pll_hdmi.13.qip",
"sys/pll_hdmi.qip",
"sys/pll_hdmi.v",
"sys/pll_hdmi/pll_hdmi_0002.qip",
"sys/pll_hdmi/pll_hdmi_0002.v",
"sys/pll_hdmi_adj.vhd",
"sys/pll_q13.qip",
"sys/pll_q17.qip",
"sys/scandoubler.v",
"sys/scanlines.v",
"sys/sd_card.sv",
"sys/shadowmask.sv",
"sys/sigma_delta_dac.v",
"sys/spdif.v",
"sys/sys.qip",
"sys/sys.tcl",
"sys/sys_analog.tcl",
"sys/sys_dual_sdram.tcl",
"sys/sys_top.sdc",
"sys/sys_top.v",
"sys/sysmem.sv",
"sys/vga_out.sv",
"sys/video_cleaner.sv",
"sys/video_freak.sv",
"sys/video_freezer.sv",
"sys/video_mixer.sv",
"sys/yc_out.sv",
"uart-reset.sdc"
]
}
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Create a checked, copyable MiSTer FAT-volume overlay from a standalone build."""
import argparse,datetime,hashlib,json,shutil,subprocess,zipfile
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
SSC={'pic-7040-510.bin':(4096,'0013cd78482cc5f2360fdf584e9ba51d34861e8ccd9d88247f1a54039c16c365'),
'sp0256-al2.bin':(2048,'98c280fd082169c54081e503dfe7d7d9a6fd46d4ffcc973e199ea0e1d9bc1ac9')}
BOOT={'boot0.rom':(32768,'ad358430568250eb8330a37f85361d9ce67e5ae6d5a28c17b31802cd3953a5d2'),
'boot1.rom':(8192,'1c40c5a74e72edaeecc2511fee1aab347eae2c3d5fc6778cb622e3df14d63157')}
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def checked(p,size,digest):
if not p.is_file() or p.stat().st_size!=size or sha(p)!=digest:raise RuntimeError('Missing or incorrect input: '+str(p))
return p
def default_config(ssc):
# Main serializes cur_status[16] in byte order, low bits first.
# Audio / SDC / ROM / Floppy, startup Slot4, 512K; migrated-layout marker.
layout=6+(3<<3)+(1<<6)+(2<<9)
status=(1<<63)|(layout<<43)|(3<<12)|((1<<42) if ssc else 0)
return status.to_bytes(16,'little')
def make_release(output,build,roms,ssc,without_ssc=False,public=False):
record=json.loads((build/'build.json').read_text())
if not record.get('passed'):raise RuntimeError('Successful standalone FPGA build required')
rbf=checked(build/'project/output_files/CoCo3.rbf',record['rbf_bytes'],record['rbf_sha256'])
for n,h in record['inputs'].items():
if sha(ROOT/n)!=h:raise RuntimeError('Source differs from built input: '+n)
inputs={} if public else {f'games/coco3plus/{n}':checked(roms/n,*identity) for n,identity in BOOT.items()}
if not without_ssc and not public:inputs.update({f'games/coco3plus/{n}':checked(ssc/n,*v) for n,v in SSC.items()})
if subprocess.check_output(['git','status','--porcelain','--untracked-files=no'],cwd=ROOT).strip():raise RuntimeError('Commit reviewed changes before creating a distributable source package')
source_revision=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip()
if output.exists():raise RuntimeError('Preserve previous release: '+str(output))
fat=output/'fat';fat.mkdir(parents=True)
core=f'_Computer/.coco3plus/{record["rbf_sha256"][:12]}/coco3plus.rbf';inputs[core]=rbf
for name in ('NOTICE.md','LICENSING.md','COPYRIGHT.md'):
inputs['games/coco3plus/licenses/'+name]=ROOT/name
for folder in (ROOT/'LICENSES',):
for file in folder.glob('*'):
if file.is_file():inputs['games/coco3plus/licenses/'+file.name]=file
inputs['games/coco3plus/licenses/SSC-BSD-3-Clause.txt']=ROOT/'rtl/ssc/LICENSE'
for n,p in inputs.items():
target=fat/n;target.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(p,target)
launcher=fat/'_Computer/Coco 3 Plus.mgl';launcher.parent.mkdir(exist_ok=True)
launcher.write_text(f'<mistergamedescription>\n <rbf>{core[:-4]}</rbf>\n <setname>coco3plus</setname>\n</mistergamedescription>\n',newline='\n')
config=fat/'config';config.mkdir()
(config/'coco3plus_v51.CFG').write_bytes(default_config(not without_ssc))
if not without_ssc:
for index,n in ((4,'pic-7040-510.bin'),(5,'sp0256-al2.bin')):
value=f'/media/fat/games/coco3plus/{n}'.encode()
(config/f'coco3plus.f{index}').write_bytes(value.ljust(1024,b'\0'))
manifest=dict(format=1,created_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),public_package=public,
rbf_sha256=record['rbf_sha256'],ssc_included=not without_ssc and not public,roms_required_separately=public,
files={p.relative_to(fat).as_posix():dict(bytes=p.stat().st_size,sha256=sha(p),
policy='create-if-missing' if p.name=='coco3plus_v51.CFG' else 'backup-and-replace') for p in sorted(fat.rglob('*')) if p.is_file()})
if public:manifest['required_roms']={n:dict(bytes=v[0],sha256=v[1]) for n,v in {**BOOT,**({} if without_ssc else SSC)}.items()}
(output/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
(output/'SHA256SUMS.txt').write_text(''.join(f'{v["sha256"]} fat/{n}\n' for n,v in manifest['files'].items()))
(output/'README.txt').write_text('Coco 3 Plus FAT-volume overlay. This is not a bootable disk image.\nCopy fat/ CONTENTS to the MiSTer FAT-volume root with MiSTer shut down.\nPreserve existing config/coco3plus_v51.CFG. Back up files before replacing.\nOriginal CoCo3 and other cores are not replaced. Start Computer/Coco 3 Plus.\nSSC ROMs, when included, are separately supplied local inputs; do not redistribute without permission.\n')
if public:
with (output/'README.txt').open('a') as file:file.write('PUBLIC CORE/SOURCE PACKAGE: no CoCo boot or SSC ROMs included.\nBefore launching, supply boot0.rom and boot1.rom in games/coco3plus and the SSC ROMs if using SSC.\nSee roms/README.md and docs/INSTALL.md in corresponding-source.zip for exact identities and source-build installation.\nThis incomplete-ROM public package is not accepted directly by the SSH installer. Build a complete local package using your own verified ROM inputs.\n')
# Git's reviewed committed tree is the only source-export allowlist. Untracked
# notes, .env files and ignored ROM/cache inputs can never enter this archive.
with (output/'corresponding-source.zip').open('xb') as file:
subprocess.run(['git','archive','--format=zip','--prefix=coco3plus/',source_revision],cwd=ROOT,stdout=file,check=True)
manifest['source_revision']=source_revision
manifest['corresponding_source_sha256']=sha(output/'corresponding-source.zip')
(output/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
archive_path=output.with_name(output.name+'.zip')
if archive_path.exists():raise RuntimeError('Preserve previous release archive: '+str(archive_path))
with zipfile.ZipFile(archive_path,'x',zipfile.ZIP_DEFLATED) as archive:
for file in sorted(output.rglob('*')):
if file.is_file():archive.write(file,file.relative_to(output).as_posix())
archive_path.with_suffix('.zip.sha256').write_text(sha(archive_path)+' '+archive_path.name+'\n')
return manifest
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--output',type=Path,default=ROOT/'dist/coco3plus')
p.add_argument('--build',type=Path,default=ROOT/'build/fpga')
p.add_argument('--roms',type=Path,default=ROOT/'build/roms')
p.add_argument('--ssc',type=Path,default=ROOT/'roms/ssc')
p.add_argument('--without-ssc',action='store_true')
p.add_argument('--public',action='store_true',help='Omit ALL separately obtained/assembled ROMs; core/source distribution only')
a=p.parse_args();m=make_release(a.output.resolve(),a.build.resolve(),a.roms.resolve(),a.ssc.resolve(),a.without_ssc,a.public)
print('Release '+str(a.output.resolve())+'; RBF SHA-256 '+m['rbf_sha256'])
if __name__=='__main__':main()
+55
View File
@@ -0,0 +1,55 @@
"""Conditional external timing coverage classification.
Copyright (c) 2026 Brian K. Holman. BSD-3-Clause; see LICENSES/.
"""
import re
def parse_ucp(path):
text = path.read_text(errors='replace')
counts = {m[1].strip(): {'setup': int(m[2]), 'hold': int(m[3])}
for m in re.finditer(r';\s*(Illegal Clocks|Unconstrained [^;]+?)\s*;\s*(\d+)\s*;\s*(\d+)\s*;', text)}
inventory = {'input_ports': {}, 'output_ports': {}}
section = None
# Retain only the setup inventory (hold inventory repeats it).
for line in text.split('; Hold Analysis ;')[0].splitlines():
cols = [x.strip() for x in line.split(';')[1:-1]]
if cols == ['Unconstrained Input Ports']:
section = 'input_ports'
elif cols == ['Unconstrained Output Ports']:
section = 'output_ports'
elif cols and cols[0] in ('Unconstrained Input Port Paths', 'Unconstrained Output Port Paths'):
section = None
elif section and len(cols) == 2 and cols[0] not in ('Input Port', 'Output Port'):
inventory[section][cols[0]] = cols[1]
if len(counts) != 6:
raise RuntimeError('Incomplete unconstrained-count summary')
return counts, inventory
def classify(port):
if port.startswith('SDRAM_'):
return 'SDRAM synchronous: must be explicitly timed; no exception allowed'
if port == 'HDMI_TX_CLK':
return 'Forwarded video clock: two generated-clock modes; clock waveform/output latency, not a data receiver'
if port.startswith('HDMI_TX_'):
return 'ADV7513 video: both clock mux modes require setup/hold budgets'
if port in ('HDMI_I2S', 'HDMI_LRCLK', 'HDMI_SCLK'):
return 'ADV7513 I2S: source protocol slots plus bounded output propagation'
if port == 'HDMI_MCLK':
return 'Forwarded audio clock: clock waveform/output latency, not a data receiver'
if port.startswith('HDMI_I2C_'):
return 'HPS hard I2C peripheral boundary: fabric STA does not prove slave bus timing'
if port in ('IO_SCL', 'IO_SDA'):
return 'MCP23009 I2C: require source-matched protocol slots, propagation and board RC/slave contract'
if port == 'SDCD_SPDIF':
return 'Mode-dependent asynchronous card detect / SPDIF output'
if port.startswith('SDIO_') or port == 'SD_SPI_CS':
return 'Mode-dependent HPS SD-SPI / analog VGA mux; cannot use one synchronous pin budget'
if port.startswith('LED['):
return 'Human status indicator / overtake mode; no synchronous external receiver'
if port == 'USER_IO[1]':
return 'Optional external UART input: UART synchronizer and direct bit-banged PIA fanout'
if port.startswith('USER_IO['):
return 'Open-drain serial/debug output or alternate I2S; receiver/RC is external'
if port.startswith('altera_reserved_'):
return 'Tool-generated JTAG interface: separate programming/test timing contract'
return 'UNCLASSIFIED: investigation required'
+36
View File
@@ -0,0 +1,36 @@
{
"lwtools_windows": {
"version": "4.25",
"url": "https://www.lwtools.ca/releases/lwtools/lwtools-4.25-win64.zip",
"archive": "lwtools-4.25-win64.zip",
"sha256": "c0c8a4d04600df2b5072de552ec37bcbf7162f6047918a56254a997ea2553ab4",
"lwasm_sha256": "8b7ee402f7de3bf8552cdf8317f7d64d9b27af4b60f1cf7bbee76b6f31d35d4d"
},
"main_reference": {
"revision": "f47acd3d71d302893d8ad49dde4268223cd4c9f8",
"files": {
"user_io.cpp": {
"sha256": "33cf025197d119b20112ba4e92c0b0cbbf2d49726fc2aea8d42e40ed88b5673a",
"url": "https://github.com/MiSTer-devel/Main_MiSTer/blob/f47acd3d71d302893d8ad49dde4268223cd4c9f8/user_io.cpp"
},
"file_io.cpp": {
"sha256": "752c2e3795c39af7ff6976ae7cac4dda40213fc1eddeb815baaf8c82cf659e20",
"url": "https://github.com/MiSTer-devel/Main_MiSTer/blob/f47acd3d71d302893d8ad49dde4268223cd4c9f8/file_io.cpp"
},
"menu.cpp": {
"sha256": "3da4c1dc89873353f9ceb1447624c1041cdf6d8c7f4bcc05846f4999464c1698",
"url": "https://github.com/MiSTer-devel/Main_MiSTer/blob/f47acd3d71d302893d8ad49dde4268223cd4c9f8/menu.cpp"
},
"user_io.h": {
"sha256": "89b00ba1b35560f83bc8190d2e648cbb5bb38f5fea1ff39243700beca38c5673",
"url": "https://github.com/MiSTer-devel/Main_MiSTer/blob/f47acd3d71d302893d8ad49dde4268223cd4c9f8/user_io.h"
}
}
},
"oss_cad_windows": {
"version": "2026-11-14",
"url": "https://github.com/YosysHQ/oss-cad-suite-build/releases/download/2026-11-14/oss-cad-suite-windows-x64-20261114.tgz",
"archive": "oss-cad-suite-windows-x64-20261114.tgz",
"sha256": "3928bd7a49c6ba4cee27205b9df9f41829a518398db8abe964b8378206232d97"
}
}