verify_motor_arithmetic.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. #!/usr/bin/env python3
  2. """Scoped proofs of extracted RTL arithmetic, selection and storage.
  3. Each mode records its assumptions and scope; none is a full 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 plaintext_vendor_model(path,name):
  11. """Select an already-visible complete module; never decode protected data."""
  12. original=Path(path).read_bytes()
  13. visible=original.split(b'`pragma protect begin_protected',1)[0]
  14. starts=re.findall(rb'(?m)^\s*module\s+(\w+)\b',visible)
  15. ends=list(re.finditer(rb'(?m)^\s*endmodule\b',visible))
  16. if starts!=[name.encode('ascii')] or len(ends)!=1 or visible[ends[0].end():].strip():
  17. raise ValueError('complete standalone plaintext vendor module unavailable: '+name)
  18. return visible,{'path':str(Path(path).resolve()),'size':len(original),
  19. 'sha256':hashlib.sha256(original).hexdigest(),'plaintext_size':len(visible),
  20. 'plaintext_sha256':hashlib.sha256(visible).hexdigest(),
  21. 'selection':'unchanged plaintext prefix before first protected section; protected contents not used'}
  22. def resolve_vendor_library(library_root=None):
  23. if library_root is not None:return Path(library_root)
  24. roots=[Path(os.environ.get('PRODU2_TD_ROOT','/data/anlogic/TD_Release_2026.1_SP2_NL')),
  25. Path('/data/prod2u/toolchain/TD_Release_2026.1_SP2_NL/TD_Release_2026.1_SP2_NL')]
  26. return next((r/'sim_release/ef2' for r in roots if os.access(r/'bin/td',os.X_OK)),roots[-1]/'sim_release/ef2')
  27. def verify_vendor_state_delay(out,library_root=None):
  28. source=ROOT/'src/motor/motor_axis_core.v';test=ROOT/'tests/sim/motor_axis_bank_tb.v'
  29. library_root=resolve_vendor_library(library_root)
  30. result={'scope':'actual EF2_LOGIC_MULT plaintext vendor model in the production state-bank path; not full vendor netlist or hardware verification',
  31. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,test,Path(__file__).resolve())},
  32. 'results':[],'hardware':'NOT_RUN','full_vendor_netlist':'NOT_RUN'}
  33. def run(name,command,expected=0,marker=None,counts=False):
  34. log=out/(name+'.log')
  35. with log.open('w') as stream:
  36. process=subprocess.Popen(command,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  37. try:code=process.wait(timeout=180)
  38. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  39. text=log.read_text(errors='replace')
  40. checks={int(a):int(n) for a,n in re.findall(r'AXIS_BANK_(\d+)_CHECKS=(\d+)',text)} if counts else None
  41. ok=code==expected and (marker is None or marker in text)
  42. if counts:ok=ok and set(checks)=={1,2,3,12} and all(n>=1000 for n in checks.values())
  43. result['results'].append({'name':name,'command':command,'exit_code':code,'expected_exit':expected,
  44. 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  45. 'checks_by_axis_count':checks,'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest()})
  46. print(name,result['results'][-1]['status'],flush=True)
  47. if not ok:raise RuntimeError(name)
  48. try:
  49. model,identity=plaintext_vendor_model(Path(library_root)/'ef2_logic_mult.v','EF2_LOGIC_MULT')
  50. result['vendor_model']=identity
  51. selected=out/'EF2_LOGIC_MULT.v';selected.write_bytes(model)
  52. result['tools']={name:subprocess.check_output([name,flag],stderr=subprocess.STDOUT).decode(errors='replace')
  53. for name,flag in [('iverilog','-V'),('verilator','--version')]}
  54. common=['-DPROD2U_TD_VENDOR_RAM','-I'+str(ROOT)]
  55. run('icarus-compile',['iverilog','-g2012',*common,'-s','motor_axis_bank_tb','-o',str(out/'bank.vvp'),str(source),str(selected),str(test)])
  56. run('icarus-run',['vvp',str(out/'bank.vvp')],marker='motor_axis_bank_tb PASS',counts=True)
  57. obj=out/'obj'
  58. run('verilator-compile',['verilator','--binary','--timing','-Wno-fatal','-j','2',*common,'--top-module','motor_axis_bank_tb','--Mdir',str(obj),str(source),str(selected),str(test)])
  59. run('verilator-run',[str(obj/'Vmotor_axis_bank_tb')],marker='motor_axis_bank_tb PASS',counts=True)
  60. original=source.read_text(encoding='utf-8');before='.OUTPUTREG("ENABLE"),.IMPLEMENT("DSP")'
  61. if original.count(before)!=1:raise ValueError('vendor output-register mutation target changed')
  62. mutant=out/'missing_product_register.v';mutant.write_text(original.replace(before,'.OUTPUTREG("DISABLE"),.IMPLEMENT("DSP")'),encoding='utf-8')
  63. run('mutation-compile',['iverilog','-g2012',*common,'-s','motor_axis_bank_tb','-o',str(out/'mutation.vvp'),str(mutant),str(selected),str(test)])
  64. run('mutation-run',['vvp',str(out/'mutation.vvp')],expected=1,marker='post-clock rotation mismatch')
  65. result['status']='PASS'
  66. except Exception as error:result.update(status='INCOMPLETE',error=repr(error))
  67. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n')
  68. return 0 if result['status']=='PASS' else 1
  69. def prove_state_delay(out,library_root=None,vendor_model=False):
  70. source=ROOT/'src/motor/motor_axis_core.v';raw=source.read_text(encoding='utf-8')
  71. bank=re.search(r'module motor_axis_words #\(.*?endmodule',raw,re.S).group(0)
  72. primitive=re.search(r'module ef2_motor_delay18\(.*?endmodule',raw,re.S).group(0)
  73. required=['.INPUT_WIDTH_A(18)','.INPUT_WIDTH_B(18)','.OUTPUT_WIDTH(36)',
  74. '.INPUTFORMAT("UNSIGNED")','.INPUTREGA("ENABLE")','.INPUTREGB("DISABLE")',
  75. '.OUTPUTREG("ENABLE")','.IMPLEMENT("DSP")','.SRMODE("ASYNC")',
  76. '.a(data)',".b(18'd1)",'.p(product)',".cea(1'b1)",".ceb(1'b1)",".cepd(1'b1)",
  77. '.clk(clk)','.rstan(rst_n)','.rstbn(rst_n)','.rstpdn(rst_n)','assign delayed=product[17:0];']
  78. if any(primitive.count(item)!=1 for item in required):raise ValueError('documented DSP configuration changed')
  79. bits=int(re.search(r'wire \[(\d+):0\] dsp_delayed;',bank).group(1))+1
  80. bank=bank.replace('output wire [321:0] read_data);','output wire [321:0] read_data,output wire [321:0] reference_data,output wire proof_bad);')
  81. bank=bank.replace(f'wire [{bits-1}:0] dsp_delayed;',f'''wire [{bits-1}:0] dsp_delayed,proof_inputs;
  82. wire [AXIS_COUNT-1:0] proof_stages_bad;
  83. assign proof_stages_bad[0]=proof_inputs!=words[AXIS_COUNT-1][32+:{bits}];
  84. assign proof_stages_bad[1]=dsp_delayed!=words[AXIS_COUNT-2][32+:{bits}];
  85. assign proof_bad=|proof_stages_bad;''')
  86. bank=bank.replace('.delayed(dsp_delayed[d*18+:18]));',
  87. '.delayed(dsp_delayed[d*18+:18]),.proof_input_stage(proof_inputs[d*18+:18]));')
  88. bank=bank.replace('assign complete_delay=stages[AXIS_COUNT-3];',f'''assign complete_delay=stages[AXIS_COUNT-3];
  89. genvar proof_i;
  90. for(proof_i=0;proof_i<AXIS_COUNT-2;proof_i=proof_i+1)begin:stage_invariant
  91. assign proof_stages_bad[proof_i+2]=stages[proof_i]!=words[AXIS_COUNT-3-proof_i][32+:{bits}];
  92. end''')
  93. bank=bank.replace('end else begin:fabric_storage','end else begin:fabric_storage\n assign proof_bad=0;')
  94. bank=bank.replace('endmodule','assign reference_data=words[0];\nendmodule')
  95. if 'reference_data=words[0]' not in bank:raise ValueError('reference observation port missing')
  96. primitive=primitive.replace('output wire[17:0]delayed);','output wire[17:0]delayed,output wire[17:0]proof_input_stage);')
  97. primitive=primitive.replace('assign delayed=product_stage;','assign delayed=product_stage;\n assign proof_input_stage=input_stage;')
  98. vendor_text='';vendor_identity=None
  99. if vendor_model:
  100. visible,vendor_identity=plaintext_vendor_model(resolve_vendor_library(library_root)/'ef2_logic_mult.v','EF2_LOGIC_MULT')
  101. vendor_text=visible.decode('utf-8')
  102. signature='clk, rstan, rstbn, rstpdn);'
  103. if vendor_text.count(signature)!=1 or 'reg [INPUT_WIDTH_A-1:0] a_use' not in vendor_text:
  104. raise ValueError('vendor model observation points changed')
  105. vendor_text=vendor_text.replace(signature,'clk, rstan, rstbn, rstpdn, proof_input_stage);')
  106. vendor_text=vendor_text.replace('endmodule','output [INPUT_WIDTH_A-1:0] proof_input_stage;\nassign proof_input_stage=a_use;\nendmodule')
  107. primitive=primitive.replace('.p(product),','.p(product),.proof_input_stage(proof_input_stage),')
  108. variants={}
  109. for axes in (1,2,3,12):
  110. miter=f'''module proof(input clk,rst_n,input [321:0] data,output bad,output observed);
  111. wire [321:0] actual,reference_data;wire stage_mismatch;
  112. motor_axis_words #(.AXIS_COUNT({axes})) dut(.clk(clk),.rst_n(rst_n),.write_data(data),.read_data(actual),.reference_data(reference_data),.proof_bad(stage_mismatch));
  113. assign bad=(actual!=reference_data) || stage_mismatch;
  114. assign observed=&actual;
  115. endmodule
  116. '''
  117. model=bank+'\n'+primitive+'\n'+vendor_text+'\n'+miter
  118. variants[f'state_{axes}_proof']=(model,'proof',axes)
  119. variants[f'state_{axes}_cover']=(model,'cover',axes)
  120. if axes>1:
  121. changed=(model.replace('.OUTPUTREG("ENABLE"),.IMPLEMENT("DSP")','.OUTPUTREG("DISABLE"),.IMPLEMENT("DSP")') if vendor_model else
  122. model.replace('product_stage<=input_stage','product_stage<=data'))
  123. if changed==model:raise ValueError('state delay mutation missing')
  124. variants[f'state_{axes}_latency_mutation']=(changed,'mutation',axes)
  125. result={'scope':'behavioral state-bank equivalence to original shift registers; documented primitive parameter check; not vendor/hardware simulation',
  126. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (source,Path(__file__).resolve())},
  127. 'primitive_configuration_checked':required,'inductive_invariant':'each DSP input/product and fabric tail stage equals the original shift-register stage at the same age',
  128. 'primitive_assumption':'UG401 section17 input A register plus product register with unsigned B=1; physical vendor model not exercised',
  129. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
  130. if vendor_model:
  131. result.update(scope='actual EF2_LOGIC_MULT functional RTL state-bank equivalence; not mapped whole-device or hardware proof',
  132. vendor_model=vendor_identity,primitive_assumption='supplied vendor functional RTL; physical timing and protected whole-device models are outside scope')
  133. for name,(rtl,kind,axes) in variants.items():
  134. path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
  135. goal=(f'sat -seq {axes+2} -set rst_n 1 -set-at 1 rst_n 0 -set-at {axes+2} observed 1 -show observed' if kind=='cover' else
  136. f'sat -seq 2 -tempinduct -maxsteps {axes+2} -set-at 1 rst_n 0 -prove bad 0 -verify')
  137. defines='-DPROD2U_TD_VENDOR_RAM ' if vendor_model else ''
  138. command=['yosys','-p',f'read_verilog -formal {defines}{json.dumps(str(path),ensure_ascii=False)}; prep -top proof -flatten; memory_map; opt; async2sync; opt; {goal}']
  139. with log.open('w') as stream:
  140. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  141. try:code=process.wait(timeout=90)
  142. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  143. output=log.read_text(errors='replace')
  144. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output))
  145. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  146. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
  147. print(name,result['results'][-1]['status'],flush=True)
  148. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'INCOMPLETE'
  149. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n')
  150. return 0 if result['status']=='PASS' else 1
  151. def prove_history_rotation(out):
  152. engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v'
  153. text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8')
  154. module=re.search(r'module motor_limit_history #\(.*?endmodule',text,re.S).group(0)
  155. # Expose storage only in the proof copy; retain all actual state updates.
  156. module=module.replace('output wire [159:0] read_data',
  157. 'output wire [159:0] read_data, output wire [AXIS_COUNT*160-1:0] proof_records')
  158. module=module.replace('endmodule','genvar p; generate for(p=0;p<AXIS_COUNT;p=p+1)begin:proof_view\n'
  159. 'assign proof_records[p*160+:160]=records[p];\nend endgenerate\nendmodule')
  160. for expression in ('scan_axis<=0;', "scan_axis<=scan_axis==AXIS_COUNT-1 ? 0 : scan_axis+1'b1;",
  161. 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;'):
  162. if expression not in producer:raise ValueError('producer scan/clear shape changed')
  163. scan_writes=re.findall(r'\bscan_axis\s*<=\s*([^;]+);',producer)
  164. if scan_writes!=['0',"scan_axis==AXIS_COUNT-1 ? 0 : scan_axis+1'b1"]:
  165. raise ValueError('producer scan has another update path')
  166. if "lower_q<=limit_lower;upper_q<=limit_upper;\n scan_axis<=scan_axis==AXIS_COUNT-1 ? 0 : scan_axis+1'b1;" not in producer:
  167. raise ValueError('producer scan no longer advances unconditionally after pulse clear')
  168. writes=re.findall(r'\blimit_event_pulse(\[[^\]]+\])?\s*<=\s*([^;]+);',producer)
  169. if not writes or any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes):
  170. raise ValueError('producer event axis changed')
  171. variants={}
  172. for axes in (3,12):
  173. miter=f'''module proof(input clk,rst_n,emit,input [159:0] data,output bad,output observed);
  174. localparam N={axes},AW=$clog2(N);
  175. reg initialized=0;
  176. reg [AW-1:0] scan_axis,emitted_axis;reg event_valid;
  177. wire [AW-1:0] head;
  178. wire [159:0] actual;
  179. wire [N*160-1:0] physical;
  180. reg [159:0] reference [0:N-1];reg [N-1:0] valid;
  181. always @(posedge clk)initialized<=1;
  182. always @(posedge clk or negedge rst_n)begin
  183. if(!rst_n)begin scan_axis<=0;event_valid<=0;emitted_axis<=0;valid<=0;end
  184. else begin
  185. scan_axis<=scan_axis==N-1 ? 0 : scan_axis+1'b1;
  186. event_valid<=emit;emitted_axis<=scan_axis;
  187. if(event_valid)valid[emitted_axis]<=1;
  188. end
  189. end
  190. always @(posedge clk)if(rst_n && event_valid)reference[emitted_axis]<=data;
  191. motor_limit_history #(.AXIS_COUNT(N)) dut(.clk(clk),.rst_n(rst_n),.write_enable(event_valid),
  192. .write_data(data),.read_axis(head),.read_data(actual),.proof_records(physical));
  193. integer k,logical_axis;reg mismatch;
  194. always @* begin
  195. mismatch=(head>=N || scan_axis>=N || head!=(scan_axis==0 ? N-1 : scan_axis-1'b1));
  196. if(event_valid && emitted_axis!=head)mismatch=1;
  197. for(k=0;k<N;k=k+1)begin
  198. logical_axis=head+k;if(logical_axis>=N)logical_axis=logical_axis-N;
  199. if(valid[logical_axis] && physical[k*160+:160]!=reference[logical_axis])mismatch=1;
  200. end
  201. if(valid[head] && actual!=reference[head])mismatch=1;
  202. end
  203. assign bad=initialized && rst_n && mismatch;
  204. assign observed=&valid;
  205. endmodule
  206. '''
  207. full=module+'\n'+miter
  208. if axes==3:
  209. variants[f'history_{axes}_proof']=(full,'proof',axes)
  210. else:
  211. # Prove the complete160-bit record as ten disjoint16-bit goals.
  212. # Each goal keeps the actual unmodified storage and all scan/valid
  213. # state; synthesis may discard unobserved data lanes. Their union
  214. # covers every bit, avoiding the monolithic million-variable SAT.
  215. for low in range(0,160,16):
  216. lane=full.replace('physical[k*160+:160]!=reference[logical_axis]',
  217. f'physical[k*160+{low}+:16]!=reference[logical_axis][{low}+:16]')
  218. lane=lane.replace('actual!=reference[head]',f'actual[{low}+:16]!=reference[head][{low}+:16]')
  219. variants[f'history_{axes}_bits_{low}_{low+15}_proof']=(lane,'proof',axes)
  220. variants[f'history_{axes}_cover']=(full,'cover',axes)
  221. phase=full.replace('read_axis<=AXIS_COUNT-1;','read_axis<=0;')
  222. drop=full.replace('write_enable ? write_data : records[0]','records[0]')
  223. if phase==full or drop==full:raise ValueError('history mutation did not alter actual module')
  224. variants[f'history_{axes}_phase_mutation']=(phase,'mutation',axes)
  225. variants[f'history_{axes}_write_mutation']=(drop,'mutation',axes)
  226. result={'scope':'inductive rotating-history storage equivalence and checked producer scan form; not full motor/event proof',
  227. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (engine,core,Path(__file__).resolve())},
  228. 'assumptions':'arbitrary record data and event enable; actual producer scan/reset/write form checked; initial reset, later reset unrestricted',
  229. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
  230. for name,(rtl,kind,axes) in variants.items():
  231. path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
  232. goal=(f'sat -seq {axes+3} -set rst_n 1 -set-at 1 rst_n 0 -set-at {axes+3} observed 1 -show observed' if kind=='cover' else
  233. 'sat -seq 2 -tempinduct -maxsteps 4 -set-at 1 rst_n 0 -prove bad 0 -verify')
  234. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof -flatten; memory_map; opt; async2sync; opt; {goal}']
  235. with log.open('w') as stream:
  236. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  237. try:code=process.wait(timeout=90)
  238. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  239. output=log.read_text(errors='replace')
  240. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output))
  241. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  242. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
  243. print(name,result['results'][-1]['status'],flush=True)
  244. result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE'
  245. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n')
  246. return 0 if result['status']=='PASS' else 1
  247. def prove_event_losses(out):
  248. engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v'
  249. text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8')
  250. shapes={}
  251. for signal_name in ('done_pulse','limit_event_pulse'):
  252. writes=re.findall(r'\b'+signal_name+r'(\[[^\]]+\])?\s*<=\s*([^;]+);',producer)
  253. if not writes or not any(index for index,_ in writes):raise ValueError('producer write shape missing')
  254. if any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes):
  255. raise ValueError('producer no longer has a single-destination write shape')
  256. if re.search(r'\b'+signal_name+r'(?:\[[^\]]+\])?\s*(?:\|=|&=|\^=|\+=|-=|=(?!=))',producer):
  257. raise ValueError('unexpected producer blocking/compound assignment')
  258. shapes[signal_name]=writes
  259. if 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;' not in producer:
  260. raise ValueError('unconditional per-clock producer clear changed')
  261. start=text.index(' for(ev_scan=0;',text.index('// The core emits at most one record'))
  262. end=text.index('\n end\n always @(posedge clk',start)
  263. body=text[start:end]
  264. condition='ax_done[ev_scan] && (event_for_stop(ax_reason[ev_scan])!=0 || (home_pending_r[ev_scan] && ax_reason[ev_scan]==SR_LOWER))'
  265. if body.count(condition)!=1:raise ValueError('completion qualification expression changed')
  266. body=body.replace(condition,'accepted_done[ev_scan]')
  267. declarations='\n'.join(re.search(r'wire\s+\[[^\]]+\]\s+'+name+r'=[^;]+;',text).group(0)
  268. for name in ('pending_loss_total','pending_losses'))
  269. variants={}
  270. for axes in (3,12):
  271. prefix=f'''module proof(input [{axes-1}:0] ax_limit_pulse,accepted_done,limit_pending,done_pending,
  272. input [{axes*4-1}:0] ax_limit_drops,input ev_wr_req,reset_pending,select_limit,event_dispatch_ready,
  273. input signed [31:0] ev_select,output bad,output [8:0] observed);
  274. localparam AXIS_COUNT={axes};
  275. integer ev_scan,j;reg [3:0] pending_drop_union;reg pending_limit_loss,pending_done_loss;
  276. reg[8:0] reference_losses;
  277. {declarations}
  278. always @* begin pending_drop_union=0;pending_limit_loss=0;pending_done_loss=0;
  279. '''
  280. reference=f'''
  281. end
  282. always @* begin
  283. reference_losses=0;
  284. for(j=0;j<{axes};j=j+1)begin
  285. if(ax_limit_pulse[j])begin
  286. reference_losses=reference_losses+ax_limit_drops[j*4+:4];
  287. if(limit_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || !select_limit || !event_dispatch_ready))reference_losses=reference_losses+1'b1;
  288. end
  289. if(accepted_done[j] && done_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || select_limit || !event_dispatch_ready))reference_losses=reference_losses+1'b1;
  290. end
  291. end
  292. wire premise=((ax_limit_pulse & (ax_limit_pulse-1'b1))==0) && ((accepted_done & (accepted_done-1'b1))==0);
  293. assign bad=premise && (pending_losses!=reference_losses);
  294. assign observed=premise ? pending_losses : 0;
  295. endmodule
  296. '''
  297. rtl=prefix+body+reference
  298. variants[f'loss_{axes}_proof']=(rtl,'proof')
  299. mutation=rtl.replace("{1'b0,pending_drop_union}","5'd0")
  300. if mutation==rtl:raise ValueError('event-loss mutation did not change RTL')
  301. variants[f'loss_{axes}_mutation']=(mutation,'mutation')
  302. variants[f'loss_{axes}_cover']=(rtl,'cover')
  303. # The checked source write form is zero plus arbitrary enables writing
  304. # bit scan_axis. Model all enables and qualification masks freely.
  305. emitter=f'''module proof(input [3:0] scan_axis,input done_enable,limit_enable,
  306. input [{axes-1}:0] qualification,output bad,output [8:0] observed);
  307. reg [{axes-1}:0] done,limit;
  308. always @* begin done=0;limit=0;if(done_enable)done[scan_axis]=1;if(limit_enable)limit[scan_axis]=1;end
  309. wire [{axes-1}:0] accepted=done & qualification;
  310. assign bad=((done & (done-1'b1))!=0) || ((limit & (limit-1'b1))!=0) || ((accepted & (accepted-1'b1))!=0);
  311. assign observed=0;
  312. endmodule
  313. '''
  314. variants[f'producer_form_{axes}_proof']=(emitter,'proof')
  315. result={'scope':'event-loss combinational equivalence plus checked producer write-form proof; not full sequential motor proof',
  316. 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (core,engine,Path(__file__).resolve())},
  317. 'producer_write_shapes':shapes,'premise':'at most one emitted limit and one qualified completion per clock; producer form checked separately',
  318. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
  319. for name,(rtl,kind) in variants.items():
  320. path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
  321. goal='sat -set observed 3 -show-inputs' if kind=='cover' else 'sat -verify -prove bad 0 -show-inputs'
  322. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof; {goal}']
  323. with log.open('w') as stream:
  324. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  325. try:code=process.wait(timeout=90)
  326. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  327. output=log.read_text(errors='replace')
  328. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else ((code==1 and 'proof did fail' in output) if kind=='mutation' else (code==0 and 'model found:' in output))
  329. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  330. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
  331. result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE'
  332. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
  333. return 0 if result['status']=='PASS' else 1
  334. def prove_selector(out):
  335. source=ROOT/'src/motor/motor_engine.v'
  336. raw=source.read_text(encoding='utf-8')
  337. start=raw.index(' always @* begin',raw.index('// Factor one-bit eligibility/priority'))
  338. end=raw.index('\n end\n',start)+len('\n end\n')
  339. actual=raw[start:end]
  340. inputs={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  341. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  342. result={'schema':'prod2u-queue-selector-proof-v1','scope':'extracted combinational eligibility and circular winner only; no sequential or STEP proof',
  343. 'source':source_identity(ROOT),'inputs':inputs,'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True).encode()).hexdigest(),
  344. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),
  345. 'assumptions':['fx_round is a legal axis index; all eligibility/control/depth input bits otherwise arbitrary'],
  346. 'results':[],'hardware':'NOT_RUN','status':'RUNNING'}
  347. for axes in (3,12):
  348. width=(axes-1).bit_length()
  349. prefix=f'''module selector(input [{width-1}:0] fx_round,
  350. input [{axes-1}:0] ax_load_ready,ax_seg_load,queue_paused_r,cs_start_mask,cs_mask,urgent_valid_r,
  351. input [1:0] cs_state,input seek_context,input [{axes*6-1}:0] depths,
  352. output bad,output reg [7:0] fx_candidate,output reg fx_candidate_valid);
  353. localparam AXIS_COUNT={axes};
  354. wire [5:0] depth_r[0:AXIS_COUNT-1];
  355. genvar g;generate for(g=0;g<AXIS_COUNT;g=g+1)begin
  356. assign depth_r[g]=depths[g*6+:6];
  357. end endgenerate
  358. reg [AXIS_COUNT-1:0] fx_eligible;
  359. integer fx_k,fx_probe;
  360. '''
  361. reference='''
  362. integer axis,distance,best_distance;
  363. reg reference_valid;reg[7:0]reference_axis;reg allowed;
  364. always @* begin
  365. reference_valid=0;reference_axis=0;best_distance=AXIS_COUNT;distance=0;allowed=0;
  366. for(axis=0;axis<AXIS_COUNT;axis=axis+1)begin
  367. allowed=ax_load_ready[axis] && !ax_seg_load[axis] && !queue_paused_r[axis] &&
  368. ((cs_state==0) || (cs_state==3 && cs_start_mask[axis]) || (seek_context && cs_mask[axis])) &&
  369. (urgent_valid_r[axis] || (|depths[axis*6+:6]));
  370. distance=axis>=fx_round ? axis-fx_round : axis+AXIS_COUNT-fx_round;
  371. if(allowed && distance<best_distance)begin
  372. reference_valid=1;reference_axis=axis;best_distance=distance;
  373. end
  374. end
  375. end
  376. assign bad=(fx_round<AXIS_COUNT) && ((reference_valid!=fx_candidate_valid) ||
  377. (reference_valid && reference_axis!=fx_candidate));
  378. endmodule
  379. '''
  380. proof=prefix+actual+reference
  381. 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)')
  382. if mutation==proof:raise ValueError('selector mutation did not change source')
  383. for kind,text in (('proof',proof),('reverse_priority_mutation',mutation),('nonempty_cover',proof)):
  384. name=f'axis{axes}_{kind}';vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  385. 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'
  386. command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top selector; {goal}']
  387. log=out/(name+'.log')
  388. with log.open('w') as stream:
  389. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  390. try:code=process.wait(timeout=90)
  391. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  392. output=log.read_text(encoding='utf-8',errors='replace')
  393. ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else (
  394. (code==1 and 'proof did fail' in output) if kind=='reverse_priority_mutation' else
  395. (code==0 and 'model found:' in output))
  396. result['results'].append({'name':name,'command':command,'exit_code':code,
  397. 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
  398. 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  399. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'INCOMPLETE'
  400. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  401. print(json.dumps(result,indent=2));return 0 if result['status']=='PASS' else 1
  402. def main():
  403. ap=argparse.ArgumentParser(description=__doc__)
  404. ap.add_argument('--run-root',type=Path,required=True)
  405. mode=ap.add_mutually_exclusive_group()
  406. mode.add_argument('--selector',action='store_true',help='prove extracted queue selection for3/12 axes, a reversed-priority mutation and nonempty covers')
  407. mode.add_argument('--event-loss',action='store_true',help='prove extracted event-loss reduction and producer write form')
  408. mode.add_argument('--history-rotation',action='store_true',help='prove rotating history storage and producer scan alignment')
  409. mode.add_argument('--state-delay',action='store_true',help='prove behavioral DSP/fabric state delay against original registers')
  410. mode.add_argument('--vendor-state-delay',action='store_true',help='run actual plaintext EF2 multiplier model with the production state bank')
  411. mode.add_argument('--vendor-state-proof',action='store_true',help='prove state-bank equivalence using the actual vendor functional RTL')
  412. ap.add_argument('--vendor-library-root',type=Path,help='TD sim_release/ef2 directory for vendor simulation/proof')
  413. args=ap.parse_args()
  414. if args.vendor_library_root and not (args.vendor_state_delay or args.vendor_state_proof):
  415. ap.error('--vendor-library-root requires a vendor verification mode')
  416. if sys.platform!='linux':ap.error('Execute in the authorized Linux container')
  417. out=args.run_root.resolve()
  418. if out==ROOT or ROOT in out.parents:ap.error('run-root must be external')
  419. out.mkdir(parents=True,exist_ok=False)
  420. if args.vendor_state_delay:return verify_vendor_state_delay(out,args.vendor_library_root)
  421. if args.vendor_state_proof:return prove_state_delay(out,args.vendor_library_root,True)
  422. if args.state_delay:return prove_state_delay(out)
  423. if args.history_rotation:return prove_history_rotation(out)
  424. if args.event_loss:return prove_event_losses(out)
  425. if args.selector:return prove_selector(out)
  426. source=ROOT/'src/motor/motor_axis_core.v'
  427. raw=source.read_text(encoding='utf-8')
  428. 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']
  429. substitutions={'now_us[33:0]':'now_time','due[scan_axis]':'deadline','s_due':'deadline','r_total[scan_axis]':'total',
  430. 's_total':'total','s_executed':'executed','s_position':'position','r_executed[scan_axis]':'executed','r_position[scan_axis]':'position','rise_pending[scan_axis]':'rise',
  431. 'r_dir_upper[scan_axis]':'up','selected_hits':'hits','lower_pending[scan_axis]':'lower_inc','upper_pending[scan_axis]':'upper_inc',
  432. 'deadline_base':'base','deadline_duration':'duration','deadline_setup':'setup'}
  433. declarations=[]
  434. for name in names:
  435. match=re.search(r'wire\s+(\[[^\]]+\]\s+)?'+re.escape(name)+r'\s*=([^;]*);',raw)
  436. if not match:raise ValueError('RTL expression missing: '+name)
  437. declaration=match.group(0)
  438. for before,after in substitutions.items():declaration=declaration.replace(before,after)
  439. declarations.append(declaration)
  440. prefix='''module arithmetic_equivalence(input [33:0] now_time,deadline,base,input [31:0] duration,setup,
  441. input [31:0] total,executed,position,input [63:0] hits,
  442. input [3:0] lower_inc,upper_inc,input rise,up,output bad);
  443. '''
  444. suffix='''
  445. wire [33:0] ref_now=now_time-deadline;
  446. wire [33:0] ref_next=(now_time+34'd1)-deadline;
  447. wire [31:0] ref_total=total+rise,ref_exec=executed+rise;
  448. wire [31:0] ref_lower=hits[31:0]+lower_inc,ref_upper=hits[63:32]+upper_inc;
  449. wire [31:0] ref_position=rise ? (up ? position+32'd1 : position-32'd1) : position;
  450. wire ref_position_wrap=rise && (up ? position==32'h7FFFFFFF : position==32'h80000000);
  451. wire [33:0] ref_planned=base+{2'd0,duration}+{2'd0,setup};
  452. assign bad=(planned_deadline!==ref_planned) || (deadline_now!==!ref_now[33]) || (deadline_next!==!ref_next[33]) ||
  453. (total_next!==ref_total) || (exec_next!==ref_exec) || (pos_next!==ref_position) ||
  454. (total_sum[32] !== (rise && total==32'hFFFFFFFF)) ||
  455. (exec_sum[32] !== (rise && executed==32'hFFFFFFFF)) ||
  456. (lower_hit_sum[31:0]!==ref_lower) || (upper_hit_sum[31:0]!==ref_upper) ||
  457. (lower_hit_sum[32] !== (ref_lower<hits[31:0])) || (upper_hit_sum[32] !== (ref_upper<hits[63:32])) ||
  458. ((rise && position_signed_overflow)!==ref_position_wrap);
  459. endmodule
  460. '''
  461. base=prefix+'\n'.join(declarations)+suffix
  462. variants={'proof':base,
  463. 'mutation_deadline_boundary':base.replace('deadline_now ^ (&deadline_difference[32:0])','deadline_now || (&deadline_difference)'),
  464. 'mutation_upper_carry':base.replace('(upper_hit_sum[32] !==','(1\'b0 !=='),
  465. 'mutation_position_delta':base.replace("up ? 32'd1 : 32'hFFFFFFFF","32'd1"),
  466. 'mutation_duration_high_bit':base.replace("{2'd0,duration}","{3'd0,duration[30:0]}",1)}
  467. manifest={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
  468. (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
  469. result={'schema':'prod2u-combinational-arithmetic-proof-v1','scope':'arithmetic expressions only; no state-machine proof',
  470. 'run_id':out.name,'inputs':manifest,'source_manifest_sha256':hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest(),
  471. 'project_sha256':manifest['projects/mrdimm-chamber/project.json'],'bitstream_sha256':None,
  472. 'commit':source_identity(ROOT)['commit'],
  473. 'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
  474. 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'assumptions':[], 'results':[],'status':'RUNNING'}
  475. for name,text in variants.items():
  476. if name!='proof' and text==base:raise ValueError('mutation did not change the extracted RTL')
  477. vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
  478. log=out/(name+'.log')
  479. 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']
  480. with log.open('w') as stream:
  481. process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
  482. try:code=process.wait(timeout=90)
  483. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
  484. output=log.read_text(encoding='utf-8',errors='replace')
  485. ok=(code==0 and 'SUCCESS!' in output) if name=='proof' else (code==1 and 'proof did fail' in output)
  486. result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else 'FAIL',
  487. 'log':str(log),'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
  488. result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'FAIL'
  489. (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
  490. print(json.dumps(result,indent=2))
  491. return 0 if result['status']=='PASS' else 1
  492. if __name__=='__main__':raise SystemExit(main())