| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- #!/usr/bin/env python3
- """Prove actual RTL arithmetic expressions and require four mutations to fail.
- This is an unconstrained combinational proof, not a sequential motor proof.
- """
- from pathlib import Path
- import argparse,datetime,hashlib,json,os,re,signal,subprocess,sys
- ROOT=Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
- from tools.source_identity import source_identity
- def prove_event_losses(out):
- engine=ROOT/'src/motor/motor_engine.v';core=ROOT/'src/motor/motor_axis_core.v'
- text=engine.read_text(encoding='utf-8');producer=core.read_text(encoding='utf-8')
- shapes={}
- for signal_name in ('done_pulse','limit_event_pulse'):
- writes=re.findall(r'\b'+signal_name+r'(\[[^\]]+\])?\s*<=\s*([^;]+);',producer)
- if not writes or not any(index for index,_ in writes):raise ValueError('producer write shape missing')
- if any(not ((not index and value.strip()=='0') or (index=='[scan_axis]' and value.strip()=='1')) for index,value in writes):
- raise ValueError('producer no longer has a single-destination write shape')
- if re.search(r'\b'+signal_name+r'(?:\[[^\]]+\])?\s*(?:\|=|&=|\^=|\+=|-=|=(?!=))',producer):
- raise ValueError('unexpected producer blocking/compound assignment')
- shapes[signal_name]=writes
- if 'end else begin\n done_pulse<=0;seg_consumed<=0;limit_event_pulse<=0;' not in producer:
- raise ValueError('unconditional per-clock producer clear changed')
- start=text.index(' for(ev_scan=0;',text.index('// The core emits at most one record'))
- end=text.index('\n end\n always @(posedge clk',start)
- body=text[start:end]
- condition='ax_done[ev_scan] && (event_for_stop(ax_reason[ev_scan])!=0 || (home_pending_r[ev_scan] && ax_reason[ev_scan]==SR_LOWER))'
- if body.count(condition)!=1:raise ValueError('completion qualification expression changed')
- body=body.replace(condition,'accepted_done[ev_scan]')
- declarations='\n'.join(re.search(r'wire\s+\[[^\]]+\]\s+'+name+r'=[^;]+;',text).group(0)
- for name in ('pending_loss_total','pending_losses'))
- variants={}
- for axes in (3,12):
- prefix=f'''module proof(input [{axes-1}:0] ax_limit_pulse,accepted_done,limit_pending,done_pending,
- input [{axes*4-1}:0] ax_limit_drops,input ev_wr_req,reset_pending,select_limit,
- input signed [31:0] ev_select,output bad,output [8:0] observed);
- localparam AXIS_COUNT={axes};
- integer ev_scan,j;reg [3:0] pending_drop_union;reg pending_limit_loss,pending_done_loss;
- reg[8:0] reference_losses;
- {declarations}
- always @* begin pending_drop_union=0;pending_limit_loss=0;pending_done_loss=0;
- '''
- reference=f'''
- end
- always @* begin
- reference_losses=0;
- for(j=0;j<{axes};j=j+1)begin
- if(ax_limit_pulse[j])begin
- reference_losses=reference_losses+ax_limit_drops[j*4+:4];
- if(limit_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || !select_limit))reference_losses=reference_losses+1'b1;
- end
- if(accepted_done[j] && done_pending[j] && (ev_wr_req || reset_pending || ev_select!=j || select_limit))reference_losses=reference_losses+1'b1;
- end
- end
- wire premise=((ax_limit_pulse & (ax_limit_pulse-1'b1))==0) && ((accepted_done & (accepted_done-1'b1))==0);
- assign bad=premise && (pending_losses!=reference_losses);
- assign observed=premise ? pending_losses : 0;
- endmodule
- '''
- rtl=prefix+body+reference
- variants[f'loss_{axes}_proof']=(rtl,'proof')
- mutation=rtl.replace("{1'b0,pending_drop_union}","5'd0")
- if mutation==rtl:raise ValueError('event-loss mutation did not change RTL')
- variants[f'loss_{axes}_mutation']=(mutation,'mutation')
- variants[f'loss_{axes}_cover']=(rtl,'cover')
- # The checked source write form is zero plus arbitrary enables writing
- # bit scan_axis. Model all enables and qualification masks freely.
- emitter=f'''module proof(input [3:0] scan_axis,input done_enable,limit_enable,
- input [{axes-1}:0] qualification,output bad,output [8:0] observed);
- reg [{axes-1}:0] done,limit;
- always @* begin done=0;limit=0;if(done_enable)done[scan_axis]=1;if(limit_enable)limit[scan_axis]=1;end
- wire [{axes-1}:0] accepted=done & qualification;
- assign bad=((done & (done-1'b1))!=0) || ((limit & (limit-1'b1))!=0) || ((accepted & (accepted-1'b1))!=0);
- assign observed=0;
- endmodule
- '''
- variants[f'producer_form_{axes}_proof']=(emitter,'proof')
- result={'scope':'event-loss combinational equivalence plus checked producer write-form proof; not full sequential motor proof',
- 'source':source_identity(ROOT),'inputs':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in (core,engine,Path(__file__).resolve())},
- 'producer_write_shapes':shapes,'premise':'at most one emitted limit and one qualified completion per clock; producer form checked separately',
- 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'results':[],'hardware':'NOT_RUN'}
- for name,(rtl,kind) in variants.items():
- path=out/(name+'.v');path.write_text(rtl,encoding='utf-8');log=out/(name+'.log')
- goal='sat -set observed 3 -show-inputs' if kind=='cover' else 'sat -verify -prove bad 0 -show-inputs'
- command=['yosys','-p',f'read_verilog -formal {json.dumps(str(path),ensure_ascii=False)}; prep -top proof; {goal}']
- with log.open('w') as stream:
- process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
- try:code=process.wait(timeout=90)
- except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
- output=log.read_text(errors='replace')
- 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))
- result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
- 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
- result['status']='PASS' if all(row['status']=='PASS' for row in result['results']) else 'INCOMPLETE'
- (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
- return 0 if result['status']=='PASS' else 1
- def prove_selector(out):
- source=ROOT/'src/motor/motor_engine.v'
- raw=source.read_text(encoding='utf-8')
- start=raw.index(' always @* begin',raw.index('// Factor one-bit eligibility/priority'))
- end=raw.index('\n end\n',start)+len('\n end\n')
- actual=raw[start:end]
- inputs={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
- (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
- result={'schema':'prod2u-queue-selector-proof-v1','scope':'extracted combinational eligibility and circular winner only; no sequential or STEP proof',
- 'source':source_identity(ROOT),'inputs':inputs,'source_manifest_sha256':hashlib.sha256(json.dumps(inputs,sort_keys=True).encode()).hexdigest(),
- 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),
- 'assumptions':['fx_round is a legal axis index; all eligibility/control/depth input bits otherwise arbitrary'],
- 'results':[],'hardware':'NOT_RUN','status':'RUNNING'}
- for axes in (3,12):
- width=(axes-1).bit_length()
- prefix=f'''module selector(input [{width-1}:0] fx_round,
- input [{axes-1}:0] ax_load_ready,ax_seg_load,queue_paused_r,cs_start_mask,cs_mask,urgent_valid_r,
- input [1:0] cs_state,input seek_context,input [{axes*6-1}:0] depths,
- output bad,output reg [7:0] fx_candidate,output reg fx_candidate_valid);
- localparam AXIS_COUNT={axes};
- wire [5:0] depth_r[0:AXIS_COUNT-1];
- genvar g;generate for(g=0;g<AXIS_COUNT;g=g+1)begin
- assign depth_r[g]=depths[g*6+:6];
- end endgenerate
- reg [AXIS_COUNT-1:0] fx_eligible;
- integer fx_k,fx_probe;
- '''
- reference='''
- integer axis,distance,best_distance;
- reg reference_valid;reg[7:0]reference_axis;reg allowed;
- always @* begin
- reference_valid=0;reference_axis=0;best_distance=AXIS_COUNT;distance=0;allowed=0;
- for(axis=0;axis<AXIS_COUNT;axis=axis+1)begin
- allowed=ax_load_ready[axis] && !ax_seg_load[axis] && !queue_paused_r[axis] &&
- ((cs_state==0) || (cs_state==3 && cs_start_mask[axis]) || (seek_context && cs_mask[axis])) &&
- (urgent_valid_r[axis] || (|depths[axis*6+:6]));
- distance=axis>=fx_round ? axis-fx_round : axis+AXIS_COUNT-fx_round;
- if(allowed && distance<best_distance)begin
- reference_valid=1;reference_axis=axis;best_distance=distance;
- end
- end
- end
- assign bad=(fx_round<AXIS_COUNT) && ((reference_valid!=fx_candidate_valid) ||
- (reference_valid && reference_axis!=fx_candidate));
- endmodule
- '''
- proof=prefix+actual+reference
- 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)')
- if mutation==proof:raise ValueError('selector mutation did not change source')
- for kind,text in (('proof',proof),('reverse_priority_mutation',mutation),('nonempty_cover',proof)):
- name=f'axis{axes}_{kind}';vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
- 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'
- command=['yosys','-p',f'read_verilog -formal {json.dumps(str(vf),ensure_ascii=False)}; prep -top selector; {goal}']
- log=out/(name+'.log')
- with log.open('w') as stream:
- process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
- try:code=process.wait(timeout=90)
- except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
- output=log.read_text(encoding='utf-8',errors='replace')
- ok=(code==0 and 'SUCCESS!' in output) if kind=='proof' else (
- (code==1 and 'proof did fail' in output) if kind=='reverse_priority_mutation' else
- (code==0 and 'model found:' in output))
- result['results'].append({'name':name,'command':command,'exit_code':code,
- 'status':'PASS' if ok else ('UNKNOWN_TIMEOUT' if code==124 else 'FAIL'),
- 'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
- result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'INCOMPLETE'
- (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
- print(json.dumps(result,indent=2));return 0 if result['status']=='PASS' else 1
- def main():
- ap=argparse.ArgumentParser(description=__doc__)
- ap.add_argument('--run-root',type=Path,required=True)
- ap.add_argument('--selector',action='store_true',help='prove extracted queue selection for3/12 axes, a reversed-priority mutation and nonempty covers')
- ap.add_argument('--event-loss',action='store_true',help='prove extracted event-loss reduction and producer write form')
- args=ap.parse_args()
- if sys.platform!='linux':ap.error('Execute in the authorized Linux container')
- out=args.run_root.resolve()
- if out==ROOT or ROOT in out.parents:ap.error('run-root must be external')
- out.mkdir(parents=True,exist_ok=False)
- if args.event_loss:return prove_event_losses(out)
- if args.selector:return prove_selector(out)
- source=ROOT/'src/motor/motor_axis_core.v'
- raw=source.read_text(encoding='utf-8')
- 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']
- substitutions={'now_us[33:0]':'now_time','due[scan_axis]':'deadline','s_due':'deadline','r_total[scan_axis]':'total',
- 's_total':'total','s_executed':'executed','s_position':'position','r_executed[scan_axis]':'executed','r_position[scan_axis]':'position','rise_pending[scan_axis]':'rise',
- 'r_dir_upper[scan_axis]':'up','selected_hits':'hits','lower_pending[scan_axis]':'lower_inc','upper_pending[scan_axis]':'upper_inc',
- 'deadline_base':'base','deadline_duration':'duration','deadline_setup':'setup'}
- declarations=[]
- for name in names:
- match=re.search(r'wire\s+(\[[^\]]+\]\s+)?'+re.escape(name)+r'\s*=([^;]*);',raw)
- if not match:raise ValueError('RTL expression missing: '+name)
- declaration=match.group(0)
- for before,after in substitutions.items():declaration=declaration.replace(before,after)
- declarations.append(declaration)
- prefix='''module arithmetic_equivalence(input [33:0] now_time,deadline,base,input [31:0] duration,setup,
- input [31:0] total,executed,position,input [63:0] hits,
- input [3:0] lower_inc,upper_inc,input rise,up,output bad);
- '''
- suffix='''
- wire [33:0] ref_now=now_time-deadline;
- wire [33:0] ref_next=(now_time+34'd1)-deadline;
- wire [31:0] ref_total=total+rise,ref_exec=executed+rise;
- wire [31:0] ref_lower=hits[31:0]+lower_inc,ref_upper=hits[63:32]+upper_inc;
- wire [31:0] ref_position=rise ? (up ? position+32'd1 : position-32'd1) : position;
- wire ref_position_wrap=rise && (up ? position==32'h7FFFFFFF : position==32'h80000000);
- wire [33:0] ref_planned=base+{2'd0,duration}+{2'd0,setup};
- assign bad=(planned_deadline!==ref_planned) || (deadline_now!==!ref_now[33]) || (deadline_next!==!ref_next[33]) ||
- (total_next!==ref_total) || (exec_next!==ref_exec) || (pos_next!==ref_position) ||
- (total_sum[32] !== (rise && total==32'hFFFFFFFF)) ||
- (exec_sum[32] !== (rise && executed==32'hFFFFFFFF)) ||
- (lower_hit_sum[31:0]!==ref_lower) || (upper_hit_sum[31:0]!==ref_upper) ||
- (lower_hit_sum[32] !== (ref_lower<hits[31:0])) || (upper_hit_sum[32] !== (ref_upper<hits[63:32])) ||
- ((rise && position_signed_overflow)!==ref_position_wrap);
- endmodule
- '''
- base=prefix+'\n'.join(declarations)+suffix
- variants={'proof':base,
- 'mutation_deadline_boundary':base.replace('deadline_now ^ (&deadline_difference[32:0])','deadline_now || (&deadline_difference)'),
- 'mutation_upper_carry':base.replace('(upper_hit_sum[32] !==','(1\'b0 !=='),
- 'mutation_position_delta':base.replace("up ? 32'd1 : 32'hFFFFFFFF","32'd1"),
- 'mutation_duration_high_bit':base.replace("{2'd0,duration}","{3'd0,duration[30:0]}",1)}
- manifest={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in
- (source,Path(__file__).resolve(),ROOT/'projects/mrdimm-chamber/project.json')}
- result={'schema':'prod2u-combinational-arithmetic-proof-v1','scope':'arithmetic expressions only; no state-machine proof',
- 'run_id':out.name,'inputs':manifest,'source_manifest_sha256':hashlib.sha256(json.dumps(manifest,sort_keys=True).encode()).hexdigest(),
- 'project_sha256':manifest['projects/mrdimm-chamber/project.json'],'bitstream_sha256':None,
- 'commit':source_identity(ROOT)['commit'],
- 'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
- 'tool':subprocess.check_output(['yosys','-V'],text=True).strip(),'assumptions':[], 'results':[],'status':'RUNNING'}
- for name,text in variants.items():
- if name!='proof' and text==base:raise ValueError('mutation did not change the extracted RTL')
- vf=out/(name+'.v');vf.write_text(text,encoding='utf-8')
- log=out/(name+'.log')
- 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']
- with log.open('w') as stream:
- process=subprocess.Popen(command,stdout=stream,stderr=subprocess.STDOUT,start_new_session=True)
- try:code=process.wait(timeout=90)
- except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();code=124
- output=log.read_text(encoding='utf-8',errors='replace')
- ok=(code==0 and 'SUCCESS!' in output) if name=='proof' else (code==1 and 'proof did fail' in output)
- result['results'].append({'name':name,'command':command,'exit_code':code,'status':'PASS' if ok else 'FAIL',
- 'log':str(log),'log_sha256':hashlib.sha256(log.read_bytes()).hexdigest(),'miter_sha256':hashlib.sha256(vf.read_bytes()).hexdigest()})
- result['status']='PASS' if all(x['status']=='PASS' for x in result['results']) else 'FAIL'
- (out/'RESULT.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
- print(json.dumps(result,indent=2))
- return 0 if result['status']=='PASS' else 1
- if __name__=='__main__':raise SystemExit(main())
|