latest fighting with litex to get pad directions connected up
[libresoc-litex.git] / ls180soc.py
1 #!/usr/bin/env python3
2
3 import os
4 import argparse
5 from functools import reduce
6 from operator import or_
7
8 from migen import (Signal, FSM, If, Display, Finish, NextValue, NextState,
9 Cat, Record, ClockSignal, wrap, ResetInserter)
10
11 from litex.build.generic_platform import Pins, Subsignal
12 from litex.build.sim import SimPlatform
13 from litex.build.io import CRG
14 from litex.build.sim.config import SimConfig
15
16 from litex.soc.integration.soc import SoCRegion
17 from litex.soc.integration.soc_core import SoCCore
18 from litex.soc.integration.soc_sdram import SoCSDRAM
19 from litex.soc.integration.builder import Builder
20 from litex.soc.integration.common import get_mem_data
21
22 from litedram import modules as litedram_modules
23 from litedram.phy.model import SDRAMPHYModel
24 #from litedram.phy.gensdrphy import GENSDRPHY, HalfRateGENSDRPHY
25 from litedram.common import PHYPadsCombiner, PhySettings
26 from litedram.phy.dfi import Interface as DFIInterface
27 from litex.soc.cores.spi import SPIMaster
28 from litex.soc.cores.pwm import PWM
29 #from litex.soc.cores.bitbang import I2CMaster
30 from litex.soc.cores import uart
31
32 from litex.tools.litex_sim import sdram_module_nphases, get_sdram_phy_settings
33
34 from litex.tools.litex_sim import Platform
35 from libresoc.ls180 import LS180Platform
36
37 from migen import Module
38 from litex.soc.interconnect.csr import AutoCSR
39
40 from libresoc import LibreSoC
41 from microwatt import Microwatt
42
43 # HACK!
44 from litex.soc.integration.soc import SoCCSRHandler
45 SoCCSRHandler.supported_address_width.append(12)
46
47 # GPIO Tristate -------------------------------------------------------
48 # doesn't work properly.
49 #from litex.soc.cores.gpio import GPIOTristate
50 from litex.soc.interconnect.csr import CSRStorage, CSRStatus, CSRField
51 from migen.genlib.cdc import MultiReg
52
53 # Imports
54 from litex.soc.interconnect import wishbone
55 from litesdcard.phy import (SDPHY, SDPHYClocker,
56 SDPHYInit, SDPHYCMDW, SDPHYCMDR,
57 SDPHYDATAW, SDPHYDATAR,
58 _sdpads_layout)
59 from litesdcard.core import SDCore
60 from litesdcard.frontend.dma import SDBlock2MemDMA, SDMem2BlockDMA
61 from litex.build.io import SDROutput, SDRInput
62
63
64 # I2C Master Bit-Banging --------------------------------------------------
65
66 class I2CMaster(Module, AutoCSR):
67 """I2C Master Bit-Banging
68
69 Provides the minimal hardware to do software I2C Master bit banging.
70
71 On the same write CSRStorage (_w), software can control SCL (I2C_SCL),
72 SDA direction and value (I2C_OE, I2C_W). Software get back SDA value
73 with the read CSRStatus (_r).
74 """
75 pads_layout = [("scl", 1), ("sda", 1)]
76 def __init__(self, pads):
77 self.pads = pads
78 self._w = CSRStorage(fields=[
79 CSRField("scl", size=1, offset=0),
80 CSRField("oe", size=1, offset=1),
81 CSRField("sda", size=1, offset=2)],
82 name="w")
83 self._r = CSRStatus(fields=[
84 CSRField("sda", size=1, offset=0)],
85 name="r")
86
87 self.connect(pads)
88
89 def connect(self, pads):
90 _sda_w = Signal()
91 _sda_oe = Signal()
92 _sda_r = Signal()
93 self.comb += [
94 pads.scl.eq(self._w.fields.scl),
95 pads.sda_oe.eq( self._w.fields.oe),
96 pads.sda_o.eq( self._w.fields.sda),
97 self._r.fields.sda.eq(pads.sda_i),
98 ]
99
100
101 class GPIOTristateASIC(Module, AutoCSR):
102 def __init__(self, name, pads, prange=None):
103 if prange is None:
104 prange = range(nbits)
105 nbits = len(prange)
106
107 self._oe = CSRStorage(nbits, description="GPIO Tristate(s) Control.")
108 self._in = CSRStatus(nbits, description="GPIO Input(s) Status.")
109 self._out = CSRStorage(nbits, description="GPIO Ouptut(s) Control.")
110
111 # # #
112
113 _pads = Record( ((name+"i", nbits),
114 (name+"o", nbits),
115 (name+"oe", nbits)))
116 _o = getattr(_pads, name+"o")
117 _oe = getattr(_pads, name+"oe")
118 _i = getattr(_pads, name+"i")
119 for j, i in enumerate(prange):
120 self.comb += _i[j].eq(pads.i[i])
121 self.comb += pads.o[i].eq(_o[j])
122 self.comb += pads.oe[i].eq(_oe[j])
123
124 clk = ClockSignal()
125 o = self._out.storage
126 oe = self._oe.storage
127 i = self._in.status
128 for j in range(nbits):
129 self.specials += SDROutput(clk=clk, i=oe[j], o=_oe[j])
130 self.specials += SDROutput(clk=clk, i=o[j], o=_o[j])
131 self.specials += SDRInput(clk=clk, i=_i[j], o=i[j])
132 #for i in range(nbits):
133 #self.comb += _pads.oe[i].eq(self._oe.storage[i])
134 #self.comb += _pads.o[i].eq(self._out.storage[i])
135 #self.specials += MultiReg(_pads.i[i], self._in.status[i])
136
137 # SDCard PHY IO -------------------------------------------------------
138
139 class SDRPad(Module):
140 def __init__(self, pad, name, o, oe, i):
141 clk = ClockSignal()
142 _o = getattr(pad, "%s_o" % name)
143 _oe = getattr(pad, "%s_oe" % name)
144 _i = getattr(pad, "%s_i" % name)
145 self.specials += SDROutput(clk=clk, i=oe, o=_oe)
146 for j in range(len(_o)):
147 self.specials += SDROutput(clk=clk, i=o[j], o=_o[j])
148 self.specials += SDRInput(clk=clk, i=_i[j], o=i[j])
149
150
151 class SDPHYIOGen(Module):
152 def __init__(self, clocker, sdpads, pads):
153 # Rst
154 if hasattr(pads, "rst"):
155 self.comb += pads.rst.eq(0)
156
157 # Clk
158 self.specials += SDROutput(
159 clk = ClockSignal(),
160 i = ~clocker.clk & sdpads.clk,
161 o = pads.clk
162 )
163
164 # Cmd
165 c = sdpads.cmd
166 self.submodules.sd_cmd = SDRPad(pads, "cmd", c.o, c.oe, c.i)
167
168 # Data
169 d = sdpads.data
170 self.submodules.sd_data = SDRPad(pads, "data", d.o, d.oe, d.i)
171
172
173 class SDPHY(Module, AutoCSR):
174 def __init__(self, pads, device, sys_clk_freq,
175 cmd_timeout=10e-3, data_timeout=10e-3):
176 self.card_detect = CSRStatus() # Assume SDCard is present if no cd pin.
177 self.comb += self.card_detect.status.eq(getattr(pads, "cd", 0))
178
179 self.submodules.clocker = clocker = SDPHYClocker()
180 self.submodules.init = init = SDPHYInit()
181 self.submodules.cmdw = cmdw = SDPHYCMDW()
182 self.submodules.cmdr = cmdr = SDPHYCMDR(sys_clk_freq,
183 cmd_timeout, cmdw)
184 self.submodules.dataw = dataw = SDPHYDATAW()
185 self.submodules.datar = datar = SDPHYDATAR(sys_clk_freq,
186 data_timeout)
187
188 # # #
189
190 self.sdpads = sdpads = Record(_sdpads_layout)
191
192 # IOs
193 sdphy_cls = SDPHYIOGen
194 self.submodules.io = sdphy_cls(clocker, sdpads, pads)
195
196 # Connect pads_out of submodules to physical pads --------------
197 pl = [init, cmdw, cmdr, dataw, datar]
198 self.comb += [
199 sdpads.clk.eq( reduce(or_, [m.pads_out.clk for m in pl])),
200 sdpads.cmd.oe.eq( reduce(or_, [m.pads_out.cmd.oe for m in pl])),
201 sdpads.cmd.o.eq( reduce(or_, [m.pads_out.cmd.o for m in pl])),
202 sdpads.data.oe.eq(reduce(or_, [m.pads_out.data.oe for m in pl])),
203 sdpads.data.o.eq( reduce(or_, [m.pads_out.data.o for m in pl])),
204 ]
205 for m in pl:
206 self.comb += m.pads_out.ready.eq(self.clocker.ce)
207
208 # Connect physical pads to pads_in of submodules ---------------
209 for m in pl:
210 self.comb += m.pads_in.valid.eq(self.clocker.ce)
211 self.comb += m.pads_in.cmd.i.eq(sdpads.cmd.i)
212 self.comb += m.pads_in.data.i.eq(sdpads.data.i)
213
214 # Speed Throttling -------------------------------------------
215 self.comb += clocker.stop.eq(dataw.stop | datar.stop)
216
217
218 # Generic SDR PHY ---------------------------------------------------------
219
220 class GENSDRPHY(Module):
221 def __init__(self, pads, cl=2, cmd_latency=1):
222 pads = PHYPadsCombiner(pads)
223 addressbits = len(pads.a)
224 bankbits = len(pads.ba)
225 nranks = 1 if not hasattr(pads, "cs_n") else len(pads.cs_n)
226 databits = len(pads.dq_i)
227 assert cl in [2, 3]
228 assert databits%8 == 0
229
230 # PHY settings ----------------------------------------------------
231 self.settings = PhySettings(
232 phytype = "GENSDRPHY",
233 memtype = "SDR",
234 databits = databits,
235 dfi_databits = databits,
236 nranks = nranks,
237 nphases = 1,
238 rdphase = 0,
239 wrphase = 0,
240 rdcmdphase = 0,
241 wrcmdphase = 0,
242 cl = cl,
243 read_latency = cl + cmd_latency,
244 write_latency = 0
245 )
246
247 # DFI Interface ---------------------------------------------------
248 self.dfi = dfi = DFIInterface(addressbits, bankbits, nranks, databits)
249
250 # # #
251
252 # Iterate on pads groups ------------------------------------------
253 for pads_group in range(len(pads.groups)):
254 pads.sel_group(pads_group)
255
256 # Addresses and Commands --------------------------------------
257 p0 = dfi.p0
258 self.specials += [SDROutput(i=p0.address[i], o=pads.a[i])
259 for i in range(len(pads.a))]
260 self.specials += [SDROutput(i=p0.bank[i], o=pads.ba[i])
261 for i in range(len(pads.ba))]
262 self.specials += SDROutput(i=p0.cas_n, o=pads.cas_n)
263 self.specials += SDROutput(i=p0.ras_n, o=pads.ras_n)
264 self.specials += SDROutput(i=p0.we_n, o=pads.we_n)
265 if hasattr(pads, "cke"):
266 for i in range(len(pads.cke)):
267 self.specials += SDROutput(i=p0.cke[i], o=pads.cke[i])
268 if hasattr(pads, "cs_n"):
269 for i in range(len(pads.cs_n)):
270 self.specials += SDROutput(i=p0.cs_n[i], o=pads.cs_n[i])
271
272 # DQ/DM Data Path -------------------------------------------------
273
274 d = dfi.p0
275 wren = []
276 self.submodules.dq = SDRPad(pads, "dq", d.wrdata, d.wrdata_en, d.rddata)
277
278 if hasattr(pads, "dm"):
279 print ("sdr pads dm len", pads.dm, len(pads.dm))
280 for i in range(len(pads.dm)):
281 self.specials += SDROutput(i=d.wrdata_en&d.wrdata_mask[i],
282 o=pads.dm[i])
283
284 # DQ/DM Control Path ----------------------------------------------
285 rddata_en = Signal(cl + cmd_latency)
286 self.sync += rddata_en.eq(Cat(dfi.p0.rddata_en, rddata_en))
287 self.sync += dfi.p0.rddata_valid.eq(rddata_en[-1])
288
289
290 # LibreSoC 180nm ASIC -------------------------------------------------------
291
292 class LibreSoCSim(SoCCore):
293 def __init__(self, cpu="libresoc", debug=False, with_sdram=True,
294 sdram_module = "AS4C16M16",
295 #sdram_data_width = 16,
296 #sdram_module = "MT48LC16M16",
297 sdram_data_width = 16,
298 irq_reserved_irqs = {'uart': 0},
299 platform='sim',
300 dff_srams=5,
301 srams_4k=4,
302 ):
303 assert cpu in ["libresoc", "microwatt"]
304 sys_clk_freq = int(50e6)
305
306 platform_name = platform
307 if platform == 'sim':
308 platform = Platform()
309 self.platform.name = 'ls180'
310 uart_name = "sim"
311 elif 'ls180' in platform:
312 platform = LS180Platform()
313 uart_name = "uart"
314
315 #cpu_data_width = 32
316 cpu_data_width = 64
317
318 variant = "ls180"
319
320 # reserve XICS ICP and XICS memory addresses.
321 self.mem_map['icp'] = 0xc0010000
322 self.mem_map['ics'] = 0xc0011000
323 #self.csr_map["icp"] = 8 # 8 x 0x800 == 0x4000
324 #self.csr_map["ics"] = 10 # 10 x 0x800 == 0x5000
325
326 ram_init = []
327 if False:
328 #ram_init = get_mem_data({
329 # ram_fname: "0x00000000",
330 # }, "little")
331 ram_init = get_mem_data(ram_fname, "little")
332
333 # remap the main RAM to reset-start-address
334
335 # without sram nothing works, therefore move it to higher up
336 self.mem_map["sram"] = 0x90000000
337
338 # put UART at 0xc000200 (w00t! this works!)
339 self.csr_map["uart"] = 4
340
341 self.mem_map["main_ram"] = 0x90000000
342 if dff_srams == 5:
343 self.mem_map["sram"] = 0x00000000
344 self.mem_map["sram1"] = 0x00000200
345 self.mem_map["sram2"] = 0x00000400
346 self.mem_map["sram3"] = 0x00000600
347 self.mem_map["sram4"] = 0x00000800
348 sram_size = 0x200
349 else:
350 sram_size = 0x80 # ridiculously small
351 if "sram4k" not in variant:
352 sram_size = 0x200 # no 4k SRAMs, make slightly bigger
353 self.mem_map["sram"] = 0x00000000
354 self.mem_map["sram1"] = 0x00000700
355 self.mem_map["sram4k_0"] = 0x00001000
356 self.mem_map["sram4k_1"] = 0x00002000
357 self.mem_map["sram4k_2"] = 0x00003000
358 self.mem_map["sram4k_3"] = 0x00004000
359
360 # SoCCore -------------------------------------------------------------
361 SoCCore.__init__(self, platform, clk_freq=sys_clk_freq,
362 cpu_type = "microwatt",
363 cpu_cls = LibreSoC if cpu == "libresoc" \
364 else Microwatt,
365 bus_data_width = 64,
366 csr_address_width = 14, # limit to 0x8000
367 cpu_variant = variant,
368 csr_data_width = 8,
369 l2_size = 0,
370 with_uart = False,
371 uart_name = None,
372 with_sdram = with_sdram,
373 sdram_module = sdram_module,
374 sdram_data_width = sdram_data_width,
375 integrated_rom_size = 0, # if ram_fname else 0x10000,
376 #integrated_sram_size = 0x1000, - problem with yosys ABC
377 integrated_sram_size = sram_size,
378 #integrated_main_ram_init = ram_init,
379 integrated_main_ram_size = 0x00000000 if with_sdram \
380 else 0x10000000 , # 256MB
381 )
382
383 self.platform.name = platform_name
384
385 if dff_srams == 5:
386 # add 4 more 4k integrated SRAMs
387 self.add_ram("sram1", self.mem_map["sram1"], 0x200)
388 self.add_ram("sram2", self.mem_map["sram2"], 0x200)
389 self.add_ram("sram3", self.mem_map["sram3"], 0x200)
390 self.add_ram("sram4", self.mem_map["sram4"], 0x200)
391 else:
392 self.add_ram("sram1", self.mem_map["sram1"], 0x80) # tiny!
393
394 # SDR SDRAM ----------------------------------------------
395 if False: # not self.integrated_main_ram_size:
396 self.submodules.sdrphy = sdrphy_cls(platform.request("sdram"))
397
398 if cpu == "libresoc":
399 # XICS interrupt devices
400 icp_addr = self.mem_map['icp']
401 icp_wb = self.cpu.xics_icp
402 icp_region = SoCRegion(origin=icp_addr, size=0x20, cached=False)
403 self.bus.add_slave(name='icp', slave=icp_wb, region=icp_region)
404
405 ics_addr = self.mem_map['ics']
406 ics_wb = self.cpu.xics_ics
407 ics_region = SoCRegion(origin=ics_addr, size=0x1000, cached=False)
408 self.bus.add_slave(name='ics', slave=ics_wb, region=ics_region)
409
410 # add 4x 4k SRAMs
411 for i, sram_wb in enumerate(self.cpu.srams):
412 name = 'sram4k_%d' % i
413 sram_adr = self.mem_map[name]
414 ics_region = SoCRegion(origin=sram_adr, size=0x1000)
415 self.bus.add_slave(name=name, slave=sram_wb, region=ics_region)
416
417 # CRG -----------------------------------------------------------------
418 self.submodules.crg = CRG(platform.request("sys_clk"),
419 platform.request("sys_rst"))
420
421 # PLL/Clock Select
422 clksel_i = platform.request("sys_clksel_i")
423 pll18_o = platform.request("sys_pll_18_o")
424 pll_lck_o = platform.request("sys_pll_lck_o")
425
426 self.comb += self.cpu.clk_sel.eq(clksel_i) # allow clock src select
427 self.comb += pll18_o.eq(self.cpu.pll_18_o) # "test feed" from the PLL
428 self.comb += pll_lck_o.eq(self.cpu.pll_lck_o) # PLL lock flag
429
430 #ram_init = []
431
432 # SDRAM ----------------------------------------------------
433 if with_sdram:
434 sdram_clk_freq = int(100e6) # FIXME: use 100MHz timings
435 sdram_module_cls = getattr(litedram_modules, sdram_module)
436 sdram_rate = "1:{}".format(
437 sdram_module_nphases[sdram_module_cls.memtype])
438 sdram_module = sdram_module_cls(sdram_clk_freq, sdram_rate)
439 phy_settings = get_sdram_phy_settings(
440 memtype = sdram_module.memtype,
441 data_width = sdram_data_width,
442 clk_freq = sdram_clk_freq)
443 #sdrphy_cls = HalfRateGENSDRPHY
444 sdrphy_cls = GENSDRPHY
445 sdram_pads = self.cpu.cpupads['sdr']
446 self.submodules.sdrphy = sdrphy_cls(sdram_pads)
447 #self.submodules.sdrphy = sdrphy_cls(sdram_module,
448 # phy_settings,
449 # init=ram_init
450 # )
451 self.add_sdram("sdram",
452 phy = self.sdrphy,
453 module = sdram_module,
454 origin = self.mem_map["main_ram"],
455 size = 0x80000000,
456 l2_cache_size = 0, # 8192
457 l2_cache_min_data_width = 128,
458 l2_cache_reverse = True
459 )
460 # FIXME: skip memtest to avoid corrupting memory
461 self.add_constant("MEMTEST_BUS_SIZE", 128//16)
462 self.add_constant("MEMTEST_DATA_SIZE", 128//16)
463 self.add_constant("MEMTEST_ADDR_SIZE", 128//16)
464 self.add_constant("MEMTEST_BUS_DEBUG", 1)
465 self.add_constant("MEMTEST_ADDR_DEBUG", 1)
466 self.add_constant("MEMTEST_DATA_DEBUG", 1)
467
468 # SDRAM clock
469 sys_clk = ClockSignal()
470 sdr_clk = self.cpu.cpupads['sdram_clock']
471 #self.specials += DDROutput(1, 0, , sdram_clk)
472 self.specials += SDROutput(clk=sys_clk, i=sys_clk, o=sdr_clk)
473
474 # UART
475 uart_core_pads = self.cpu.cpupads['uart']
476 self.submodules.uart_phy = uart.UARTPHY(
477 pads = uart_core_pads,
478 clk_freq = self.sys_clk_freq,
479 baudrate = 115200)
480 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy,
481 tx_fifo_depth = 16,
482 rx_fifo_depth = 16))
483
484 self.csr.add("uart_phy", use_loc_if_exists=True)
485 self.csr.add("uart", use_loc_if_exists=True)
486 self.irq.add("uart", use_loc_if_exists=True)
487
488 # GPIOs (bi-directional)
489 gpio_core_pads = self.cpu.cpupads['gpio']
490 self.submodules.gpio0 = GPIOTristateASIC("gpio0", gpio_core_pads,
491 range(8))
492 self.add_csr("gpio0")
493
494 self.submodules.gpio1 = GPIOTristateASIC("gpio1", gpio_core_pads,
495 range(8, 16))
496 self.add_csr("gpio1")
497
498 # SPI Master
499 print ("cpupadkeys", self.cpu.cpupads.keys())
500 if hasattr(self.cpu.cpupads, 'mspi0'):
501 sd_clk_freq = 8e6
502 pads = self.cpu.cpupads['mspi0']
503 spimaster = SPIMaster(pads, 8, self.sys_clk_freq, sd_clk_freq)
504 spimaster.add_clk_divider()
505 setattr(self.submodules, 'spimaster', spimaster)
506 self.add_csr('spimaster')
507
508 if hasattr(self.cpu.cpupads, 'mspi1'):
509 # SPI SDCard (1 wide)
510 spi_clk_freq = 400e3
511 pads = self.cpu.cpupads['mspi1']
512 spisdcard = SPIMaster(pads, 8, self.sys_clk_freq, spi_clk_freq)
513 spisdcard.add_clk_divider()
514 setattr(self.submodules, 'spisdcard', spisdcard)
515 self.add_csr('spisdcard')
516
517 # EINTs - very simple, wire up top 3 bits to ls180 "eint" pins
518 eintpads = self.cpu.cpupads['eint']
519 print ("eintpads", eintpads)
520 self.comb += self.cpu.interrupt[13:16].eq(eintpads)
521
522 # JTAG
523 jtagpads = platform.request("jtag")
524 self.comb += self.cpu.jtag_tck.eq(jtagpads.tck)
525 self.comb += self.cpu.jtag_tms.eq(jtagpads.tms)
526 self.comb += self.cpu.jtag_tdi.eq(jtagpads.tdi)
527 self.comb += jtagpads.tdo.eq(self.cpu.jtag_tdo)
528
529 # NC - allows some iopads to be connected up
530 # sigh, just do something, anything, to stop yosys optimising these out
531 nc_pads = platform.request("nc")
532 num_nc = len(nc_pads)
533 self.nc = Signal(num_nc)
534 self.comb += self.nc.eq(nc_pads)
535 self.dummy = Signal(num_nc)
536 for i in range(num_nc):
537 self.sync += self.dummy[i].eq(self.nc[i] | self.cpu.interrupt[0])
538
539 # PWM
540 if hasattr(self.cpu.cpupads, 'pwm'):
541 pwmpads = self.cpu.cpupads['pwm']
542 for i in range(2):
543 name = "pwm%d" % i
544 setattr(self.submodules, name, PWM(pwmpads[i]))
545 self.add_csr(name)
546
547 # I2C Master
548 i2c_core_pads = self.cpu.cpupads['mtwi']
549 self.submodules.i2c = I2CMaster(i2c_core_pads)
550 self.add_csr("i2c")
551
552 # SDCard -----------------------------------------------------
553
554 if hasattr(self.cpu.cpupads, 'sd0'):
555 # Emulator / Pads
556 sdcard_pads = self.cpu.cpupads['sd0']
557
558 # Core
559 self.submodules.sdphy = SDPHY(sdcard_pads,
560 self.platform.device, self.clk_freq)
561 self.submodules.sdcore = SDCore(self.sdphy)
562 self.add_csr("sdphy")
563 self.add_csr("sdcore")
564
565 # Block2Mem DMA
566 bus = wishbone.Interface(data_width=self.bus.data_width,
567 adr_width=self.bus.address_width)
568 self.submodules.sdblock2mem = SDBlock2MemDMA(bus=bus,
569 endianness=self.cpu.endianness)
570 self.comb += self.sdcore.source.connect(self.sdblock2mem.sink)
571 dma_bus = self.bus if not hasattr(self, "dma_bus") else self.dma_bus
572 dma_bus.add_master("sdblock2mem", master=bus)
573 self.add_csr("sdblock2mem")
574
575 # Mem2Block DMA
576 bus = wishbone.Interface(data_width=self.bus.data_width,
577 adr_width=self.bus.address_width)
578 self.submodules.sdmem2block = SDMem2BlockDMA(bus=bus,
579 endianness=self.cpu.endianness)
580 self.comb += self.sdmem2block.source.connect(self.sdcore.sink)
581 dma_bus = self.bus if not hasattr(self, "dma_bus") else self.dma_bus
582 dma_bus.add_master("sdmem2block", master=bus)
583 self.add_csr("sdmem2block")
584
585 # Debug ---------------------------------------------------------------
586 if not debug:
587 return
588
589 jtag_en = ('jtag' in variant) or ('ls180' in variant)
590
591 # setup running of DMI FSM
592 dmi_addr = Signal(4)
593 dmi_din = Signal(64)
594 dmi_dout = Signal(64)
595 dmi_wen = Signal(1)
596 dmi_req = Signal(1)
597
598 # debug log out
599 dbg_addr = Signal(4)
600 dbg_dout = Signal(64)
601 dbg_msg = Signal(1)
602
603 # capture pc from dmi
604 pc = Signal(64)
605 active_dbg = Signal()
606 active_dbg_cr = Signal()
607 active_dbg_xer = Signal()
608
609 # xer flags
610 xer_so = Signal()
611 xer_ca = Signal()
612 xer_ca32 = Signal()
613 xer_ov = Signal()
614 xer_ov32 = Signal()
615
616 # increment counter, Stop after 100000 cycles
617 uptime = Signal(64)
618 self.sync += uptime.eq(uptime + 1)
619 #self.sync += If(uptime == 1000000000000, Finish())
620
621 # DMI FSM counter and FSM itself
622 dmicount = Signal(10)
623 dmirunning = Signal(1)
624 dmi_monitor = Signal(1)
625 dmifsm = FSM()
626 self.submodules += dmifsm
627
628 # DMI FSM
629 dmifsm.act("START",
630 If(dmi_req & dmi_wen,
631 (self.cpu.dmi_addr.eq(dmi_addr), # DMI Addr
632 self.cpu.dmi_din.eq(dmi_din), # DMI in
633 self.cpu.dmi_req.eq(1), # DMI request
634 self.cpu.dmi_wr.eq(1), # DMI write
635 If(self.cpu.dmi_ack,
636 (NextState("IDLE"),
637 )
638 ),
639 ),
640 ),
641 If(dmi_req & ~dmi_wen,
642 (self.cpu.dmi_addr.eq(dmi_addr), # DMI Addr
643 self.cpu.dmi_req.eq(1), # DMI request
644 self.cpu.dmi_wr.eq(0), # DMI read
645 If(self.cpu.dmi_ack,
646 # acknowledge received: capture data.
647 (NextState("IDLE"),
648 NextValue(dbg_addr, dmi_addr),
649 NextValue(dbg_dout, self.cpu.dmi_dout),
650 NextValue(dbg_msg, 1),
651 ),
652 ),
653 ),
654 )
655 )
656
657 # DMI response received: reset the dmi request and check if
658 # in "monitor" mode
659 dmifsm.act("IDLE",
660 If(dmi_monitor,
661 NextState("FIRE_MONITOR"), # fire "monitor" on next cycle
662 ).Else(
663 NextState("START"), # back to start on next cycle
664 ),
665 NextValue(dmi_req, 0),
666 NextValue(dmi_addr, 0),
667 NextValue(dmi_din, 0),
668 NextValue(dmi_wen, 0),
669 )
670
671 # "monitor" mode fires off a STAT request
672 dmifsm.act("FIRE_MONITOR",
673 (NextValue(dmi_req, 1),
674 NextValue(dmi_addr, 1), # DMI STAT address
675 NextValue(dmi_din, 0),
676 NextValue(dmi_wen, 0), # read STAT
677 NextState("START"), # back to start on next cycle
678 )
679 )
680
681 self.comb += xer_so.eq((dbg_dout & 1) == 1)
682 self.comb += xer_ca.eq((dbg_dout & 4) == 4)
683 self.comb += xer_ca32.eq((dbg_dout & 8) == 8)
684 self.comb += xer_ov.eq((dbg_dout & 16) == 16)
685 self.comb += xer_ov32.eq((dbg_dout & 32) == 32)
686
687 # debug messages out
688 self.sync += If(dbg_msg,
689 (If(active_dbg & (dbg_addr == 0b10), # PC
690 Display("pc : %016x", dbg_dout),
691 ),
692 If(dbg_addr == 0b10, # PC
693 pc.eq(dbg_dout), # capture PC
694 ),
695 #If(dbg_addr == 0b11, # MSR
696 # Display(" msr: %016x", dbg_dout),
697 #),
698 If(dbg_addr == 0b1000, # CR
699 Display(" cr : %016x", dbg_dout),
700 ),
701 If(dbg_addr == 0b1001, # XER
702 Display(" xer: so %d ca %d 32 %d ov %d 32 %d",
703 xer_so, xer_ca, xer_ca32, xer_ov, xer_ov32),
704 ),
705 If(dbg_addr == 0b101, # GPR
706 Display(" gpr: %016x", dbg_dout),
707 ),
708 # also check if this is a "stat"
709 If(dbg_addr == 1, # requested a STAT
710 #Display(" stat: %x", dbg_dout),
711 If(dbg_dout & 2, # bit 2 of STAT is "stopped" mode
712 dmirunning.eq(1), # continue running
713 dmi_monitor.eq(0), # and stop monitor mode
714 ),
715 ),
716 dbg_msg.eq(0)
717 )
718 )
719
720 # kick off a "stop"
721 self.sync += If(uptime == 0,
722 (dmi_addr.eq(0), # CTRL
723 dmi_din.eq(1<<0), # STOP
724 dmi_req.eq(1),
725 dmi_wen.eq(1),
726 )
727 )
728
729 self.sync += If(uptime == 4,
730 dmirunning.eq(1),
731 )
732
733 self.sync += If(dmirunning,
734 dmicount.eq(dmicount + 1),
735 )
736
737 # loop every 1<<N cycles
738 cyclewid = 9
739
740 # get the PC
741 self.sync += If(dmicount == 4,
742 (dmi_addr.eq(0b10), # NIA
743 dmi_req.eq(1),
744 dmi_wen.eq(0),
745 )
746 )
747
748 # kick off a "step"
749 self.sync += If(dmicount == 8,
750 (dmi_addr.eq(0), # CTRL
751 dmi_din.eq(1<<3), # STEP
752 dmi_req.eq(1),
753 dmi_wen.eq(1),
754 dmirunning.eq(0), # stop counter, need to fire "monitor"
755 dmi_monitor.eq(1), # start "monitor" instead
756 )
757 )
758
759 # limit range of pc for debug reporting
760 #self.comb += active_dbg.eq((0x378c <= pc) & (pc <= 0x38d8))
761 #self.comb += active_dbg.eq((0x0 < pc) & (pc < 0x58))
762 self.comb += active_dbg.eq(1)
763
764
765 # get the MSR
766 self.sync += If(active_dbg & (dmicount == 12),
767 (dmi_addr.eq(0b11), # MSR
768 dmi_req.eq(1),
769 dmi_wen.eq(0),
770 )
771 )
772
773 if cpu == "libresoc":
774 #self.comb += active_dbg_cr.eq((0x10300 <= pc) & (pc <= 0x12600))
775 self.comb += active_dbg_cr.eq(0)
776
777 # get the CR
778 self.sync += If(active_dbg_cr & (dmicount == 16),
779 (dmi_addr.eq(0b1000), # CR
780 dmi_req.eq(1),
781 dmi_wen.eq(0),
782 )
783 )
784
785 #self.comb += active_dbg_xer.eq((0x10300 <= pc) & (pc <= 0x1094c))
786 self.comb += active_dbg_xer.eq(active_dbg_cr)
787
788 # get the CR
789 self.sync += If(active_dbg_xer & (dmicount == 20),
790 (dmi_addr.eq(0b1001), # XER
791 dmi_req.eq(1),
792 dmi_wen.eq(0),
793 )
794 )
795
796 # read all 32 GPRs
797 for i in range(32):
798 self.sync += If(active_dbg & (dmicount == 24+(i*8)),
799 (dmi_addr.eq(0b100), # GSPR addr
800 dmi_din.eq(i), # r1
801 dmi_req.eq(1),
802 dmi_wen.eq(1),
803 )
804 )
805
806 self.sync += If(active_dbg & (dmicount == 28+(i*8)),
807 (dmi_addr.eq(0b101), # GSPR data
808 dmi_req.eq(1),
809 dmi_wen.eq(0),
810 )
811 )
812
813 # monitor bbus read/write
814 self.sync += If(active_dbg & self.cpu.dbus.stb & self.cpu.dbus.ack,
815 Display(" [%06x] dadr: %8x, we %d s %01x w %016x r: %016x",
816 #uptime,
817 0,
818 self.cpu.dbus.adr,
819 self.cpu.dbus.we,
820 self.cpu.dbus.sel,
821 self.cpu.dbus.dat_w,
822 self.cpu.dbus.dat_r
823 )
824 )
825
826 return
827
828 # monitor ibus write
829 self.sync += If(active_dbg & self.cpu.ibus.stb & self.cpu.ibus.ack &
830 self.cpu.ibus.we,
831 Display(" [%06x] iadr: %8x, s %01x w %016x",
832 #uptime,
833 0,
834 self.cpu.ibus.adr,
835 self.cpu.ibus.sel,
836 self.cpu.ibus.dat_w,
837 )
838 )
839 # monitor ibus read
840 self.sync += If(active_dbg & self.cpu.ibus.stb & self.cpu.ibus.ack &
841 ~self.cpu.ibus.we,
842 Display(" [%06x] iadr: %8x, s %01x r %016x",
843 #uptime,
844 0,
845 self.cpu.ibus.adr,
846 self.cpu.ibus.sel,
847 self.cpu.ibus.dat_r
848 )
849 )
850
851 # Build -----------------------------------------------------------------------
852
853 def main():
854 parser = argparse.ArgumentParser(description="LiteX LibreSoC CPU Sim")
855 parser.add_argument("--cpu", default="libresoc",
856 help="CPU to use: libresoc (default) or microwatt")
857 parser.add_argument("--platform", default="sim",
858 help="platform (sim or ls180)")
859 parser.add_argument("--debug", action="store_true",
860 help="Enable debug traces")
861 parser.add_argument("--trace", action="store_true",
862 help="Enable tracing")
863 parser.add_argument("--trace-start", default=0,
864 help="Cycle to start FST tracing")
865 parser.add_argument("--trace-end", default=-1,
866 help="Cycle to end FST tracing")
867 parser.add_argument("--num-srams", default=5,
868 help="number of srams")
869 parser.add_argument("--build", action="store_true", help="Build bitstream")
870 args = parser.parse_args()
871
872 print ("number of SRAMs", args.num_srams)
873
874 if 'ls180' in args.platform:
875 soc = LibreSoCSim(cpu=args.cpu, debug=args.debug,
876 platform=args.platform,
877 dff_srams=args.num_srams)
878 builder = Builder(soc, compile_gateware = True)
879 builder.build(run = True)
880 os.chdir("../")
881 else:
882
883 sim_config = SimConfig(default_clk="sys_clk")
884 sim_config.add_module("serial2console", "serial")
885
886 for i in range(2):
887 soc = LibreSoCSim(cpu=args.cpu, debug=args.debug,
888 platform=args.platform,
889 dff_srams=args.num_srams)
890 builder = Builder(soc, compile_gateware = i!=0)
891 builder.build(sim_config=sim_config,
892 run = i!=0,
893 trace = args.trace,
894 trace_start = int(args.trace_start),
895 trace_end = int(args.trace_end),
896 trace_fst = 0)
897 os.chdir("../")
898
899 if __name__ == "__main__":
900 main()