Figured out how to send jtag bs stream, and how to read, now need to add asserts.
[pinmux.git] / src / spec / testing_stage1.py
1 #!/usr/bin/env python3
2 """
3 pinmux documented here https://libre-soc.org/docs/pinmux/
4 """
5 from nmigen.build.dsl import Resource, Subsignal, Pins
6 from nmigen.build.plat import TemplatedPlatform
7 from nmigen.build.res import ResourceManager, ResourceError
8 from nmigen.hdl.rec import Layout
9 from nmigen import Elaboratable, Signal, Module, Instance
10 from collections import OrderedDict
11 from jtag import JTAG, resiotypes
12 from copy import deepcopy
13 from nmigen.cli import rtlil
14 import sys
15
16 # extra dependencies for jtag testing (?)
17 #from soc.bus.sram import SRAM
18
19 #from nmigen import Memory
20 from nmigen.sim import Simulator, Delay, Settle, Tick, Passive
21
22 from nmutil.util import wrap
23
24 #from soc.debug.jtagutils import (jtag_read_write_reg,
25 # jtag_srv, jtag_set_reset,
26 # jtag_set_ir, jtag_set_get_dr)
27
28 from soc.debug.test.test_jtag_tap import (jtag_read_write_reg,
29 jtag_set_reset,
30 jtag_set_shift_ir,
31 jtag_set_shift_dr,
32 jtag_set_run,
33 jtag_set_idle)
34
35 from c4m.nmigen.jtag.tap import TAP, IOType
36 from c4m.nmigen.jtag.bus import Interface as JTAGInterface
37 from soc.debug.dmi import DMIInterface, DBGCore
38 #from soc.debug.test.dmi_sim import dmi_sim
39 #from soc.debug.test.jtagremote import JTAGServer, JTAGClient
40 from nmigen.build.res import ResourceError
41
42 # Was thinking of using these functions, but skipped for simplicity for now
43 # XXX nope. the output from JSON file.
44 #from pinfunctions import (i2s, lpc, emmc, sdmmc, mspi, mquadspi, spi,
45 # quadspi, i2c, mi2c, jtag, uart, uartfull, rgbttl, ulpi, rgmii, flexbus1,
46 # flexbus2, sdram1, sdram2, sdram3, vss, vdd, sys, eint, pwm, gpio)
47
48 # File for stage 1 pinmux tested proposed by Luke,
49 # https://bugs.libre-soc.org/show_bug.cgi?id=50#c10
50
51
52 def dummy_pinset():
53 # sigh this needs to come from pinmux.
54 gpios = []
55 for i in range(4):
56 gpios.append("%d*" % i)
57 return {'uart': ['tx+', 'rx-'],
58 'gpio': gpios,
59 #'jtag': ['tms-', 'tdi-', 'tdo+', 'tck+'],
60 'i2c': ['sda*', 'scl+']}
61
62 """
63 a function is needed which turns the results of dummy_pinset()
64 into:
65
66 [UARTResource("uart", 0, tx=..., rx=..),
67 I2CResource("i2c", 0, scl=..., sda=...),
68 Resource("gpio", 0, Subsignal("i"...), Subsignal("o"...)
69 Resource("gpio", 1, Subsignal("i"...), Subsignal("o"...)
70 ...
71 ]
72 """
73
74
75 def create_resources(pinset):
76 resources = []
77 for periph, pins in pinset.items():
78 print(periph, pins)
79 if periph == 'i2c':
80 #print("I2C required!")
81 resources.append(I2CResource('i2c', 0, sda='sda', scl='scl'))
82 elif periph == 'uart':
83 #print("UART required!")
84 resources.append(UARTResource('uart', 0, tx='tx', rx='rx'))
85 elif periph == 'gpio':
86 #print("GPIO required!")
87 print ("GPIO is defined as '*' type, meaning i, o and oe needed")
88 ios = []
89 for pin in pins:
90 pname = "gpio"+pin[:-1] # strip "*" on end
91 # urrrr... tristsate and io assume a single pin which is
92 # of course exactly what we don't want in an ASIC: we want
93 # *all three* pins but the damn port is not outputted
94 # as a triplet, it's a single Record named "io". sigh.
95 # therefore the only way to get a triplet of i/o/oe
96 # is to *actually* create explicit triple pins
97 # XXX ARRRGH, doesn't work
98 #pad = Subsignal("io",
99 # Pins("%s_i %s_o %s_oe" % (pname, pname, pname),
100 # dir="io", assert_width=3))
101 #ios.append(Resource(pname, 0, pad))
102 pads = []
103 pads.append(Subsignal("i",
104 Pins(pname+"_i", dir="i", assert_width=1)))
105 pads.append(Subsignal("o",
106 Pins(pname+"_o", dir="o", assert_width=1)))
107 pads.append(Subsignal("oe",
108 Pins(pname+"_oe", dir="o", assert_width=1)))
109 ios.append(Resource.family(pname, 0, default_name=pname,
110 ios=pads))
111 resources.append(Resource.family(periph, 0, default_name="gpio",
112 ios=ios))
113
114 # add clock and reset
115 clk = Resource("clk", 0, Pins("sys_clk", dir="i"))
116 rst = Resource("rst", 0, Pins("sys_rst", dir="i"))
117 resources.append(clk)
118 resources.append(rst)
119 return resources
120
121
122 def JTAGResource(*args):
123 io = []
124 io.append(Subsignal("tms", Pins("tms", dir="i", assert_width=1)))
125 io.append(Subsignal("tdi", Pins("tdi", dir="i", assert_width=1)))
126 io.append(Subsignal("tck", Pins("tck", dir="i", assert_width=1)))
127 io.append(Subsignal("tdo", Pins("tdo", dir="o", assert_width=1)))
128 return Resource.family(*args, default_name="jtag", ios=io)
129
130 def UARTResource(*args, rx, tx):
131 io = []
132 io.append(Subsignal("rx", Pins(rx, dir="i", assert_width=1)))
133 io.append(Subsignal("tx", Pins(tx, dir="o", assert_width=1)))
134 return Resource.family(*args, default_name="uart", ios=io)
135
136
137 def I2CResource(*args, scl, sda):
138 ios = []
139 pads = []
140 pads.append(Subsignal("i", Pins(sda+"_i", dir="i", assert_width=1)))
141 pads.append(Subsignal("o", Pins(sda+"_o", dir="o", assert_width=1)))
142 pads.append(Subsignal("oe", Pins(sda+"_oe", dir="o", assert_width=1)))
143 ios.append(Resource.family(sda, 0, default_name=sda, ios=pads))
144 pads = []
145 pads.append(Subsignal("i", Pins(scl+"_i", dir="i", assert_width=1)))
146 pads.append(Subsignal("o", Pins(scl+"_o", dir="o", assert_width=1)))
147 pads.append(Subsignal("oe", Pins(scl+"_oe", dir="o", assert_width=1)))
148 ios.append(Resource.family(scl, 0, default_name=scl, ios=pads))
149 return Resource.family(*args, default_name="i2c", ios=ios)
150
151
152 # top-level demo module.
153 class Blinker(Elaboratable):
154 def __init__(self, pinset, resources, no_jtag_connect=False):
155 self.no_jtag_connect = no_jtag_connect
156 self.jtag = JTAG({}, "sync", resources=resources)
157 #memory = Memory(width=32, depth=16)
158 #self.sram = SRAM(memory=memory, bus=self.jtag.wb)
159
160 def elaborate(self, platform):
161 jtag_resources = self.jtag.pad_mgr.resources
162 m = Module()
163 m.submodules.jtag = self.jtag
164 #m.submodules.sram = self.sram
165
166 #count = Signal(5)
167 #m.d.sync += count.eq(count+1)
168 print ("resources", platform, jtag_resources.items())
169 gpio = self.jtag.request('gpio')
170 print (gpio, gpio.layout, gpio.fields)
171 # get the GPIO bank, mess about with some of the pins
172 #m.d.comb += gpio.gpio0.o.eq(1)
173 #m.d.comb += gpio.gpio1.o.eq(gpio.gpio2.i)
174 #m.d.comb += gpio.gpio1.oe.eq(count[4])
175 #m.d.sync += count[0].eq(gpio.gpio1.i)
176
177 num_gpios = 4
178 gpio_i_ro = Signal(num_gpios)
179 gpio_o_test = Signal(num_gpios)
180 gpio_oe_test = Signal(num_gpios)
181
182 # Create a read-only copy of core-side GPIO input signals
183 # for Simulation asserts
184 m.d.comb += gpio_i_ro[0].eq(gpio.gpio0.i)
185 m.d.comb += gpio_i_ro[1].eq(gpio.gpio1.i)
186 m.d.comb += gpio_i_ro[2].eq(gpio.gpio2.i)
187 m.d.comb += gpio_i_ro[3].eq(gpio.gpio3.i)
188
189 # Wire up the output signal of each gpio by XOR'ing each bit of
190 # gpio_o_test with gpio's input
191 # Wire up each bit of gpio_oe_test signal to oe signal of each gpio.
192 # Turn into a loop at some point, probably a way without
193 # using get_attr()
194 m.d.comb += gpio.gpio0.o.eq(gpio_o_test[0] ^ gpio.gpio0.i)
195 m.d.comb += gpio.gpio1.o.eq(gpio_o_test[1] ^ gpio.gpio1.i)
196 m.d.comb += gpio.gpio2.o.eq(gpio_o_test[2] ^ gpio.gpio2.i)
197 m.d.comb += gpio.gpio3.o.eq(gpio_o_test[3] ^ gpio.gpio3.i)
198
199 m.d.comb += gpio.gpio0.oe.eq(gpio_oe_test[0])
200 m.d.comb += gpio.gpio1.oe.eq(gpio_oe_test[1])
201 m.d.comb += gpio.gpio2.oe.eq(gpio_oe_test[2])
202 m.d.comb += gpio.gpio3.oe.eq(gpio_oe_test[3])
203
204 # get the UART resource, mess with the output tx
205 uart = self.jtag.request('uart')
206 print ("uart fields", uart, uart.fields)
207 self.intermediary = Signal()
208 m.d.comb += uart.tx.eq(self.intermediary)
209 m.d.comb += self.intermediary.eq(uart.rx)
210
211 # I2C
212 num_i2c = 1
213 i2c_sda_oe_test = Signal(num_i2c)
214 i2c_scl_oe_test = Signal(num_i2c)
215 i2c = self.jtag.request('i2c')
216 print ("i2c fields", i2c, i2c.fields)
217 # Connect in loopback
218 m.d.comb += i2c.scl.o.eq(i2c.scl.i)
219 m.d.comb += i2c.sda.o.eq(i2c.sda.i)
220 # Connect output enable to test port for sim
221 m.d.comb += i2c.sda.oe.eq(i2c_sda_oe_test)
222 m.d.comb += i2c.scl.oe.eq(i2c_scl_oe_test)
223
224 # to even be able to get at objects, you first have to make them
225 # available - i.e. not as local variables
226 # Public attributes are equivalent to input/output ports in hdl's
227 self.gpio = gpio
228 self.uart = uart
229 self.i2c = i2c
230 self.i2c_sda_oe_test = i2c_sda_oe_test
231 self.i2c_scl_oe_test = i2c_scl_oe_test
232 self.gpio_i_ro = gpio_i_ro
233 self.gpio_o_test = gpio_o_test
234 self.gpio_oe_test = gpio_oe_test
235
236 # sigh these wire up to the pads so you cannot set Signals
237 # that are already wired
238 if self.no_jtag_connect: # bypass jtag pad connect for testing purposes
239 return m
240 return self.jtag.boundary_elaborate(m, platform)
241
242 def ports(self):
243 return list(self)
244
245 def __iter__(self):
246 yield from self.jtag.iter_ports()
247
248 '''
249 _trellis_command_templates = [
250 r"""
251 {{invoke_tool("yosys")}}
252 {{quiet("-q")}}
253 {{get_override("yosys_opts")|options}}
254 -l {{name}}.rpt
255 {{name}}.ys
256 """,
257 ]
258 '''
259
260 # sigh, have to create a dummy platform for now.
261 # TODO: investigate how the heck to get it to output ilang. or verilog.
262 # or, anything, really. but at least it doesn't barf
263 class ASICPlatform(TemplatedPlatform):
264 connectors = []
265 resources = OrderedDict()
266 required_tools = []
267 command_templates = ['/bin/true'] # no command needed: stops barfing
268 file_templates = {
269 **TemplatedPlatform.build_script_templates,
270 "{{name}}.il": r"""
271 # {{autogenerated}}
272 {{emit_rtlil()}}
273 """,
274 "{{name}}.debug.v": r"""
275 /* {{autogenerated}} */
276 {{emit_debug_verilog()}}
277 """,
278 }
279 toolchain = None
280 default_clk = "clk" # should be picked up / overridden by platform sys.clk
281 default_rst = "rst" # should be picked up / overridden by platform sys.rst
282
283 def __init__(self, resources, jtag):
284 self.jtag = jtag
285 super().__init__()
286
287 # create set of pin resources based on the pinset, this is for the core
288 #jtag_resources = self.jtag.pad_mgr.resources
289 self.add_resources(resources)
290
291 # add JTAG without scan
292 self.add_resources([JTAGResource('jtag', 0)], no_boundary_scan=True)
293
294 def add_resources(self, resources, no_boundary_scan=False):
295 print ("ASICPlatform add_resources", resources)
296 return super().add_resources(resources)
297
298 #def iter_ports(self):
299 # yield from super().iter_ports()
300 # for io in self.jtag.ios.values():
301 # print ("iter ports", io.layout, io)
302 # for field in io.core.fields:
303 # yield getattr(io.core, field)
304 # for field in io.pad.fields:
305 # yield getattr(io.pad, field)
306
307 # XXX these aren't strictly necessary right now but the next
308 # phase is to add JTAG Boundary Scan so it maaay be worth adding?
309 # at least for the print statements
310 def get_input(self, pin, port, attrs, invert):
311 self._check_feature("single-ended input", pin, attrs,
312 valid_xdrs=(0,), valid_attrs=None)
313
314 m = Module()
315 print (" get_input", pin, "port", port, port.layout)
316 m.d.comb += pin.i.eq(self._invert_if(invert, port))
317 return m
318
319 def get_output(self, pin, port, attrs, invert):
320 self._check_feature("single-ended output", pin, attrs,
321 valid_xdrs=(0,), valid_attrs=None)
322
323 m = Module()
324 print (" get_output", pin, "port", port, port.layout)
325 m.d.comb += port.eq(self._invert_if(invert, pin.o))
326 return m
327
328 def get_tristate(self, pin, port, attrs, invert):
329 self._check_feature("single-ended tristate", pin, attrs,
330 valid_xdrs=(0,), valid_attrs=None)
331
332 print (" get_tristate", pin, "port", port, port.layout)
333 m = Module()
334 print (" pad", pin, port, attrs)
335 print (" pin", pin.layout)
336 return m
337 # m.submodules += Instance("$tribuf",
338 # p_WIDTH=pin.width,
339 # i_EN=pin.oe,
340 # i_A=self._invert_if(invert, pin.o),
341 # o_Y=port,
342 # )
343 m.d.comb += io.core.o.eq(pin.o)
344 m.d.comb += io.core.oe.eq(pin.oe)
345 m.d.comb += pin.i.eq(io.core.i)
346 m.d.comb += io.pad.i.eq(port.i)
347 m.d.comb += port.o.eq(io.pad.o)
348 m.d.comb += port.oe.eq(io.pad.oe)
349 return m
350
351 def get_input_output(self, pin, port, attrs, invert):
352 self._check_feature("single-ended input/output", pin, attrs,
353 valid_xdrs=(0,), valid_attrs=None)
354
355 print (" get_input_output", pin, "port", port, port.layout)
356 m = Module()
357 print (" port layout", port.layout)
358 print (" pin", pin)
359 print (" layout", pin.layout)
360 #m.submodules += Instance("$tribuf",
361 # p_WIDTH=pin.width,
362 # i_EN=io.pad.oe,
363 # i_A=self._invert_if(invert, io.pad.o),
364 # o_Y=port,
365 #)
366 # Create aliases for the port sub-signals
367 port_i = port.io[0]
368 port_o = port.io[1]
369 port_oe = port.io[2]
370
371 m.d.comb += pin.i.eq(self._invert_if(invert, port_i))
372 m.d.comb += port_o.eq(self._invert_if(invert, pin.o))
373 m.d.comb += port_oe.eq(pin.oe)
374
375 return m
376
377 def toolchain_prepare(self, fragment, name, **kwargs):
378 """override toolchain_prepare in order to grab the fragment
379 """
380 self.fragment = fragment
381 return super().toolchain_prepare(fragment, name, **kwargs)
382
383
384
385 def test_case0():
386 print("Starting sanity test case!")
387 print("printing out list of stuff in top")
388 print ("JTAG IOs", top.jtag.ios)
389 # ok top now has a variable named "gpio", let's enumerate that too
390 print("printing out list of stuff in top.gpio and its type")
391 print(top.gpio.__class__.__name__, dir(top.gpio))
392 # ok, it's a nmigen Record, therefore it has a layout. let's print
393 # that too
394 print("top.gpio is a Record therefore has fields and a layout")
395 print(" layout:", top.gpio.layout)
396 print(" fields:", top.gpio.fields)
397 print("Fun never ends...")
398 print(" layout, gpio2:", top.gpio.layout['gpio2'])
399 print(" fields, gpio2:", top.gpio.fields['gpio2'])
400 print(top.jtag.__class__.__name__, dir(top.jtag))
401 print("Pads:")
402 print(top.jtag.resource_table_pads[('gpio', 0)])
403
404 # etc etc. you get the general idea
405 delayVal = 0.2e-6
406 yield top.uart.rx.eq(0)
407 yield Delay(delayVal)
408 yield Settle()
409 yield top.gpio.gpio2.o.eq(0)
410 yield top.gpio.gpio3.o.eq(1)
411 yield
412 yield top.gpio.gpio3.oe.eq(1)
413 yield
414 yield top.gpio.gpio3.oe.eq(0)
415 # grab the JTAG resource pad
416 gpios_pad = top.jtag.resource_table_pads[('gpio', 0)]
417 yield gpios_pad.gpio3.i.eq(1)
418 yield Delay(delayVal)
419 yield Settle()
420 yield top.gpio.gpio2.oe.eq(1)
421 yield top.gpio.gpio3.oe.eq(1)
422 yield gpios_pad.gpio3.i.eq(0)
423 yield top.jtag.gpio.gpio2.i.eq(1)
424 yield Delay(delayVal)
425 yield Settle()
426 gpio_o2 = 0
427 for _ in range(20):
428 # get a value first (as an integer). you were trying to set
429 # it to the actual Signal. this is not going to work. or if
430 # it does, it's very scary.
431 gpio_o2 = not gpio_o2
432 yield top.gpio.gpio2.o.eq(gpio_o2)
433
434 # ditto: here you are trying to set to an AST expression
435 # which is inadviseable (likely to fail)
436 gpio_o3 = not gpio_o2
437 yield top.gpio.gpio3.o.eq(gpio_o3)
438 yield Delay(delayVal)
439 yield Settle()
440 # grab the JTAG resource pad
441 uart_pad = top.jtag.resource_table_pads[('uart', 0)]
442 yield uart_pad.rx.i.eq(gpio_o2)
443 yield Delay(delayVal)
444 yield Settle()
445 yield # one clock cycle
446 tx_val = yield uart_pad.tx.o
447 print ("xmit uart", tx_val, gpio_o2)
448
449 print ("jtag pad table keys")
450 print (top.jtag.resource_table_pads.keys())
451 uart_pad = top.jtag.resource_table_pads[('uart', 0)]
452 print ("uart pad", uart_pad)
453 print ("uart pad", uart_pad.layout)
454
455 yield top.gpio.gpio2.oe.eq(0)
456 yield top.gpio.gpio3.oe.eq(0)
457 yield top.jtag.gpio.gpio2.i.eq(0)
458 yield Delay(delayVal)
459 yield Settle()
460
461 # Code borrowed from cesar, runs, but shouldn't actually work because of
462 # self. statements and non-existent signal names.
463 def test_case1():
464 print("Example test case")
465 yield Passive()
466 while True:
467 # Settle() is needed to give a quick response to
468 # the zero delay case
469 yield Settle()
470 # wait for rel_o to become active
471 while not (yield self.rel_o):
472 yield
473 yield Settle()
474 # read the transaction parameters
475 assert self.expecting, "an unexpected result was produced"
476 delay = (yield self.delay)
477 expected = (yield self.expected)
478 # wait for `delay` cycles
479 for _ in range(delay):
480 yield
481 # activate go_i for one cycle
482 yield self.go_i.eq(1)
483 yield self.count.eq(self.count + 1)
484 yield
485 # check received data against the expected value
486 result = (yield self.port)
487 assert result == expected,\
488 f"expected {expected}, received {result}"
489 yield self.go_i.eq(0)
490 yield self.port.eq(0)
491
492 def test_gpios():
493 print("Starting GPIO test case!")
494
495 num_gpios = top.gpio_o_test.width
496 # Grab GPIO outpud pad resource from JTAG BS - end of chain
497 print (top.jtag.boundary_scan_pads.keys())
498 gpio0_o = top.jtag.boundary_scan_pads['gpio_0__gpio0__o']['o']
499 gpio1_o = top.jtag.boundary_scan_pads['gpio_0__gpio1__o']['o']
500 gpio2_o = top.jtag.boundary_scan_pads['gpio_0__gpio2__o']['o']
501 gpio3_o = top.jtag.boundary_scan_pads['gpio_0__gpio3__o']['o']
502 gpio_pad_out = [ gpio0_o, gpio1_o, gpio2_o, gpio3_o]
503
504 # Grab GPIO output enable pad resource from JTAG BS - end of chain
505 gpio0_oe = top.jtag.boundary_scan_pads['gpio_0__gpio0__oe']['o']
506 gpio1_oe = top.jtag.boundary_scan_pads['gpio_0__gpio1__oe']['o']
507 gpio2_oe = top.jtag.boundary_scan_pads['gpio_0__gpio2__oe']['o']
508 gpio3_oe = top.jtag.boundary_scan_pads['gpio_0__gpio3__oe']['o']
509 gpio_pad_oe = [gpio0_oe, gpio1_oe, gpio2_oe, gpio3_oe]
510
511 # Grab GPIO input pad resource from JTAG BS - start of chain
512 gpio0_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio0__i']['i']
513 gpio1_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio1__i']['i']
514 gpio2_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio2__i']['i']
515 gpio3_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio3__i']['i']
516 gpio_pad_in = [gpio0_pad_in, gpio1_pad_in, gpio2_pad_in, gpio3_pad_in]
517
518 # Have the sim run through a for-loop where the gpio_o_test is
519 # incremented like a counter (0000, 0001...)
520 # At each iteration of the for-loop, assert:
521 # + output set at core matches output seen at pad
522 # TODO + input set at pad matches input seen at core
523 # TODO + if gpio_o_test bit is cleared, output seen at pad matches
524 # input seen at pad
525 num_gpio_o_states = num_gpios**2
526 pad_out = [0] * num_gpios
527 pad_oe = [0] * num_gpios
528 #print("Num of permutations of gpio_o_test record: ", num_gpio_o_states)
529 for gpio_o_val in range(0, num_gpio_o_states):
530 yield top.gpio_o_test.eq(gpio_o_val)
531 #yield Settle()
532 yield # Move to the next clk cycle
533
534 # Cycle through all input combinations
535 for gpio_i_val in range(0, num_gpio_o_states):
536 # Set each gpio input at pad to test value
537 for gpio_bit in range(0, num_gpios):
538 yield gpio_pad_in[gpio_bit].eq((gpio_i_val >> gpio_bit) & 0x1)
539 yield
540 # After changing the gpio0/1/2/3 inputs,
541 # the output is also going to change.
542 # *therefore it must be read again* to get the
543 # snapshot (as a python value)
544 for gpio_bit in range(0, num_gpios):
545 pad_out[gpio_bit] = yield gpio_pad_out[gpio_bit]
546 yield
547 for gpio_bit in range(0, num_gpios):
548 # check core and pad in
549 gpio_i_ro = yield top.gpio_i_ro[gpio_bit]
550 out_test_bit = ((gpio_o_val & (1 << gpio_bit)) != 0)
551 in_bit = ((gpio_i_val & (1 << gpio_bit)) != 0)
552 # Check that the core end input matches pad
553 assert in_bit == gpio_i_ro
554 # Test that the output at pad matches:
555 # Pad output == given test output XOR test input
556 assert (out_test_bit ^ in_bit) == pad_out[gpio_bit]
557
558 # For debugging - VERY verbose
559 #print("---------------------")
560 #print("Test Out: ", bin(gpio_o_val))
561 #print("Test Input: ", bin(gpio_i_val))
562 # Print MSB first
563 #print("Pad Output: ", list(reversed(pad_out)))
564 #print("---------------------")
565
566 # For-loop for testing output enable signals
567 for gpio_o_val in range(0, num_gpio_o_states):
568 yield top.gpio_oe_test.eq(gpio_o_val)
569 yield # Move to the next clk cycle
570
571 for gpio_bit in range(0, num_gpios):
572 pad_oe[gpio_bit] = yield gpio_pad_oe[gpio_bit]
573 yield
574
575 for gpio_bit in range(0, num_gpios):
576 oe_test_bit = ((gpio_o_val & (1 << gpio_bit)) != 0)
577 # oe set at core matches oe seen at pad:
578 assert oe_test_bit == pad_oe[gpio_bit]
579 # For debugging - VERY verbose
580 #print("---------------------")
581 #print("Test Output Enable: ", bin(gpio_o_val))
582 # Print MSB first
583 #print("Pad Output Enable: ", list(reversed(pad_oe)))
584 #print("---------------------")
585 print("GPIO Test PASSED!")
586
587 def test_uart():
588 # grab the JTAG resource pad
589 print ()
590 print ("bs pad keys", top.jtag.boundary_scan_pads.keys())
591 print ()
592 uart_rx_pad = top.jtag.boundary_scan_pads['uart_0__rx']['i']
593 uart_tx_pad = top.jtag.boundary_scan_pads['uart_0__tx']['o']
594
595 print ("uart rx pad", uart_rx_pad)
596 print ("uart tx pad", uart_tx_pad)
597
598 # Test UART by writing 0 and 1 to RX
599 # Internally TX connected to RX,
600 # so match pad TX with RX
601 for i in range(0, 2):
602 yield uart_rx_pad.eq(i)
603 #yield uart_rx_pad.eq(i)
604 yield Settle()
605 yield # one clock cycle
606 tx_val = yield uart_tx_pad
607 print ("xmit uart", tx_val, 1)
608 assert tx_val == i
609
610 print("UART Test PASSED!")
611
612 def test_i2c():
613 i2c_sda_i_pad = top.jtag.boundary_scan_pads['i2c_0__sda__i']['i']
614 i2c_sda_o_pad = top.jtag.boundary_scan_pads['i2c_0__sda__o']['o']
615 i2c_sda_oe_pad = top.jtag.boundary_scan_pads['i2c_0__sda__oe']['o']
616
617 i2c_scl_i_pad = top.jtag.boundary_scan_pads['i2c_0__scl__i']['i']
618 i2c_scl_o_pad = top.jtag.boundary_scan_pads['i2c_0__scl__o']['o']
619 i2c_scl_oe_pad = top.jtag.boundary_scan_pads['i2c_0__scl__oe']['o']
620
621 #i2c_pad = top.jtag.resource_table_pads[('i2c', 0)]
622 #print ("i2c pad", i2c_pad)
623 #print ("i2c pad", i2c_pad.layout)
624
625 for i in range(0, 2):
626 yield i2c_sda_i_pad.eq(i) #i2c_pad.sda.i.eq(i)
627 yield i2c_scl_i_pad.eq(i) #i2c_pad.scl.i.eq(i)
628 yield top.i2c_sda_oe_test.eq(i)
629 yield top.i2c_scl_oe_test.eq(i)
630 yield Settle()
631 yield # one clock cycle
632 sda_o_val = yield i2c_sda_o_pad
633 scl_o_val = yield i2c_scl_o_pad
634 sda_oe_val = yield i2c_sda_oe_pad
635 scl_oe_val = yield i2c_scl_oe_pad
636 print ("Test input: ", i, " SDA/SCL out: ", sda_o_val, scl_o_val,
637 " SDA/SCL oe: ", sda_oe_val, scl_oe_val)
638 assert sda_o_val == i
639 assert scl_o_val == i
640 assert sda_oe_val == i
641 assert scl_oe_val == i
642
643 print("I2C Test PASSED!")
644
645 def test_jtag_bs_chain():
646 #print(dir(top.jtag))
647 #print(dir(top))
648 print("JTAG BS Reset")
649 yield from jtag_set_reset(top.jtag)
650
651 print("JTAG I/O dictionary of core/pad signals:")
652 print(top.jtag.ios.keys())
653 # Based on number of ios entries, produce a test shift reg pattern - TODO
654 bs_data = 0xFFFFF # hard coded for now
655 len_bs_data = len(bin(bs_data)) - 2
656 print("TDI BS Data: {0:b}, Data Length (bits): {1}"
657 .format(bs_data, len_bs_data))
658
659 # TODO: make into a loop for future expansion
660 # All pad input signals to drive and output via TDO
661 i2c_sda_i_pad = top.jtag.boundary_scan_pads['i2c_0__sda__i']['i']
662 i2c_scl_i_pad = top.jtag.boundary_scan_pads['i2c_0__scl__i']['i']
663 uart_rx_pad = top.jtag.boundary_scan_pads['uart_0__rx']['i']
664 gpio0_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio0__i']['i']
665 gpio1_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio1__i']['i']
666 gpio2_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio2__i']['i']
667 gpio3_pad_in = top.jtag.boundary_scan_pads['gpio_0__gpio3__i']['i']
668
669 # Assert all for now
670 yield i2c_sda_i_pad.eq(1)
671 yield i2c_scl_i_pad.eq(1)
672 yield uart_rx_pad.eq(1)
673 yield gpio0_pad_in.eq(1)
674 yield gpio1_pad_in.eq(1)
675 yield gpio2_pad_in.eq(1)
676 yield gpio3_pad_in.eq(1)
677 yield # leave a space to see more easily
678
679 result = yield from jtag_read_write_reg(top.jtag, 0x0, len_bs_data, bs_data)
680 print("TDO BS Data: {0:b}".format(result))
681
682 # Implement a decode which uses ios keys to determine if correct bits in
683 # the TDO stream are set (using asserts) - TODO
684
685 print("JTAG Boundary Scan Chain Test PASSED!")
686
687 # Copied from test_jtag_tap.py
688 # JTAG-ircodes for accessing DMI
689 DMI_ADDR = 5
690 DMI_READ = 6
691 DMI_WRRD = 7
692
693 # JTAG-ircodes for accessing Wishbone
694 WB_ADDR = 8
695 WB_READ = 9
696 WB_WRRD = 10
697
698 def test_jtag_dmi_wb():
699 print(dir(top.jtag))
700 print(dir(top))
701 print("JTAG BS Reset")
702 yield from jtag_set_reset(top.jtag)
703
704 print("JTAG I/O dictionary of core/pad signals:")
705 print(top.jtag.ios.keys())
706
707 # Copied from test_jtag_tap
708 # Don't know if the ID is the same for all JTAG instances
709 ####### JTAGy stuff (IDCODE) ######
710
711 # read idcode
712 idcode = yield from jtag_read_write_reg(top.jtag, 0b1, 32)
713 print ("idcode", hex(idcode))
714 assert idcode == 0x18ff
715
716 ####### JTAG to DMI ######
717
718 # write DMI address
719 yield from jtag_read_write_reg(top.jtag, DMI_ADDR, 8, DBGCore.CTRL)
720
721 # read DMI CTRL register
722 status = yield from jtag_read_write_reg(top.jtag, DMI_READ, 64)
723 print ("dmi ctrl status", hex(status))
724 #assert status == 4
725
726 # write DMI address
727 yield from jtag_read_write_reg(top.jtag, DMI_ADDR, 8, 0)
728
729 # write DMI CTRL register
730 status = yield from jtag_read_write_reg(top.jtag, DMI_WRRD, 64, 0b101)
731 print ("dmi ctrl status", hex(status))
732 #assert status == 4 # returned old value (nice! cool feature!)
733
734 # write DMI address
735 yield from jtag_read_write_reg(top.jtag, DMI_ADDR, 8, DBGCore.CTRL)
736
737 # read DMI CTRL register
738 status = yield from jtag_read_write_reg(top.jtag, DMI_READ, 64)
739 print ("dmi ctrl status", hex(status))
740 #assert status == 6
741
742 # write DMI MSR address
743 yield from jtag_read_write_reg(top.jtag, DMI_ADDR, 8, DBGCore.MSR)
744
745 # read DMI MSR register
746 msr = yield from jtag_read_write_reg(top.jtag, DMI_READ, 64)
747 print ("dmi msr", hex(msr))
748 #assert msr == 0xdeadbeef
749
750 ####### JTAG to Wishbone ######
751
752 # write Wishbone address
753 yield from jtag_read_write_reg(top.jtag, WB_ADDR, 16, 0x18)
754
755 # write/read wishbone data
756 data = yield from jtag_read_write_reg(top.jtag, WB_WRRD, 16, 0xfeef)
757 print ("wb write", hex(data))
758
759 # write Wishbone address
760 yield from jtag_read_write_reg(top.jtag, WB_ADDR, 16, 0x18)
761
762 # write/read wishbone data
763 data = yield from jtag_read_write_reg(top.jtag, WB_READ, 16, 0)
764 print ("wb read", hex(data))
765
766 ####### done - tell dmi_sim to stop (otherwise it won't) ########
767
768 top.jtag.stop = True
769
770 def test_debug_print():
771 print("Test used for getting object methods/information")
772 print("Moved here to clear clutter of gpio test")
773
774 print ("printing out info about the resource gpio0")
775 print (top.gpio['gpio0']['i'])
776 print ("this is a PIN resource", type(top.gpio['gpio0']['i']))
777 # yield can only be done on SIGNALS or RECORDS,
778 # NOT Pins/Resources gpio0_core_in = yield top.gpio['gpio0']['i']
779 #print("Test gpio0 core in: ", gpio0_core_in)
780
781 print("JTAG")
782 print(top.jtag.__class__.__name__, dir(top.jtag))
783 print("TOP")
784 print(top.__class__.__name__, dir(top))
785 print("PORT")
786 print(top.ports.__class__.__name__, dir(top.ports))
787 print("GPIO")
788 print(top.gpio.__class__.__name__, dir(top.gpio))
789
790 print("UART")
791 print(dir(top.jtag.boundary_scan_pads['uart_0__rx__pad__i']))
792 print(top.jtag.boundary_scan_pads['uart_0__rx__pad__i'].keys())
793 print(top.jtag.boundary_scan_pads['uart_0__tx__pad__o'])
794 #print(type(top.jtag.boundary_scan_pads['uart_0__rx__pad__i']['rx']))
795 print ("jtag pad table keys")
796 print (top.jtag.resource_table_pads.keys())
797 print(type(top.jtag.resource_table_pads[('uart', 0)].rx.i))
798 print(top.jtag.boundary_scan_pads['uart_0__rx__i'])
799
800 print("I2C")
801 print(top.jtag.boundary_scan_pads['i2c_0__sda__i'])
802 print(type(top.jtag.boundary_scan_pads['i2c_0__sda__i']['i']))
803
804 print(top.jtag.resource_table_pads)
805 print(top.jtag.boundary_scan_pads)
806
807
808 # Trying to read input from core side, looks like might be a pin...
809 # XXX don't "look like" - don't guess - *print it out*
810 #print ("don't guess, CHECK", type(top.gpio.gpio0.i))
811
812 print () # extra print to divide the output
813 yield
814
815 if __name__ == '__main__':
816 """
817 and to create a Platform instance with that list, and build
818 something random
819
820 p=Platform()
821 p.resources=listofstuff
822 p.build(Blinker())
823 """
824 pinset = dummy_pinset()
825 print(pinset)
826 resources = create_resources(pinset)
827 top = Blinker(pinset, resources, no_jtag_connect=False)#True)
828
829 vl = rtlil.convert(top, ports=top.ports())
830 with open("test_jtag_blinker.il", "w") as f:
831 f.write(vl)
832
833 if False:
834 # XXX these modules are all being added *AFTER* the build process links
835 # everything together. the expectation that this would work is...
836 # unrealistic. ordering, clearly, is important.
837
838 # dut = JTAG(test_pinset(), wb_data_wid=64, domain="sync")
839 top.jtag.stop = False
840 # rather than the client access the JTAG bus directly
841 # create an alternative that the client sets
842 class Dummy: pass
843 cdut = Dummy()
844 cdut.cbus = JTAGInterface()
845
846 # set up client-server on port 44843-something
847 top.jtag.s = JTAGServer()
848 cdut.c = JTAGClient()
849 top.jtag.s.get_connection()
850 #else:
851 # print ("running server only as requested,
852 # use openocd remote to test")
853 # sys.stdout.flush()
854 # top.jtag.s.get_connection(None) # block waiting for connection
855
856 # take copy of ir_width and scan_len
857 cdut._ir_width = top.jtag._ir_width
858 cdut.scan_len = top.jtag.scan_len
859
860 p = ASICPlatform (resources, top.jtag)
861 p.build(top)
862 # this is what needs to gets treated as "top", after "main module" top
863 # is augmented with IO pads with JTAG tacked on. the expectation that
864 # the get_input() etc functions will be called magically by some other
865 # function is unrealistic.
866 top_fragment = p.fragment
867
868 # XXX simulating top (the module that does not itself contain IO pads
869 # because that's covered by build) cannot possibly be expected to work
870 # particularly when modules have been added *after* the platform build()
871 # function has been called.
872
873 sim = Simulator(top)
874 sim.add_clock(1e-6, domain="sync") # standard clock
875
876 #sim.add_sync_process(wrap(jtag_srv(top))) #? jtag server
877 #if len(sys.argv) != 2 or sys.argv[1] != 'server':
878 # actual jtag tester
879 #sim.add_sync_process(wrap(jtag_sim(cdut, top.jtag)))
880 # handles (pretends to be) DMI
881 #sim.add_sync_process(wrap(dmi_sim(top.jtag)))
882
883 #sim.add_sync_process(wrap(test_case1()))
884 #sim.add_sync_process(wrap(test_case0()))
885
886 #sim.add_sync_process(wrap(test_gpios()))
887 #sim.add_sync_process(wrap(test_uart()))
888 #sim.add_sync_process(wrap(test_i2c()))
889 sim.add_sync_process(wrap(test_jtag_bs_chain()))
890 #sim.add_sync_process(wrap(test_debug_print()))
891
892 with sim.write_vcd("blinker_test.vcd"):
893 sim.run()