3 from operator
import itemgetter
7 from litex
.soc
.cores
import identifier
, timer
, uart
8 from litex
.soc
.cores
.cpu
import *
9 from litex
.soc
.interconnect
.csr
import *
10 from litex
.soc
.interconnect
import wishbone
, csr_bus
, wishbone2csr
13 __all__
= ["mem_decoder", "get_mem_data", "SoCCore", "soc_core_args", "soc_core_argdict"]
16 def version(with_time
=True):
20 return datetime
.datetime
.fromtimestamp(
21 time
.time()).strftime("%Y-%m-%d %H:%M:%S")
23 return datetime
.datetime
.fromtimestamp(
24 time
.time()).strftime("%Y-%m-%d")
27 def mem_decoder(address
, start
=26, end
=29):
28 return lambda a
: a
[start
:end
] == ((address
>> (start
+2)) & (2**(end
-start
))-1)
31 def get_mem_data(filename
, endianness
="big", mem_size
=None):
33 with
open(filename
, "rb") as mem_file
:
38 if endianness
== "little":
39 data
.append(struct
.unpack("<I", w
)[0])
41 data
.append(struct
.unpack(">I", w
)[0])
42 data_size
= len(data
)*4
44 if mem_size
is not None:
45 assert data_size
< mem_size
, (
46 "file is too big: {}/{} bytes".format(
51 class ReadOnlyDict(dict):
52 def __readonly__(self
, *args
, **kwargs
):
53 raise RuntimeError("Cannot modify ReadOnlyDict")
54 __setitem__
= __readonly__
55 __delitem__
= __readonly__
57 popitem
= __readonly__
60 setdefault
= __readonly__
64 class SoCController(Module
, AutoCSR
):
67 self
._scratch
= CSRStorage(32, reset
=0x12345678)
68 self
._bus
_errors
= CSRStatus(32)
74 self
.comb
+= self
.reset
.eq(self
._reset
.re
)
77 self
.bus_error
= Signal()
78 bus_errors
= Signal(32)
80 If(bus_errors
!= (2**len(bus_errors
)-1),
82 bus_errors
.eq(bus_errors
+ 1)
85 self
.comb
+= self
._bus
_errors
.status
.eq(bus_errors
)
88 class SoCCore(Module
):
90 "ctrl": 0, # provided by default (optional)
92 "uart_phy": 2, # provided by default (optional)
93 "uart": 3, # provided by default (optional)
94 "identifier_mem": 4, # provided by default (optional)
95 "timer0": 5, # provided by default (optional)
100 soc_interrupt_map
= {
101 "timer0": 1, # LiteX Timer
102 "uart": 2, # LiteX UART (IRQ 2 for UART matches mor1k standard config).
105 "rom": 0x00000000, # (default shadow @0x80000000)
106 "sram": 0x10000000, # (default shadow @0x90000000)
107 "main_ram": 0x40000000, # (default shadow @0xc0000000)
108 "csr": 0x60000000, # (default shadow @0xe0000000)
110 def __init__(self
, platform
, clk_freq
,
111 cpu_type
="lm32", cpu_reset_address
=0x00000000, cpu_variant
=None,
112 integrated_rom_size
=0, integrated_rom_init
=[],
113 integrated_sram_size
=4096,
114 integrated_main_ram_size
=0, integrated_main_ram_init
=[],
115 shadow_base
=0x80000000,
116 csr_data_width
=8, csr_address_width
=14, csr_expose
=False,
117 with_uart
=True, uart_name
="serial", uart_baudrate
=115200, uart_stub
=False,
118 ident
="", ident_version
=False,
119 reserve_nmi_interrupt
=True,
124 self
.platform
= platform
125 self
.clk_freq
= clk_freq
127 self
.cpu_type
= cpu_type
128 self
.cpu_variant
= cpu_variant
129 if integrated_rom_size
:
130 cpu_reset_address
= self
.mem_map
["rom"]
131 self
.cpu_reset_address
= cpu_reset_address
132 self
.config
["CPU_RESET_ADDR"] = self
.cpu_reset_address
134 self
.integrated_rom_size
= integrated_rom_size
135 self
.integrated_rom_initialized
= integrated_rom_init
!= []
136 self
.integrated_sram_size
= integrated_sram_size
137 self
.integrated_main_ram_size
= integrated_main_ram_size
139 self
.with_uart
= with_uart
140 self
.uart_baudrate
= uart_baudrate
142 self
.shadow_base
= shadow_base
144 self
.csr_data_width
= csr_data_width
145 self
.csr_address_width
= csr_address_width
146 self
.csr_expose
= csr_expose
148 self
.csr
= csr_bus
.Interface(csr_data_width
, csr_address_width
)
150 self
.with_ctrl
= with_ctrl
152 self
._memory
_regions
= [] # list of (name, origin, length)
153 self
._csr
_regions
= [] # list of (name, origin, busword, csr_list/Memory)
154 self
._constants
= [] # list of (name, value)
156 self
._wb
_masters
= []
160 self
.submodules
.ctrl
= SoCController()
162 if cpu_type
is not None:
163 if cpu_type
== "lm32":
164 self
.add_cpu(lm32
.LM32(platform
, self
.cpu_reset_address
, self
.cpu_variant
))
165 elif cpu_type
== "or1k":
166 self
.add_cpu(mor1kx
.MOR1KX(platform
, self
.cpu_reset_address
, self
.cpu_variant
))
167 elif cpu_type
== "picorv32":
168 self
.add_cpu(picorv32
.PicoRV32(platform
, self
.cpu_reset_address
, self
.cpu_variant
))
169 elif cpu_type
== "vexriscv":
170 self
.add_cpu(vexriscv
.VexRiscv(platform
, self
.cpu_reset_address
, self
.cpu_variant
))
171 elif cpu_type
== "minerva":
172 self
.add_cpu(minerva
.Minerva(platform
, self
.cpu_reset_address
, self
.cpu_variant
))
174 raise ValueError("Unsupported CPU type: {}".format(cpu_type
))
175 self
.add_wb_master(self
.cpu
.ibus
)
176 self
.add_wb_master(self
.cpu
.dbus
)
178 self
.comb
+= self
.cpu
.reset
.eq(self
.ctrl
.reset
)
179 self
.config
["CPU_TYPE"] = str(cpu_type
).upper()
181 self
.config
["CPU_VARIANT"] = str(cpu_type
).upper()
183 if integrated_rom_size
:
184 self
.submodules
.rom
= wishbone
.SRAM(integrated_rom_size
, read_only
=True, init
=integrated_rom_init
)
185 self
.register_rom(self
.rom
.bus
, integrated_rom_size
)
187 if integrated_sram_size
:
188 self
.submodules
.sram
= wishbone
.SRAM(integrated_sram_size
)
189 self
.register_mem("sram", self
.mem_map
["sram"], self
.sram
.bus
, integrated_sram_size
)
191 # Note: Main Ram can be used when no external SDRAM is available and use SDRAM mapping.
192 if integrated_main_ram_size
:
193 self
.submodules
.main_ram
= wishbone
.SRAM(integrated_main_ram_size
, init
=integrated_main_ram_init
)
194 self
.register_mem("main_ram", self
.mem_map
["main_ram"], self
.main_ram
.bus
, integrated_main_ram_size
)
196 self
.submodules
.wishbone2csr
= wishbone2csr
.WB2CSR(
197 bus_csr
=csr_bus
.Interface(csr_data_width
, csr_address_width
))
198 self
.config
["CSR_DATA_WIDTH"] = csr_data_width
199 self
.add_constant("CSR_DATA_WIDTH", csr_data_width
)
200 self
.register_mem("csr", self
.mem_map
["csr"], self
.wishbone2csr
.wishbone
)
202 if reserve_nmi_interrupt
:
203 self
.soc_interrupt_map
["nmi"] = 0 # Reserve zero for "non-maskable interrupt"
207 self
.submodules
.uart
= uart
.UARTStub()
209 self
.submodules
.uart_phy
= uart
.RS232PHY(platform
.request(uart_name
), clk_freq
, uart_baudrate
)
210 self
.submodules
.uart
= ResetInserter()(uart
.UART(self
.uart_phy
))
213 # del self.soc_interrupt_map["uart"]
217 ident
= ident
+ " " + version()
218 self
.submodules
.identifier
= identifier
.Identifier(ident
)
219 self
.config
["CLOCK_FREQUENCY"] = int(clk_freq
)
220 self
.add_constant("SYSTEM_CLOCK_FREQUENCY", int(clk_freq
))
223 self
.submodules
.timer0
= timer
.Timer()
225 # del self.soc_interrupt_map["timer0"]
227 # Invert the interrupt map.
229 for mod_name
, interrupt
in self
.interrupt_map
.items():
230 assert interrupt
not in interrupt_rmap
, (
231 "Interrupt vector conflict for IRQ %s, user defined %s conflicts with user defined %s" % (
232 interrupt
, mod_name
, interrupt_rmap
[interrupt
]))
234 interrupt_rmap
[interrupt
] = mod_name
236 # Add the base SoC's interrupt map
237 for mod_name
, interrupt
in self
.soc_interrupt_map
.items():
238 assert interrupt
not in interrupt_rmap
or mod_name
== interrupt_rmap
[interrupt
], (
239 "Interrupt vector conflict for IRQ %s, user defined %s conflicts with SoC inbuilt %s" % (
240 interrupt
, mod_name
, interrupt_rmap
[interrupt
]))
242 self
.interrupt_map
[mod_name
] = interrupt
243 interrupt_rmap
[interrupt
] = mod_name
245 # Make sure other functions are not using this value.
246 self
.soc_interrupt_map
= None
248 # Make the interrupt vector read only
249 self
.interrupt_map
= ReadOnlyDict(self
.interrupt_map
)
251 # Save the interrupt reverse map
252 self
.interrupt_rmap
= ReadOnlyDict(interrupt_rmap
)
255 def add_cpu(self
, cpu
):
258 if hasattr(self
, "cpu"):
259 raise NotImplementedError("More than one CPU is not supported")
260 self
.submodules
.cpu
= cpu
262 def add_cpu_or_bridge(self
, cpu_or_bridge
):
263 print("[WARNING] Please update SoCCore's \"add_cpu_or_bridge\" call to \"add_cpu\"")
264 self
.add_cpu(cpu_or_bridge
)
265 self
.cpu_or_bridge
= self
.cpu
267 def initialize_rom(self
, data
):
268 self
.rom
.mem
.init
= data
270 def add_wb_master(self
, wbm
):
273 self
._wb
_masters
.append(wbm
)
275 def add_wb_slave(self
, address_decoder
, interface
):
278 self
._wb
_slaves
.append((address_decoder
, interface
))
280 def add_memory_region(self
, name
, origin
, length
):
281 def in_this_region(addr
):
282 return addr
>= origin
and addr
< origin
+ length
283 for n
, o
, l
in self
._memory
_regions
:
284 if n
== name
or in_this_region(o
) or in_this_region(o
+l
-1):
285 raise ValueError("Memory region conflict between {} and {}".format(n
, name
))
287 self
._memory
_regions
.append((name
, origin
, length
))
289 def register_mem(self
, name
, address
, interface
, size
=None):
290 self
.add_wb_slave(mem_decoder(address
), interface
)
292 self
.add_memory_region(name
, address
, size
)
294 def register_rom(self
, interface
, rom_size
=0xa000):
295 self
.add_wb_slave(mem_decoder(self
.mem_map
["rom"]), interface
)
296 self
.add_memory_region("rom", self
.cpu_reset_address
, rom_size
)
298 def get_memory_regions(self
):
299 return self
._memory
_regions
301 def check_csr_region(self
, name
, origin
):
302 for n
, o
, l
, obj
in self
._csr
_regions
:
303 if n
== name
or o
== origin
:
304 raise ValueError("CSR region conflict between {} and {}".format(n
, name
))
306 def add_csr_region(self
, name
, origin
, busword
, obj
):
307 self
.check_csr_region(name
, origin
)
308 self
._csr
_regions
.append((name
, origin
, busword
, obj
))
310 def get_csr_regions(self
):
311 return self
._csr
_regions
313 def add_constant(self
, name
, value
=None):
314 self
._constants
.append((name
, value
))
316 def get_constants(self
):
318 for interrupt
, name
in sorted(self
.interrupt_rmap
.items()):
319 r
.append((name
.upper() + "_INTERRUPT", interrupt
))
323 def get_csr_dev_address(self
, name
, memory
):
324 if memory
is not None:
325 name
= name
+ "_" + memory
.name_override
327 return self
.csr_map
[name
]
328 except KeyError as e
:
329 msg
= "Undefined \"{}\" CSR.\n".format(name
)
330 msg
+= "Avalaible CSRs in {} ({}):\n".format(
331 self
.__class
__.__name
__, inspect
.getfile(self
.__class
__))
332 for k
in sorted(self
.csr_map
.keys()):
333 msg
+= "- {}\n".format(k
)
334 raise RuntimeError(msg
)
338 def do_finalize(self
):
339 registered_mems
= {regions
[0] for regions
in self
._memory
_regions
}
340 if self
.cpu_type
is not None:
341 for mem
in "rom", "sram":
342 if mem
not in registered_mems
:
343 raise FinalizeError("CPU needs a {} to be registered with SoC.register_mem()".format(mem
))
345 if len(self
._wb
_masters
):
347 self
.submodules
.wishbonecon
= wishbone
.InterconnectShared(self
._wb
_masters
,
348 self
._wb
_slaves
, register
=True)
350 self
.comb
+= self
.ctrl
.bus_error
.eq(self
.wishbonecon
.timeout
.error
)
353 self
.submodules
.csrbankarray
= csr_bus
.CSRBankArray(self
,
354 self
.get_csr_dev_address
,
355 data_width
=self
.csr_data_width
, address_width
=self
.csr_address_width
)
357 self
.submodules
.csrcon
= csr_bus
.InterconnectShared(
358 [self
.csr
, self
.wishbone2csr
.csr
], self
.csrbankarray
.get_buses())
360 self
.submodules
.csrcon
= csr_bus
.Interconnect(
361 self
.wishbone2csr
.csr
, self
.csrbankarray
.get_buses())
362 for name
, csrs
, mapaddr
, rmap
in self
.csrbankarray
.banks
:
363 self
.add_csr_region(name
, (self
.mem_map
["csr"] + 0x800*mapaddr
) | self
.shadow_base
, self
.csr_data_width
, csrs
)
364 for name
, memory
, mapaddr
, mmap
in self
.csrbankarray
.srams
:
365 self
.add_csr_region(name
+ "_" + memory
.name_override
, (self
.mem_map
["csr"] + 0x800*mapaddr
) | self
.shadow_base
, self
.csr_data_width
, memory
)
366 for name
, constant
in self
.csrbankarray
.constants
:
367 self
._constants
.append(((name
+ "_" + constant
.name
).upper(), constant
.value
.value
))
368 for name
, value
in sorted(self
.config
.items(), key
=itemgetter(0)):
369 self
._constants
.append(("CONFIG_" + name
.upper(), value
))
372 if hasattr(self
.cpu
, "interrupt"):
373 for interrupt
, mod_name
in sorted(self
.interrupt_rmap
.items()):
374 if mod_name
== "nmi":
376 if hasattr(self
, mod_name
):
377 mod_impl
= getattr(self
, mod_name
)
378 assert hasattr(mod_impl
, 'ev'), "Submodule %s does not have EventManager (xx.ev) module" % mod_name
379 self
.comb
+= self
.cpu
.interrupt
[interrupt
].eq(mod_impl
.ev
.irq
)
381 def build(self
, *args
, **kwargs
):
382 return self
.platform
.build(self
, *args
, **kwargs
)
385 def soc_core_args(parser
):
386 parser
.add_argument("--cpu-type", default
=None,
387 help="select CPU: lm32, or1k, picorv32, vexriscv, minerva")
388 parser
.add_argument("--cpu-variant", default
=None,
389 help="select CPU variant")
390 parser
.add_argument("--integrated-rom-size", default
=None, type=int,
391 help="size/enable the integrated (BIOS) ROM")
392 parser
.add_argument("--integrated-main-ram-size", default
=None, type=int,
393 help="size/enable the integrated main RAM")
394 parser
.add_argument("--uart-stub", default
=False, type=bool,
395 help="enable uart stub")
398 def soc_core_argdict(args
):
403 "integrated_rom_size",
404 "integrated_main_ram_size",
406 arg
= getattr(args
, a
)