class CrossoverUART: def __init__(self, host="localhost", base_address=0): # FIXME: add command line arguments self.bus = RemoteClient(host=host, base_address=base_address) def open(self): self.bus.open() self.file, self.name = pty.openpty() self.pty2crossover_thread = multiprocessing.Process(target=self.pty2crossover) self.crossover2pty_thread = multiprocessing.Process(target=self.crossover2pty) self.pty2crossover_thread.start() self.crossover2pty_thread.start() def close(self): self.bus.close() self.pty2crossover_thread.terminate() self.crossover2pty_thread.terminate() def pty2crossover(self): while True: r = os.read(self.file, 1) self.bus.regs.uart_xover_rxtx.write(ord(r)) def crossover2pty(self): while True: if self.bus.regs.uart_txfull.read(): length = 16 elif not self.bus.regs.uart_xover_rxempty.read(): length = 1 else: length = 0 if length: r = self.bus.read(self.bus.regs.uart_xover_rxtx.addr, length=length, burst="fixed") for v in r: os.write(self.file, bytes(chr(v).encode("utf-8")))
def us_set_sys_clk(clk_freq, vco_freq): import time from litex import RemoteClient bus = RemoteClient() bus.open() # # # # (Re)Configuring sys_clk. print("Configuring sys_clk to {:3.3f}MHz...".format(clk_freq / 1e6)) uspll = USPLL(bus) clkout0_clkreg1 = ClkReg1(uspll.read(0x8)) vco_div = int(vco_freq / clk_freq) clkout0_clkreg1.high_time = vco_div // 2 + vco_div % 2 clkout0_clkreg1.low_time = vco_div // 2 uspll.write(0x08, clkout0_clkreg1.pack()) # Measure/verify sys_clk print("Measuring sys_clk...", end=" ") duration = 5 start = bus.regs.crg_sys_clk_counter.read() time.sleep(duration) end = bus.regs.crg_sys_clk_counter.read() print(": {:3.2f}MHz.".format((end - start) / (1e6 * duration))) # # # bus.close()
def init_test(port, retries): bus = RemoteClient(port=port) bus.open() init_done = False for i in range(retries): # Reset PHY bus.regs.sata_phy_enable.write(0) bus.regs.sata_phy_enable.write(1) # Wait time.sleep(10e-3) # Check Status if (bus.regs.sata_phy_status.read() & 0x1) != 0: init_done = True break print(".", end="") sys.stdout.flush() print("") print("Success (retries: {:d})".format(i) if init_done else "Failed") bus.close()
def main(): parser = argparse.ArgumentParser( description="LiteSDCard Bench on Genesys2") parser.add_argument("--with-analyzer", action="store_true", help="Add Analyzer to Bench") parser.add_argument("--build", action="store_true", help="Build bitstream") parser.add_argument("--load", action="store_true", help="Load bitstream") parser.add_argument("--load-bios", action="store_true", help="Load BIOS over Etherbone and reboot SoC") args = parser.parse_args() bench = BenchSoC(with_analyzer=args.with_analyzer) builder = Builder(bench, csr_csv="csr.csv") builder.build(run=args.build) if args.load: prog = bench.platform.create_programmer() prog.load_bitstream( os.path.join(builder.gateware_dir, bench.build_name + ".bit")) if args.load_bios: from litex import RemoteClient wb = RemoteClient() wb.open() ctrl = SoCCtrl() ctrl.load_rom(wb, os.path.join(builder.software_dir, "bios", "bios.bin")) ctrl.reboot(wb) wb.close()
def block2mem_test(port, sector, count): wb = RemoteClient(port=port) wb.open() class Block2MemDriver: def __init__(self, base): self.base = base def read(self, sector): wb.regs.sata_block2mem_sector.write(sector) wb.regs.sata_block2mem_base.write(self.base) wb.regs.sata_block2mem_start.write(1) while wb.regs.sata_block2mem_done.read() == 0: time.sleep(0.1) def dump(self): for addr in range(self.base, self.base + 512, 4): if (addr%16 == 0): if addr != self.base: print("") print("0x{:08x}".format(addr), end=" ") data = wb.read(addr) for i in reversed(range(4)): print("{:02x}".format((data >> (8*i)) & 0xff), end=" ") print("") block2mem = Block2MemDriver(base=wb.mems.sram.base) for s in range(sector, sector + count): print("Sector {:d}:".format(s)) block2mem.read(s) block2mem.dump() wb.close()
def prbs_test(port=1234, mode="prbs7", loopback=False, duration=60): wb = RemoteClient(port=port) wb.open() wb.regs.ctrl_scratch.read() def serdes_reset(): print("Reseting SerDes...") if hasattr(wb.regs, "serdes_clock_aligner_disable"): wb.regs.serdes_clock_aligner_disable.write(0) wb.regs.serdes_tx_prbs_config.write(0) wb.regs.serdes_rx_prbs_config.write(0) time.sleep(1) # Enable Loopback if loopback: print("Enabling SerDes loopback...") wb.regs.serdes_loopback.write(near_end_pma_loopback) # Reset SerDes serdes_reset() # Configure PRBS print(f"Configuring SerDes for {mode.upper()}...") wb.regs.serdes_tx_prbs_config.write(prbs_modes[mode]) wb.regs.serdes_rx_prbs_config.write(prbs_modes[mode]) # Run PRBS/BER Test print("Running PRBS/BER test...") errors_current = 0 errors_last = 0 errors_total = 0 duration_current = 0 interval = 1 try: while duration_current < duration: # Interval / Duration time.sleep(interval) duration_current += interval # Errors errors_current = (wb.regs.serdes_rx_prbs_errors.read() - errors_last) errors_total += errors_current errors_last = errors_current # Log print("Errors: {:12d} / Duration: {:8d}s / BER: {:1.3e} ".format( errors_current, duration_current, errors_total / (duration_current * 5e9))) except KeyboardInterrupt: pass # Reset SerDes serdes_reset() # Disable Loopback if loopback: print("Disabling SerDes loopback...") wb.regs.serdes_loopback.write(0) wb.close()
class BridgeUART: def __init__(self, name="uart_xover", host="localhost", base_address=None, csr_csv=None): self.bus = RemoteClient(host=host, base_address=base_address, csr_csv=csr_csv) present = False for k, v in self.bus.regs.d.items(): if f"{name}_" in k: setattr(self, k.replace(f"{name}_", ""), v) present = True if not present: raise ValueError(f"CrossoverUART {name} not present in design.") # FIXME: On PCIe designs, CSR is remapped to 0 to limit BAR0 size. if base_address is None and hasattr(self.bus.bases, "pcie_phy"): self.bus.base_address = -self.bus.mems.csr.base def open(self): self.bus.open() self.file, self.name = pty.openpty() self.pty2crossover_thread = multiprocessing.Process( target=self.pty2crossover) self.crossover2pty_thread = multiprocessing.Process( target=self.crossover2pty) self.pty2crossover_thread.start() self.crossover2pty_thread.start() def close(self): self.bus.close() self.pty2crossover_thread.terminate() self.crossover2pty_thread.terminate() def pty2crossover(self): while True: r = os.read(self.file, 1) self.rxtx.write(ord(r)) def crossover2pty(self): while True: if self.rxfull.read(): length = 16 elif not self.rxempty.read(): length = 1 else: time.sleep(1e-3) continue r = self.bus.read(self.rxtx.addr, length=length, burst="fixed") for v in r: os.write(self.file, bytes(chr(v).encode("utf-8")))
def main(): port = 1234 r = RemoteClient(csr_csv='out/csr.csv', debug=False, port=port) r.open() print('\nTesting reads ...') print(getId(r)) print('\nTesting writes ...') for i in range(6, 30): r.regs.ctrl_scratch.write(i) print(r.regs.ctrl_scratch.read())
def conLitexServer(csr_csv="build/csr.csv", port=1234): for i in range(32): try: r = RemoteClient(csr_csv=csr_csv, debug=False, port=port + i) r.open() print("Connected to Port", 1234 + i) break except ConnectionRefusedError: r = None if r: print(getId(r)) else: print("Could not connect to RemoteClient") return r
def ident_test(port): wb = RemoteClient(port=port) wb.open() fpga_identifier = "" for i in range(256): c = chr(wb.read(wb.bases.identifier_mem + 4 * i) & 0xff) fpga_identifier += c if c == "\0": break print(fpga_identifier) wb.close()
def main(): args = parse_args() basename = os.path.splitext(os.path.basename(args.csv))[0] # Check if analyzer file is present and exit if not. if not os.path.exists(args.csv): raise ValueError( "{} not found. This is necessary to load the wires which have been tapped to scope." "Try setting --csv to value of the csr_csv argument to LiteScopeAnalyzer in the SoC." .format(args.csv)) sys.exit(1) # Get list of signals from analyzer configuratio file. signals = get_signals(args.csv, args.group) # If in list mode, list signals and exit. if args.list: for signal in signals: print(signal) sys.exit(0) # Create and open remote control. if not os.path.exists(args.csr_csv): raise ValueError( "{} not found. This is necessary to load the 'regs' of the remote. Try setting --csr-csv here to " "the path to the --csr-csv argument of the SoC build.".format( args.csr_csv)) bus = RemoteClient(csr_csv=args.csr_csv) bus.open() # Configure and run LiteScope analyzer. try: analyzer = LiteScopeAnalyzerDriver(bus.regs, basename, debug=True) analyzer.configure_group(int(args.group, 0)) analyzer.configure_subsampler(int(args.subsampling, 0)) if not add_triggers(args, analyzer, signals): print("No trigger, immediate capture.") analyzer.run( offset=int(args.offset, 0), length=None if args.length is None else int(args.length, 0)) analyzer.wait_done() analyzer.upload() analyzer.save(args.dump) # Close remove control. finally: bus.close()
class BridgeUART: def __init__(self, name="uart_xover", host="localhost", base_address=0): # FIXME: add command line arguments self.bus = RemoteClient(host=host, base_address=base_address) present = False for k, v in self.bus.regs.d.items(): if f"{name}_" in k: setattr(self, k.replace(f"{name}_", ""), v) present = True if not present: raise ValueError(f"CrossoverUART {name} not present in design.") def open(self): self.bus.open() self.file, self.name = pty.openpty() self.pty2crossover_thread = multiprocessing.Process( target=self.pty2crossover) self.crossover2pty_thread = multiprocessing.Process( target=self.crossover2pty) self.pty2crossover_thread.start() self.crossover2pty_thread.start() def close(self): self.bus.close() self.pty2crossover_thread.terminate() self.crossover2pty_thread.terminate() def pty2crossover(self): while True: r = os.read(self.file, 1) self.rxtx.write(ord(r)) def crossover2pty(self): while True: if self.rxfull.read(): length = 16 elif not self.rxempty.read(): length = 1 else: time.sleep(1e-3) continue r = self.bus.read(self.rxtx.addr, length=length, burst="fixed") for v in r: os.write(self.file, bytes(chr(v).encode("utf-8")))
def sram_test(port): wb = RemoteClient(port=port) wb.open() def mem_dump(base, length): for addr in range(base, base + length, 4): if (addr % 16 == 0): if addr != base: print("") print("0x{:08x}".format(addr), end=" ") data = wb.read(addr) for i in reversed(range(4)): print("{:02x}".format((data >> (8 * i)) & 0xff), end=" ") print("") def mem_write(base, datas): for n, addr in enumerate(range(base, base + 4 * len(datas), 4)): if (addr % 16 == 0): if addr != base: print("") print("0x{:08x}".format(addr), end=" ") data = datas[n] for i in reversed(range(4)): print("{:02x}".format((data >> (8 * i)) & 0xff), end=" ") wb.write(addr, data) print("") print("Fill SRAM with counter:") mem_write(wb.mems.serwb.base, [i for i in range(128)]) print("") print("Dump SRAM:") mem_dump(wb.mems.serwb.base, 128) print("") print("Fill SRAM with 4 32-bit words:") mem_write(wb.mems.serwb.base, [0x01234567, 0x89abcdef, 0x5aa55aa5, 0xa55aa55a]) print("") print("Dump SRAM:") mem_dump(wb.mems.serwb.base, 128) print("") wb.close()
def main(): parser = argparse.ArgumentParser( description="LiteSDCard Bench on Trellis Board") parser.add_argument("--bench", default="soc", help="Bench: soc (default) or phy") parser.add_argument("--variant", default="standard", help="Bench variant") parser.add_argument("--with-sampler", action="store_true", help="Add Sampler to Bench") parser.add_argument("--with-analyzer", action="store_true", help="Add Analyzer to Bench") parser.add_argument("--build", action="store_true", help="Build bitstream") parser.add_argument("--load", action="store_true", help="Load bitstream") parser.add_argument("--load-bios", action="store_true", help="Load BIOS over Etherbone and reboot SoC") args = parser.parse_args() bench = { "soc": BenchSoC, "phy": BenchPHY }[args.bench]( variant=args.variant, with_sampler=args.with_sampler, with_analyzer=args.with_analyzer, ) builder = Builder(bench, csr_csv="csr.csv") builder.build(run=args.build) if args.load: prog = bench.platform.create_programmer() prog.load_bitstream( os.path.join(builder.gateware_dir, bench.build_name + ".svf")) if args.load_bios: from litex import RemoteClient wb = RemoteClient() wb.open() ctrl = SoCCtrl() ctrl.load_rom(wb, os.path.join(builder.software_dir, "bios", "bios.bin")) ctrl.reboot(wb) wb.close()
def load_bios(bios_filename): from litex import RemoteClient bus = RemoteClient() bus.open() # # # # Load BIOS and reboot SoC. print("Loading BIOS...") ctrl = BenchController(bus) ctrl.load_rom(bios_filename, delay=1e-4) # FIXME: delay needed @ 115200bauds. ctrl.reboot() # # # bus.close()
def main(): parser = argparse.ArgumentParser( description="Script to test correct DDR behaviour." ) parser.add_argument( '--bitslip', default=None, help="Defines a bitslip value." ) parser.add_argument('--delay', default=None, help="Defines a delay value.") args = parser.parse_args() wb = RemoteClient(debug=False) wb.open() # software control wb.regs.sdram_dfii_control.write(0) # sdram initialization for i, (comment, a, ba, cmd, delay) in enumerate(init_sequence): print(comment) wb.regs.sdram_dfii_pi0_address.write(a) wb.regs.sdram_dfii_pi0_baddress.write(ba) if i < 2: wb.regs.sdram_dfii_control.write(cmd) else: wb.regs.sdram_dfii_pi0_command.write(cmd) wb.regs.sdram_dfii_pi0_command_issue.write(1) # hardware control wb.regs.sdram_dfii_control.write(dfii_control_sel) if args.bitslip is None or args.delay is None: bitslip, delay = find_bitslips_delays(wb) else: bitslip = int(args.bitslip) delay = int(args.delay) set_bitslip_delay(wb, bitslip, delay) start_command_interface(wb) wb.close()
def main(): port = 1234 r = RemoteClient(csr_csv='out/csr.csv', debug=False, port=port) r.open() print("Connected to Port", port) print(getId(r)) def SDAR(): return r.regs.i2c_master_r.read() # This should print `1`! (see verilator_sim.py:59) print(SDAR()) # I2C_W_SCL = 0 # I2C_W_OE = 1 # I2C_W_SDA = 2 # I2C_R_SDA = 0 for i in range(5, 30): r.regs.i2c_master_w.write(i) print(r.regs.i2c_master_w.read())
class LTCOnMarblemini(Carrier): def __init__(self, count=10, log_decimation_factor=0, test=False): ADC.bits = 14 ADC.sample_rate = 120000000. self.n_channels = 2 self._db = None self.test = test self.pts_per_ch = 8192 self.subscriptions, self.results = {}, {} self.set_log_decimation_factor(log_decimation_factor) self.wb = RemoteClient() self.wb.open() print(self.wb.regs.acq_buf_full.read()) initLTC(self.wb) def set_log_decimation_factor(self, ldf): ADC.decimation_factor = 1 << ldf ADC.fpga_output_rate = ADC.sample_rate / ADC.decimation_factor if ldf != 0: ''' This feature is missing in gateware ''' raise NotImplementedError def acquire_data(self, *args): if self.test: return self.test_data(*args) while True: # self.wb.regs.acq_acq_start.write(1) d = get_data(self.wb) if d is None: print('recovering') time.sleep(0.1) continue self._db = DataBlock(d, int(time.time())) # ADC count / FULL SCALE => [-1.0, 1.] self._process_subscriptions() # time.sleep(0.1) self.wb.close()
def dma_test(port, mode, sector, count): assert mode in ["r", "r+w"] bus = RemoteClient(port=port) bus.open() dma = DMADriver(bus=bus, base=bus.mems.sram.base) for s in range(sector, sector + count): print("Sector {:d}:".format(s)) error = dma.read(s) dma.dump() print("Error: {:d}".format(error)) if mode == "r+w": s = 1000 dma.fill([i for i in range(512 // 4)]) error = dma.write(s) print("Sector {:d}:".format(s)) error += dma.read(s) dma.dump() print("Error: {:d}".format(error)) bus.close()
def trigger_hardware(n_points, cap_ip, cap_port, csr_csv=None): wb = RemoteClient(csr_csv=csr_csv) wb.open() # Try communication a few times before giving up try_list = range(0, 3) for i in try_list: try: print(f"Tryout {i}") fifo_size = wb.regs.data_pipe_fifo_size.read() print(f"Fifo size was set to {fifo_size}") if n_points != fifo_size: print(f"Setting fifo size to {n_points}") wb.regs.data_pipe_fifo_size.write(n_points) print(f"fifo size set to {wb.regs.data_pipe_fifo_size.read()}") print(wb.regs.data_pipe_dst_ip.write(convert_ip(cap_ip))) print(wb.regs.data_pipe_dst_port.write(cap_port)) print(wb.regs.data_pipe_fifo_read.write(0)) print(wb.regs.data_pipe_fifo_load.write(1)) triggered_at = time.time() print(wb.regs.data_pipe_fifo_load.read()) while wb.regs.data_pipe_fifo_full.read() != 1: pass full_at = time.time() print(f"triggered at {triggered_at}") print(f"full at {full_at}. Now sending read command") wb.regs.data_pipe_fifo_read.write(1) except socket.timeout as e: # Last try if i == try_list[-1]: raise e else: continue else: break
#!/usr/bin/env python3 import time from litex import RemoteClient wb = RemoteClient() wb.open() # # # print("Toggling Led...") for i in range(2): wb.regs.led_out.write(1) time.sleep(0.5) wb.regs.led_out.write(0) time.sleep(0.5) # # # wb.close()
def us_bench_test(freq_min, freq_max, freq_step, vco_freq, bios_filename, bios_timeout=40): import time from litex import RemoteClient bus = RemoteClient() bus.open() # # # # Load BIOS and reboot SoC ctrl = BenchController(bus) ctrl.load_rom(bios_filename, delay=1e-4) # FIXME: delay needed @ 115200bauds. ctrl.reboot() # PLL/ClkReg uspll = USPLL(bus) clkout0_clkreg1 = ClkReg1(uspll.read(0x8)) # Run calibration from freq_min to freq_max and log BIOS output. print("-" * 80) print( "Running calibration; sys_clk from {:3.3f}MHz to {:3.2f}MHz (step: {:3.2f}MHz)" .format(freq_min / 1e6, freq_max / 1e6, freq_step / 1e6)) print("-" * 80) print("") tested_vco_divs = [] for clk_freq in range(int(freq_min), int(freq_max), int(freq_step)): # Compute VCO divider, skip if already tested. vco_div = int(vco_freq / clk_freq) if vco_div in tested_vco_divs: continue tested_vco_divs.append(vco_div) print("-" * 40) print("sys_clk = {}MHz...".format(vco_freq / vco_div / 1e6)) print("-" * 40) # Reconfigure PLL to change sys_clk clkout0_clkreg1.high_time = vco_div // 2 + vco_div % 2 clkout0_clkreg1.low_time = vco_div // 2 uspll.write(0x08, clkout0_clkreg1.pack()) # Measure/verify sys_clk duration = 5e-1 start = bus.regs.crg_sys_clk_counter.read() time.sleep(duration) end = bus.regs.crg_sys_clk_counter.read() print("Measured sys_clk: {:3.2f}MHz.".format( (end - start) / (1e6 * duration))) # Reboot SoC and log BIOS output print("-" * 40) print("Reboot SoC and get BIOS log...") print("-" * 40) ctrl.reboot() start = time.time() while (time.time() - start) < bios_timeout: if bus.regs.uart_xover_rxfull.read(): length = 16 elif not bus.regs.uart_xover_rxempty.read(): length = 1 else: time.sleep(1e-3) continue for c in bus.read(bus.regs.uart_xover_rxtx.addr, length=length, burst="fixed"): print("{:c}".format(c), end="") print("") # # # bus.close()
def init_test(port): wb = RemoteClient(port=port) wb.open() # Reset SerWB Master print("Reseting SerWB Master...") wb.regs.serwb_master_phy_control_reset.write(1) # Initialize SerWB Master timeout = 4 print(f"Initializing SerWB Master...") while (wb.regs.serwb_master_phy_control_ready.read() == 0 and wb.regs.serwb_master_phy_control_error.read() == 0 and timeout > 0): time.sleep(0.1) print(f"{timeout:2.2f}s", end="\r") sys.stdout.flush() timeout -= 0.1 print("") if (timeout <= 0): print("Failed.") return else: print("Success.") # Show Master Config print("Master config") print("-------------") if hasattr(wb.regs, "serwb_master_phy_control_delay"): print("delay_min_found: {:d}".format( wb.regs.serwb_master_phy_control_delay_min_found.read())) print("delay_min: {:d}".format( wb.regs.serwb_master_phy_control_delay_min.read())) print("delay_max_found: {:d}".format( wb.regs.serwb_master_phy_control_delay_max_found.read())) print("delay_max: {:d}".format( wb.regs.serwb_master_phy_control_delay_max.read())) print("delay: {:d}".format( wb.regs.serwb_master_phy_control_delay.read())) print("bitslip: {:d}".format( wb.regs.serwb_master_phy_control_shift.read())) print("ready: {:d}".format(wb.regs.serwb_master_phy_control_ready.read())) print("error: {:d}".format(wb.regs.serwb_master_phy_control_error.read())) print("") # Show Slave Config print("Slave config") print("------------") if hasattr(wb.regs, "serwb_slave_phy_control_delay"): print("delay_min_found: {:d}".format( wb.regs.serwb_slave_phy_control_delay_min_found.read())) print("delay_min: {:d}".format( wb.regs.serwb_slave_phy_control_delay_min.read())) print("delay_max_found: {:d}".format( wb.regs.serwb_slave_phy_control_delay_max_found.read())) print("delay_max: {:d}".format( wb.regs.serwb_slave_phy_control_delay_max.read())) print("delay: {:d}".format( wb.regs.serwb_slave_phy_control_delay.read())) print("bitslip: {:d}".format(wb.regs.serwb_slave_phy_control_shift.read())) print("ready: {:d}".format(wb.regs.serwb_slave_phy_control_ready.read())) print("error: {:d}".format(wb.regs.serwb_slave_phy_control_error.read())) wb.close()