soc/integration/soc_core: revert default mem_map (do specific RocketChip remapping...
[litex.git] / litex / soc / integration / soc_core.py
index 9ce86c95686c3565e50effc60972610b67ba336e..cbd1fb54825fa69ef673ce409bf0fc7a4da7d6a4 100644 (file)
@@ -164,16 +164,7 @@ class SoCController(Module, AutoCSR):
 
 
 class SoCCore(Module):
-    csr_map = {
-        "ctrl":           0,  # provided by default (optional)
-        "crg":            1,  # user
-        "uart_phy":       2,  # provided by default (optional)
-        "uart":           3,  # provided by default (optional)
-        "identifier_mem": 4,  # provided by default (optional)
-        "timer0":         5,  # provided by default (optional)
-        "buttons":        6,  # user
-        "leds":           7,  # user
-    }
+    csr_map = {}
     interrupt_map = {}
     mem_map = {
         "rom":      0x00000000,  # (default shadow @0x80000000)
@@ -187,7 +178,7 @@ class SoCCore(Module):
                 integrated_sram_size=4096, integrated_sram_init=[],
                 integrated_main_ram_size=0, integrated_main_ram_init=[],
                 shadow_base=0x80000000,
-                csr_data_width=8, csr_address_width=14, csr_expose=False,
+                csr_data_width=8, csr_address_width=14,
                 with_uart=True, uart_name="serial", uart_baudrate=115200, uart_stub=False,
                 ident="", ident_version=False,
                 wishbone_timeout_cycles=1e6,
@@ -198,6 +189,16 @@ class SoCCore(Module):
         self.platform = platform
         self.clk_freq = clk_freq
 
+        self.soc_csr_map = {}
+        self.soc_interrupt_map = {}
+        self.soc_mem_map = self.mem_map
+
+        # FIXME: RocketChip reserves the first 256Mbytes for internal use
+        # remap rom to 0x10000000, sram to 0x20000000
+        if cpu_type == "rocket":
+            self.soc_mem_map["rom"]  = 0x10000000
+            self.soc_mem_map["sram"] = 0x20000000
+
         if cpu_type == "None":
             cpu_type = None
         self.cpu_type = cpu_type
@@ -223,7 +224,7 @@ class SoCCore(Module):
             self.cpu_variant += "+"+ext
 
         if integrated_rom_size:
-            cpu_reset_address = self.mem_map["rom"]
+            cpu_reset_address = self.soc_mem_map["rom"]
         self.cpu_reset_address = cpu_reset_address
         self.config["CPU_RESET_ADDR"] = self.cpu_reset_address
 
@@ -241,9 +242,6 @@ class SoCCore(Module):
 
         self.csr_data_width = csr_data_width
         self.csr_address_width = csr_address_width
-        self.csr_expose = csr_expose
-        if csr_expose:
-            self.csr = csr_bus.Interface(csr_data_width, csr_address_width)
 
         self.with_ctrl = with_ctrl
 
@@ -253,11 +251,15 @@ class SoCCore(Module):
 
         self._wb_masters = []
         self._wb_slaves = []
+        self._csr_masters = []
 
-        self.soc_interrupt_map = {}
+        # add user csrs
+        for _name, _id in self.csr_map.items():
+            self.add_csr(_name, _id)
 
         if with_ctrl:
             self.submodules.ctrl = SoCController()
+            self.add_csr("ctrl", allow_user_defined=True)
 
         if cpu_type is not None:
             if cpu_type == "lm32":
@@ -272,19 +274,22 @@ class SoCCore(Module):
                 self.add_cpu(vexriscv.VexRiscv(platform, self.cpu_reset_address, self.cpu_variant))
             elif cpu_type == "minerva":
                 self.add_cpu(minerva.Minerva(platform, self.cpu_reset_address, self.cpu_variant))
+            elif cpu_type == "rocket":
+                self.add_cpu(rocket.RocketRV64(platform, self.cpu_reset_address, self.cpu_variant))
             else:
                 raise ValueError("Unsupported CPU type: {}".format(cpu_type))
+            self.add_csr("cpu", allow_user_defined=True)
             self.add_wb_master(self.cpu.ibus)
             self.add_wb_master(self.cpu.dbus)
             if with_ctrl:
                 self.comb += self.cpu.reset.eq(self.ctrl.reset)
             # add cpu reserved interrupts
-            for name, _id in self.cpu.reserved_interrupts.items():
-                self.add_interrupt(name, _id)
+            for _name, _id in self.cpu.reserved_interrupts.items():
+                self.add_interrupt(_name, _id)
 
         # add user interrupts
-        for name, _id in self.interrupt_map.items():
-            self.add_interrupt(name, _id)
+        for _name, _id in self.interrupt_map.items():
+            self.add_interrupt(_name, _id)
 
         self.config["CPU_TYPE"] = str(cpu_type).upper()
         if self.cpu_variant:
@@ -296,18 +301,19 @@ class SoCCore(Module):
 
         if integrated_sram_size:
             self.submodules.sram = wishbone.SRAM(integrated_sram_size, init=integrated_sram_init)
-            self.register_mem("sram", self.mem_map["sram"], self.sram.bus, integrated_sram_size)
+            self.register_mem("sram", self.soc_mem_map["sram"], self.sram.bus, integrated_sram_size)
 
         # Note: Main Ram can be used when no external SDRAM is available and use SDRAM mapping.
         if integrated_main_ram_size:
             self.submodules.main_ram = wishbone.SRAM(integrated_main_ram_size, init=integrated_main_ram_init)
-            self.register_mem("main_ram", self.mem_map["main_ram"], self.main_ram.bus, integrated_main_ram_size)
+            self.register_mem("main_ram", self.soc_mem_map["main_ram"], self.main_ram.bus, integrated_main_ram_size)
 
         self.submodules.wishbone2csr = wishbone2csr.WB2CSR(
             bus_csr=csr_bus.Interface(csr_data_width, csr_address_width))
+        self.add_csr_master(self.wishbone2csr.csr)
         self.config["CSR_DATA_WIDTH"] = csr_data_width
         self.add_constant("CSR_DATA_WIDTH", csr_data_width)
-        self.register_mem("csr", self.mem_map["csr"], self.wishbone2csr.wishbone)
+        self.register_mem("csr", self.soc_mem_map["csr"], self.wishbone2csr.wishbone)
 
         if with_uart:
             if uart_stub:
@@ -315,18 +321,22 @@ class SoCCore(Module):
             else:
                 self.submodules.uart_phy = uart.RS232PHY(platform.request(uart_name), clk_freq, uart_baudrate)
                 self.submodules.uart = ResetInserter()(uart.UART(self.uart_phy))
-            self.add_interrupt("uart")
+            self.add_csr("uart_phy", allow_user_defined=True)
+            self.add_csr("uart", allow_user_defined=True)
+            self.add_interrupt("uart", allow_user_defined=True)
 
         if ident:
             if ident_version:
                 ident = ident + " " + version()
             self.submodules.identifier = identifier.Identifier(ident)
+            self.add_csr("identifier_mem", allow_user_defined=True)
         self.config["CLOCK_FREQUENCY"] = int(clk_freq)
         self.add_constant("SYSTEM_CLOCK_FREQUENCY", int(clk_freq))
 
         if with_timer:
             self.submodules.timer0 = timer.Timer()
-            self.add_interrupt("timer0")
+            self.add_csr("timer0", allow_user_defined=True)
+            self.add_interrupt("timer0", allow_user_defined=True)
 
     def add_cpu(self, cpu):
         if self.finalized:
@@ -340,14 +350,16 @@ class SoCCore(Module):
         self.add_cpu(cpu_or_bridge)
         self.cpu_or_bridge = self.cpu
 
-    def add_interrupt(self, interrupt_name, interrupt_id=None):
+    def add_interrupt(self, interrupt_name, interrupt_id=None, allow_user_defined=False):
         # check that interrupt_name is not already used
         if interrupt_name in self.soc_interrupt_map.keys():
-            print(self.soc_interrupt_map)
-            raise ValueError("Interrupt conflit, {} name already used".format(interrupt_name))
+            if allow_user_defined:
+                return
+            else:
+                raise ValueError("Interrupt conflit, {} name already used".format(interrupt_name))
 
         # check that interrupt_id is in range
-        if interrupt_id is not None and interrupt_id > 31:
+        if interrupt_id is not None and interrupt_id >= 32:
             raise ValueError("{} Interrupt ID out of range ({}, max=31)".format(
                 interrupt_namename, interrupt_id))
 
@@ -366,6 +378,34 @@ class SoCCore(Module):
                         interrupt_id, _name))
             self.soc_interrupt_map.update({interrupt_name: interrupt_id})
 
+    def add_csr(self, csr_name, csr_id=None, allow_user_defined=False):
+        # check that csr_name is not already used
+        if csr_name in self.soc_csr_map.keys():
+            if allow_user_defined:
+                return
+            else:
+                raise ValueError("CSR conflit, {} name already used".format(csr_name))
+
+        # check that csr_id is in range
+        if csr_id is not None and csr_id >= 2**self.csr_address_width:
+            raise ValueError("{} CSR ID out of range ({}, max=31)".format(
+                csr_name, csr_id))
+
+        # csr_id not provided: allocate csr to the first available id
+        if csr_id is None:
+            for n in range(2**self.csr_address_width):
+                if n not in self.soc_csr_map.values():
+                    self.soc_csr_map.update({csr_name: n})
+                    return
+            raise ValueError("No more space to allocate {} csr".format(name))
+        # csr_id provided: check that csr_id is not already used and add csr
+        else:
+            for _name, _id in self.soc_csr_map.items():
+                if csr_id == _id:
+                    raise ValueError("CSR conflict, {} already used by {} csr".format(
+                        csr_id, _name))
+            self.soc_csr_map.update({csr_name: csr_id})
+
     def initialize_rom(self, data):
         self.rom.mem.init = data
 
@@ -379,6 +419,12 @@ class SoCCore(Module):
             raise FinalizeError
         self._wb_slaves.append((address_decoder, interface))
 
+    def add_csr_master(self, csrm):
+        # CSR masters are not arbitrated, use this with precaution.
+        if self.finalized:
+            raise FinalizeError
+        self._csr_masters.append(csrm)
+
     def add_memory_region(self, name, origin, length):
         def in_this_region(addr):
             return addr >= origin and addr < origin + length
@@ -394,7 +440,7 @@ class SoCCore(Module):
             self.add_memory_region(name, address, size)
 
     def register_rom(self, interface, rom_size=0xa000):
-        self.add_wb_slave(mem_decoder(self.mem_map["rom"]), interface)
+        self.add_wb_slave(mem_decoder(self.soc_mem_map["rom"]), interface)
         self.add_memory_region("rom", self.cpu_reset_address, rom_size)
 
     def get_memory_regions(self):
@@ -430,12 +476,12 @@ class SoCCore(Module):
         if memory is not None:
             name = name + "_" + memory.name_override
         try:
-            return self.csr_map[name]
+            return self.soc_csr_map[name]
         except KeyError as e:
             msg = "Undefined \"{}\" CSR.\n".format(name)
             msg += "Avalaible CSRs in {} ({}):\n".format(
                 self.__class__.__name__, inspect.getfile(self.__class__))
-            for k in sorted(self.csr_map.keys()):
+            for k in sorted(self.soc_csr_map.keys()):
                 msg += "- {}\n".format(k)
             raise RuntimeError(msg)
         except ValueError:
@@ -448,44 +494,40 @@ class SoCCore(Module):
                 if mem not in registered_mems:
                     raise FinalizeError("CPU needs a {} to be registered with SoC.register_mem()".format(mem))
 
+        # Wishbone
         if len(self._wb_masters):
-            # Wishbone
             self.submodules.wishbonecon = wishbone.InterconnectShared(self._wb_masters,
                 self._wb_slaves, register=True, timeout_cycles=self.wishbone_timeout_cycles)
             if self.with_ctrl and (self.wishbone_timeout_cycles is not None):
                 self.comb += self.ctrl.bus_error.eq(self.wishbonecon.timeout.error)
 
-            # CSR
-            self.submodules.csrbankarray = csr_bus.CSRBankArray(self,
-                self.get_csr_dev_address,
-                data_width=self.csr_data_width, address_width=self.csr_address_width)
-            if self.csr_expose:
-                self.submodules.csrcon = csr_bus.InterconnectShared(
-                    [self.csr, self.wishbone2csr.csr], self.csrbankarray.get_buses())
-            else:
-                self.submodules.csrcon = csr_bus.Interconnect(
-                    self.wishbone2csr.csr, self.csrbankarray.get_buses())
-            for name, csrs, mapaddr, rmap in self.csrbankarray.banks:
-                self.check_csr_range(name, 0x800*mapaddr)
-                self.add_csr_region(name, (self.mem_map["csr"] + 0x800*mapaddr) | self.shadow_base, self.csr_data_width, csrs)
-            for name, memory, mapaddr, mmap in self.csrbankarray.srams:
-                self.check_csr_range(name, 0x800*mapaddr)
-                self.add_csr_region(name + "_" + memory.name_override, (self.mem_map["csr"] + 0x800*mapaddr) | self.shadow_base, self.csr_data_width, memory)
-            for name, constant in self.csrbankarray.constants:
-                self._constants.append(((name + "_" + constant.name).upper(), constant.value.value))
-            for name, value in sorted(self.config.items(), key=itemgetter(0)):
-                self._constants.append(("CONFIG_" + name.upper(), value))
-
-            # Interrupts
-            if hasattr(self, "cpu"):
-                if hasattr(self.cpu, "interrupt"):
-                    for _name, _id in sorted(self.soc_interrupt_map.items()):
-                        if _name in self.cpu.reserved_interrupts.keys():
-                            continue
-                        if hasattr(self, _name):
-                            module = getattr(self, _name)
-                            assert hasattr(module, 'ev'), "Submodule %s does not have EventManager (xx.ev) module" % _name
-                            self.comb += self.cpu.interrupt[_id].eq(module.ev.irq)
+        # CSR
+        self.submodules.csrbankarray = csr_bus.CSRBankArray(self,
+            self.get_csr_dev_address,
+            data_width=self.csr_data_width, address_width=self.csr_address_width)
+        self.submodules.csrcon = csr_bus.InterconnectShared(
+                self._csr_masters, self.csrbankarray.get_buses())
+        for name, csrs, mapaddr, rmap in self.csrbankarray.banks:
+            self.check_csr_range(name, 0x800*mapaddr)
+            self.add_csr_region(name, (self.soc_mem_map["csr"] + 0x800*mapaddr) | self.shadow_base, self.csr_data_width, csrs)
+        for name, memory, mapaddr, mmap in self.csrbankarray.srams:
+            self.check_csr_range(name, 0x800*mapaddr)
+            self.add_csr_region(name + "_" + memory.name_override, (self.soc_mem_map["csr"] + 0x800*mapaddr) | self.shadow_base, self.csr_data_width, memory)
+        for name, constant in self.csrbankarray.constants:
+            self._constants.append(((name + "_" + constant.name).upper(), constant.value.value))
+        for name, value in sorted(self.config.items(), key=itemgetter(0)):
+            self._constants.append(("CONFIG_" + name.upper(), value))
+
+        # Interrupts
+        if hasattr(self, "cpu"):
+            if hasattr(self.cpu, "interrupt"):
+                for _name, _id in sorted(self.soc_interrupt_map.items()):
+                    if _name in self.cpu.reserved_interrupts.keys():
+                        continue
+                    if hasattr(self, _name):
+                        module = getattr(self, _name)
+                        assert hasattr(module, 'ev'), "Submodule %s does not have EventManager (xx.ev) module" % _name
+                        self.comb += self.cpu.interrupt[_id].eq(module.ev.irq)
 
     def build(self, *args, **kwargs):
         return self.platform.build(self, *args, **kwargs)