def random_inputs(dut):
    drv = BPCEncoderDriver(dut, TA, TT)
    sb = BPCEncoderScoreboard(dut, BLOCK_SIZE, DATA_W, stim_report_file=STIM_REPORT_FILE)
    mon = BPCEncoderMonitor(dut, BLOCK_SIZE, DATA_W, sb)
    num_input_blocks = 1000
    input_vals = [BinaryValue(n_bits=DATA_W, bigEndian=False, value=random.randint(-2**(DATA_W-1), 2**(DATA_W-1)-1), binaryRepresentation=2) for k in range(BLOCK_SIZE*num_input_blocks)]
    flush = [0] * (len(input_vals)-1)
    flush.append(1)
    cocotb.fork(Clock(dut.clk_i, CLOCK_PERIOD).start())
    drv.apply_defaults()
    yield reset_dut(dut.rst_ni, RESET_TIME)
    dut._log.info("Reset Done!")
    for k in range(4):
        yield RisingEdge(dut.clk_i)
    mon.start()
    read_task = cocotb.fork(drv.read_outputs(len(input_vals)*2, tmin=0, tmax=0))
    yield drv.drive_input(zip(input_vals, flush), tmin=0, tmax=0)
    yield Timer(4*CLOCK_PERIOD*len(input_vals))
    read_task.kill()
    mon.stop()
    if sb.report():
        raise TestFailure("Scoreboard reported problems - check log!")
Beispiel #2
0
def si_sumador(dut):
    data_range = 2**dut.WIDTH.value.integer

    sender = AdderSender(dut)
    receiver = AdderReceiver(dut)
    mon_a = SIMonitor(clk=dut.clk,
                      data=dut.a,
                      valid=dut.input_valid,
                      ack=dut.input_ack)
    mon_b = SIMonitor(clk=dut.clk,
                      data=dut.b,
                      valid=dut.input_valid,
                      ack=dut.input_ack)
    mon_sum = SIMonitor(clk=dut.clk,
                        data=dut.sum,
                        valid=dut.output_valid,
                        ack=dut.output_ack)

    cocotb.fork(Clock(dut.clk, 10, units='ns').start())
    yield reset(dut)
    cocotb.fork(receiver.start())
    cocotb.fork(mon_a.start())
    cocotb.fork(mon_b.start())
    cocotb.fork(mon_sum.start())

    cr = cocotb.fork(sender.rand_send(n=30, max_latency=5))
    yield cr.join()

    for _ in range(10):
        yield RisingEdge(dut.clk)

    test_a = mon_a.get_buffer()
    test_b = mon_b.get_buffer()
    test_sum = mon_sum.get_buffer()

    expected_sum = [(a + b) % data_range for a, b in zip(test_a, test_b)]

    if test_sum != expected_sum:
        raise TestFailure('sum != expected')
Beispiel #3
0
def test_congestion(dut):
    '''
    Writes out data into the afifo, however
    congestion is simulated.
    '''   

    # Generate the testbench environment.
    te = yield perform_setup(dut)

    # Generate the parameters of the test.
    max_value      = (1<<te.width)-1
    te.cntns.total = 256
    te.setwrallow(CoinTossAllow)
    te.setrdallow(CoinTossAllow)   

    # Write out the data.
    for _ in range(te.cntns.total): te.source.write(data=Transaction(data=randint(0,max_value)))    

    # If something goes wrong, this test can timeout.
    yield Timer(1000, "us")
    te.log.info("Timed out!")
    raise TestFailure() 
Beispiel #4
0
async def check_results(dut):
    """
    Compare outputs with expected values.
    """
    num_samples = 1024
    input_width = 14
    tb = WindowTB(dut, num_samples, input_width)
    await tb.setup()

    cocotb.fork(tb.write_continuous())

    # Latency of 2 clock cycles
    await FallingEdge(tb.dut.clk_en)

    # TODO this used to work as 1
    tol = 100
    i = 0
    while i < len(tb.outputs):
        await FallingEdge(tb.dut.clk_en)
        await ReadOnly()
        valid = tb.dut.dvalid.value.integer
        if valid:
            out_val = tb.dut.dout.value.signed_integer
            out_exp = int(round(tb.outputs[i]))
            if abs(out_val - out_exp) > tol:
                raise TestFailure(
                    (
                        "Actual output differs from expected."
                        " Actual: %d, expected: %d"
                    )
                    % (out_val, out_exp)
                )

        i += 1

    i = 0
    while i < 5:
        await FallingEdge(tb.dut.clk_en)
        i += 1
Beispiel #5
0
def test_sequential(dut):
    '''
    Simply writes data sequentially into the flip flop syncrhonizer
    and checks for the correct output.

    ***This test isn't really thought out. A better should eventually
       be created instead.
    '''

    # Prepare the test environment.
    te = yield perform_setup(dut)

    width = te.ffsd.W
    total = 1 << width
    te.log.info("Total transactions <{}>...".format(total))

    # Perform the test.
    te.log.info("Performing the test...")

    te.log.info("Writing out the non-zero, sequential data...")
    ds = [value + 1 for value in range(total - 1)]
    for d in ds:
        te.ffsd.append(transaction=Transaction(d=d, vld=1))

    prev_q = 0
    q = 0
    for d in ds:

        # Keep reading until a different value is seen.
        while prev_q == q:
            q = yield te.ffsd.read()

        te.log.info("D=<{}>, Q=<{}>...".format(d, q))
        if d != q: raise TestFailure()

        prev_q = q

    te.log.info("Test completed successfully...")
    raise TestSuccess()
Beispiel #6
0
def stc0_lfsr_test(dut):
    """Verifies basic LFSR X operation.

    The LFSR is run and LFSR values are streamed out for comparison.
    """

    numpy.set_printoptions(formatter={'int':lambda x:hex(int(x))})
    dut.ARst <= 1
    stc0 = stc0SIMcocotb(dut, CLK_PERIOD_NS)
    cocotb.fork(Clock(dut.Clk, CLK_PERIOD_NS, units='ns').start())
    yield Timer(CLK_PERIOD_NS * 10, units='ns')
    dut.ARst <= 0
    yield Timer(CLK_PERIOD_NS * 10, units='ns')
    yield stc0.hk.reset()

    seedVal = 0x1
    yield stc0.hk.set_sfifoWrSrc(hk.HW_SFFWRSRC_INGRESS)
    yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_CTRLWORD << stc0.HW_RAL), [(stc0.HW_CTRL_BF0 << stc0.HW_RB_CTRL_ADDR) | (0x1 << stc0.HW_RB_BFCTRL_BFBYPASS)])
    yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_CTRLWORD << stc0.HW_RAL), [(stc0.HW_CTRL_ES << stc0.HW_RB_CTRL_ADDR) | (0x1 << stc0.HW_RB_EGRESSCTRL_OUTPUTEN) | (0x1 << stc0.HW_RB_EGRESSCTRL_CRCBYPASS)|(0x1 << stc0.HW_RB_EGRESSCTRL_OUTPUTMUX) ])
    yield stc0.configAndStartLFSRs(0x4, 0x10, 0x0, 0x1, 0x1)
    #yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_MUXCTRL << stc0.HW_RAL), [0x1])
    #yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_LFSRS_STRIDE << stc0.HW_RAL), [0x3])
    #yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_LFSRS_ITERATIONS << stc0.HW_RAL), [0x10])
    #yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_LFSRX_SEED << stc0.HW_RAL), [seedVal])
    #yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_LFSRS_CTRL << stc0.HW_RAL), [0x1])
    yield stc0.hk.send_write_command(stc0.hk.HW_HK_WRITE, stc0.hk.HW_ADDR_SFFRB_NUMBYTES, [64])
    yield Timer(CLK_PERIOD_NS * 5, units='ns')
    a = yield stc0.hk.ft245m.read_bytes(64)
    yield Timer(CLK_PERIOD_NS * 30, units='ns')

    data = numpy.arange(16)
    for i in range(16):
        data[i] = seedVal
        seedVal = lfsr32(seedVal, 1)
    print(data)
    print(a)
    if numpy.array_equal(data, a) is False:
        # Fail
        raise TestFailure("Readback data does not match")
Beispiel #7
0
    def host_expect_packet(self, packet, msg=None):
        self.monitor.prime()
        result = yield self.monitor.wait_for_recv(1e9)  # 1 ms max
        if result is None:
            current = get_sim_time("us")
            raise TestFailure(f"No full packet received @{current}")

        yield RisingEdge(self.dut.clk48_host)
        self.dut.usb_d_p = 1
        self.dut.usb_d_n = 0

        # Check the packet received matches
        expected = pp_packet(wrap_packet(packet))
        actual = pp_packet(result)
        nak = pp_packet(wrap_packet(handshake_packet(PID.NAK)))
        if (actual == nak) and (expected != nak):
            self.dut._log.warn("Got NAK, retry")
            yield Timer(self.RETRY_INTERVAL, 'us')
            return
        else:
            self.retry = False
            assertEqual(expected, actual, msg)
def run_test(dut,
             data_in=None,
             config_coroutine=None,
             idle_inserter=None,
             backpressure_inserter=None):

    cocotb.fork(Clock(dut.clk, 5000).start())
    tb = EndianSwapperTB(dut)

    yield tb.reset()
    dut.stream_out_ready <= 1

    # Start off any optional coroutines
    if config_coroutine is not None:
        cocotb.fork(config_coroutine(tb.csr))
    if idle_inserter is not None:
        tb.stream_in.set_valid_generator(idle_inserter())
    if backpressure_inserter is not None:
        tb.backpressure.start(backpressure_inserter())

    # Send in the packets
    for transaction in data_in():
        yield tb.stream_in.send(transaction)

    # Wait at least 2 cycles where output ready is low before ending the test
    for i in range(2):
        yield RisingEdge(dut.clk)
        while not dut.stream_out_ready.value:
            yield RisingEdge(dut.clk)

    pkt_count = yield tb.csr.read(1)

    if pkt_count.integer != tb.pkts_sent:
        raise TestFailure("DUT recorded %d packets but tb counted %d" %
                          (pkt_count.integer, tb.pkts_sent))
    else:
        dut._log.info("DUT correctly counted %d packets" % pkt_count.integer)

    raise tb.scoreboard.result
Beispiel #9
0
async def recursive_discovery(dut):
    """Recursively discover every single object in the design."""

    pass_total = total_object_count()

    tlog = logging.getLogger("cocotb.test")
    await Timer(100)

    def dump_all_the_things(parent):
        count = 0
        for thing in parent:
            count += 1
            tlog.debug("Found %s.%s (%s)", parent._name, thing._name,
                       type(thing))
            count += dump_all_the_things(thing)
        return count

    total = dump_all_the_things(dut)
    tlog.info("Found a total of %d things", total)
    if total != pass_total:
        raise TestFailure("Expected %d objects but found %d" %
                          (pass_total, total))
Beispiel #10
0
def _sim_event(level, message):
    """Function that can be called externally to signal an event"""
    SIM_INFO = 0
    SIM_TEST_FAIL = 1
    SIM_FAIL = 2
    from cocotb.result import TestFailure, SimFailure

    if level is SIM_TEST_FAIL:
        scheduler.log.error("Failing test at simulator request")
        scheduler.finish_test(
            TestFailure("Failure from external source: %s" % message))
    elif level is SIM_FAIL:
        # We simply return here as the simulator will exit
        # so no cleanup is needed
        msg = ("Failing test at simulator request before test run completion: "
               "%s" % message)
        scheduler.log.error(msg)
        scheduler.finish_scheduler(SimFailure(msg))
    else:
        scheduler.log.error("Unsupported sim event")

    return True
Beispiel #11
0
async def write_sequence_continuous_delay_read_sequence_continuous(dut):
    """
    Write an uninterrupted sequence of values to the FIFO, delay some
    number of read clock cycles then read them (also uninterrupted)
    and check that the values match.
    """
    fifo = AsyncFifoTB(dut)
    await fifo.setup()
    num_items = 500
    wrvals = [random.randint(0, 2**64 - 1) for n in range(num_items)]
    for i, _ in enumerate(wrvals):
        await fifo.write(wrvals[i])

    ncycles = random.randint(0, 100)
    await fifo.wait_n_read_cycles(ncycles)

    for i in range(num_items):
        rdval = await fifo.read()
        if wrvals[i] != rdval.integer:
            raise TestFailure(
                ("Sequence item %d: Write value differs from read value."
                 " Write: %d, read: %d.") % (i, wrvals[i], rdval.integer))
Beispiel #12
0
def test_immediate_coro(dut):
    """
    Test that coroutines can return immediately
    """
    @cocotb.coroutine
    def immediate_value():
        return 42
        yield

    @cocotb.coroutine
    def immediate_exception():
        raise ValueError
        yield

    assert (yield immediate_value()) == 42

    try:
        yield immediate_exception()
    except ValueError:
        pass
    else:
        raise TestFailure("Exception was not raised")
Beispiel #13
0
def write_and_read(dut):
    """
    Description:
        Write to the register at address 0
        read back from that register and verify the value is the same

    Test ID: 2

    Expected Results:
        The contents of the register is the same as the value written
    """

    #Reset
    dut.rst <=  1
    dut.test_id <= 2
    axim = AXI4LiteMaster(dut, "AXIML", dut.clk)
    setup_dut(dut)
    yield Timer(CLK_PERIOD * 10)
    dut.rst <= 0

    #Shift the adress up by 2 in order to make the addresses 32-bit aligned
    ADDRESS = 0x00 << 2
    DATA = 0xAB

    #Write to the register
    yield axim.write(ADDRESS, DATA)
    yield Timer(CLK_PERIOD * 10)

    #Read back the value
    value = yield axim.read(ADDRESS)
    yield Timer(CLK_PERIOD * 10)

    value = dut.dut.r_temp_0
    if value != DATA:
        #Fail
        raise TestFailure("Register at address 0x%08X should have been: \
                           0x%08X but was 0x%08X" % (ADDRESS, DATA, int(value)))

    dut._log.info("Write 0x%08X to addres 0x%08X" % (int(value), ADDRESS))
Beispiel #14
0
def adder_random_test(dut):
    PERIOD = 10
    clk = dut.clk
    cocotb.fork(gen_clk(clk, PERIOD))

    """Test for adding 2 random numbers multiple times"""
    yield Timer(20 * PERIOD)

    for i in range(10):
        A = random.randint(0, 5)
        B = random.randint(0, 5)
        dut.A = A
        dut.B = B

        yield Timer(20 * PERIOD)

        if int(dut.X) != adder_model(A, B):
            raise TestFailure(
                "Randomised test failed with: %s + %s = %s" %
                (int(dut.A), int(dut.B), int(dut.X)))
        else:  # these last two lines are not strictly necessary
            dut._log.info("Ok!")
Beispiel #15
0
def standard_deviation_basic_test(dut):
    """windowed standard deviation test for a step transition"""

    window_size = 128
    max_value = 2**14 - 1

    ## model
    data = np.append(np.zeros(window_size * 2),
                     np.ones(window_size * 10) * (2**14 - 1))
    result = standard_deviation_filter(data, window_size)

    # non_zero = [hex(x) for x in result if x != 0]
    # print(non_zero)

    ## simulation
    # reset the dut
    dut.reset = 0
    dut.data_in = 0
    dut.clk = 0
    yield Timer(TICK)
    dut.clk = 1
    yield Timer(TICK)
    dut.reset = 1

    for i in range(window_size * 2 + window_size * 8):
        dut.data_in = int(data[i])
        dut.clk = 0
        yield Timer(TICK)
        dut.clk = 1
        yield Timer(TICK)

        # clock in 'window_size' integers, plus the 28 cycle delay for variance and 14 cycle delay for sqrt
        if i >= (window_size + 28 + 6):
            desired_result = result[i - (window_size + 28 + 6)]
            if int(dut.data_out) != desired_result:
                raise TestFailure(
                    "standard deviation output was wrong; got %i, expected %i"
                    % (int(dut.data_out), desired_result))
Beispiel #16
0
def stc0_both_lfsr_test(dut):
    """Verifies both LFSRs and transmitting data from both streams.

    The LFSRs are run and LFSR values are streamed out for comparison.
    Due to the egress setup, the LFSR values are interleaved.
    """

    numpy.set_printoptions(formatter={'int':lambda x:hex(int(x))})
    dut.ARst <= 1
    stc0 = stc0SIMcocotb(dut, CLK_PERIOD_NS)
    cocotb.fork(Clock(dut.Clk, CLK_PERIOD_NS, units='ns').start())
    yield Timer(CLK_PERIOD_NS * 10, units='ns')
    dut.ARst <= 0
    yield Timer(CLK_PERIOD_NS * 10, units='ns')
    yield stc0.hk.reset()

    seedValA = 0x1
    seedValB = 0x2
    yield stc0.hk.set_sfifoWrSrc(hk.HW_SFFWRSRC_INGRESS)
    yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_CTRLWORD << stc0.HW_RAL), [(stc0.HW_CTRL_BF0 << stc0.HW_RB_CTRL_ADDR) | (0x1 << stc0.HW_RB_BFCTRL_BFBYPASS)])
    yield stc0.hk.send_write_command(0x1, (stc0.HW_RM_CTRL << stc0.HW_RML) | (stc0.HW_RA_CTRL_CTRLWORD << stc0.HW_RAL), [(stc0.HW_CTRL_ES << stc0.HW_RB_CTRL_ADDR) | (0x1 << stc0.HW_RB_EGRESSCTRL_OUTPUTEN) | (0x1 << stc0.HW_RB_EGRESSCTRL_CRCBYPASS)|(0x0 << stc0.HW_RB_EGRESSCTRL_OUTPUTMUX) ])
    yield stc0.configAndStartLFSRs(0x8, 0x10, 0x0, 0x1, 0x2)
    yield stc0.hk.send_write_command(stc0.hk.HW_HK_WRITE, stc0.hk.HW_ADDR_SFFRB_NUMBYTES, [128])
    yield Timer(CLK_PERIOD_NS * 5, units='ns')
    a = yield stc0.hk.ft245m.read_bytes(128)
    yield Timer(CLK_PERIOD_NS * 40, units='ns')

    data = numpy.arange(32)
    for i in range(0,32,2):
        data[i] = seedValA
        data[i+1] = seedValB
        seedValA = lfsr32(seedValA, 1)
        seedValB = lfsr32(seedValB, 1)
    print(data)
    print(a)
    if numpy.array_equal(data, a) is False:
        # Fail
        raise TestFailure("Readback data does not match")
def read_address_1(dut):
    """
    Description
        Use cocotb to set the value of the register at address 0x01
        Use AXIML to read the contents of that register and
        compare the values

    Test ID: 1

    Expected Results:
        The value read from the register is the same as the value written
    """
    #Reset
    dut.S_AXI_ARESETN <= 0
    #dut.test_id <= 0
    axim = AXI4LiteMaster(dut, "S_AXI", dut.S_AXI_ACLK)
    setup_dut(dut)
    yield Timer(CLK_PERIOD * 10)
    dut.S_AXI_ARESETN <= 1

    ADDRESS = 0x01
    DATA = 0xCD

    #    dut.slv_reg0 <= DATA
    dut.slv_reg1 <= DATA
    #    dut.slv_reg2 <= DATA
    #    dut.slv_reg3 <= DATA
    yield Timer(CLK_PERIOD * 10)

    value = yield axim.read(ADDRESS)
    yield Timer(CLK_PERIOD * 10)

    if value != DATA:
        #Fail
        raise TestFailure("Register at address 0x%08X should have been: \
                           0x%08X but was 0x%08X" % (ADDRESS, DATA, value))

    dut.log.info("Read: 0x%08X From Address: 0x%08X" % (value, ADDRESS))
def hash_test(dut,expected_value) :
    
    i = 0
    while dut.end_signal.value == 0 :
        #print(int(dut.current_state.value))
        
        if(dut.end_hash.value ):
            
            print('++++++++++++++++++++++++')
            print(i)
            print(int(dut.counter_output))
            #print(hex(int(dut.plaintext)))
            #print(hex(int(dut.c.value)))
            print(hex(int(dut.h_left_o.value)))
            print(hex(int(dut.h_right_o.value)))
            print(hex(int(dut.hash_o.value)))

            print("~~~~~~~~~~~~~~~~~~")
            print(hex(int(dut.hash_impl.key_i.value)))
            print(hex(int(dut.hash_impl.input_left.value)))
            print(hex(int(dut.hash_impl.input_right.value)))
            print(hex(int(dut.hash_impl.output_left.value)))
            print(hex(int(dut.hash_impl.output_right.value)))
            
            
            
            print('++++++++++++++++++++++++++')
            
        i = i+1
        
        yield n_cycles_clock(dut,1)
        
        
    
    #yield n_cycles_clock(dut,1)
    print(hex(int(dut.hash_output.value)))
    if(dut.hash_output != expected_value) :
            raise TestFailure("""Error hash,wrong value = {0}, expected value is {1}""".format(hex(int(dut.hash_output.value)),hex(expected_value)))
Beispiel #19
0
async def test_illegal_operations(dut):
    """Test whether illegal operations are correctly refused by the driver"""

    axim = AXI4Master(dut, AXI_PREFIX, dut.clk)
    _, data_width, ram_start, _ = get_parameters(dut)

    illegal_operations = (
        (AXIBurst.INCR, -1, None),
        (AXIBurst.INCR, 0, None),
        (AXIBurst.FIXED, 17, None),
        (AXIBurst.INCR, 257, None),
        (AXIBurst.WRAP, 3, None),
        (AXIBurst.INCR, 4, -1),
        (AXIBurst.INCR, 4, data_width - 1),
        (AXIBurst.INCR, 4, data_width * 2),
    )

    await setup_dut(dut)

    for rw in ("Read", "Write"):
        for burst, length, size in illegal_operations:
            try:
                if rw == "Read":
                    await axim.read(ram_start, length, size=size, burst=burst)
                else:
                    values = [
                        randrange(0, 2**(data_width * 8))
                        for i in range(length)
                    ]
                    await axim.write(ram_start, values, size=size, burst=burst)

                raise TestFailure(
                    "{} with length={}, size={} and burst={} has been "
                    "performed by the driver, but it is an illegal "
                    "operation".format(rw, length, size, burst.name))

            except ValueError:
                pass
Beispiel #20
0
async def test_negatives(dut):

    dut._log.info("Running test_negatives...")

    await init_test(dut)

    stream_input_a = Stream.Driver(dut.clk, dut, 'a__')
    stream_input_b = Stream.Driver(dut.clk, dut, 'b__')
    stream_output = Stream.Driver(dut.clk, dut, 'r__')

    dut._log.info(stream_input_a)

    N = 20
    width_a = len(dut.a__data)
    width_b = len(dut.b__data)
    mask = int('1' * width_a, 2)

    data_a = [-getrandbits(width_a) for _ in range(N)]
    data_b = [-getrandbits(width_b) for _ in range(N)]

    expected = [(a + b) & mask for a, b in zip(data_a, data_b)]

    # for a, b, r in zip(data_a, data_b, expected):
    #    dut._log.info("[a]:{:02X}, [b]:{:02X}, [r]:{:02X}".format(a, b, r))

    send_a = cocotb.fork(stream_input_a.send(data_a))
    send_b = cocotb.fork(stream_input_b.send(data_b))
    send_a.join()
    send_b.join()

    received = await stream_output.recv(N)

    for expctd, rcvd in zip(expected, received):
        if expctd != rcvd:
            dut._log.info("Expected {} Got {}".format(expctd, rcvd))
            raise TestFailure("Test failed")

    raise TestSuccess("Test passed")
def write_and_read(dut):
    """
    Description:
        Write to the register at address 0
        read back from that register and verify the value is the same

    Test ID: 2

    Expected Results:
        The contents of the register is the same as the value written
    """

    #Reset
    dut.S_AXI_ARESETN <= 0
    #dut.test_id <= 2
    axim = AXI4LiteMaster(dut, "S_AXI", dut.S_AXI_ACLK)
    setup_dut(dut)
    yield Timer(CLK_PERIOD * 10)
    dut.S_AXI_ARESETN <= 1

    ADDRESS = 0x03
    DATA = 0xEB

    #Write to the register
    yield axim.write(ADDRESS, DATA)
    yield Timer(CLK_PERIOD * 10)

    #Read back the value
    value = yield axim.read(ADDRESS)
    yield Timer(CLK_PERIOD * 10)

    #value = dut.slv_reg0
    if value != DATA:
        #Fail
        raise TestFailure("Register at address 0x%08X should have been: \
                           0x%08X but was 0x%08X" % (ADDRESS, DATA, value))

    dut.log.info("Write 0x%08X to addres 0x%08X" % (value, ADDRESS))
Beispiel #22
0
	def __init__(self, dut):
		self.dut = dut
		self.stopped = False
		self.address_bits = dut.ADDR_BITS.value
		self.data_bits = dut.DATA_BITS.value

		cache_lines = dut.CACHE_LINES.value      # total number of cache lines
		self.associativity = dut.ASSOCIATIVITY.value
		self.cache_sets = cache_lines / self.associativity # number of cache sets

		self.index_bits = log2ceil(self.cache_sets)
		tag_bits = self.address_bits - self.index_bits

		self.index_mask = 2**self.index_bits-1
		self.tag_mask = 2**tag_bits-1

		if DEBUG: print("Testbench: {0}, {1}, {2}".format(self.index_bits, self.index_mask, self.tag_mask))

		replacement_policy = dut.REPLACEMENT_POLICY.value
		if replacement_policy != "LRU":
			raise TestFailure("Unsupported configuration: REPLACEMENT_POLICY=%s" % replacement_policy)

		# TODO: create LRU dictionary for each cache set
		self.lrus = tuple([LeastRecentlyUsedDict(size_limit=self.associativity) for _ in range(self.cache_sets)])

		init_val = OutputTransaction(self)

		self.input_drv = InputDriver(dut)
		self.output_mon = OutputMonitor(dut, self)

		# Create a scoreboard on the outputs
		self.expected_output = [ init_val ]
		self.scoreboard = Testbench.MyScoreboard(dut)
		self.scoreboard.add_interface(self.output_mon, self.expected_output)

		# Reconstruct the input transactions from the pins
		# and send them to our 'model'
		self.input_mon = InputMonitor(dut, callback=self.model)
Beispiel #23
0
    def _close_cycle(self):
        #Close current wishbone cycle  
        clkedge = RisingEdge(self.clock)
        count           = 0
        last_acked_ops  = 0
        #Wait for all Operations being acknowledged by the slave before lowering the cycle line
        #This is not mandatory by the bus standard, but a crossbar might send acks to the wrong master
        #if we don't wait. We don't want to risk that, it could hang the bus
        while self._acked_ops < self._op_cnt:
            if last_acked_ops != self._acked_ops:
                self.log.debug("Waiting for missing acks: %u/%u" % (self._acked_ops, self._op_cnt) )
            last_acked_ops = self._acked_ops    
            #check for timeout when finishing the cycle            
            count += 1
            if (not (self._timeout is None)):
                if (count > self._timeout): 
                    raise TestFailure("Timeout of %u clock cycles reached when waiting for reply from slave" % self._timeout)                
            yield clkedge

        self.busy = False
        self.busy_event.set()
        self.bus.cyc <= 0 
        yield clkedge
Beispiel #24
0
def A_load_data_test(dut):
    """
    Test for data properly shifted in
    w(0) gets loaded in LAST
    """
    log = SimLog("cocotb.%s" % dut._name)
    cocotb.fork(Clock(dut.clk_i, 10000).start())
    
    mockObject = Sha1Model()
    
    yield reset(dut)
    yield load_data(dut, log, mockObject, 16)

    #mockObject.displayAll()
    mockOut = "{:08x}".format(mockObject.W[15])

    #print convert_hex(dut.dat_1_o) + " " + convert_hex(dut.dat_2_o) + " " + convert_hex(dut.dat_3_o) + " " + convert_hex(dut.dat_4_o) + " " + convert_hex(dut.dat_5_o)

    if convert_hex(dut.test_sha1_load_o).zfill(8) != mockOut:
        raise TestFailure(
            "Load data is incorrect: {0} != {1}".format(convert_hex(dut.test_sha1_load_o), mockOut))
    else:
        log.info("Ok!")
Beispiel #25
0
 def axi_wr(self, a, d):
     dut = self.dut
     dut.awvalid = 0
     dut.wvalid = 0
     dut.bready = 0
     yield self.wait_clk()
     dut.awaddr = a<<2
     dut.wdata = d
     dut.awvalid = 1
     dut.wvalid = 1
     dut.bready = 1
     for i in range(10):
         yield self.wait_clk()
         if Int(dut.awready) and Int(dut.wready):
             break
         if i==9:
             raise TestFailure("timeout(awready/wready)")
     dut.awaddr = 0
     dut.wdata = 0
     dut.awvalid = 0
     dut.wvalid = 0
     dut.bready = 0
     yield self.wait_clk()
Beispiel #26
0
def expecteq(fmt, got, exp):
    """
    Compare 'exp' with 'got' and if neq complain using format 'fmt'
    """
    global expecteq_nok
    global expecteq_nfail
    global expecteq_oksofar
    if got != exp:
        if fmt=="":
            fmt = "%s: "%(got._path) + "%x != %x"
            fmt += "  @t=%d"%(get_ns())
        expecteq_nfail += 1
        expecteq_oksofar = False
        errmsg = fmt%(got, exp)
        print errmsg
        expecteq_errmsg_list.append(errmsg)
        if not expecteq_nonfatal:
            raise TestFailure(fmt%(got, exp))
        else:
            stack = traceback.extract_stack()
            print stack[-2]
    else:
        expecteq_nok += 1
def enc_dec_test(dut, expected_value):
    print("VERILOG_VALUES")
    while dut.end_signal == 0:
        if (dut.current_state == 3):
            print('//////////////////////////')
            print(int(dut.counter_out.value))
            print(int(dut.stage_impl.i.value))
            print(hex(int(dut.stage_impl.R0.value)))
            print(hex(int(dut.stage_impl.R1.value)))
            print(hex(int(dut.stage_impl.R2.value)))
            print(hex(int(dut.stage_impl.R3.value)))
            print(hex(int(dut.R0.value)))
            print(hex(int(dut.R1.value)))
            print(hex(int(dut.R2.value)))
            print(hex(int(dut.R3.value)))
            print('//////////////////////////')
        yield n_cycles_clock(dut, 1)

    print(hex(int(dut.text_output.value)))
    if (dut.text_output != expected_value):
        raise TestFailure(
            """Error enc_test,wrong value = {0}, expected value is {1}""".
            format(hex(int(dut.text_output.value)), hex(expected_value)))
    def bp_predict(dut, index, model_prediction):
        # read
        dut.r_v_i <= 1
        dut.idx_r_i <= index

        # simulate a clock edge
        yield RisingEdge(dut.clk_i)

        # read prediction
        dut_prediction = bool(dut.predict_o.value)
        dut._log.info(
            "Address: {}, dut prediction: {}, model prediction: {}".format(
                index, dut_prediction, model_prediction))
        if dut_prediction != model_prediction:
            raise TestFailure("Mismatch detected: dut {}, model {}".format(
                dut_prediction, model_prediction))

        # reset flags
        dut.r_v_i <= 0
        dut.idx_r_i <= 0

        # simulate a clock edge
        yield RisingEdge(dut.clk_i)
Beispiel #29
0
def recursive_discovery(dut):
    """
    Recursively discover every single object in the design
    """
    if cocotb.SIM_NAME.lower().startswith(("ncsim","modelsim")):
        # Finds regions, signal, generics, constants, varibles and ports.
        pass_total = 34569
    else:
        pass_total = 32393

    tlog = logging.getLogger("cocotb.test")
    yield Timer(100)
    def dump_all_the_things(parent):
        count = 0
        for thing in parent:
            count += 1
            tlog.info("Found %s.%s (%s)", parent._name, thing._name, type(thing))
            count += dump_all_the_things(thing)
        return count
    total = dump_all_the_things(dut)
    tlog.info("Found a total of %d things", total)
    if total != pass_total:
        raise TestFailure("Expected %d objects but found %d" % (pass_total, total))
Beispiel #30
0
def B_compare_data_test(dut):
    """
    Tests that generated data gets compared against test values
    """
    log = SimLog("cocotb.%s" % dut._name)
    cocotb.fork(Clock(dut.clk_i, 10000).start())
    
    outStr = ''
    
    yield reset(dut)
    yield RisingEdge(dut.clk_i)
        
    for x in xrange(0x90):
        complete = int(dut.main1.comp_complete)
        
        outStr = str(x) + ' - ' + str(int(dut.main1.i.value)) + ' - ' + str(complete) + ' - ' + \
            '{:x}'.format(int(dut.main1.comp1.mk_test_comp.value)) + ": " + \
            '{:x}'.format(int(dut.main1.comp1.mk_test9.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test8.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test7.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test6.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test5.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test4.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test3.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test2.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test1.value)) + \
            '{:x}'.format(int(dut.main1.comp1.mk_test0.value))
            
        if complete == 1:
            break
        
        yield RisingEdge(dut.clk_i)
        
    if complete == 0:
        raise TestFailure("Comparison never reached")
    else:
        log.info("Ok!")