back.verilog: refactor Yosys script generation. NFCI.
[nmigen.git] / nmigen / vendor / lattice_machxo2.py
1 from abc import abstractproperty
2
3 from ..hdl import *
4 from ..build import *
5
6
7 __all__ = ["LatticeMachXO2Platform"]
8
9
10 class LatticeMachXO2Platform(TemplatedPlatform):
11 """
12 Required tools:
13 * ``pnmainc``
14 * ``ddtcmd``
15
16 The environment is populated by running the script specified in the environment variable
17 ``NMIGEN_ENV_Diamond``, if present.
18
19 Available overrides:
20 * ``script_project``: inserts commands before ``prj_project save`` in Tcl script.
21 * ``script_after_export``: inserts commands after ``prj_run Export`` in Tcl script.
22 * ``add_preferences``: inserts commands at the end of the LPF file.
23 * ``add_constraints``: inserts commands at the end of the XDC file.
24
25 Build products:
26 * ``{{name}}_impl/{{name}}_impl.htm``: consolidated log.
27 * ``{{name}}.jed``: JEDEC fuse file.
28 * ``{{name}}.bit``: binary bitstream.
29 * ``{{name}}.svf``: JTAG programming vector.
30 """
31
32 toolchain = "Diamond"
33
34 device = abstractproperty()
35 package = abstractproperty()
36 speed = abstractproperty()
37 grade = "C" # [C]ommercial, [I]ndustrial
38
39 required_tools = [
40 "yosys",
41 "pnmainc",
42 "ddtcmd"
43 ]
44 file_templates = {
45 **TemplatedPlatform.build_script_templates,
46 "build_{{name}}.sh": r"""
47 # {{autogenerated}}
48 set -e{{verbose("x")}}
49 if [ -z "$BASH" ] ; then exec /bin/bash "$0" "$@"; fi
50 if [ -n "${{platform._toolchain_env_var}}" ]; then
51 bindir=$(dirname "${{platform._toolchain_env_var}}")
52 . "${{platform._toolchain_env_var}}"
53 fi
54 {{emit_commands("sh")}}
55 """,
56 "{{name}}.v": r"""
57 /* {{autogenerated}} */
58 {{emit_verilog()}}
59 """,
60 "{{name}}.debug.v": r"""
61 /* {{autogenerated}} */
62 {{emit_debug_verilog()}}
63 """,
64 "{{name}}.tcl": r"""
65 prj_project new -name {{name}} -impl impl -impl_dir top_impl \
66 -dev {{platform.device}}-{{platform.speed}}{{platform.package}}{{platform.grade}} \
67 -lpf {{name}}.lpf \
68 -synthesis synplify
69 {% for file in platform.iter_extra_files(".v", ".sv", ".vhd", ".vhdl") -%}
70 prj_src add {{file|tcl_escape}}
71 {% endfor %}
72 prj_src add {{name}}.v
73 prj_impl option top {{name}}
74 prj_src add {{name}}.sdc
75 {{get_override("script_project")|default("# (script_project placeholder)")}}
76 prj_project save
77 prj_run Synthesis -impl impl -forceAll
78 prj_run Translate -impl impl -forceAll
79 prj_run Map -impl impl -forceAll
80 prj_run PAR -impl impl -forceAll
81 prj_run Export -impl impl -forceAll -task Bitgen
82 prj_run Export -impl impl -forceAll -task Jedecgen
83 {{get_override("script_after_export")|default("# (script_after_export placeholder)")}}
84 """,
85 "{{name}}.lpf": r"""
86 # {{autogenerated}}
87 BLOCK ASYNCPATHS;
88 BLOCK RESETPATHS;
89 {% for port_name, pin_name, attrs in platform.iter_port_constraints_bits() -%}
90 LOCATE COMP "{{port_name}}" SITE "{{pin_name}}";
91 {% if attrs -%}
92 IOBUF PORT "{{port_name}}"
93 {%- for key, value in attrs.items() %} {{key}}={{value}}{% endfor %};
94 {% endif %}
95 {% endfor %}
96 {{get_override("add_preferences")|default("# (add_preferences placeholder)")}}
97 """,
98 "{{name}}.sdc": r"""
99 {% for net_signal, port_signal, frequency in platform.iter_clock_constraints() -%}
100 {% if port_signal is not none -%}
101 create_clock -name {{port_signal.name|tcl_escape}} -period {{1000000000/frequency}} [get_ports {{port_signal.name|tcl_escape}}]
102 {% else -%}
103 create_clock -name {{net_signal.name|tcl_escape}} -period {{1000000000/frequency}} [get_nets {{net_signal|hierarchy("/")|tcl_escape}}]
104 {% endif %}
105 {% endfor %}
106 {{get_override("add_constraints")|default("# (add_constraints placeholder)")}}
107 """,
108 }
109 command_templates = [
110 # These don't have any usable command-line option overrides.
111 r"""
112 {{invoke_tool("pnmainc")}}
113 {{name}}.tcl
114 """,
115 r"""
116 {{invoke_tool("ddtcmd")}}
117 -oft -bit
118 -if {{name}}_impl/{{name}}_impl.bit -of {{name}}.bit
119 """,
120 r"""
121 {{invoke_tool("ddtcmd")}}
122 -oft -jed
123 -dev {{platform.device}}-{{platform.speed}}{{platform.package}}{{platform.grade}}
124 -if {{name}}_impl/{{name}}_impl.jed -of {{name}}.jed
125 """,
126 r"""
127 {{invoke_tool("ddtcmd")}}
128 -oft -svfsingle -revd -op "FLASH Erase,Program,Verify"
129 -if {{name}}_impl/{{name}}_impl.jed -of {{name}}.svf
130 """,
131 ]
132
133 def create_missing_domain(self, name):
134 # Lattice MachXO2 devices have two global set/reset signals: PUR, which is driven at
135 # startup by the configuration logic and unconditionally resets every storage element,
136 # and GSR, which is driven by user logic and each storage element may be configured as
137 # affected or unaffected by GSR. PUR is purely asynchronous, so even though it is
138 # a low-skew global network, its deassertion may violate a setup/hold constraint with
139 # relation to a user clock. To avoid this, a GSR/SGSR instance should be driven
140 # synchronized to user clock.
141 if name == "sync" and self.default_clk is not None:
142 clk_i = self.request(self.default_clk).i
143 if self.default_rst is not None:
144 rst_i = self.request(self.default_rst).i
145 else:
146 rst_i = Const(0)
147
148 gsr0 = Signal()
149 gsr1 = Signal()
150 m = Module()
151 # There is no end-of-startup signal on MachXO2, but PUR is released after IOB enable,
152 # so a simple reset synchronizer (with PUR as the asynchronous reset) does the job.
153 m.submodules += [
154 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=~rst_i, o_Q=gsr0),
155 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=gsr0, o_Q=gsr1),
156 # Although we already synchronize the reset input to user clock, SGSR has dedicated
157 # clock routing to the center of the FPGA; use that just in case it turns out to be
158 # more reliable. (None of this is documented.)
159 Instance("SGSR", i_CLK=clk_i, i_GSR=gsr1),
160 ]
161 # GSR implicitly connects to every appropriate storage element. As such, the sync
162 # domain is reset-less; domains driven by other clocks would need to have dedicated
163 # reset circuitry or otherwise meet setup/hold constraints on their own.
164 m.domains += ClockDomain("sync", reset_less=True)
165 m.d.comb += ClockSignal("sync").eq(clk_i)
166 return m
167
168 _single_ended_io_types = [
169 "PCI33", "LVTTL33", "LVCMOS33", "LVCMOS25", "LVCMOS18", "LVCMOS15", "LVCMOS12",
170 "LVCMOS25R33", "LVCMOS18R33", "LVCMOS18R25", "LVCMOS15R33", "LVCMOS15R25", "LVCMOS12R33",
171 "LVCMOS12R25", "LVCMOS10R33", "LVCMOS10R25", "SSTL25_I", "SSTL25_II", "SSTL18_I",
172 "SSTL18_II", "HSTL18_I", "HSTL18_II",
173 ]
174 _differential_io_types = [
175 "LVDS25", "LVDS25E", "RSDS25", "RSDS25E", "BLVDS25", "BLVDS25E", "MLVDS25", "MLVDS25E",
176 "LVPECL33", "LVPECL33E", "SSTL25D_I", "SSTL25D_II", "SSTL18D_I", "SSTL18D_II",
177 "HSTL18D_I", "HSTL18D_II", "LVTTL33D", "LVCMOS33D", "LVCMOS25D", "LVCMOS18D", "LVCMOS15D",
178 "LVCMOS12D", "MIPI",
179 ]
180
181 def should_skip_port_component(self, port, attrs, component):
182 # On ECP5, a differential IO is placed by only instantiating an IO buffer primitive at
183 # the PIOA or PIOC location, which is always the non-inverting pin.
184 if attrs.get("IO_TYPE", "LVCMOS25") in self._differential_io_types and component == "n":
185 return True
186 return False
187
188 def _get_xdr_buffer(self, m, pin, *, i_invert=False, o_invert=False):
189 def get_ireg(clk, d, q):
190 for bit in range(len(q)):
191 m.submodules += Instance("IFS1P3DX",
192 i_SCLK=clk,
193 i_SP=Const(1),
194 i_CD=Const(0),
195 i_D=d[bit],
196 o_Q=q[bit]
197 )
198
199 def get_oreg(clk, d, q):
200 for bit in range(len(q)):
201 m.submodules += Instance("OFS1P3DX",
202 i_SCLK=clk,
203 i_SP=Const(1),
204 i_CD=Const(0),
205 i_D=d[bit],
206 o_Q=q[bit]
207 )
208
209 def get_iddr(sclk, d, q0, q1):
210 for bit in range(len(d)):
211 m.submodules += Instance("IDDRXE",
212 i_SCLK=sclk,
213 i_RST=Const(0),
214 i_D=d[bit],
215 o_Q0=q0[bit], o_Q1=q1[bit]
216 )
217
218 def get_oddr(sclk, d0, d1, q):
219 for bit in range(len(q)):
220 m.submodules += Instance("ODDRXE",
221 i_SCLK=sclk,
222 i_RST=Const(0),
223 i_D0=d0[bit], i_D1=d1[bit],
224 o_Q=q[bit]
225 )
226
227 def get_ineg(z, invert):
228 if invert:
229 a = Signal.like(z, name_suffix="_n")
230 m.d.comb += z.eq(~a)
231 return a
232 else:
233 return z
234
235 def get_oneg(a, invert):
236 if invert:
237 z = Signal.like(a, name_suffix="_n")
238 m.d.comb += z.eq(~a)
239 return z
240 else:
241 return a
242
243 if "i" in pin.dir:
244 if pin.xdr < 2:
245 pin_i = get_ineg(pin.i, i_invert)
246 elif pin.xdr == 2:
247 pin_i0 = get_ineg(pin.i0, i_invert)
248 pin_i1 = get_ineg(pin.i1, i_invert)
249 if "o" in pin.dir:
250 if pin.xdr < 2:
251 pin_o = get_oneg(pin.o, o_invert)
252 elif pin.xdr == 2:
253 pin_o0 = get_oneg(pin.o0, o_invert)
254 pin_o1 = get_oneg(pin.o1, o_invert)
255
256 i = o = t = None
257 if "i" in pin.dir:
258 i = Signal(pin.width, name="{}_xdr_i".format(pin.name))
259 if "o" in pin.dir:
260 o = Signal(pin.width, name="{}_xdr_o".format(pin.name))
261 if pin.dir in ("oe", "io"):
262 t = Signal(1, name="{}_xdr_t".format(pin.name))
263
264 if pin.xdr == 0:
265 if "i" in pin.dir:
266 i = pin_i
267 if "o" in pin.dir:
268 o = pin_o
269 if pin.dir in ("oe", "io"):
270 t = ~pin.oe
271 elif pin.xdr == 1:
272 # Note that currently nextpnr will not pack an FF (*FS1P3DX) into the PIO.
273 if "i" in pin.dir:
274 get_ireg(pin.i_clk, i, pin_i)
275 if "o" in pin.dir:
276 get_oreg(pin.o_clk, pin_o, o)
277 if pin.dir in ("oe", "io"):
278 get_oreg(pin.o_clk, ~pin.oe, t)
279 elif pin.xdr == 2:
280 if "i" in pin.dir:
281 get_iddr(pin.i_clk, i, pin_i0, pin_i1)
282 if "o" in pin.dir:
283 get_oddr(pin.o_clk, pin_o0, pin_o1, o)
284 if pin.dir in ("oe", "io"):
285 # It looks like Diamond will not pack an OREG as a tristate register in a DDR PIO.
286 # It is not clear what is the recommended set of primitives for this task.
287 # Similarly, nextpnr will not pack anything as a tristate register in a DDR PIO.
288 get_oreg(pin.o_clk, ~pin.oe, t)
289 else:
290 assert False
291
292 return (i, o, t)
293
294 def get_input(self, pin, port, attrs, invert):
295 self._check_feature("single-ended input", pin, attrs,
296 valid_xdrs=(0, 1, 2), valid_attrs=True)
297 m = Module()
298 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
299 for bit in range(len(port)):
300 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
301 i_I=port[bit],
302 o_O=i[bit]
303 )
304 return m
305
306 def get_output(self, pin, port, attrs, invert):
307 self._check_feature("single-ended output", pin, attrs,
308 valid_xdrs=(0, 1, 2), valid_attrs=True)
309 m = Module()
310 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
311 for bit in range(len(port)):
312 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
313 i_I=o[bit],
314 o_O=port[bit]
315 )
316 return m
317
318 def get_tristate(self, pin, port, attrs, invert):
319 self._check_feature("single-ended tristate", pin, attrs,
320 valid_xdrs=(0, 1, 2), valid_attrs=True)
321 m = Module()
322 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
323 for bit in range(len(port)):
324 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
325 i_T=t,
326 i_I=o[bit],
327 o_O=port[bit]
328 )
329 return m
330
331 def get_input_output(self, pin, port, attrs, invert):
332 self._check_feature("single-ended input/output", pin, attrs,
333 valid_xdrs=(0, 1, 2), valid_attrs=True)
334 m = Module()
335 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
336 for bit in range(len(port)):
337 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
338 i_T=t,
339 i_I=o[bit],
340 o_O=i[bit],
341 io_B=port[bit]
342 )
343 return m
344
345 def get_diff_input(self, pin, p_port, n_port, attrs, invert):
346 self._check_feature("differential input", pin, attrs,
347 valid_xdrs=(0, 1, 2), valid_attrs=True)
348 m = Module()
349 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
350 for bit in range(len(p_port)):
351 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
352 i_I=p_port[bit],
353 o_O=i[bit]
354 )
355 return m
356
357 def get_diff_output(self, pin, p_port, n_port, attrs, invert):
358 self._check_feature("differential output", pin, attrs,
359 valid_xdrs=(0, 1, 2), valid_attrs=True)
360 m = Module()
361 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
362 for bit in range(len(p_port)):
363 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
364 i_I=o[bit],
365 o_O=p_port[bit],
366 )
367 return m
368
369 def get_diff_tristate(self, pin, p_port, n_port, attrs, invert):
370 self._check_feature("differential tristate", pin, attrs,
371 valid_xdrs=(0, 1, 2), valid_attrs=True)
372 m = Module()
373 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
374 for bit in range(len(p_port)):
375 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
376 i_T=t,
377 i_I=o[bit],
378 o_O=p_port[bit],
379 )
380 return m
381
382 def get_diff_input_output(self, pin, p_port, n_port, attrs, invert):
383 self._check_feature("differential input/output", pin, attrs,
384 valid_xdrs=(0, 1, 2), valid_attrs=True)
385 m = Module()
386 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
387 for bit in range(len(p_port)):
388 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
389 i_T=t,
390 i_I=o[bit],
391 o_O=i[bit],
392 io_B=p_port[bit],
393 )
394 return m
395
396 # CDC primitives are not currently specialized for MachXO2.