#!/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()