Merge pull request #113 from stffrdhrn/litex-trivial
[litex.git] / litex / soc / integration / soc_core.py
1 import struct
2 import inspect
3 from operator import itemgetter
4
5 from migen import *
6
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
11
12
13 __all__ = ["mem_decoder", "get_mem_data", "SoCCore", "soc_core_args", "soc_core_argdict"]
14
15
16 def version(with_time=True):
17 import datetime
18 import time
19 if with_time:
20 return datetime.datetime.fromtimestamp(
21 time.time()).strftime("%Y-%m-%d %H:%M:%S")
22 else:
23 return datetime.datetime.fromtimestamp(
24 time.time()).strftime("%Y-%m-%d")
25
26
27 def mem_decoder(address, start=26, end=29):
28 return lambda a: a[start:end] == ((address >> (start+2)) & (2**(end-start))-1)
29
30
31 def get_mem_data(filename, endianness="big", mem_size=None):
32 data = []
33 with open(filename, "rb") as mem_file:
34 while True:
35 w = mem_file.read(4)
36 if not w:
37 break
38 if endianness == "little":
39 data.append(struct.unpack("<I", w)[0])
40 else:
41 data.append(struct.unpack(">I", w)[0])
42 data_size = len(data)*4
43 assert data_size > 0
44 if mem_size is not None:
45 assert data_size < mem_size, (
46 "file is too big: {}/{} bytes".format(
47 data_size, mem_size))
48 return data
49
50
51 class ReadOnlyDict(dict):
52 def __readonly__(self, *args, **kwargs):
53 raise RuntimeError("Cannot modify ReadOnlyDict")
54 __setitem__ = __readonly__
55 __delitem__ = __readonly__
56 pop = __readonly__
57 popitem = __readonly__
58 clear = __readonly__
59 update = __readonly__
60 setdefault = __readonly__
61 del __readonly__
62
63
64 class SoCController(Module, AutoCSR):
65 def __init__(self):
66 self._reset = CSR()
67 self._scratch = CSRStorage(32, reset=0x12345678)
68 self._bus_errors = CSRStatus(32)
69
70 # # #
71
72 # reset
73 self.reset = Signal()
74 self.comb += self.reset.eq(self._reset.re)
75
76 # bus errors
77 self.bus_error = Signal()
78 bus_errors = Signal(32)
79 self.sync += \
80 If(bus_errors != (2**len(bus_errors)-1),
81 If(self.bus_error,
82 bus_errors.eq(bus_errors + 1)
83 )
84 )
85 self.comb += self._bus_errors.status.eq(bus_errors)
86
87
88 class SoCCore(Module):
89 csr_map = {
90 "ctrl": 0, # provided by default (optional)
91 "crg": 1, # user
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)
96 "buttons": 6, # user
97 "leds": 7, # user
98 }
99 interrupt_map = {}
100 soc_interrupt_map = {
101 "timer0": 1, # LiteX Timer
102 "uart": 2, # LiteX UART (IRQ 2 for UART matches mor1k standard config).
103 }
104 mem_map = {
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)
109 }
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,
120 with_timer=True,
121 with_ctrl=True):
122 self.config = dict()
123
124 self.platform = platform
125 self.clk_freq = clk_freq
126
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
133
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
138
139 self.with_uart = with_uart
140 self.uart_baudrate = uart_baudrate
141
142 self.shadow_base = shadow_base
143
144 self.csr_data_width = csr_data_width
145 self.csr_address_width = csr_address_width
146 self.csr_expose = csr_expose
147 if csr_expose:
148 self.csr = csr_bus.Interface(csr_data_width, csr_address_width)
149
150 self.with_ctrl = with_ctrl
151
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)
155
156 self._wb_masters = []
157 self._wb_slaves = []
158
159 if with_ctrl:
160 self.submodules.ctrl = SoCController()
161
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))
173 else:
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)
177 if with_ctrl:
178 self.comb += self.cpu.reset.eq(self.ctrl.reset)
179 self.config["CPU_TYPE"] = str(cpu_type).upper()
180 if self.cpu_variant:
181 self.config["CPU_VARIANT"] = str(cpu_type).upper()
182
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)
186
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)
190
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)
195
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)
201
202 if reserve_nmi_interrupt:
203 self.soc_interrupt_map["nmi"] = 0 # Reserve zero for "non-maskable interrupt"
204
205 if with_uart:
206 if uart_stub:
207 self.submodules.uart = uart.UARTStub()
208 else:
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))
211
212 #else:
213 # del self.soc_interrupt_map["uart"]
214
215 if ident:
216 if ident_version:
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))
221
222 if with_timer:
223 self.submodules.timer0 = timer.Timer()
224 #else:
225 # del self.soc_interrupt_map["timer0"]
226
227 # Invert the interrupt map.
228 interrupt_rmap = {}
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]))
233
234 interrupt_rmap[interrupt] = mod_name
235
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]))
241
242 self.interrupt_map[mod_name] = interrupt
243 interrupt_rmap[interrupt] = mod_name
244
245 # Make sure other functions are not using this value.
246 self.soc_interrupt_map = None
247
248 # Make the interrupt vector read only
249 self.interrupt_map = ReadOnlyDict(self.interrupt_map)
250
251 # Save the interrupt reverse map
252 self.interrupt_rmap = ReadOnlyDict(interrupt_rmap)
253
254
255 def add_cpu(self, cpu):
256 if self.finalized:
257 raise FinalizeError
258 if hasattr(self, "cpu"):
259 raise NotImplementedError("More than one CPU is not supported")
260 self.submodules.cpu = cpu
261
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
266
267 def initialize_rom(self, data):
268 self.rom.mem.init = data
269
270 def add_wb_master(self, wbm):
271 if self.finalized:
272 raise FinalizeError
273 self._wb_masters.append(wbm)
274
275 def add_wb_slave(self, address_decoder, interface):
276 if self.finalized:
277 raise FinalizeError
278 self._wb_slaves.append((address_decoder, interface))
279
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))
286
287 self._memory_regions.append((name, origin, length))
288
289 def register_mem(self, name, address, interface, size=None):
290 self.add_wb_slave(mem_decoder(address), interface)
291 if size is not None:
292 self.add_memory_region(name, address, size)
293
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)
297
298 def get_memory_regions(self):
299 return self._memory_regions
300
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))
305
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))
309
310 def get_csr_regions(self):
311 return self._csr_regions
312
313 def add_constant(self, name, value=None):
314 self._constants.append((name, value))
315
316 def get_constants(self):
317 r = []
318 for interrupt, name in sorted(self.interrupt_rmap.items()):
319 r.append((name.upper() + "_INTERRUPT", interrupt))
320 r += self._constants
321 return r
322
323 def get_csr_dev_address(self, name, memory):
324 if memory is not None:
325 name = name + "_" + memory.name_override
326 try:
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)
335 except ValueError:
336 return None
337
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))
344
345 if len(self._wb_masters):
346 # Wishbone
347 self.submodules.wishbonecon = wishbone.InterconnectShared(self._wb_masters,
348 self._wb_slaves, register=True)
349 if self.with_ctrl:
350 self.comb += self.ctrl.bus_error.eq(self.wishbonecon.timeout.error)
351
352 # CSR
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)
356 if self.csr_expose:
357 self.submodules.csrcon = csr_bus.InterconnectShared(
358 [self.csr, self.wishbone2csr.csr], self.csrbankarray.get_buses())
359 else:
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))
370
371 # Interrupts
372 if hasattr(self.cpu, "interrupt"):
373 for interrupt, mod_name in sorted(self.interrupt_rmap.items()):
374 if mod_name == "nmi":
375 continue
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)
380
381 def build(self, *args, **kwargs):
382 return self.platform.build(self, *args, **kwargs)
383
384
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")
396
397
398 def soc_core_argdict(args):
399 r = dict()
400 for a in [
401 "cpu_type",
402 "cpu_variant",
403 "integrated_rom_size",
404 "integrated_main_ram_size",
405 "uart_stub"]:
406 arg = getattr(args, a)
407 if arg is not None:
408 r[a] = arg
409 return r