示例#1
0
            spimem.sclk.eq(timer[0]),
            #spimem.copi.eq((timer == 0x30) | (timer == 0x10)), # read address 1
            spimem.copi.eq((timer == 0x30)
                           | (timer == 0x40)),  # write address 1, dout = 1
            spimem.csn.eq(timer == 0),
            spimem.din.eq(0x55)
        ]

        return m


if __name__ == "__main__":
    m = Module()
    m.submodules.test = test = TestSPI()

    sim = Simulator(m)
    sim.add_clock(1e-6)

    def process():

        for i in range(67):
            yield

        addr = yield test.spimem.addr
        print("addr:", addr)
        dout = yield test.spimem.dout
        print("dout:", dout)

    sim.add_sync_process(process)
    with sim.write_vcd("test.vcd", "test.gtkw"):
        sim.run()
示例#2
0
def main():
    # parser = main_parser()
    # args = parser.parse_args()

    m = Module()

    m.submodules.ft = ft = FT600()
    m.submodules.wfifo = wfifo = AsyncFIFOBuffered(
        width=16, depth=1024, r_domain="sync", w_domain="sync")
    m.submodules.rfifo = rfifo = AsyncFIFOBuffered(
        width=16, depth=1024, r_domain="sync", w_domain="sync")

    ft_oe = Signal()
    ft_be = Signal()
    ft_txe = Signal()

    # FT control
    m.d.comb += ft_oe.eq(ft.ft_oe)
    m.d.comb += ft_be.eq(ft.ft_be)
    m.d.comb += ft_txe.eq(ft.ft_txe)

    # FT to Write FIFO
    m.d.comb += ft.input_payload.eq(wfifo.r_data)
    m.d.comb += wfifo.r_en.eq(ft.input_ready)
    m.d.comb += ft.input_valid.eq(wfifo.r_rdy)

    # FT to Read FIFO
    m.d.comb += rfifo.w_data.eq(ft.output_payload)
    m.d.comb += rfifo.w_en.eq(ft.output_valid)
    m.d.comb += ft.output_ready.eq(rfifo.w_rdy)

    sim = Simulator(m)
    sim.add_clock(1e-7, domain="sync")      # 10 MHz FPGA clock

    def process():
        yield wfifo.w_en.eq(1)
        yield wfifo.w_data.eq(1)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(2)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(3)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(4)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(5)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(6)
        yield Tick(domain="sync")
        yield wfifo.w_data.eq(7)
        yield Tick(domain="sync")
        yield wfifo.w_en.eq(0)
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield ft.ft_txe.eq(1)
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield ft.ft_txe.eq(0)
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield ft.ft_txe.eq(1)
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield ft.ft_rxf.eq(1)
        yield Tick(domain="sync")
        yield ft.ft_override.eq(1)
        yield Tick(domain="sync")
        yield ft.ft_override.eq(2)
        yield Tick(domain="sync")
        yield ft.ft_override.eq(3)
        yield Tick(domain="sync")
        yield ft.ft_rxf.eq(0)
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")
        yield Tick(domain="sync")

    sim.add_sync_process(process)
    with sim.write_vcd("test.vcd", "test.gtkw", traces=[]):
        sim.run()
from up_counter import *

dut = UpCounter(25)


def bench():
    # Disabled counter should not overflow.
    yield dut.en.eq(0)
    for _ in range(30):
        yield
        assert not (yield dut.ovf)

    # Once enabled, the counter should overflow in 25 cycles.
    yield dut.en.eq(1)
    for _ in range(25):
        yield
        assert not (yield dut.ovf)
    yield
    assert (yield dut.ovf)

    # The overflow should clear in one cycle.
    yield
    assert not (yield dut.ovf)


sim = Simulator(dut)
sim.add_clock(1e-6)  # 1 MHz
sim.add_sync_process(bench)
with sim.write_vcd("up_counter.vcd"):
    sim.run()
示例#4
0
            'WF': 3,
            'ovfl': 'wrap',
            'quant': 'round',
            'W': 9
        },
        'QCB': {
            'WI': 5,
            'WF': 3,
            'ovfl': 'wrap',
            'quant': 'round',
            'W': 9
        }
    }
    dut = FIR_DF_nmigen(p)

    def process():
        # input = stimulus
        output = []
        for i in np.ones(20):
            yield dut.i.eq(int(i))
            yield Tick()
            output.append((yield dut.o))
        print(output)

    sim = Simulator(dut)
    # with Simulator(m) as sim:

    sim.add_clock(1 / 48000)
    sim.add_process(process)
    sim.run()
def run_sim(dut, data, n):
    sim = Simulator(dut, engine=os.getenv('NMIGEN_SIM', 'pysim'))
    sim.add_clock(10e-9, domain='sync')
    sim.add_sync_process(dut.input.send_driver(data))
    sim.add_sync_process(dut.output.recv_driver(n))
    with sim.write_vcd('bla.vcd'):
        sim.run()
from nmigen import *
from nmigen.sim import Simulator, Delay, Settle, Passive
from st7789 import *

if __name__ == "__main__":
    m = Module()
    m.submodules.st7789 = st7789 = ST7789(1)

    sim = Simulator(m)
    sim.add_clock(4e-8)

    def process():
        yield st7789.color.eq(0xf800)
        yield Passive()

    sim.add_process(process)
    with sim.write_vcd("test.vcd", "test.gtkw", traces=st7789.ports()):
        sim.run_until(30e-6, run_passive=True)
示例#7
0
文件: fwtest.py 项目: zignig/spork
    parser.add_argument("-g", "--generate", action="store_true")
    args = parser.parse_args()

    fw = FIRM  # use this firmware

    if args.simulate:
        spork = build(fw, mem_size=1024)
        from nmigen.sim import Simulator
        from sim_data import test_rx, str_data

        st = "sphinx of black quartz judge my vow"
        # print(hex(_crc(st.encode("utf-8"))))
        data = str_data(st)
        dut = spork.cpu.pc.devices[0]._phy
        dut.divisor_val = spork.divisor
        sim = Simulator(spork)
        sim.add_clock(1e-3)
        sim.add_sync_process(test_rx(data, dut))
        with sim.write_vcd("sim.vcd"):
            sim.run()

    if args.list:
        spork = build(fw, detail=True)

    if args.program:
        spork = build(fw, detail=True)
        spork.platform.build(spork, do_program=True)

    if args.generate:
        spork = build(fw, mem_size=1024, sim=True)
        from nmigen.back import cxxrtl
示例#8
0
    args = parser.parse_args()

    oper: Optional[Operation] = None
    if args.oper is not None:
        oper = Operation[args.oper]

    m = Module()
    m.submodules.alu = alu = ALU_big(oper)

    if oper is not None:
        m.d.comb += Assume(~ResetSignal())
        m.d.comb += Assume(alu.oper == oper)
        main_runner(parser, args, m, ports=alu.ports())

    else:
        sim = Simulator(m)

        def process():
            yield
            yield alu.inputa.eq(0x12)
            yield alu.inputb.eq(0x34)
            yield alu.oper.eq(Operation.ADC)
            yield
            yield
            yield alu.inputa.eq(0x7F)
            yield alu.inputb.eq(0x7F)
            yield alu.oper.eq(Operation.ADC)
            yield
            yield

        sim.add_clock(1e-6)  # 1 MHz
示例#9
0
    def generic_chacha20(self, implementation):
        print("")

        # Encrypt a test message with a known good implementation
        import json
        from base64 import b64encode
        from Crypto.Cipher import ChaCha20
        from Crypto.Random import get_random_bytes
        from struct import pack, unpack
        from binascii import hexlify

        def byte_xor(ba1, ba2):
            """ XOR two byte strings """
            return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])

        plaintext = b'A' * 64
        # key = get_random_bytes(32)
        key = bytes([i for i in range(32)])

        # nonce = get_random_bytes(12)
        nonce = bytes([(i * 16 + i) for i in range(12)])
        cipher = ChaCha20.new(key=key, nonce=nonce)
        ciphertext = cipher.encrypt(plaintext)

        nonceb64 = b64encode(cipher.nonce).decode('utf-8')
        ciphertextb64 = b64encode(ciphertext).decode('utf-8')
        keystream = byte_xor(plaintext, ciphertext)
        keystream_hex = hexlify(keystream).decode('utf8')
        result = json.dumps({
            'nonce': nonceb64,
            'ciphertext': ciphertextb64,
            'keystream': keystream_hex
        })
        # print(result)

        # cipher = ChaCha20.new(key=key, nonce=nonce)
        # cipher.seek(0)
        # print(cipher.decrypt(ciphertext))

        m = Module()

        m.submodules.chacha20 = chacha20 = ChaCha20Cipher(implementation)

        key_words = unpack("<8I", key)
        m.d.comb += [
            chacha20.i_key[i].eq(key_words[i]) for i in range(len(key_words))
        ]

        nonce_words = unpack("<3I", nonce)
        m.d.comb += [
            chacha20.i_nonce[i].eq(nonce_words[i])
            for i in range(len(nonce_words))
        ]

        sim = Simulator(m)
        sim.add_clock(1e-6, domain="sync")

        def process():
            ks = []
            iterations = 0
            yield chacha20.i_en.eq(1)
            yield
            for i in range(30 * 4):
                # Simulate until it'd finished
                iterations += 1
                if (yield chacha20.o_ready) != 0:
                    yield
                    yield
                    yield
                    break
                yield
            for i in range(16):
                ks.append((yield chacha20.o_stream[i]))
            keystream_hdl = pack("<16I", *ks)
            print(f"Took {iterations} iterations")
            print("Keystream generated by simulation: ",
                  hexlify(keystream_hdl))
            print("Decryption using simulation: ",
                  byte_xor(keystream_hdl, ciphertext))

            self.assertEqual(keystream_hdl, keystream)
            self.assertEqual(plaintext, byte_xor(keystream_hdl, ciphertext))

        sim.add_sync_process(process)
        with sim.write_vcd("test.vcd", "test.gtkw"):
            sim.run()
示例#10
0
        mem = {
            0x0000: 0x5F,
            0x1000: 0x12,
            0x2000: 0x34,
            0x1234: 0x5F,
            0x1334: 0x00,
            0x1434: 0x00,
        }
        with m.Switch(core.addr):
            for addr, data in mem.items():
                with m.Case(addr):
                    m.d.comb += core.dout.eq(data)
            with m.Default():
                m.d.comb += core.dout.eq(0xFF)

        sim = Simulator(m)
        sim.add_clock(1e-6, domain="sync")

        def process():
            yield
            yield
            yield
            yield
            yield
            yield
            yield
            yield
            yield
            yield
            yield
            yield
示例#11
0
            register_file_r.addr.eq(self.CPU.data_port.addr),
            self.CPU.data_port.r_data.eq(register_file_r.data),
            register_file_w.addr.eq(self.CPU.data_port.addr),
            register_file_w.data.eq(self.CPU.data_port.w_data),
            register_file_w.en.eq(self.CPU.data_port.w_en)
        ]
        
        return m


if __name__ == "__main__":
    with open("infinite_helloworld.bf", "r") as f:
        m = Module()
        m.submodules.DUT = DUT = Sim_top(f, brainfuck_array_size=64)

        sim = Simulator(m)

        def process():
            yield DUT.si_data.eq(ord("A"))
            yield DUT.si_valid.eq(0)
            yield DUT.so_ready.eq(0)
            for _ in range(3210):
                yield 
            yield DUT.si_valid.eq(1)
            yield DUT.so_ready.eq(1)
            yield

        sim.add_clock(0.02083e-6, domain="sync")
        sim.add_sync_process(process)
        with sim.write_vcd("bf_tb.vcd", "bf_tb.gtkw"):
            sim.run_until(500e-5, run_passive=True)
示例#12
0
    yield from jtagPDI((0x4C, 1), (0xEB, 1))
    yield
    yield from jtagPDI((0xCA, 0), (0xEB, 1))
    yield
    yield from jtagPDI((0x01, 1), (0xEB, 1))
    yield
    yield from jtagPDI((0x00, 0), (0xEB, 1))
    yield
    yield from jtagPDI((0x01, 1), (0xEB, 1))
    yield
    yield from jtagPDI((0x00, 0), (0xEB, 1))
    yield
    yield
    yield
    yield


sim = Simulator(subtarget)
# Define the JTAG clock to have a period of 1/4MHz
#sim.add_clock(250e-9, domain = 'jtag')
sim.add_clock(2e-6, domain='jtag')
# Define the system clock to have a period of 1/48MHz
sim.add_clock(20.8e-9)

sim.add_sync_process(benchSync, domain='sync')
sim.add_sync_process(benchJTAG, domain='jtag')

with sim.write_vcd('jtag_pdi-sniffer.vcd'):
    sim.reset()
    sim.run()
示例#13
0
class LunaGatewareTestCase(unittest.TestCase):

    domain = 'sync'

    # Convenience property: if set, instantiate_dut will automatically create
    # the relevant fragment with FRAGMENT_ARGUMENTS.
    FRAGMENT_UNDER_TEST = None
    FRAGMENT_ARGUMENTS = {}

    # Convenience properties: if not None, a clock with the relevant frequency
    # will automatically be added.
    FAST_CLOCK_FREQUENCY = None
    SYNC_CLOCK_FREQUENCY = 120e6
    USB_CLOCK_FREQUENCY = None
    SS_CLOCK_FREQUENCY = None

    def instantiate_dut(self):
        """ Basic-most function to instantiate a device-under-test.

        By default, instantiates FRAGMENT_UNDER_TEST.
        """
        return self.FRAGMENT_UNDER_TEST(**self.FRAGMENT_ARGUMENTS)

    def get_vcd_name(self):
        """ Return the name to use for any VCDs generated by this class. """
        return "test_{}".format(self.__class__.__name__)

    def setUp(self):
        self.dut = self.instantiate_dut()
        self.sim = Simulator(self.dut)

        if self.USB_CLOCK_FREQUENCY:
            self.sim.add_clock(1 / self.USB_CLOCK_FREQUENCY, domain="usb")
        if self.SYNC_CLOCK_FREQUENCY:
            self.sim.add_clock(1 / self.SYNC_CLOCK_FREQUENCY, domain="sync")
        if self.FAST_CLOCK_FREQUENCY:
            self.sim.add_clock(1 / self.FAST_CLOCK_FREQUENCY, domain="fast")
        if self.SS_CLOCK_FREQUENCY:
            self.sim.add_clock(1 / self.SS_CLOCK_FREQUENCY, domain="ss")

    def initialize_signals(self):
        """ Provide an opportunity for the test apparatus to initialize siganls. """
        yield Signal()

    def traces_of_interest(self):
        """ Returns an interable of traces to include in any generated output. """
        return ()

    def simulate(self, *, vcd_suffix=None):
        """ Runs our core simulation. """

        # If we're generating VCDs, run the test under a VCD writer.
        if os.getenv('GENERATE_VCDS', default=False):

            # Figure out the name of our VCD files...
            vcd_name = self.get_vcd_name()
            if vcd_suffix:
                vcd_name = "{}_{}".format(vcd_name, vcd_suffix)

            # ... and run the simulation while writing them.
            traces = self.traces_of_interest()
            with self.sim.write_vcd(vcd_name + ".vcd",
                                    vcd_name + ".gtkw",
                                    traces=traces):
                self.sim.run()

        else:
            self.sim.run()

    @staticmethod
    def pulse(signal, *, step_after=True):
        """ Helper method that asserts a signal for a cycle. """
        yield signal.eq(1)
        yield
        yield signal.eq(0)

        if step_after:
            yield

    @staticmethod
    def advance_cycles(cycles):
        """ Helper methods that waits for a given number of cycles. """

        for _ in range(cycles):
            yield

    @staticmethod
    def wait_until(strobe, *, timeout=None):
        """ Helper method that advances time until a strobe signal becomes true. """

        cycles_passed = 0

        while not (yield strobe):
            yield

            cycles_passed += 1
            if timeout and cycles_passed > timeout:
                raise RuntimeError(
                    f"Timeout waiting for '{strobe.name}' to go high!")

    def _ensure_clocks_present(self):
        """ Function that validates that a clock is present for our simulation domain. """
        frequencies = {
            'sync': self.SYNC_CLOCK_FREQUENCY,
            'usb': self.USB_CLOCK_FREQUENCY,
            'fast': self.FAST_CLOCK_FREQUENCY,
            'ss': self.SS_CLOCK_FREQUENCY
        }
        self.assertIsNotNone(
            frequencies[self.domain],
            f"no frequency provied for `{self.domain}`-domain clock!")

    def wait(self, time):
        """ Helper method that waits for a given number of seconds in a *_test_case. """

        # Figure out the period of the clock we want to work with...
        if self.domain == 'sync':
            period = 1 / self.SYNC_CLOCK_FREQUENCY
        elif self.domain == 'usb':
            period = 1 / self.USB_CLOCK_FREQUENCY
        elif self.domain == 'fast':
            period = 1 / self.FAST_CLOCK_FREQUENCY

        # ... and, accordingly, how many cycles we want to delay.
        cycles = math.ceil(time / period)
        print(cycles)

        # Finally, wait that many cycles.
        yield from self.advance_cycles(cycles)
示例#14
0
from nmigen.back import verilog
from nmigen.sim import Simulator

from lfsr import Lfsr

dut = Lfsr()


def bench():
    yield dut.en.eq(1)
    for _ in range(100):
        yield


sim = Simulator(dut)
sim.add_clock(1e-6)
sim.add_sync_process(bench)
with sim.write_vcd("lfsr.vcd"):
    sim.run()

with open("lfsr.v", "w") as f:
    f.write(verilog.convert(dut, ports=[dut.out]))