1 # SPDX-License-Identifier: LGPL-2-or-later
2 """TestRunner class, part of the Test API
6 Copyright (C) 2020,2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
7 Copyright (C) 2021 Kyle Lehman <klehman9@comcast.net>
8 Copyright (C) 2021 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
9 Copyright (C) 2021 Tobias Platen <tplaten@posteo.de>
10 Copyright (C) 2021 Cesar Strauss <cestrauss@gmail.com>
14 * https://bugs.libre-soc.org/show_bug.cgi?id=363
15 * https://bugs.libre-soc.org/show_bug.cgi?id=686#c51
18 from unittest
.mock
import Mock
19 from nmigen
import Module
, ClockSignal
20 from copy
import copy
, deepcopy
21 from pprint
import pformat
23 # NOTE: to use cxxsim, export NMIGEN_SIM_MODE=cxxsim from the shell
24 # Also, check out the cxxsim nmigen branch, and latest yosys from git
25 from nmutil
.sim_tmp_alternative
import Simulator
, Settle
27 from nmutil
.formaltest
import FHDLTestCase
28 from nmutil
.gtkw
import write_gtkw
29 from openpower
.decoder
.isa
.all
import ISA
30 from openpower
.endian
import bigendian
32 from openpower
.decoder
.power_decoder2
import PowerDecode2
34 from nmutil
.util
import wrap
35 from openpower
.test
.wb_get
import wb_get
36 import openpower
.test
.wb_get
as wbget
37 from openpower
.test
.state
import TestState
, StateRunner
, ExpectedState
38 from openpower
.util
import log
, LogKind
41 class SimRunner(StateRunner
):
42 """SimRunner: Implements methods for the setup, preparation, and
43 running of tests using ISACaller simulation
46 def __init__(self
, dut
, m
, pspec
):
47 super().__init
__("sim", SimRunner
)
50 self
.mmu
= pspec
.mmu
== True
51 fp_en
= pspec
.fp_en
== True
52 regreduce_en
= pspec
.regreduce_en
== True
53 self
.simdec2
= simdec2
= PowerDecode2(
54 None, regreduce_en
=regreduce_en
, fp_en
=fp_en
)
55 m
.submodules
.simdec2
= simdec2
# pain in the neck
57 def prepare_for_test(self
, test
):
62 def run_test(self
, instructions
, gen
, insncode
):
63 """run_sim_state - runs an ISACaller simulation
66 dut
, test
, simdec2
= self
.dut
, self
.test
, self
.simdec2
69 # set up the Simulator (which must track TestIssuer exactly)
70 sim
= ISA(simdec2
, test
.regs
, test
.sprs
, test
.cr
, test
.mem
,
72 initial_insns
=gen
, respect_pc
=True,
75 initial_svstate
=test
.svstate
,
77 fpregfile
=test
.fpregs
,
78 initial_fpscr
=test
.initial_fpscr
)
80 # run the loop of the instructions on the current test
81 index
= sim
.pc
.CIA
.value
//4
82 while index
< len(instructions
):
83 ins
, code
= instructions
[index
]
85 # extra new-line so it's easier to visually separate each
86 # instruction in output
87 log(f
"\n0x{sim.pc.CIA.value:04X}: {ins % (1 << 32):08X} {code}",
88 kind
=LogKind
.InstrInOuts
)
90 log("sim instr: 0x{:X} pc=0x{:X}".format(ins
& 0xffffffff,
94 # set up simulated instruction (in simdec2)
96 yield from sim
.setup_one()
97 except KeyError: # instruction not in imem: stop
101 # call simulated operation
103 yield from sim
.execute_one()
105 index
= sim
.pc
.CIA
.value
//4
107 # get sim register and memory TestState, add to list
108 state
= yield from TestState("sim", sim
, dut
, code
)
109 sim_states
.append(state
)
111 log(f
"final pc: 0x{sim.pc.CIA.value:X}", kind
=LogKind
.InstrInOuts
)
113 if self
.dut
.allow_overlap
:
114 # get last state, at end of run
115 state
= yield from TestState("sim", sim
, dut
, code
)
116 sim_states
.append(state
)
121 class TestRunnerBase(FHDLTestCase
):
122 """TestRunnerBase: Sets up and executes the running of tests
123 contained in tst_data. run_hdl (if provided) is an HDLRunner
124 object. If not provided, hdl simulation is skipped.
126 ISACaller simulation can be skipped by setting run_sim=False.
128 When using an Expected state to test with, the expected state
129 is passed in with tst_data.
132 def __init__(self
, tst_data
, microwatt_mmu
=False, rom
=None,
133 svp64
=True, run_hdl
=None, run_sim
=True,
134 allow_overlap
=False, inorder
=False, fp
=False):
135 super().__init
__("run_all")
136 self
.test_data
= tst_data
137 self
.microwatt_mmu
= microwatt_mmu
140 self
.allow_overlap
= allow_overlap
141 self
.inorder
= inorder
142 self
.run_hdl
= run_hdl
143 self
.run_sim
= run_sim
149 if self
.microwatt_mmu
:
150 # do not wire these up to anything if wb_get is to be used
151 if self
.rom
is not None:
152 ldst_ifacetype
= 'mmu_cache_wb'
153 imem_ifacetype
= 'mmu_cache_wb'
155 ldst_ifacetype
= 'test_mmu_cache_wb'
156 imem_ifacetype
= 'test_bare_wb'
158 ldst_ifacetype
= 'test_bare_wb'
159 imem_ifacetype
= 'test_bare_wb'
161 pspec
= Mock(ldst_ifacetype
=ldst_ifacetype
,
162 imem_ifacetype
=imem_ifacetype
,
172 regreduce
=not self
.allow_overlap
,
173 core_domain
="sync", # no alternative domain
175 allow_overlap
=self
.allow_overlap
,
176 inorder
=self
.inorder
,
177 mmu
=self
.microwatt_mmu
,
181 ###### SETUP PHASE #######
182 # Determine the simulations needed and add to state_list
183 # for setup and running
184 # The methods contained in the respective Runner classes are
185 # called using this list when possible
187 # allow wb_get to run
188 if self
.rom
is not None:
194 hdlrun
= self
.run_hdl(self
, m
, pspec
)
195 state_list
.append(hdlrun
)
198 simrun
= SimRunner(self
, m
, pspec
)
199 state_list
.append(simrun
)
201 # run core clock at same rate as test clock
202 # XXX this has to stay here! TODO, work out why,
203 # but Simulation-only fails without it
204 intclk
= ClockSignal("coresync")
205 comb
+= intclk
.eq(ClockSignal())
206 dbgclk
= ClockSignal("dbgsync")
207 comb
+= dbgclk
.eq(ClockSignal())
209 # nmigen Simulation - everything runs around this, so it
210 # still has to be created.
216 ###### PREPARATION PHASE AT START OF RUNNING #######
218 for runner
in state_list
:
219 yield from runner
.setup_during_test()
221 # get each test, completely reset the core, and run it
223 for test
in self
.test_data
:
224 with self
.subTest(test
.name
, **test
.subtest_args
):
226 ###### PREPARATION PHASE AT START OF TEST #######
228 # HACK: if there is test memory and wb_get is in use,
229 # overwrite (reset) the wb_get memory dictionary with
230 # the test's memory contents (oh, and put the wb_get
231 # memory back in as well)
232 self
.default_mem
.clear()
233 if self
.rom
is not None:
234 self
.default_mem
.update(deepcopy(self
.rom
))
235 if test
.mem
is not None:
236 self
.default_mem
.update(deepcopy(test
.mem
))
238 for runner
in state_list
:
239 yield from runner
.prepare_for_test(test
)
241 log("running test: ", test
.name
, test
.subtest_args
,
242 kind
=LogKind
.InstrInOuts
)
243 program
= test
.program
245 def format_regs(regs
):
246 # type: (list[int]) -> str
248 for i
, v
in enumerate(regs
):
251 for signed
in ("u", "i"):
252 value
= v
% (1 << sz
)
253 if signed
== "i" and \
254 value
& (1 << (sz
- 1)) != 0:
256 values
+= f
" {signed}{sz}:{value}"
257 out
.append(f
"r{i} = 0x{v:X} {values}")
258 return "\n".join(out
)
259 log("regs:", format_regs(test
.regs
),
260 kind
=LogKind
.InstrInOuts
)
261 log("sprs", test
.sprs
, kind
=LogKind
.InstrInOuts
)
262 log("cr", test
.cr
, kind
=LogKind
.InstrInOuts
)
264 log("msr", test
.msr
, kind
=LogKind
.InstrInOuts
)
266 def format_assembly(assembly
):
270 for line
in assembly
.splitlines():
271 out
.append(f
"pc=0x{pc:04X}: {line}")
272 if not line
.startswith(".set ") and \
273 line
.partition('#')[0].strip() != "":
275 return "\n".join(out
)
276 log("assembly:\n" + format_assembly(program
.assembly
),
277 kind
=LogKind
.InstrInOuts
)
278 gen
= list(program
.generate_instructions())
279 insncode
= program
.assembly
.splitlines()
280 instructions
= list(zip(gen
, insncode
))
282 ###### RUNNING OF EACH TEST #######
283 # StateRunner.step_test()
285 # Run two tests (TODO, move these to functions)
286 # * first the Simulator, collate a batch of results
287 # * then the HDL, likewise
288 # (actually, the other way round because running
289 # Simulator somehow modifies the test state!)
290 # * finally, compare all the results
292 # TODO https://bugs.libre-soc.org/show_bug.cgi?id=686#c73
298 hdl_states
= yield from hdlrun
.run_test(instructions
)
305 sim_states
= yield from simrun
.run_test(
309 ###### COMPARING THE TESTS #######
315 # TODO: here just grab one entry from list_of_sim_runners
316 # (doesn't matter which one, honestly)
317 # TODO https://bugs.libre-soc.org/show_bug.cgi?id=686#c73
320 last_sim
= copy(sim_states
[-1])
322 last_sim
= copy(hdl_states
[-1])
324 last_sim
= None # err what are you doing??
328 for state
in hdl_states
:
331 # FIXME: commented until SimState has a __repr__
334 # for state in sim_states:
338 if self
.run_hdl
and self
.run_sim
:
339 # if allow_overlap is enabled, because allow_overlap
340 # can commit out-of-order, only compare the last ones
341 if self
.allow_overlap
:
342 log("allow_overlap: truncating %d %d "
343 "states to last" % (len(sim_states
),
345 sim_states
= sim_states
[-1:]
346 hdl_states
= hdl_states
[-1:]
347 sim_states
[-1].dump_state_tofile()
348 log("allow_overlap: last hdl_state")
349 hdl_states
[-1].dump_state_tofile()
350 for simstate
, hdlstate
in zip(sim_states
, hdl_states
):
351 simstate
.compare(hdlstate
) # register check
352 simstate
.compare_mem(hdlstate
) # memory check
354 # if no expected, create /tmp/case_name.py with code
355 # setting expected state to last_sim
356 if test
.expected
is None:
357 last_sim
.dump_state_tofile(test
.name
, test
.test_file
)
359 # compare against expected results
360 if test
.expected
is not None:
361 # have to put these in manually
362 test
.expected
.to_test
= test
.expected
363 test
.expected
.dut
= self
364 test
.expected
.state_type
= "expected"
365 test
.expected
.code
= 0
366 # do actual comparison, against last item
367 last_sim
.compare(test
.expected
)
369 # check number of instructions run (sanity)
370 if self
.run_hdl
and self
.run_sim
:
371 n_hdl
= len(hdl_states
)
372 n_sim
= len(sim_states
)
373 self
.assertTrue(n_hdl
== n_sim
,
374 "number of instructions %d %d "
375 "run not the same" % (n_hdl
, n_sim
))
377 ###### END OF A TEST #######
378 # StateRunner.end_test()
380 for runner
in state_list
:
381 yield from runner
.end_test() # TODO, some arguments?
383 ###### END OF EVERYTHING (but none needs doing, still call fn) ####
384 # StateRunner.cleanup()
386 for runner
in state_list
:
387 yield from runner
.cleanup() # TODO, some arguments?
389 # finally stop wb_get from going
390 if self
.rom
is not None:
394 'dec': {'base': 'dec'},
395 'bin': {'base': 'bin'},
396 'closed': {'closed': True}
401 ('state machines', 'closed', [
402 'fetch_pc_i_valid', 'fetch_pc_o_ready',
404 'fetch_insn_o_valid', 'fetch_insn_i_ready',
405 'pred_insn_i_valid', 'pred_insn_o_ready',
406 'fetch_predicate_state',
407 'pred_mask_o_valid', 'pred_mask_i_ready',
409 'exec_insn_i_valid', 'exec_insn_o_ready',
411 'exec_pc_o_valid', 'exec_pc_i_ready',
412 'insn_done', 'core_stop_o', 'pc_i_ok', 'pc_changed',
413 'is_last', 'dec2.no_out_vec']),
414 {'comment': 'fetch and decode'},
416 'cia[63:0]', 'nia[63:0]', 'pc[63:0]', 'msr[63:0]',
417 'cur_pc[63:0]', 'core_core_cia[63:0]']),
419 'raw_opcode_in[31:0]', 'insn_type', 'dec2.dec2_exc_happened',
420 ('svp64 decoding', 'closed', [
421 'svp64_rm[23:0]', ('dec2.extra[8:0]', 'bin'),
422 'dec2.sv_rm_dec.mode', 'dec2.sv_rm_dec.predmode',
423 'dec2.sv_rm_dec.ptype_in',
424 'dec2.sv_rm_dec.dstpred[2:0]', 'dec2.sv_rm_dec.srcpred[2:0]',
425 'dstmask[63:0]', 'srcmask[63:0]',
426 'dregread[4:0]', 'dinvert',
427 'sregread[4:0]', 'sinvert',
428 'core.int.pred__addr[4:0]', 'core.int.pred__data_o[63:0]',
429 'core.int.pred__ren']),
430 ('register augmentation', 'dec', 'closed', [
431 {'comment': 'v3.0b registers'},
432 'dec2.dec_o.RT[4:0]',
433 'dec2.dec_a.RA[4:0]',
434 'dec2.dec_b.RB[4:0]',
436 'dec2.o_svdec.reg_in[4:0]',
437 ('dec2.o_svdec.spec[2:0]', 'bin'),
438 'dec2.o_svdec.reg_out[6:0]']),
440 'dec2.in1_svdec.reg_in[4:0]',
441 ('dec2.in1_svdec.spec[2:0]', 'bin'),
442 'dec2.in1_svdec.reg_out[6:0]']),
444 'dec2.in2_svdec.reg_in[4:0]',
445 ('dec2.in2_svdec.spec[2:0]', 'bin'),
446 'dec2.in2_svdec.reg_out[6:0]']),
447 {'comment': 'SVP64 registers'},
448 'dec2.rego[6:0]', 'dec2.reg1[6:0]', 'dec2.reg2[6:0]'
450 {'comment': 'svp64 context'},
451 'core_core_vl[6:0]', 'core_core_maxvl[6:0]',
452 'core_core_srcstep[6:0]', 'next_srcstep[6:0]',
453 'core_core_dststep[6:0]',
454 {'comment': 'issue and execute'},
455 'core.core_core_insn_type',
457 'core_rego[6:0]', 'core_reg1[6:0]', 'core_reg2[6:0]']),
460 'dbg.dmi_req_i', 'dbg.dmi_ack_o',
461 {'comment': 'instruction memory'},
462 'imem.sram.rdport.memory(0)[63:0]',
463 {'comment': 'registers'},
464 # match with soc.regfile.regfiles.IntRegs port names
465 'core.int.rp_src1.memory(0)[63:0]',
466 'core.int.rp_src1.memory(1)[63:0]',
467 'core.int.rp_src1.memory(2)[63:0]',
468 'core.int.rp_src1.memory(3)[63:0]',
469 'core.int.rp_src1.memory(4)[63:0]',
470 'core.int.rp_src1.memory(5)[63:0]',
471 'core.int.rp_src1.memory(6)[63:0]',
472 'core.int.rp_src1.memory(7)[63:0]',
473 'core.int.rp_src1.memory(9)[63:0]',
474 'core.int.rp_src1.memory(10)[63:0]',
475 'core.int.rp_src1.memory(13)[63:0]',
476 # Exceptions: see list archive for description of the chain
477 # http://lists.libre-soc.org/pipermail/libre-soc-dev/2021-December/004220.html
478 ('exceptions', 'closed', [
480 'pdecode2.exc_happened',
482 'core.fus.ldst0.exc_o_happened']),
485 # PortInterface module path varies depending on MMU option
486 if self
.microwatt_mmu
:
487 pi_module
= 'core.ldst0'
489 pi_module
= 'core.fus.ldst0'
491 traces
+= [('ld/st port interface', {'submodule': pi_module
}, [
494 'ldst_port0_is_ld_i',
495 'ldst_port0_is_st_i',
497 'ldst_port0_addr_i[47:0]',
498 'ldst_port0_addr_i_ok',
499 'ldst_port0_addr_ok_o',
500 'ldst_port0_exc_happened',
501 'ldst_port0_st_data_i[63:0]',
502 'ldst_port0_st_data_i_ok',
503 'ldst_port0_ld_data_o[63:0]',
504 'ldst_port0_ld_data_o_ok',
510 if self
.microwatt_mmu
:
512 {'comment': 'microwatt_mmu'},
513 'core.fus.mmu0.alu_mmu0.illegal',
514 'core.fus.mmu0.alu_mmu0.debug0[3:0]',
515 'core.fus.mmu0.alu_mmu0.mmu.state',
516 'core.fus.mmu0.alu_mmu0.mmu.pid[31:0]',
517 'core.fus.mmu0.alu_mmu0.mmu.prtbl[63:0]',
518 {'comment': 'wishbone_memory'},
519 'core.l0.pimem.bus__ack',
520 'core.l0.pimem.bus__adr[4:0]',
521 'core.l0.pimem.bus__bte',
522 'core.l0.pimem.bus__cti',
523 'core.l0.pimem.bus__cyc',
524 'core.l0.pimem.bus__dat_r[63:0]',
525 'core.l0.pimem.bus__dat_w[63:0]',
526 'core.l0.pimem.bus__dat_err',
527 'core.l0.pimem.bus__dat_sel[7:0]',
528 'core.l0.pimem.bus__dat_stb',
529 'core.l0.pimem.bus__dat_we',
532 gtkname
= "issuer_simulator"
536 write_gtkw("%s.gtkw" % gtkname
,
538 traces
, styles
, module
='bench.top.issuer')
540 # add run of instructions
541 sim
.add_sync_process(process
)
543 # ARGH oh whoops. TODO, core is not passed in!
544 # urrr... work out a hacky-way to sort this (access run_hdl
545 # core directly for now)
547 # optionally, if a wishbone-based ROM is passed in, run that as an
548 # extra emulated process
549 self
.default_mem
= {}
550 if self
.rom
is not None:
551 log("TestRunner with MMU ROM")
552 log(pformat(self
.rom
))
553 dcache
= hdlrun
.issuer
.core
.fus
.fus
["mmu0"].alu
.dcache
554 icache
= hdlrun
.issuer
.core
.fus
.fus
["mmu0"].alu
.icache
555 self
.default_mem
= deepcopy(self
.rom
)
556 sim
.add_sync_process(wrap(wb_get(dcache
.bus
,
557 self
.default_mem
, "DCACHE")))
558 sim
.add_sync_process(wrap(wb_get(icache
.ibus
,
559 self
.default_mem
, "ICACHE")))
561 with sim
.write_vcd("%s.vcd" % gtkname
):