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