Remove wait state to demonstrate zero-delay reception.
[soc.git] / src / soc / experiment / compalu_multi.py
index 815ff15a77b98a8e57c56a450d225d89aa5d278c..e2f8683a16fca02d44b73e68355807a0f7e84a9c 100644 (file)
@@ -10,19 +10,24 @@ its result(s) have been successfully stored in the regfile(s)
 Documented at http://libre-soc.org/3d_gpu/architecture/compunit
 """
 
-from nmigen.compat.sim import run_simulation
-from nmigen.cli import verilog, rtlil
-from nmigen import Module, Signal, Mux, Elaboratable, Repl, Array, Cat, Const
+from nmigen import Module, Signal, Mux, Elaboratable, Repl, Cat, Const
 from nmigen.hdl.rec import (Record, DIR_FANIN, DIR_FANOUT)
 
 from nmutil.latch import SRLatch, latchregister
 from nmutil.iocontrol import RecordObject
 
-from soc.decoder.power_decoder2 import Data
-from soc.decoder.power_enums import InternalOp
 from soc.fu.regspec import RegSpec, RegSpecALUAPI
 
 
+def find_ok(fields):
+    """find_ok helper function - finds field ending in "_ok"
+    """
+    for field_name in fields:
+        if field_name.endswith("_ok"):
+            return field_name
+    return None
+
+
 def go_record(n, name):
     r = Record([('go', n, DIR_FANIN),
                 ('rel', n, DIR_FANOUT)], name=name)
@@ -30,6 +35,7 @@ def go_record(n, name):
     r.rel.reset_less = True
     return r
 
+
 # see https://libre-soc.org/3d_gpu/architecture/regfile/ section on regspecs
 
 class CompUnitRecord(RegSpec, RecordObject):
@@ -69,8 +75,9 @@ class CompUnitRecord(RegSpec, RecordObject):
         dst = []
         for i in range(n_dst):
             j = i + 1 # name numbering to match dest1/2...
-            name = "dest%d_i" % j
+            name = "dest%d_o" % j
             rw = self._get_dstwid(i)
+            #dreg = Data(rw, name=name) XXX ??? output needs to be a Data type?
             dreg = Signal(rw, name=name, reset_less=True)
             setattr(self, name, dreg)
             dst.append(dreg)
@@ -82,6 +89,8 @@ class CompUnitRecord(RegSpec, RecordObject):
         # create read/write and other scoreboard signalling
         self.rd = go_record(n_src, name="rd") # read in, req out
         self.wr = go_record(n_dst, name="wr") # write in, req out
+        self.rdmaskn = Signal(n_src, reset_less=True) # read mask
+        self.wrmask = Signal(n_dst, reset_less=True) # write mask
         self.issue_i = Signal(reset_less=True) # fn issue in
         self.shadown_i = Signal(reset=1) # shadow function, defaults to ON
         self.go_die_i = Signal() # go die (reset)
@@ -92,7 +101,7 @@ class CompUnitRecord(RegSpec, RecordObject):
 
 
 class MultiCompUnit(RegSpecALUAPI, Elaboratable):
-    def __init__(self, rwid, alu, opsubsetkls, n_src=2, n_dst=1):
+    def __init__(self, rwid, alu, opsubsetkls, n_src=2, n_dst=1, name=None):
         """MultiCompUnit
 
         * :rwid:        width of register latches (TODO: allocate per regspec)
@@ -102,6 +111,7 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         * :n_dst:       number of destination operands
         """
         RegSpecALUAPI.__init__(self, rwid, alu)
+        self.alu_name = name or "alu"
         self.opsubsetkls = opsubsetkls
         self.cu = cu = CompUnitRecord(opsubsetkls, rwid, n_src, n_dst)
         n_src, n_dst = self.n_src, self.n_dst = cu._n_src, cu._n_dst
@@ -116,12 +126,14 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         # convenience names for dest operands
         for i in range(n_dst):
             j = i + 1 # name numbering to match dest1/2...
-            name = "dest%d_i" % j
+            name = "dest%d_o" % j
             setattr(self, name, getattr(cu, name))
 
         # more convenience names
         self.rd = cu.rd
         self.wr = cu.wr
+        self.rdmaskn = cu.rdmaskn
+        self.wrmask = cu.wrmask
         self.go_rd_i = self.rd.go # temporary naming
         self.go_wr_i = self.wr.go # temporary naming
         self.rd_rel_o = self.rd.rel # temporary naming
@@ -139,7 +151,6 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         self.data_o = self.dest[0] # Dest out
         self.done_o = cu.done_o
 
-
     def _mux_op(self, m, sl, op_is_imm, imm, i):
         # select imm if opcode says so. however also change the latch
         # to trigger *from* the opcode latch instead.
@@ -154,7 +165,7 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
 
     def elaborate(self, platform):
         m = Module()
-        m.submodules.alu = self.alu
+        setattr(m.submodules, self.alu_name, self.alu)
         m.submodules.src_l = src_l = SRLatch(False, self.n_src, name="src")
         m.submodules.opc_l = opc_l = SRLatch(sync=False, name="opc")
         m.submodules.req_l = req_l = SRLatch(False, self.n_dst, name="req")
@@ -168,14 +179,43 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         m.d.comb += all_rd.eq(self.busy_o & rok_l.q &
                     (((~self.rd.rel) | self.rd.go).all()))
 
+        # generate read-done pulse
+        all_rd_dly = Signal(reset_less=True)
+        all_rd_pulse = Signal(reset_less=True)
+        m.d.sync += all_rd_dly.eq(all_rd)
+        m.d.comb += all_rd_pulse.eq(all_rd & ~all_rd_dly)
+
+        # create rising pulse from alu valid condition.
+        alu_done = Signal(reset_less=True)
+        alu_done_dly = Signal(reset_less=True)
+        alu_pulse = Signal(reset_less=True)
+        alu_pulsem = Signal(self.n_dst, reset_less=True)
+        m.d.comb += alu_done.eq(self.alu.n.valid_o)
+        m.d.sync += alu_done_dly.eq(alu_done)
+        m.d.comb += alu_pulse.eq(alu_done & ~alu_done_dly)
+        m.d.comb += alu_pulsem.eq(Repl(alu_pulse, self.n_dst))
+
+        # sigh bug where req_l gets both set and reset raised at same time
+        prev_wr_go = Signal(self.n_dst)
+        brd = Repl(self.busy_o, self.n_dst)
+        m.d.sync += prev_wr_go.eq(self.wr.go & brd)
+
         # write_requests all done
         # req_done works because any one of the last of the writes
         # is enough, when combined with when read-phase is done (rst_l.q)
         wr_any = Signal(reset_less=True)
         req_done = Signal(reset_less=True)
-        m.d.comb += self.done_o.eq(self.busy_o & ~(self.wr.rel.bool()))
-        m.d.comb += wr_any.eq(self.wr.go.bool())
-        m.d.comb += req_done.eq(rst_l.q & wr_any)
+        m.d.comb += self.done_o.eq(self.busy_o & \
+                                   ~((self.wr.rel & ~self.wrmask).bool()))
+        m.d.comb += wr_any.eq(self.wr.go.bool() | prev_wr_go.bool())
+        m.d.comb += req_done.eq(wr_any & ~self.alu.n.ready_i & \
+                ((req_l.q & self.wrmask) == 0))
+        # argh, complicated hack: if there are no regs to write,
+        # instead of waiting for regs that are never going to happen,
+        # we indicate "done" when the ALU is "done"
+        with m.If((self.wrmask == 0) & \
+                    self.alu.n.ready_i & self.alu.n.valid_o & self.busy_o):
+            m.d.comb += req_done.eq(1)
 
         # shadow/go_die
         reset = Signal(reset_less=True)
@@ -189,7 +229,7 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
 
         # read-done,wr-proceed latch
         m.d.comb += rok_l.s.eq(self.issue_i)  # set up when issue starts
-        m.d.comb += rok_l.r.eq(self.alu.p.ready_o) # off when ALU acknowledges
+        m.d.sync += rok_l.r.eq(self.alu.n.valid_o & self.busy_o) # ALU done
 
         # wr-done, back-to-start latch
         m.d.comb += rst_l.s.eq(all_rd)     # set when read-phase is fully done
@@ -197,28 +237,46 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
 
         # opcode latch (not using go_rd_i) - inverted so that busy resets to 0
         m.d.sync += opc_l.s.eq(self.issue_i)       # set on issue
-        m.d.sync += opc_l.r.eq(self.alu.n.valid_o & req_done) # reset on ALU
+        m.d.sync += opc_l.r.eq(req_done) # reset on ALU
 
         # src operand latch (not using go_wr_i)
         m.d.sync += src_l.s.eq(Repl(self.issue_i, self.n_src))
         m.d.sync += src_l.r.eq(reset_r)
 
         # dest operand latch (not using issue_i)
-        m.d.sync += req_l.s.eq(Repl(all_rd, self.n_dst))
-        m.d.sync += req_l.r.eq(reset_w)
+        m.d.comb += req_l.s.eq(alu_pulsem & self.wrmask)
+        m.d.comb += req_l.r.eq(reset_w | prev_wr_go)
 
         # create a latch/register for the operand
         oper_r = self.opsubsetkls(name="oper_r")
         latchregister(m, self.oper_i, oper_r, self.issue_i, "oper_l")
 
-        # and for each output from the ALU
+        # and for each output from the ALU: capture when ALU output is valid
         drl = []
+        wrok = []
         for i in range(self.n_dst):
             name = "data_r%d" % i
-            data_r = Signal(self.cu._get_dstwid(i), name=name, reset_less=True)
-            latchregister(m, self.get_out(i), data_r, req_l.q[i], name + "_l")
+            lro = self.get_out(i)
+            ok = Const(1, 1)
+            if isinstance(lro, Record):
+                data_r = Record.like(lro, name=name)
+                print ("wr fields", i, lro, data_r.fields)
+                # bye-bye abstract interface design..
+                fname = find_ok(data_r.fields)
+                if fname:
+                    ok = data_r[fname]
+            else:
+                data_r = Signal.like(lro, name=name, reset_less=True)
+            wrok.append(ok)
+            latchregister(m, lro, data_r, alu_pulsem, name + "_l")
             drl.append(data_r)
 
+        # ok, above we collated anything with an "ok" on the output side
+        # now actually use those to create a write-mask.  this basically
+        # is now the Function Unit API tells the Comp Unit "do not request
+        # a regfile port because this particular output is not valid"
+        m.d.comb += self.wrmask.eq(Cat(*wrok))
+
         # pass the operation to the ALU
         m.d.comb += self.get_op().eq(oper_r)
 
@@ -253,6 +311,23 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
             src, alusrc, latch, _ = sl[i]
             latchregister(m, src, alusrc, latch, name="src_r%d" % i)
 
+        # -----
+        # ALU connection / interaction
+        # -----
+
+        # on a go_read, tell the ALU we're accepting data.
+        m.submodules.alui_l = alui_l = SRLatch(False, name="alui")
+        m.d.comb += self.alu.p.valid_i.eq(alui_l.q)
+        m.d.sync += alui_l.r.eq(self.alu.p.ready_o & alui_l.q)
+        m.d.comb += alui_l.s.eq(all_rd_pulse)
+
+        # ALU output "ready" side.  alu "ready" indication stays hi until
+        # ALU says "valid".
+        m.submodules.alu_l = alu_l = SRLatch(False, name="alu")
+        m.d.comb += self.alu.n.ready_i.eq(alu_l.q)
+        m.d.sync += alu_l.r.eq(self.alu.n.valid_o & alu_l.q)
+        m.d.comb += alu_l.s.eq(all_rd_pulse)
+
         # -----
         # outputs
         # -----
@@ -260,24 +335,14 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         slg = Cat(*map(lambda x: x[3], sl)) # get req gate conditions
         # all request signals gated by busy_o.  prevents picker problems
         m.d.comb += self.busy_o.eq(opc_l.q) # busy out
-        bro = Repl(self.busy_o, self.n_src)
-        m.d.comb += self.rd.rel.eq(src_l.q & bro & slg) # src1/src2 req rel
 
-        # on a go_read, tell the ALU we're accepting data.
-        # NOTE: this spells TROUBLE if the ALU isn't ready!
-        # go_read is only valid for one clock!
-        with m.If(all_rd):                           # src operands ready, GO!
-            with m.If(~self.alu.p.ready_o):          # no ACK yet
-                m.d.comb += self.alu.p.valid_i.eq(1) # so indicate valid
+        # read-release gated by busy (and read-mask)
+        bro = Repl(self.busy_o, self.n_src)
+        m.d.comb += self.rd.rel.eq(src_l.q & bro & slg & ~self.rdmaskn)
 
+        # write-release gated by busy and by shadow (and write-mask)
         brd = Repl(self.busy_o & self.shadown_i, self.n_dst)
-        # only proceed if ALU says its output is valid
-        with m.If(self.alu.n.valid_o):
-            # when ALU ready, write req release out. waits for shadow
-            m.d.comb += self.wr.rel.eq(req_l.q & brd)
-            # when output latch is ready, and ALU says ready, accept ALU output
-            with m.If(reset):
-                m.d.comb += self.alu.n.ready_i.eq(1) # tells ALU "got it"
+        m.d.comb += self.wr.rel.eq(req_l.q & brd & self.wrmask)
 
         # output the data from the latch on go_write
         for i in range(self.n_dst):
@@ -304,257 +369,3 @@ class MultiCompUnit(RegSpecALUAPI, Elaboratable):
         return list(self)
 
 
-def op_sim(dut, a, b, op, inv_a=0, imm=0, imm_ok=0, zero_a=0):
-    yield dut.issue_i.eq(0)
-    yield
-    yield dut.src_i[0].eq(a)
-    yield dut.src_i[1].eq(b)
-    yield dut.oper_i.insn_type.eq(op)
-    yield dut.oper_i.invert_a.eq(inv_a)
-    yield dut.oper_i.imm_data.imm.eq(imm)
-    yield dut.oper_i.imm_data.imm_ok.eq(imm_ok)
-    yield dut.oper_i.zero_a.eq(zero_a)
-    yield dut.issue_i.eq(1)
-    yield
-    yield dut.issue_i.eq(0)
-    yield
-    if not imm_ok or not zero_a:
-        yield dut.rd.go.eq(0b11)
-        while True:
-            yield
-            rd_rel_o = yield dut.rd.rel
-            print ("rd_rel", rd_rel_o)
-            if rd_rel_o:
-                break
-        yield dut.rd.go.eq(0)
-    req_rel_o = yield dut.wr.rel
-    result = yield dut.data_o
-    print ("req_rel", req_rel_o, result)
-    while True:
-        req_rel_o = yield dut.wr.rel
-        result = yield dut.data_o
-        print ("req_rel", req_rel_o, result)
-        if req_rel_o:
-            break
-        yield
-    yield dut.wr.go[0].eq(1)
-    yield
-    result = yield dut.data_o
-    print ("result", result)
-    yield dut.wr.go[0].eq(0)
-    yield
-    return result
-
-
-def scoreboard_sim(dut):
-    result = yield from op_sim(dut, 5, 2, InternalOp.OP_ADD, inv_a=0,
-                                    imm=8, imm_ok=1)
-    assert result == 13
-
-    result = yield from op_sim(dut, 5, 2, InternalOp.OP_ADD)
-    assert result == 7
-
-    result = yield from op_sim(dut, 5, 2, InternalOp.OP_ADD, inv_a=1)
-    assert result == 65532
-
-    result = yield from op_sim(dut, 5, 2, InternalOp.OP_ADD, zero_a=1,
-                                    imm=8, imm_ok=1)
-    assert result == 8
-
-    result = yield from op_sim(dut, 5, 2, InternalOp.OP_ADD, zero_a=1)
-    assert result == 2
-
-
-def test_compunit():
-    from alu_hier import ALU
-    from soc.fu.alu.alu_input_record import CompALUOpSubset
-
-    m = Module()
-    alu = ALU(16)
-    dut = MultiCompUnit(16, alu, CompALUOpSubset)
-    m.submodules.cu = dut
-
-    vl = rtlil.convert(dut, ports=dut.ports())
-    with open("test_compunit1.il", "w") as f:
-        f.write(vl)
-
-    run_simulation(m, scoreboard_sim(dut), vcd_name='test_compunit1.vcd')
-
-
-class CompUnitParallelTest:
-    def __init__(self, dut):
-        self.dut = dut
-
-        # Operation cycle should not take longer than this:
-        self.MAX_BUSY_WAIT = 50
-
-        # Minimum duration in which issue_i will be kept inactive,
-        # during which busy_o must remain low.
-        self.MIN_BUSY_LOW = 5
-
-        # store common data for the input operation of the processes
-        # input operation:
-        self.op = 0
-        self.inv_a = self.zero_a = 0
-        self.imm = self.imm_ok = 0
-        # input data:
-        self.a = self.b = 0
-
-    def driver(self):
-        print("Begin parallel test.")
-        yield from self.operation(5, 2, InternalOp.OP_ADD, inv_a=0,
-                                  imm=8, imm_ok=1)
-
-    def operation(self, a, b, op, inv_a=0, imm=0, imm_ok=0, zero_a=0):
-        # store data for the operation
-        self.a = a
-        self.b = b
-        self.op = op
-        self.inv_a = inv_a
-        self.imm = imm
-        self.imm_ok = imm_ok
-        self.zero_a = zero_a
-
-        # trigger operation cycle
-        yield from self.issue()
-
-    def issue(self):
-        # issue_i starts inactive
-        yield self.dut.issue_i.eq(0)
-
-        for n in range(self.MIN_BUSY_LOW):
-            yield
-            # busy_o must remain inactive. It cannot rise on its own.
-            busy_o = yield self.dut.busy_o
-            assert not busy_o
-
-        # activate issue_i to begin the operation cycle
-        yield self.dut.issue_i.eq(1)
-
-        # at the same time, present the operation
-        yield self.dut.oper_i.insn_type.eq(self.op)
-        yield self.dut.oper_i.invert_a.eq(self.inv_a)
-        yield self.dut.oper_i.imm_data.imm.eq(self.imm)
-        yield self.dut.oper_i.imm_data.imm_ok.eq(self.imm_ok)
-        yield self.dut.oper_i.zero_a.eq(self.zero_a)
-
-        # give one cycle for the CompUnit to latch the data
-        yield
-
-        # busy_o must keep being low in this cycle, because issue_i was
-        # low on the previous cycle.
-        # It cannot rise on its own.
-        # Also, busy_o and issue_i must never be active at the same time, ever.
-        busy_o = yield self.dut.busy_o
-        assert not busy_o
-
-        # Lower issue_i
-        yield self.dut.issue_i.eq(0)
-
-        # deactivate inputs along with issue_i, so we can be sure the data
-        # was latched at the correct cycle
-        yield self.dut.oper_i.insn_type.eq(0)
-        yield self.dut.oper_i.invert_a.eq(0)
-        yield self.dut.oper_i.imm_data.imm.eq(0)
-        yield self.dut.oper_i.imm_data.imm_ok.eq(0)
-        yield self.dut.oper_i.zero_a.eq(0)
-        yield
-
-        # wait for busy_o to lower
-        # timeout after self.MAX_BUSY_WAIT cycles
-        for n in range(self.MAX_BUSY_WAIT):
-            # sample busy_o in the current cycle
-            busy_o = yield self.dut.busy_o
-            if not busy_o:
-                # operation cycle ends when busy_o becomes inactive
-                break
-            yield
-
-        # if busy_o is still active, a timeout has occurred
-        # TODO: Uncomment this, once the test is complete:
-        # assert not busy_o
-
-        if busy_o:
-            print("If you are reading this, "
-                  "it's because the above test failed, as expected,\n"
-                  "with a timeout. It must pass, once the test is complete.")
-            return
-
-        print("If you are reading this, "
-              "it's because the above test unexpectedly passed.")
-
-    def rd(self, rd_idx):
-        # wait for issue_i to rise
-        while True:
-            issue_i = yield self.dut.issue_i
-            if issue_i:
-                break
-            # issue_i has not risen yet, so rd must keep low
-            rd = yield self.dut.rd.rel[rd_idx]
-            assert not rd
-            yield
-
-        # we do not want rd to rise on an immediate operand
-        # if it is immediate, exit the process
-        # TODO: don't exit the process, monitor rd instead to ensure it
-        #       doesn't rise on its own
-        if (self.zero_a and rd_idx == 0) or (self.imm_ok and rd_idx == 1):
-            return
-
-        # issue_i has risen. rd must rise on the next cycle
-        rd = yield self.dut.rd.rel[rd_idx]
-        assert not rd
-        yield
-        rd = yield self.dut.rd.rel[rd_idx]
-        assert rd
-
-        # TODO: set dut.rd.go[idx] for one cycle
-        yield
-        # TODO: also when dut.rd.go is set, put the expected value into
-        # the src_i.  use dut.get_in[rd_idx] to do so
-
-    def wr(self, wr_idx):
-        # monitor self.dut.wr.req[rd_idx] and sets dut.wr.go[idx] for one cycle
-        yield
-        # TODO: also when dut.wr.go is set, check the output against the
-        # self.expected_o and assert.  use dut.get_out(wr_idx) to do so.
-
-    def run_simulation(self, vcd_name):
-        run_simulation(self.dut, [self.driver(),
-                                  self.rd(0),  # one read port (a)
-                                  self.rd(1),  # one read port (b)
-                                  self.wr(0),  # one write port (o)
-                                  ],
-                       vcd_name=vcd_name)
-
-
-def test_compunit_regspec1():
-    from alu_hier import ALU
-    from soc.fu.alu.alu_input_record import CompALUOpSubset
-
-    inspec = [('INT', 'a', '0:15'),
-              ('INT', 'b', '0:15')]
-    outspec = [('INT', 'o', '0:15'),
-              ]
-
-    regspec = (inspec, outspec)
-
-    m = Module()
-    alu = ALU(16)
-    dut = MultiCompUnit(regspec, alu, CompALUOpSubset)
-    m.submodules.cu = dut
-
-    vl = rtlil.convert(dut, ports=dut.ports())
-    with open("test_compunit_regspec1.il", "w") as f:
-        f.write(vl)
-
-    run_simulation(m, scoreboard_sim(dut),
-                   vcd_name='test_compunit_regspec1.vcd')
-
-    test = CompUnitParallelTest(dut)
-    test.run_simulation("test_compunit_parallel.vcd")
-
-
-if __name__ == '__main__':
-    test_compunit()
-    test_compunit_regspec1()