This repository was archived by the owner on Oct 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhypernova.py
More file actions
executable file
·341 lines (285 loc) · 13.2 KB
/
hypernova.py
File metadata and controls
executable file
·341 lines (285 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env python3
import os, argparse, json, math
from litex_boards.platforms import colorlight_5a_75e, redpitaya
from litex.gen import *
from litex.build.generic_platform import *
from litex.soc.integration.soc import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex.soc.interconnect import wishbone
from litex.soc.interconnect.csr import *
from litex.soc.cores.clock import *
from litex.soc.cores.led import LedChaser
from liteeth.phy.ecp5rgmii import LiteEthPHYRGMII
from litescope import LiteScopeAnalyzer
from litespi.modules import W25Q32JV as SpiFlashModule
from litespi.opcodes import SpiNorFlashOpCodes as Codes
from migen.fhdl.bitcontainer import bits_for
from stepgen import Stepgen
class Timebase(Module, AutoCSR, AutoDoc):
def __init__(self):
self.counter = counter = Signal(64)
self._count = CSRStatus(64, description="Current clock value")
self.sync += counter.eq(counter + 1)
self.comb += [
self._count.status.eq(counter),
]
class StatusSignaller(Module, AutoCSR):
def __init__(self, freq):
count_reset = math.floor(freq / 1000.0)
count = Signal(max=count_reset)
advance = Signal()
self.comb += advance.eq(count == 0)
self.sync += If(advance, count.eq(count_reset)).Else(count.eq(count - 1))
self.time_high = CSRStorage(16, reset=10000)
self.time_low = CSRStorage(16, reset=10000)
self.count = CSRStorage(8, reset=1)
self.between_delay = CSRStorage(16, reset=0)
reset = Signal()
self.comb += reset.eq(self.time_high.re | self.time_low.re | self.count.re | self.between_delay.re)
fsm = FSM(reset_state="IDLE")
self.submodules += fsm
self.output = Signal()
counter = Signal(16)
rounds = Signal(8)
fsm.act("IDLE",
self.output.eq(0),
If(self.count.storage != 0, [
NextValue(count, count_reset),
NextValue(rounds, self.count.storage),
NextValue(counter, self.time_high.storage),
NextState("HIGH")
]),
)
fsm.act("HIGH",
self.output.eq(1),
If(advance,
If(counter == 0, [NextValue(counter, self.time_low.storage), NextState("LOW")])
.Else(NextValue(counter, counter-1))
),
If(reset, NextState("IDLE")),
)
fsm.act("LOW",
self.output.eq(0),
If(advance,
If(counter == 0, [
If(rounds == 1, [
NextValue(counter, self.between_delay.storage),
NextState("SPACE")
]).Else([
NextValue(rounds, rounds - 1),
NextValue(counter, self.time_high.storage),
NextState("HIGH")
])
])
.Else(NextValue(counter, counter-1))
),
If(reset, NextState("IDLE")),
)
fsm.act("SPACE",
self.output.eq(0),
If(advance,
If(counter == 0, [
NextValue(counter, self.time_high.storage),
NextValue(rounds, self.count.storage),
NextState("HIGH")
])
.Else(NextValue(counter, counter-1))
),
If(reset, NextState("IDLE")),
)
class BaseSoC(SoCMini):
def __init__(self, platform, sys_clk_freq, num_stepgens):
SoCMini.__init__(
self,
platform,
ident="Annex Engineering Hypernova",
clk_freq=sys_clk_freq,
cpu_type="vexriscv",
cpu_variant="full",
with_uart=True,
uart_name="crossover",
)
self.timebase = Timebase()
self.stepgen = Stepgen(num_outputs=num_stepgens, counter=self.timebase.counter[0:32])
class RedPitayaCRG(LiteXModule):
def __init__(self, platform, sys_clk_freq):
self.rst = Signal()
self.cd_sys = ClockDomain()
self.pll = pll = S7PLL(speedgrade=-1)
self.comb += pll.reset.eq(self.rst)
pll.register_clkin(platform.request(platform.default_clk_name), platform.default_clk_freq)
pll.create_clkout(self.cd_sys, sys_clk_freq)
platform.add_false_path_constraints(self.cd_sys.clk, pll.clkin)
class RedPitaya(BaseSoC):
def __init__(self, platform):
sys_clk_freq = 120.0e6
platform.add_extension([
("stepper", 0, Subsignal("step", Pins("E1:2")), Subsignal("dir", Pins("E1:3")), IOStandard("LVCMOS33")),
("stepper", 1, Subsignal("step", Pins("E1:4")), Subsignal("dir", Pins("E1:5")), IOStandard("LVCMOS33")),
("stepper", 2, Subsignal("step", Pins("E1:6")), Subsignal("dir", Pins("E1:7")), IOStandard("LVCMOS33")),
("stepper", 3, Subsignal("step", Pins("E1:8")), Subsignal("dir", Pins("E1:9")), IOStandard("LVCMOS33")),
])
BaseSoC.__init__(self, platform, sys_clk_freq, 4)
self.crg = RedPitayaCRG(platform, sys_clk_freq)
self.add_jtagbone()
# Memories
self.add_rom("rom", 0x00000000, 0x20000)
self.add_ram("sram", 0x01000000, 0x4000)
for idx in range(self.stepgen.num_outputs):
pads = self.platform.request("stepper", idx)
self.comb += [
pads.step.eq(self.stepgen.outputs_step[idx]),
pads.dir.eq(self.stepgen.outputs_dir[idx]),
]
class HypernovaCRG(LiteXModule):
def __init__(self, platform, sys_clk_freq):
self.rst = Signal()
self.cd_sys = ClockDomain()
# Use 25 MHz crystal oscillator
clk = platform.request("clk25")
clk_freq = 25e6
rst_n = 1
self.pll = pll = ECP5PLL()
self.comb += pll.reset.eq(~rst_n | self.rst)
pll.register_clkin(clk, clk_freq)
pll.create_clkout(self.cd_sys, sys_clk_freq)
class Hypernova(BaseSoC):
def __init__(self, platform):
sys_clk_freq = 62.5e6
platform.add_extension([
("stepper", 0, Subsignal("step", Pins("j1:0 j1:1")), Subsignal("dir", Pins("j1:4 j1:5")), IOStandard("LVCMOS33"), Misc("SLEWRATE=FAST")),
("stepper", 1, Subsignal("step", Pins("j2:0 j2:1")), Subsignal("dir", Pins("j2:4 j2:5")), IOStandard("LVCMOS33"), Misc("SLEWRATE=FAST")),
("stepper", 2, Subsignal("step", Pins("j3:0 j3:1")), Subsignal("dir", Pins("j3:4 j3:5")), IOStandard("LVCMOS33"), Misc("SLEWRATE=FAST")),
("stepper", 3, Subsignal("step", Pins("j4:0 j4:1")), Subsignal("dir", Pins("j4:4 j4:5")), IOStandard("LVCMOS33"), Misc("SLEWRATE=FAST")),
])
BaseSoC.__init__(self, platform, sys_clk_freq, 4)
self.crg = HypernovaCRG(platform, sys_clk_freq)
self.add_jtagbone()
# Memories
self.add_rom("rom", 0x00000000, 0x20000)
self.add_ram("sram", 0x01000000, 0x6000)
self.add_spi_flash(mode='1x', module=SpiFlashModule(Codes.READ_1_1_1))
# Peripherals
self.ethphy = LiteEthPHYRGMII(
clock_pads = self.platform.request("eth_clocks", 0),
pads = self.platform.request("eth", 0),
with_hw_init_reset=False, # Make sure we don't reset this thing, will kill our clock
tx_delay = 0)
self.add_ethernet(phy=self.ethphy, data_width=32, nrxslots=8, ntxslots=2)
for idx in range(self.stepgen.num_outputs):
pads = self.platform.request("stepper", idx)
self.comb += [
pads.step[0].eq(self.stepgen.outputs_step[idx]),
pads.step[1].eq(~self.stepgen.outputs_step[idx]),
pads.dir[0].eq(self.stepgen.outputs_dir[idx]),
pads.dir[1].eq(~self.stepgen.outputs_dir[idx]),
]
self.signaller = StatusSignaller(sys_clk_freq)
led = self.platform.request("user_led_n", 0)
self.comb += led[0].eq(~self.signaller.output)
# signals = [
# *self.stepgen.outputs[0]._debug,
# ]
# self.submodules.analyzer = LiteScopeAnalyzer(signals, depth=512, clock_domain="sys", samplerate=sys_clk_freq, csr_csv="build/analyzer.csv")
class SoftwareBuilder:
def __init__(self, soc):
self.topdir = os.path.dirname(os.path.realpath(__file__))
self.soc = soc
def _map_constant_to_rust(self, key, value):
try:
intval = int(value)
bits = bits_for(intval)
return ("usize", value)
except ValueError:
pass
return ("&str", '"%s"' % (value.replace('"', '\\"')))
def build(self):
# Build Rust PAC
svd_path = os.path.join(self.topdir, "sw", "pac")
cmd = 'cd "{svd_path}" && svd2rust --target riscv -i "{csr_path}"'.format(
svd_path=svd_path,
csr_path=os.path.join(self.topdir, "build", "csr.svd"))
if os.system(cmd) != 0:
raise OSError('svd2rust failed')
# Constants are an svd vendor extension, so we need to manually add those in
constants = []
for (key, value) in self.soc.constants.items():
if value == None:
continue
(type, value) = self._map_constant_to_rust(key, value)
doc = ""
constants.append("#[doc = r\"{doc}\"]\npub const {key}: {type} = {value};".format(
doc=doc.replace('"', '\\"'), key=key, type=type, value=value))
if constants:
with open(os.path.join(svd_path, "lib.rs"), "a") as f:
f.write("\n#[doc = r\"SOC Constants\"]\npub mod constants {\n" + "\n".join(constants) + "\n}\n")
# The SVD points to the CSR segments, not the memory segments. We need both, so create them here.
memories = []
for (name, region) in self.soc.mem_regions.items():
memories.append(f"#[doc = r\"Base address for {name} memory region\"]")
memories.append(f"pub const {name.upper()}_BASE: *const u8 = 0x{region.origin:08x}u32 as _;")
memories.append(f"#[doc = r\"Size of {name} memory region\"]")
memories.append(f"pub const {name.upper()}_SIZE: usize = 0x{region.length:08x}usize;")
if memories:
with open(os.path.join(svd_path, "lib.rs"), "a") as f:
f.write("\n#[doc = r\"Memory regions\"]\npub mod memory_regions {\n" + "\n".join(memories) + "\n}\n")
# Format the PAC and split to files
cmd = 'cd "{svd_path}" && rm -rf "{svd_path}/src/" && form -i lib.rs -o src/ && rm lib.rs && cargo fmt'.format(
svd_path=svd_path)
if os.system(cmd) != 0:
raise OSError('pac format failed')
# Build firmware
fw_path = os.path.join(self.topdir, "sw", "fw")
cmd = 'cd {fw_path} && cargo build --release'.format(fw_path=fw_path)
if os.system(cmd) != 0:
raise OSError('Firmware compilation failed')
cmd = 'riscv64-unknown-elf-objcopy -O binary "{fw_path}/../target/riscv32i-unknown-none-elf/release/sw" "{topdir}/build/sw.bin"'.format(
fw_path=fw_path, topdir=self.topdir)
if os.system(cmd) != 0:
raise OSError('objcopy failed')
def load(self):
bios_file = os.path.join(self.topdir, "build", "sw.bin")
bios_data = soc_core.get_mem_data(bios_file,
data_width = self.soc.bus.data_width,
endianness = self.soc.cpu.endianness,
)
# Initialize SoC with with BIOS data.
self.soc.initialize_rom(bios_data)
def main():
platforms = {
'colorlight_5a_75e': [Hypernova, colorlight_5a_75e.Platform(revision="6.0")],
'redpitaya': [RedPitaya, redpitaya.Platform(board="redpitaya14")],
}
parser = argparse.ArgumentParser(description="Hypernova SoC Builder")
parser.add_argument("--build-software", action="store_true", help="Build software")
parser.add_argument("--build-gateware", action="store_true", help="Build gateware")
parser.add_argument("--build", action="store_true", help="Build bitstream")
parser.add_argument("--platform", required=True, choices=list(platforms.keys()))
args = parser.parse_args()
[soc_class, platform] = platforms[args.platform]
soc = soc_class(platform)
builder = Builder(soc,
output_dir="build",
csr_svd="build/csr.svd",
csr_csv="build/csr.csv",
generate_doc=True,
compile_software=False)
swbuilder = SoftwareBuilder(soc)
# Build the CSR and basic stuff
soc.finalize()
builder._generate_includes(with_bios=False)
builder._generate_csr_map()
builder._generate_includes()
regions_contents = export.get_linker_regions(soc.mem_regions)
write_to_file(os.path.join(builder.generated_dir, "regions.ld"), regions_contents)
if args.build or args.build_software:
swbuilder.build()
if args.build or args.build_gateware:
swbuilder.load()
builder.build(build_name="hypernova", run=True)
if not args.build and not args.build_gateware:
# Make sure Sphinx builds the docs
builder.build(build_name="hypernova", run=False)
if __name__ == "__main__":
main()