verify_motor_arithmetic.py 5.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python3
  2. """Prove actual RTL arithmetic expressions and require three mutations to fail.
  3. This is an unconstrained combinational proof, not a sequential motor proof.
  4. """
  5. from pathlib import Path
  6. import argparse,datetime,hashlib,json,os,re,signal,subprocess,sys
  7. ROOT=Path(__file__).resolve().parents[1]
  8. def main():
  9. ap=argparse.ArgumentParser(description=__doc__)
  10. ap.add_argument('--run-root',type=Path,required=True)
  11. args=ap.parse_args()
  12. if sys.platform!='linux':ap.error('Execute in the authorized Linux container')
  13. out=args.run_root.resolve()
  14. if out==ROOT or ROOT in out.parents:ap.error('run-root must be external')
  15. out.mkdir(parents=True,exist_ok=False)
  16. source=ROOT/'src/motor/motor_axis_core.v'
  17. raw=source.read_text(encoding='utf-8')
  18. names=['deadline_difference','deadline_now','deadline_next','total_sum','exec_sum','lower_hit_sum','upper_hit_sum','total_next','exec_next','position_delta','moved_position','pos_next','position_signed_overflow']
  19. substitutions={'now_us[33:0]':'now_time','due[scan_axis]':'deadline','r_total[scan_axis]':'total',
  20. 'r_executed[scan_axis]':'executed','r_position[scan_axis]':'position','rise_pending[scan_axis]':'rise',
  21. 'r_dir_upper[scan_axis]':'up','selected_hits':'hits','lower_pending[scan_axis]':'lower_inc','upper_pending[scan_axis]':'upper_inc'}
  22. declarations=[]
  23. for name in names:
  24. match=re.search(r'wire\s+(\[[^\]]+\]\s+)?'+re.escape(name)+r'\s*=([^;]*);',raw)
  25. if not match:raise ValueError('RTL expression missing: '+name)
  26. declaration=match.group(0)
  27. for before,after in substitutions.items():declaration=declaration.replace(before,after)
  28. declarations.append(declaration)
  29. prefix='''module arithmetic_equivalence(input [33:0] now_time,deadline,
  30. input [31:0] total,executed,position,input [63:0] hits,
  31. input [3:0] lower_inc,upper_inc,input rise,up,output bad);
  32. '''
  33. suffix='''
  34. wire [33:0] ref_now=now_time-deadline;
  35. wire [33:0] ref_next=(now_time+34'd1)-deadline;
  36. wire [31:0] ref_total=total+rise,ref_exec=executed+rise;
  37. wire [31:0] ref_lower=hits[31:0]+lower_inc,ref_upper=hits[63:32]+upper_inc;
  38. wire [31:0] ref_position=rise ? (up ? position+32'd1 : position-32'd1) : position;
  39. wire ref_position_wrap=rise && (up ? position==32'h7FFFFFFF : position==32'h80000000);
  40. assign bad=(deadline_now!==!ref_now[33]) || (deadline_next!==!ref_next[33]) ||
  41. (total_next!==ref_total) || (exec_next!==ref_exec) || (pos_next!==ref_position) ||
  42. (total_sum[32] !== (rise && total==32'hFFFFFFFF)) ||
  43. (exec_sum[32] !== (rise && executed==32'hFFFFFFFF)) ||
  44. (lower_hit_sum[31:0]!==ref_lower) || (upper_hit_sum[31:0]!==ref_upper) ||
  45. (lower_hit_sum[32] !== (ref_lower<hits[31:0])) || (upper_hit_sum[32] !== (ref_upper<hits[63:32])) ||
  46. ((rise && position_signed_overflow)!==ref_position_wrap);
  47. endmodule
  48. '''
  49. base=prefix+'\n'.join(declarations)+suffix
  50. variants={'proof':base,
  51. 'mutation_deadline_boundary':base.replace('deadline_now ^ (&deadline_difference[32:0])','deadline_now || (&deadline_difference)'),
  52. 'mutation_upper_carry':base.replace('(upper_hit_sum[32] !==','(1\'b0 !=='),
  53. 'mutation_position_delta':base.replace("up ? 32'd1 : 32'hFFFFFFFF","32'd1")}
  54. manifest={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  55. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  56. result={'schema':'prod2u-combinational-arithmetic-proof-v1','scope':'arithmetic expressions only; no state-machine proof',
  57. 'run_id':out.name,'inputs':manifest,'source_manifest_sha256':hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest(),
  58. 'project_sha256':manifest['projects/mrdimm-chamber/project.json'],'bitstream_sha256':None,
  59. 'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),
  60. 'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
  61. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'assumptions':[], 'results':[],'status':'RUNNING'}
  62. for name,text in variants.items():
  63. if name!='proof' and text==base:raise ValueError('mutation did not change the extracted RTL')
  64. vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  65. log=out/(name+'.log')
  66. command=['yosys','-p',f'read_verilog -formal {vf}; prep -top arithmetic_equivalence; sat -verify -prove bad 0 -show-inputs']
  67. with log.open('w') as stream:
  68. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  69. try:code=process.wait(timeout=90)
  70. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  71. output=log.read_text(encoding='utf-8',errors='replace')
  72. ok=(code==0 and 'SUCCESS!' in output) if name=='proof' else (code==1 and 'proof did fail' in output)
  73. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else 'FAIL',
  74. 'log':str(log),'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  75. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'FAIL'
  76. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  77. print(json.dumps(result,indent=2))
  78. return 0 if result['status']=='PASS' else 1
  79. if __name__=='__main__':raise SystemExit(main())