Added nmigen wrapper and support code for JTAG interface.
[c4m-jtag.git] / rtl / nmigen / jtag.py
1 #!/bin/env python3
2 import os
3
4 from nmigen import *
5 from nmigen.build import *
6 from nmigen.lib.io import *
7
8 from wishbone import Wishbone
9
10 __all__ = [
11 "PmodJTAGMasterResource",
12 "PmodJTAGMasterAResource",
13 "PmodJTAGSlaveResource",
14 "PmodJTAGSlaveAResource",
15 "JTAG",
16 ]
17
18 #TODO: Provide more documentation
19
20 def PmodJTAGMasterResource(name, number, *, pmod, attrs=Attrs(IOSTANDARD="LVCMOS33")):
21 return Resource(name, number,
22 Subsignal("TCK", Pins("1", dir="o", conn=("pmod", pmod))),
23 Subsignal("TMS", Pins("2", dir="o", conn=("pmod", pmod))),
24 Subsignal("TDO", Pins("3", dir="o", conn=("pmod", pmod))),
25 Subsignal("TDI", Pins("4", dir="i", conn=("pmod", pmod))),
26 attrs,
27 )
28
29 def PmodJTAGMasterAResource(name, number, *, pmod, attrs=Attrs(IOSTANDARD="LVCMOS33")):
30 return Resource(name, number,
31 Subsignal("TCK", Pins("1", dir="o", conn=("pmod", pmod))),
32 Subsignal("TMS", Pins("2", dir="o", conn=("pmod", pmod))),
33 Subsignal("TDO", Pins("3", dir="o", conn=("pmod", pmod))),
34 Subsignal("TDI", Pins("4", dir="i", conn=("pmod", pmod))),
35 Subsignal("TRST", PinsN("7", dir="o", conn=("pmod", pmod))),
36 attrs,
37 )
38
39 def PmodJTAGSlaveResource(name, number, *, pmod, attrs=Attrs(IOSTANDARD="LVCMOS33")):
40 return Resource(name, number,
41 Subsignal("TCK", Pins("1", dir="i", conn=("pmod", pmod))),
42 Subsignal("TMS", Pins("2", dir="i", conn=("pmod", pmod))),
43 Subsignal("TDI", Pins("3", dir="i", conn=("pmod", pmod))),
44 Subsignal("TDO", Pins("4", dir="o", conn=("pmod", pmod))),
45 attrs,
46 )
47
48 def PmodJTAGSlaveAResource(name, number, *, pmod, attrs=Attrs(IOSTANDARD="LVCMOS33")):
49 return Resource(name, number,
50 Subsignal("TCK", Pins("1", dir="i", conn=("pmod", pmod))),
51 Subsignal("TMS", Pins("2", dir="i", conn=("pmod", pmod))),
52 Subsignal("TDI", Pins("3", dir="i", conn=("pmod", pmod))),
53 Subsignal("TDO", Pins("4", dir="o", conn=("pmod", pmod))),
54 Subsignal("TRST", PinsN("7", dir="i", conn=("pmod", pmod))),
55 attrs,
56 )
57
58
59 def _add_files(platform, prefix):
60 d = os.path.realpath("{0}{1}{2}{1}vhdl".format(
61 os.path.dirname(__file__), os.path.sep, os.path.pardir
62 )) + os.path.sep
63 for fname in [
64 "c4m_jtag_pkg.vhdl",
65 "c4m_jtag_idblock.vhdl",
66 "c4m_jtag_iocell.vhdl",
67 "c4m_jtag_ioblock.vhdl",
68 "c4m_jtag_irblock.vhdl",
69 "c4m_jtag_tap_fsm.vhdl",
70 "c4m_jtag_tap_controller.vhdl",
71 ]:
72 f = open(d + fname, "r")
73 platform.add_file(prefix + fname, f)
74 f.close()
75
76
77 class ShiftReg(Elaboratable):
78 def __init__(self, ircodes, length, domain):
79 # The sr record will be returned to user code
80 self.sr = Record([("i", length), ("o", length), ("oe", len(ircodes)), ("ack", 1)])
81 # The next attributes are for JTAG class usage only
82 self.ir = None # made None as width is not known yet
83 self.tdi = Signal()
84 self.tdo = Signal()
85 self.tdo_en = Signal()
86 self.capture = Signal()
87 self.shift = Signal()
88 self.update = Signal()
89 self.jtag_cd = None # The JTAG clock domain
90
91 ##
92
93 self._ircodes = ircodes
94 self._domain = domain
95
96 def elaborate(self, platform):
97 length = len(self.sr.o)
98 domain = self._domain
99
100 m = Module()
101
102 m.domains.jtag = self.jtag_cd
103
104 sr_jtag = Signal(length)
105
106 assert isinstance(self.ir, Signal)
107 isir = Signal(len(self._ircodes))
108 capture = Signal()
109 shift = Signal()
110 update = Signal()
111 m.d.comb += [
112 isir.eq(Cat(self.ir == ircode for ircode in self._ircodes)),
113 capture.eq((isir != 0) & self.capture),
114 shift.eq((isir != 0) & self.shift),
115 update.eq((isir != 0) & self.update),
116 ]
117
118 # On update set o, oe and wait for ack
119 # update signal is on JTAG clockdomain, latch it
120 update_core = Signal()
121 m.d[domain] += update_core.eq(update) # This is CDC from JTAG domain to given domain
122 with m.FSM(domain=domain):
123 with m.State("IDLE"):
124 m.d.comb += self.sr.oe.eq(0)
125 with m.If(update_core):
126 # Latch sr_jtag cross domain but it should be stable due to latching of update_core
127 m.d[domain] += self.sr.o.eq(sr_jtag)
128 # Wait one cycle to raise oe so sr.o has one more cycle to stabilize
129 m.next = "WAIT4ACK"
130 with m.State("WAIT4ACK"):
131 m.d.comb += self.sr.oe.eq(isir)
132 with m.If(self.sr.ack):
133 m.next = "WAIT4END"
134 with m.State("WAIT4END"):
135 m.d.comb += self.sr.oe.eq(0)
136 with m.If(~update_core):
137 m.next = "IDLE"
138
139 m.d.comb += [
140 self.tdo.eq(sr_jtag[0]),
141 self.tdo_en.eq(shift),
142 ]
143
144 with m.If(shift):
145 m.d.jtag += sr_jtag.eq(Cat(sr_jtag[1:], self.tdi))
146 with m.If(capture):
147 m.d.jtag += sr_jtag.eq(self.sr.i)
148
149 return m
150
151 class JTAGWishbone(Elaboratable):
152 def __init__(self, sr_addr, sr_data, wb, domain):
153 self._sr_addr = sr_addr
154 self._sr_data = sr_data
155 self._wb = wb
156 self._domain = domain
157
158 # To be set by JTAG
159 self._ir = None
160
161 def elaborate(self, platform):
162 sr_addr = self._sr_addr
163 sr_data = self._sr_data
164 wb = self._wb
165 domain = self._domain
166 ir = self._ir
167
168 m = Module()
169
170 if hasattr(wb, "sel"):
171 # Always selected
172 m.d.comb += [s.eq(1) for s in wb.sel]
173
174 # Immediately ack oe
175 m.d[domain] += [
176 sr_addr.ack.eq(sr_addr.oe),
177 sr_data.ack.eq(sr_data.oe != 0),
178 ]
179
180 with m.FSM(domain=domain) as fsm:
181 with m.State("IDLE"):
182 m.d.comb += [
183 wb.cyc.eq(0),
184 wb.stb.eq(0),
185 wb.we.eq(0),
186 ]
187 with m.If(sr_addr.oe): # WBADDR code
188 m.d[domain] += wb.addr.eq(sr_addr.o)
189 m.next = "READ"
190 with m.If(sr_data.oe[0]): # WBREAD code
191 m.d[domain] += wb.addr.eq(wb.addr + 1)
192 m.next = "READ"
193 with m.If(sr_data.oe[1]): # WBWRITE code
194 m.d[domain] += wb.dat_w.eq(sr_data.o)
195 m.next = "WRITEREAD"
196 with m.State("READ"):
197 m.d.comb += [
198 wb.cyc.eq(1),
199 wb.stb.eq(1),
200 wb.we.eq(0),
201 ]
202 m.next = "READACK"
203 with m.State("READACK"):
204 m.d.comb += [
205 wb.cyc.eq(1),
206 wb.stb.eq(0),
207 wb.we.eq(0),
208 ]
209 with m.If(wb.ack):
210 m.d[domain] += sr_data.i.eq(wb.dat_r)
211 m.next = "IDLE"
212 with m.State("WRITEREAD"):
213 m.d.comb += [
214 wb.cyc.eq(1),
215 wb.stb.eq(1),
216 wb.we.eq(1),
217 ]
218 m.next = "WRITEREADACK"
219 with m.State("WRITEREADACK"):
220 m.d.comb += [
221 wb.cyc.eq(1),
222 wb.stb.eq(0),
223 wb.we.eq(0),
224 ]
225 with m.If(wb.ack):
226 m.d[domain] += wb.addr.eq(wb.addr + 1)
227 m.next = "READ"
228
229 return m
230
231
232 class JTAG(Elaboratable):
233 _files_added = []
234
235 def __init__(self, io_count, *, ir_width=None, manufacturer_id=Const(0b10001111111, 11),
236 part_number=Const(1, 16), version=Const(0, 4)
237 ):
238 assert(isinstance(io_count, int) and io_count > 0)
239 assert((ir_width is None) or (isinstance(ir_width, int) and ir_width >= 2))
240 assert(len(version) == 4)
241
242 # TODO: Handle IOs with different directions
243 self.tck = Signal()
244 self.tms = Signal()
245 self.tdo = Signal()
246 self.tdi = Signal()
247 self.core = Array(Pin(1, "io") for _ in range(io_count)) # Signals to use for core
248 self.pad = Array(Pin(1, "io") for _ in range(io_count)) # Signals going to IO pads
249
250 self.jtag_cd = ClockDomain(name="jtag", local=True) # Own clock domain using TCK as clock signal
251
252 ##
253
254 self._io_count = io_count
255 self._ir_width = ir_width
256 self._manufacturer_id = manufacturer_id
257 self._part_number = part_number
258 self._version = version
259
260 self._ircodes = [0, 1, 2] # Already taken codes, all ones added at the end
261 self._srs = []
262
263 self._wbs = []
264
265 def elaborate(self, platform):
266 _add_files(platform, "jtag" + os.path.sep)
267
268 m = Module()
269
270 tdo_jtag = Signal()
271 reset = Signal()
272 capture = Signal()
273 shift = Signal()
274 update = Signal()
275
276
277 ir_max = max(self._ircodes) + 1 # One extra code needed with all ones
278 ir_width = len("{:b}".format(ir_max))
279 if self._ir_width is not None:
280 assert self._ir_width >= ir_width, "Specified JTAG IR width not big enough for allocated shiift registers"
281 ir_width = self._ir_width
282 ir = Signal(ir_width)
283
284 core_i = Cat(pin.i for pin in self.core)
285 core_o = Cat(pin.o for pin in self.core)
286 core_oe = Cat(pin.oe for pin in self.core)
287 pad_i = Cat(pin.i for pin in self.pad)
288 pad_o = Cat(pin.o for pin in self.pad)
289 pad_oe = Cat(pin.oe for pin in self.pad)
290
291 params = {
292 "p_IOS": self._io_count,
293 "p_IR_WIDTH": ir_width,
294 "p_MANUFACTURER": self._manufacturer_id,
295 "p_PART_NUMBER": self._part_number,
296 "p_VERSION": self._version,
297 "i_TCK": self.tck,
298 "i_TMS": self.tms,
299 "i_TDI": self.tdi,
300 "o_TDO": tdo_jtag,
301 "i_TRST_N": Const(1),
302 "o_RESET": reset,
303 "o_DRCAPTURE": capture,
304 "o_DRSHIFT": shift,
305 "o_DRUPDATE": update,
306 "o_IR": ir,
307 "o_CORE_IN": core_i,
308 "i_CORE_OUT": core_o,
309 "i_CORE_EN": core_oe,
310 "i_PAD_IN": pad_i,
311 "o_PAD_OUT": pad_o,
312 "o_PAD_EN": pad_oe,
313 }
314 m.submodules.tap = Instance("c4m_jtag_tap_controller", **params)
315
316 m.d.comb += [
317 self.jtag_cd.clk.eq(self.tck),
318 self.jtag_cd.rst.eq(reset),
319 ]
320
321 for i, sr in enumerate(self._srs):
322 m.submodules["sr{}".format(i)] = sr
323 sr.ir = ir
324 m.d.comb += [
325 sr.tdi.eq(self.tdi),
326 sr.capture.eq(capture),
327 sr.shift.eq(shift),
328 sr.update.eq(update),
329 ]
330
331 if len(self._srs) > 0:
332 first = True
333 for sr in self._srs:
334 if first:
335 first = False
336 with m.If(sr.tdo_en):
337 m.d.comb += self.tdo.eq(sr.tdo)
338 else:
339 with m.Elif(sr.tdo_en):
340 m.d.comb += self.tdo.eq(sr.tdo)
341 with m.Else():
342 m.d.comb += self.tdo.eq(tdo_jtag)
343 else:
344 m.d.comb += self.tdo.eq(tdo_jtag)
345
346 for i, wb in enumerate(self._wbs):
347 m.submodules["wb{}".format(i)] = wb
348 wb._ir = ir
349
350 return m
351
352
353 def add_shiftreg(self, ircode, length, domain="sync"):
354 """Add a shift register to the JTAG interface
355
356 Parameters:
357 - ircode: code(s) for the IR; int or sequence of ints. In the latter case this
358 shiftreg is shared between different IR codes.
359 - length: the length of the shift register
360 - domain: the domain on which the signal will be used"""
361
362 try:
363 ir_it = iter(ircode)
364 ircodes = ircode
365 except TypeError:
366 ir_it = ircodes = (ircode,)
367 for _ircode in ir_it:
368 assert(isinstance(_ircode, int) and _ircode > 0 and _ircode not in self._ircodes)
369
370 sr = ShiftReg(ircodes, length, domain)
371 sr.jtag_cd = self.jtag_cd
372 self._ircodes.extend(ircodes)
373 self._srs.append(sr)
374
375 return sr.sr
376
377
378 def add_wishbone(self, ircodes, address_width, data_width, sel_width=None, domain="sync"):
379 """Add a wishbone interface
380
381 Parameters:
382 - ircodes: sequence of three integer for the JTAG IR codes;
383 they represent resp. WBADDR, WBREAD and WBREADWRITE. First code
384 has a shift register of length 'address_width', the two other codes
385 share a shift register of length data_width.
386 - address_width: width of the address
387 - data_width: width of the data"""
388
389 assert len(ircodes) == 3
390
391 sr_addr = self.add_shiftreg(ircodes[0], address_width, domain=domain)
392 sr_data = self.add_shiftreg(ircodes[1:], data_width, domain=domain)
393
394 wb = Wishbone(data_width=data_width, address_width=address_width, sel_width=sel_width, master=True)
395
396 self._wbs.append(JTAGWishbone(sr_addr, sr_data, wb, domain))
397
398 return wb