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