vendor.lattice_ecp5: drive GSR synchronous to user clock by default.
[nmigen.git] / nmigen / vendor / lattice_ecp5.py
1 from abc import abstractproperty
2
3 from ..hdl import *
4 from ..build import *
5
6
7 __all__ = ["LatticeECP5Platform"]
8
9
10 class LatticeECP5Platform(TemplatedPlatform):
11 """
12 Trellis toolchain
13 -----------------
14
15 Required tools:
16 * ``yosys``
17 * ``nextpnr-ecp5``
18 * ``ecppack``
19
20 The environment is populated by running the script specified in the environment variable
21 ``NMIGEN_Trellis_env``, if present.
22
23 Available overrides:
24 * ``verbose``: enables logging of informational messages to standard error.
25 * ``read_verilog_opts``: adds options for ``read_verilog`` Yosys command.
26 * ``synth_opts``: adds options for ``synth_ecp5`` Yosys command.
27 * ``script_after_read``: inserts commands after ``read_ilang`` in Yosys script.
28 * ``script_after_synth``: inserts commands after ``synth_ecp5`` in Yosys script.
29 * ``yosys_opts``: adds extra options for ``yosys``.
30 * ``nextpnr_opts``: adds extra options for ``nextpnr-ecp5``.
31 * ``ecppack_opts``: adds extra options for ``ecppack``.
32
33 Build products:
34 * ``{{name}}.rpt``: Yosys log.
35 * ``{{name}}.json``: synthesized RTL.
36 * ``{{name}}.tim``: nextpnr log.
37 * ``{{name}}.config``: ASCII bitstream.
38 * ``{{name}}.bit``: binary bitstream.
39 * ``{{name}}.svf``: JTAG programming vector.
40
41 Diamond toolchain
42 -----------------
43
44 Required tools:
45 * ``pnmainc``
46 * ``ddtcmd``
47
48 The environment is populated by running the script specified in the environment variable
49 ``NMIGEN_Diamond_env``, if present.
50
51 Available overrides:
52 * ``script_project``: inserts commands before ``prj_project save`` in Tcl script.
53 * ``script_after_export``: inserts commands after ``prj_run Export`` in Tcl script.
54 * ``add_preferences``: inserts commands in LPF file.
55 * ``add_constraints``: inserts commands in XDC file.
56
57 Build products:
58 * ``{{name}}_impl/{{name}}_impl.htm``: consolidated log.
59 * ``{{name}}.bit``: binary bitstream.
60 * ``{{name}}.svf``: JTAG programming vector.
61 """
62
63 toolchain = None # selected when creating platform
64
65 device = abstractproperty()
66 package = abstractproperty()
67 speed = abstractproperty()
68 grade = "C" # [C]ommercial, [I]ndustrial
69
70 # Trellis templates
71
72 _nextpnr_device_options = {
73 "LFE5U-12F": "--25k",
74 "LFE5U-25F": "--25k",
75 "LFE5U-45F": "--45k",
76 "LFE5U-85F": "--85k",
77 "LFE5UM-12F": "--um-25k",
78 "LFE5UM-25F": "--um-25k",
79 "LFE5UM-45F": "--um-45k",
80 "LFE5UM-85F": "--um-85k",
81 "LFE5UM5G-12F": "--um5g-25k",
82 "LFE5UM5G-25F": "--um5g-25k",
83 "LFE5UM5G-45F": "--um5g-45k",
84 "LFE5UM5G-85F": "--um5g-85k",
85 }
86 _nextpnr_package_options = {
87 "BG256": "caBGA256",
88 "MG285": "csfBGA285",
89 "BG381": "caBGA381",
90 "BG554": "caBGA554",
91 "BG756": "caBGA756",
92 }
93
94 _trellis_file_templates = {
95 **TemplatedPlatform.build_script_templates,
96 "{{name}}.il": r"""
97 # {{autogenerated}}
98 {{emit_design("rtlil")}}
99 """,
100 "{{name}}.ys": r"""
101 # {{autogenerated}}
102 {% for file in platform.iter_extra_files(".v") -%}
103 read_verilog {{get_override("read_opts")|options}} {{file}}
104 {% endfor %}
105 {% for file in platform.iter_extra_files(".sv") -%}
106 read_verilog -sv {{get_override("read_opts")|options}} {{file}}
107 {% endfor %}
108 read_ilang {{name}}.il
109 {{get_override("script_after_read")|default("# (script_after_read placeholder)")}}
110 synth_ecp5 {{get_override("synth_opts")|options}} -top {{name}}
111 {{get_override("script_after_synth")|default("# (script_after_synth placeholder)")}}
112 write_json {{name}}.json
113 """,
114 "{{name}}.lpf": r"""
115 # {{autogenerated}}
116 BLOCK ASYNCPATHS;
117 BLOCK RESETPATHS;
118 {% for port_name, pin_name, extras in platform.iter_port_constraints_bits() -%}
119 LOCATE COMP "{{port_name}}" SITE "{{pin_name}}";
120 IOBUF PORT "{{port_name}}"
121 {%- for key, value in extras.items() %} {{key}}={{value}}{% endfor %};
122 {% endfor %}
123 {% for signal, frequency in platform.iter_clock_constraints() -%}
124 FREQUENCY PORT "{{signal.name}}" {{frequency}} HZ;
125 {% endfor %}
126 """
127 }
128 _trellis_command_templates = [
129 r"""
130 {{get_tool("yosys")}}
131 {{quiet("-q")}}
132 {{get_override("yosys_opts")|options}}
133 -l {{name}}.rpt
134 {{name}}.ys
135 """,
136 r"""
137 {{get_tool("nextpnr-ecp5")}}
138 {{quiet("--quiet")}}
139 {{get_override("nextpnr_opts")|options}}
140 --log {{name}}.tim
141 {{platform._nextpnr_device_options[platform.device]}}
142 --package {{platform._nextpnr_package_options[platform.package]|upper}}
143 --speed {{platform.speed}}
144 --json {{name}}.json
145 --lpf {{name}}.lpf
146 --textcfg {{name}}.config
147 """,
148 r"""
149 {{get_tool("ecppack")}}
150 {{verbose("--verbose")}}
151 --input {{name}}.config
152 --bit {{name}}.bit
153 --svf {{name}}.svf
154 """
155 ]
156
157 # Diamond templates
158
159 _diamond_file_templates = {
160 **TemplatedPlatform.build_script_templates,
161 "build_{{name}}.sh": r"""
162 # {{autogenerated}}
163 set -e{{verbose("x")}}
164 if [ -z "$BASH" ] ; then exec /bin/bash "$0" "$@"; fi
165 if [ -n "$NMIGEN_{{platform.toolchain}}_env" ]; then
166 bindir=$(dirname "$NMIGEN_{{platform.toolchain}}_env")
167 . "$NMIGEN_{{platform.toolchain}}_env"
168 fi
169 {{emit_commands("sh")}}
170 """,
171 "{{name}}.v": r"""
172 /* {{autogenerated}} */
173 {{emit_design("verilog")}}
174 """,
175 "{{name}}.tcl": r"""
176 prj_project new -name "{{name}}" -impl "impl" -impl_dir "top_impl" \
177 -dev {{platform.device}}-{{platform.speed}}{{platform.package}}{{platform.grade}} \
178 -lpf "{{name}}.lpf" \
179 -synthesis synplify
180 {% for file in platform.iter_extra_files(".v", ".sv", ".vhd", ".vhdl") -%}
181 prj_src add "{{file}}"
182 {% endfor %}
183 prj_src add "{{name}}.v"
184 prj_impl option top "{{name}}"
185 prj_src add "{{name}}.sdc"
186 {{get_override("script_project")|default("# (script_project placeholder)")}}
187 prj_project save
188 prj_run Synthesis -impl "impl" -forceAll
189 prj_run Translate -impl "impl" -forceAll
190 prj_run Map -impl "impl" -forceAll
191 prj_run PAR -impl "impl" -forceAll
192 prj_run Export -impl "impl" -forceAll -task Bitgen
193 {{get_override("script_after_export")|default("# (script_after_export placeholder)")}}
194 """,
195 "{{name}}.lpf": r"""
196 # {{autogenerated}}
197 BLOCK ASYNCPATHS;
198 BLOCK RESETPATHS;
199 {% for port_name, pin_name, extras in platform.iter_port_constraints_bits() -%}
200 LOCATE COMP "{{port_name}}" SITE "{{pin_name}}";
201 IOBUF PORT "{{port_name}}"
202 {%- for key, value in extras.items() %} {{key}}={{value}}{% endfor %};
203 {% endfor %}
204 {% for signal, frequency in platform.iter_clock_constraints() -%}
205 FREQUENCY PORT "{{signal.name}}" {{frequency/1000000}} MHZ;
206 {% endfor %}
207 {{get_override("add_preferences")|default("# (add_preferences placeholder)")}}
208 """,
209 "{{name}}.sdc": r"""
210 {% for signal, frequency in platform.iter_clock_constraints() -%}
211 create_clock -period {{1000000000/frequency}} [get_ports {{signal.name}}]
212 {% endfor %}
213 {{get_override("add_constraints")|default("# (add_constraints placeholder)")}}
214 """,
215 }
216 _diamond_command_templates = [
217 # These don't have any usable command-line option overrides.
218 r"""
219 {{get_tool("pnmainc")}}
220 {{name}}.tcl
221 """,
222 r"""
223 {{get_tool("ddtcmd")}}
224 -oft -bit
225 -if {{name}}_impl/{{name}}_impl.bit -of {{name}}.bit
226 """,
227 r"""
228 {{get_tool("ddtcmd")}}
229 -oft -svfsingle -revd -op "Fast Program"
230 -if {{name}}_impl/{{name}}_impl.bit -of {{name}}.svf
231 """,
232 ]
233
234 # Common logic
235
236 def __init__(self, *, toolchain="Trellis"):
237 super().__init__()
238
239 assert toolchain in ("Trellis", "Diamond")
240 self.toolchain = toolchain
241
242 @property
243 def file_templates(self):
244 if self.toolchain == "Trellis":
245 return self._trellis_file_templates
246 if self.toolchain == "Diamond":
247 return self._diamond_file_templates
248 assert False
249
250 @property
251 def command_templates(self):
252 if self.toolchain == "Trellis":
253 return self._trellis_command_templates
254 if self.toolchain == "Diamond":
255 return self._diamond_command_templates
256 assert False
257
258 def create_missing_domain(self, name):
259 # Lattice ECP devices have two global set/reset signals: PUR, which is driven at startup
260 # by the configuration logic and unconditionally resets every storage element, and GSR,
261 # which is driven by user logic and each storage element may be configured as affected or
262 # unaffected by GSR. PUR is purely asynchronous, so even though it is a low-skew global
263 # network, its deassertion may violate a setup/hold constraint with relation to a user
264 # clock. To avoid this, a GSR/SGSR instance should be driven synchronized to user clock.
265 if name == "sync" and self.default_clk is not None:
266 clk_i = self.request(self.default_clk).i
267 if self.default_rst is not None:
268 rst_i = self.request(self.default_rst).i
269 else:
270 rst_i = Const(0)
271
272 gsr0 = Signal()
273 gsr1 = Signal()
274 m = Module()
275 # There is no end-of-startup signal on ECP5, but PUR is released after IOB enable, so
276 # a simple reset synchronizer (with PUR as the asynchronous reset) does the job.
277 m.submodules += [
278 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=~rst_i, o_Q=gsr0),
279 Instance("FD1S3AX", p_GSR="DISABLED", i_CK=clk_i, i_D=gsr0, o_Q=gsr1),
280 # Although we already synchronize the reset input to user clock, SGSR has dedicated
281 # clock routing to the center of the FPGA; use that just in case it turns out to be
282 # more reliable. (None of this is documented.)
283 Instance("SGSR", i_CLK=clk_i, i_GSR=gsr1),
284 ]
285 # GSR implicitly connects to every appropriate storage element. As such, the sync
286 # domain is reset-less; domains driven by other clocks would need to have dedicated
287 # reset circuitry or otherwise meet setup/hold constraints on their own.
288 m.domains += ClockDomain("sync", reset_less=True)
289 m.d.comb += ClockSignal("sync").eq(clk_i)
290 return m
291
292 _single_ended_io_types = [
293 "HSUL12", "LVCMOS12", "LVCMOS15", "LVCMOS18", "LVCMOS25", "LVCMOS33", "LVTTL33",
294 "SSTL135_I", "SSTL135_II", "SSTL15_I", "SSTL15_II", "SSTL18_I", "SSTL18_II",
295 ]
296 _differential_io_types = [
297 "BLVDS25", "BLVDS25E", "HSUL12D", "LVCMOS18D", "LVCMOS25D", "LVCMOS33D",
298 "LVDS", "LVDS25E", "LVPECL33", "LVPECL33E", "LVTTL33D", "MLVDS", "MLVDS25E",
299 "SLVS", "SSTL135D_II", "SSTL15D_II", "SSTL18D_II", "SUBLVDS",
300 ]
301
302 def should_skip_port_component(self, port, attrs, component):
303 # On ECP5, a differential IO is placed by only instantiating an IO buffer primitive at
304 # the PIOA or PIOC location, which is always the non-inverting pin.
305 if attrs.get("IO_TYPE", "LVCMOS25") in self._differential_io_types and component == "n":
306 return True
307 return False
308
309 def _get_xdr_buffer(self, m, pin, *, i_invert=False, o_invert=False):
310 def get_ireg(clk, d, q):
311 for bit in range(len(q)):
312 m.submodules += Instance("IFS1P3DX",
313 i_SCLK=clk,
314 i_SP=Const(1),
315 i_CD=Const(0),
316 i_D=d[bit],
317 o_Q=q[bit]
318 )
319
320 def get_oreg(clk, d, q):
321 for bit in range(len(q)):
322 m.submodules += Instance("OFS1P3DX",
323 i_SCLK=clk,
324 i_SP=Const(1),
325 i_CD=Const(0),
326 i_D=d[bit],
327 o_Q=q[bit]
328 )
329
330 def get_iddr(sclk, d, q0, q1):
331 for bit in range(len(d)):
332 m.submodules += Instance("IDDRX1F",
333 i_SCLK=sclk,
334 i_RST=Const(0),
335 i_D=d[bit],
336 o_Q0=q0[bit], o_Q1=q1[bit]
337 )
338
339 def get_oddr(sclk, d0, d1, q):
340 for bit in range(len(q)):
341 m.submodules += Instance("ODDRX1F",
342 i_SCLK=sclk,
343 i_RST=Const(0),
344 i_D0=d0[bit], i_D1=d1[bit],
345 o_Q=q[bit]
346 )
347
348 def get_ineg(z, invert):
349 if invert:
350 a = Signal.like(z, name_suffix="_n")
351 m.d.comb += z.eq(~a)
352 return a
353 else:
354 return z
355
356 def get_oneg(a, invert):
357 if invert:
358 z = Signal.like(a, name_suffix="_n")
359 m.d.comb += z.eq(~a)
360 return z
361 else:
362 return a
363
364 if "i" in pin.dir:
365 if pin.xdr < 2:
366 pin_i = get_ineg(pin.i, i_invert)
367 elif pin.xdr == 2:
368 pin_i0 = get_ineg(pin.i0, i_invert)
369 pin_i1 = get_ineg(pin.i1, i_invert)
370 if "o" in pin.dir:
371 if pin.xdr < 2:
372 pin_o = get_oneg(pin.o, o_invert)
373 elif pin.xdr == 2:
374 pin_o0 = get_oneg(pin.o0, o_invert)
375 pin_o1 = get_oneg(pin.o1, o_invert)
376
377 i = o = t = None
378 if "i" in pin.dir:
379 i = Signal(pin.width, name="{}_xdr_i".format(pin.name))
380 if "o" in pin.dir:
381 o = Signal(pin.width, name="{}_xdr_o".format(pin.name))
382 if pin.dir in ("oe", "io"):
383 t = Signal(1, name="{}_xdr_t".format(pin.name))
384
385 if pin.xdr == 0:
386 if "i" in pin.dir:
387 i = pin_i
388 if "o" in pin.dir:
389 o = pin_o
390 if pin.dir in ("oe", "io"):
391 t = ~pin_oe
392 elif pin.xdr == 1:
393 # Note that currently nextpnr will not pack an FF (*FS1P3DX) into the PIO.
394 if "i" in pin.dir:
395 get_ireg(pin.i_clk, i, pin_i)
396 if "o" in pin.dir:
397 get_oreg(pin.o_clk, pin_o, o)
398 if pin.dir in ("oe", "io"):
399 get_oreg(pin.o_clk, ~pin.oe, t)
400 elif pin.xdr == 2:
401 if "i" in pin.dir:
402 get_iddr(pin.i_clk, i, pin_i0, pin_i1)
403 if "o" in pin.dir:
404 get_oddr(pin.o_clk, pin_o0, pin_o1, o)
405 if pin.dir in ("oe", "io"):
406 # It looks like Diamond will not pack an OREG as a tristate register in a DDR PIO.
407 # It is not clear what is the recommended set of primitives for this task.
408 # Similarly, nextpnr will not pack anything as a tristate register in a DDR PIO.
409 get_oreg(pin.o_clk, ~pin.oe, t)
410 else:
411 assert False
412
413 return (i, o, t)
414
415 def get_input(self, pin, port, attrs, invert):
416 self._check_feature("single-ended input", pin, attrs,
417 valid_xdrs=(0, 1, 2), valid_attrs=True)
418 m = Module()
419 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
420 for bit in range(len(port)):
421 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
422 i_I=port[bit],
423 o_O=i[bit]
424 )
425 return m
426
427 def get_output(self, pin, port, attrs, invert):
428 self._check_feature("single-ended output", pin, attrs,
429 valid_xdrs=(0, 1, 2), valid_attrs=True)
430 m = Module()
431 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
432 for bit in range(len(port)):
433 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
434 i_I=o[bit],
435 o_O=port[bit]
436 )
437 return m
438
439 def get_tristate(self, pin, port, attrs, invert):
440 self._check_feature("single-ended tristate", pin, attrs,
441 valid_xdrs=(0, 1, 2), valid_attrs=True)
442 m = Module()
443 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
444 for bit in range(len(port)):
445 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
446 i_T=t,
447 i_I=o[bit],
448 o_O=port[bit]
449 )
450 return m
451
452 def get_input_output(self, pin, port, attrs, invert):
453 self._check_feature("single-ended input/output", pin, attrs,
454 valid_xdrs=(0, 1, 2), valid_attrs=True)
455 m = Module()
456 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
457 for bit in range(len(port)):
458 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
459 i_T=t,
460 i_I=o[bit],
461 o_O=i[bit],
462 io_B=port[bit]
463 )
464 return m
465
466 def get_diff_input(self, pin, p_port, n_port, attrs, invert):
467 self._check_feature("differential input", pin, attrs,
468 valid_xdrs=(0, 1, 2), valid_attrs=True)
469 m = Module()
470 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert)
471 for bit in range(len(p_port)):
472 m.submodules["{}_{}".format(pin.name, bit)] = Instance("IB",
473 i_I=p_port[bit],
474 o_O=i[bit]
475 )
476 return m
477
478 def get_diff_output(self, pin, p_port, n_port, attrs, invert):
479 self._check_feature("differential output", pin, attrs,
480 valid_xdrs=(0, 1, 2), valid_attrs=True)
481 m = Module()
482 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
483 for bit in range(len(p_port)):
484 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OB",
485 i_I=o[bit],
486 o_O=p_port[bit],
487 )
488 return m
489
490 def get_diff_tristate(self, pin, p_port, n_port, attrs, invert):
491 self._check_feature("differential tristate", pin, attrs,
492 valid_xdrs=(0, 1, 2), valid_attrs=True)
493 m = Module()
494 i, o, t = self._get_xdr_buffer(m, pin, o_invert=invert)
495 for bit in range(len(p_port)):
496 m.submodules["{}_{}".format(pin.name, bit)] = Instance("OBZ",
497 i_T=t,
498 i_I=o[bit],
499 o_O=p_port[bit],
500 )
501 return m
502
503 def get_diff_input_output(self, pin, p_port, n_port, attrs, invert):
504 self._check_feature("differential input/output", pin, attrs,
505 valid_xdrs=(0, 1, 2), valid_attrs=True)
506 m = Module()
507 i, o, t = self._get_xdr_buffer(m, pin, i_invert=invert, o_invert=invert)
508 for bit in range(len(p_port)):
509 m.submodules["{}_{}".format(pin.name, bit)] = Instance("BB",
510 i_T=t,
511 i_I=o[bit],
512 o_O=i[bit],
513 io_B=p_port[bit],
514 )
515 return m