verify_motor_arithmetic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/env python3
  2. """Prove actual RTL arithmetic expressions and require four 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. if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
  9. from tools.source_identity import source_identity
  10. def prove_selector(out):
  11. source=ROOT/'src/motor/motor_engine.v'
  12. raw=source.read_text(encoding='utf-8')
  13. start=raw.index(' always @* begin',raw.index('// Factor one-bit eligibility/priority'))
  14. end=raw.index('\n end\n',start)+len('\n end\n')
  15. actual=raw[start:end]
  16. inputs={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  17. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  18. result={'schema':'prod2u-queue-selector-proof-v1','scope':'extracted combinational eligibility and circular winner only; no sequential or STEP proof',
  19. 'source':source_identity(ROOT),'inputs':inputs,'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True).encode()).hexdigest(),
  20. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),
  21. 'assumptions':['fx_round is a legal axis index; all eligibility/control/depth input bits otherwise arbitrary'],
  22. 'results':[],'hardware':'NOT_RUN','status':'RUNNING'}
  23. for axes in (3,12):
  24. width=(axes-1).bit_length()
  25. prefix=f'''module selector(input [{width-1}:0] fx_round,
  26. input [{axes-1}:0] ax_load_ready,ax_seg_load,queue_paused_r,cs_start_mask,cs_mask,urgent_valid_r,
  27. input [1:0] cs_state,input seek_context,input [{axes*6-1}:0] depths,
  28. output bad,output reg [7:0] fx_candidate,output reg fx_candidate_valid);
  29. localparam AXIS_COUNT={axes};
  30. wire [5:0] depth_r[0:AXIS_COUNT-1];
  31. genvar g;generate for(g=0;g<AXIS_COUNT;g=g+1)begin
  32. assign depth_r[g]=depths[g*6+:6];
  33. end endgenerate
  34. reg [AXIS_COUNT-1:0] fx_eligible;
  35. integer fx_k,fx_probe;
  36. '''
  37. reference='''
  38. integer axis,distance,best_distance;
  39. reg reference_valid;reg[7:0]reference_axis;reg allowed;
  40. always @* begin
  41. reference_valid=0;reference_axis=0;best_distance=AXIS_COUNT;distance=0;allowed=0;
  42. for(axis=0;axis<AXIS_COUNT;axis=axis+1)begin
  43. allowed=ax_load_ready[axis] && !ax_seg_load[axis] && !queue_paused_r[axis] &&
  44. ((cs_state==0) || (cs_state==3 && cs_start_mask[axis]) || (seek_context && cs_mask[axis])) &&
  45. (urgent_valid_r[axis] || (|depths[axis*6+:6]));
  46. distance=axis>=fx_round ? axis-fx_round : axis+AXIS_COUNT-fx_round;
  47. if(allowed && distance<best_distance)begin
  48. reference_valid=1;reference_axis=axis;best_distance=distance;
  49. end
  50. end
  51. end
  52. assign bad=(fx_round<AXIS_COUNT) && ((reference_valid!=fx_candidate_valid) ||
  53. (reference_valid && reference_axis!=fx_candidate));
  54. endmodule
  55. '''
  56. proof=prefix+actual+reference
  57. mutation=proof.replace('for(fx_k=AXIS_COUNT-1;fx_k>=0;fx_k=fx_k-1)','for(fx_k=0;fx_k<AXIS_COUNT;fx_k=fx_k+1)')
  58. if mutation==proof:raise ValueError('selector mutation did not change source')
  59. for kind,text in (('proof',proof),('reverse_priority_mutation',mutation),('nonempty_cover',proof)):
  60. name=f'axis{axes}_{kind}';vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  61. goal='sat -set fx_round 0 -set fx_candidate_valid 1 -show-inputs' if kind=='nonempty_cover' else 'sat -verify -prove bad 0 -show-inputs'
  62. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top selector; {goal}']
  63. log=out/(name+'.log')
  64. with log.open('w') as stream:
  65. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  66. try:code=process.wait(timeout=90)
  67. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  68. output=log.read_text(encoding='utf-8',errors='replace')
  69. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else (
  70. (code==1 and 'proof did fail' in output) if kind=='reverse_priority_mutation' else
  71. (code==0 and 'model found:' in output))
  72. result['results'].append({'name':name,'command':command,'exit_code':code,
  73. 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  74. '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 'INCOMPLETE'
  76. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  77. print(json.dumps(result,indent=2));return 0 if result['status']=='PASS' else 1
  78. def main():
  79. ap=argparse.ArgumentParser(description=__doc__)
  80. ap.add_argument('--run-root',type=Path,required=True)
  81. ap.add_argument('--selector',action='store_true',help='prove extracted queue selection for3/12 axes, a reversed-priority mutation and nonempty covers')
  82. args=ap.parse_args()
  83. if sys.platform!='linux':ap.error('Execute in the authorized Linux container')
  84. out=args.run_root.resolve()
  85. if out==ROOT or ROOT in out.parents:ap.error('run-root must be external')
  86. out.mkdir(parents=True,exist_ok=False)
  87. if args.selector:return prove_selector(out)
  88. source=ROOT/'src/motor/motor_axis_core.v'
  89. raw=source.read_text(encoding='utf-8')
  90. names=['deadline_span','planned_deadline','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']
  91. substitutions={'now_us[33:0]':'now_time','due[scan_axis]':'deadline','s_due':'deadline','r_total[scan_axis]':'total',
  92. 's_total':'total','s_executed':'executed','s_position':'position','r_executed[scan_axis]':'executed','r_position[scan_axis]':'position','rise_pending[scan_axis]':'rise',
  93. 'r_dir_upper[scan_axis]':'up','selected_hits':'hits','lower_pending[scan_axis]':'lower_inc','upper_pending[scan_axis]':'upper_inc',
  94. 'deadline_base':'base','deadline_duration':'duration','deadline_setup':'setup'}
  95. declarations=[]
  96. for name in names:
  97. match=re.search(r'wire\s+(\[[^\]]+\]\s+)?'+re.escape(name)+r'\s*=([^;]*);',raw)
  98. if not match:raise ValueError('RTL expression missing: '+name)
  99. declaration=match.group(0)
  100. for before,after in substitutions.items():declaration=declaration.replace(before,after)
  101. declarations.append(declaration)
  102. prefix='''module arithmetic_equivalence(input [33:0] now_time,deadline,base,input [31:0] duration,setup,
  103. input [31:0] total,executed,position,input [63:0] hits,
  104. input [3:0] lower_inc,upper_inc,input rise,up,output bad);
  105. '''
  106. suffix='''
  107. wire [33:0] ref_now=now_time-deadline;
  108. wire [33:0] ref_next=(now_time+34'd1)-deadline;
  109. wire [31:0] ref_total=total+rise,ref_exec=executed+rise;
  110. wire [31:0] ref_lower=hits[31:0]+lower_inc,ref_upper=hits[63:32]+upper_inc;
  111. wire [31:0] ref_position=rise ? (up ? position+32'd1 : position-32'd1) : position;
  112. wire ref_position_wrap=rise && (up ? position==32'h7FFFFFFF : position==32'h80000000);
  113. wire [33:0] ref_planned=base+{2'd0,duration}+{2'd0,setup};
  114. assign bad=(planned_deadline!==ref_planned) || (deadline_now!==!ref_now[33]) || (deadline_next!==!ref_next[33]) ||
  115. (total_next!==ref_total) || (exec_next!==ref_exec) || (pos_next!==ref_position) ||
  116. (total_sum[32] !== (rise && total==32'hFFFFFFFF)) ||
  117. (exec_sum[32] !== (rise && executed==32'hFFFFFFFF)) ||
  118. (lower_hit_sum[31:0]!==ref_lower) || (upper_hit_sum[31:0]!==ref_upper) ||
  119. (lower_hit_sum[32] !== (ref_lower<hits[31:0])) || (upper_hit_sum[32] !== (ref_upper<hits[63:32])) ||
  120. ((rise && position_signed_overflow)!==ref_position_wrap);
  121. endmodule
  122. '''
  123. base=prefix+'\n'.join(declarations)+suffix
  124. variants={'proof':base,
  125. 'mutation_deadline_boundary':base.replace('deadline_now ^ (&deadline_difference[32:0])','deadline_now || (&deadline_difference)'),
  126. 'mutation_upper_carry':base.replace('(upper_hit_sum[32] !==','(1\'b0 !=='),
  127. 'mutation_position_delta':base.replace("up ? 32'd1 : 32'hFFFFFFFF","32'd1"),
  128. 'mutation_duration_high_bit':base.replace("{2'd0,duration}","{3'd0,duration[30:0]}",1)}
  129. manifest={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  130. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  131. result={'schema':'prod2u-combinational-arithmetic-proof-v1','scope':'arithmetic expressions only; no state-machine proof',
  132. 'run_id':out.name,'inputs':manifest,'source_manifest_sha256':hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest(),
  133. 'project_sha256':manifest['projects/mrdimm-chamber/project.json'],'bitstream_sha256':None,
  134. 'commit':source_identity(ROOT)['commit'],
  135. 'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
  136. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'assumptions':[], 'results':[],'status':'RUNNING'}
  137. for name,text in variants.items():
  138. if name!='proof' and text==base:raise ValueError('mutation did not change the extracted RTL')
  139. vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  140. log=out/(name+'.log')
  141. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top arithmetic_equivalence; sat -verify -prove bad 0 -show-inputs']
  142. with log.open('w') as stream:
  143. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  144. try:code=process.wait(timeout=90)
  145. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  146. output=log.read_text(encoding='utf-8',errors='replace')
  147. ok=(code==0 and 'SUCCESS!' in output) if name=='proof' else (code==1 and 'proof did fail' in output)
  148. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else 'FAIL',
  149. 'log':str(log),'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  150. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'FAIL'
  151. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  152. print(json.dumps(result,indent=2))
  153. return 0 if result['status']=='PASS' else 1
  154. if __name__=='__main__':raise SystemExit(main())