1 """Simple GPIO peripheral on wishbone
3 This is an extremely simple GPIO peripheral intended for use in XICS
4 testing, however it could also be used as an actual GPIO peripheral
6 Modified for use with pinmux, will probably change the class name later.
8 from random
import randint
9 from math
import ceil
, floor
10 from nmigen
import Elaboratable
, Module
, Signal
, Record
, Array
, Cat
, Const
11 from nmigen
.hdl
.rec
import Layout
12 from nmigen
.utils
import log2_int
13 from nmigen
.cli
import rtlil
14 from soc
.minerva
.wishbone
import make_wb_layout
15 from nmutil
.util
import wrap
16 from soc
.bus
.test
.wb_rw
import wb_read
, wb_write
18 from nmutil
.gtkw
import write_gtkw
22 from nmigen
.sim
.cxxsim
import Simulator
, Settle
24 from nmigen
.sim
import Simulator
, Settle
26 # Layout of 8-bit configuration word:
27 # bank[2:0] i/o | pden puen ien oe
28 NUMBANKBITS
= 3 # max 3 bits, only supporting 4 banks (0-3)
29 csrbus_layout
= (("oe", 1),
37 gpio_layout
= (("i", 1),
45 class SimpleGPIO(Elaboratable
):
47 def __init__(self
, wordsize
=4, n_gpio
=16):
48 print("SimpleGPIO: WB Data # of bytes: {0}, # of GPIOs: {1}"
49 .format(wordsize
, n_gpio
))
50 self
.wordsize
= wordsize
56 spec
.reg_wid
= wordsize
*8 # 32
57 self
.bus
= Record(make_wb_layout(spec
), name
="gpio_wb")
59 #print("CSRBUS layout: ", csrbus_layout)
60 # create array - probably a cleaner way to do this...
62 for i
in range(self
.wordsize
):
63 temp_str
= "word{}".format(i
)
64 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
65 self
.multicsrbus
= Array(temp
)
68 for i
in range(self
.n_gpio
):
69 temp_str
= "gpio{}".format(i
)
70 temp
.append(Record(name
=temp_str
, layout
=gpio_layout
))
71 self
.gpio_ports
= Array(temp
)
73 def elaborate(self
, platform
):
75 comb
, sync
= m
.d
.comb
, m
.d
.sync
78 wb_rd_data
= bus
.dat_r
79 wb_wr_data
= bus
.dat_w
82 gpio_ports
= self
.gpio_ports
83 multi
= self
.multicsrbus
87 # log2_int(1) will give 0, which wouldn't work?
88 if (self
.n_gpio
== 1):
91 row_start
= Signal(log2_int(self
.n_gpio
))
93 # Flag for indicating rd/wr transactions
94 new_transaction
= Signal(1)
97 #print("gpio_addr: ", type(gpio_addr))
99 # One address used to configure CSR, set output, read input
100 with m
.If(bus
.cyc
& bus
.stb
):
101 comb
+= wb_ack
.eq(1) # always ack
103 sync
+= row_start
.eq(bus
.adr
* self
.wordsize
)
104 sync
+= new_transaction
.eq(1)
105 with m
.If(bus
.we
): # write
107 for byte
in range(0, self
.wordsize
):
108 sync
+= multi
[byte
].eq(wb_wr_data
[byte
*8:8+byte
*8])
109 with m
.Else(): # read
110 # Concatinate the GPIO configs that are on the same "row" or
113 for i
in range(0, self
.wordsize
):
114 multi_cat
.append(multi
[i
])
115 comb
+= wb_rd_data
.eq(Cat(multi_cat
))
117 sync
+= new_transaction
.eq(0)
119 # Only update GPIOs config if a new transaction happened last cycle
120 # (read or write). Always lags from multi csrbus by 1 clk cycle, most
121 # sane way I could think of while using Record().
122 with m
.If(new_transaction
):
123 print("#GPIOs is greater than, and is a multiple of WB wordsize")
124 # Case where all gpios fit within full words
125 if self
.n_gpio
% self
.wordsize
== 0:
127 while (gpio
< self
.n_gpio
):
128 for byte
in range(self
.wordsize
):
129 sync
+= gpio_ports
[gpio
].oe
.eq(multi
[byte
].oe
)
130 sync
+= gpio_ports
[gpio
].puen
.eq(multi
[byte
].puen
)
131 sync
+= gpio_ports
[gpio
].pden
.eq(multi
[byte
].pden
)
132 # prevent output being set if GPIO configured as i
133 # TODO: No checking is done if ie/oe high together
134 with m
.If(multi
[byte
].oe
):
135 sync
+= gpio_ports
[gpio
].o
.eq(multi
[byte
].io
)
137 sync
+= multi
[byte
].io
.eq(gpio_ports
[gpio
].i
)
138 sync
+= gpio_ports
[gpio
].bank
.eq(multi
[byte
].bank
)
140 elif self
.n_gpio
> self
.wordsize
:
141 # This is a complex case, not needed atm
142 print("#GPIOs is greater than WB wordsize")
143 print("NOT IMPLEMENTED THIS CASE")
146 print("#GPIOs is less or equal to WB wordsize (in bytes)")
147 for byte
in range(self
.n_gpio
):
148 sync
+= gpio_ports
[byte
].oe
.eq(multi
[byte
].oe
)
149 sync
+= gpio_ports
[byte
].puen
.eq(multi
[byte
].puen
)
150 sync
+= gpio_ports
[byte
].pden
.eq(multi
[byte
].pden
)
151 # Check to prevent output being set if GPIO configured as i
152 # TODO: No checking is done if ie/oe high together
153 with m
.If(multi
[byte
].oe
): # gpio_ports[byte].oe):
154 sync
+= gpio_ports
[byte
].o
.eq(multi
[byte
].io
)
156 sync
+= multi
[byte
].io
.eq(gpio_ports
[byte
].i
)
157 sync
+= gpio_ports
[byte
].bank
.eq(multi
[byte
].bank
)
158 # TODO: need logic for reading gpio config...
160 # print("Copy gpio_ports to multi...")
165 for field
in self
.bus
.fields
.values():
167 for gpio
in range(len(self
.gpio_ports
)):
168 for field
in self
.gpio_ports
[gpio
].fields
.values():
175 def gpio_test_in_pattern(dut, pattern):
176 num_gpios = len(dut.gpio_ports)
177 print("Test pattern:")
179 for pat in range(0, len(pattern)):
180 for gpio in range(0, num_gpios):
181 yield gpio_set_in_pad(dut, gpio, pattern[pat])
183 temp = yield from gpio_rd_input(dut, gpio)
184 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
185 assert (temp == pattern[pat])
187 if pat == len(pattern):
191 def test_gpio_single(dut
, gpio
, use_random
=True):
198 bank
= randint(0, (2**NUMBANKBITS
)-1)
199 print("Random bank select: {0:b}".format(bank
))
201 bank
= 3 # not special, chose for testing
203 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
207 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
210 # Shadow reg container class
211 class GPIOConfigReg():
212 def __init__(self
, shift_dict
):
213 self
.shift_dict
= shift_dict
222 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
229 self
.pack() # Produce packed byte for sending
231 def set_out(self
, outval
):
233 self
.pack() # Produce packed byte for sending
235 # Take config parameters of specified GPIOs, and combine them to produce
236 # bytes for sending via WB bus
238 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
239 |
(self
.ie
<< self
.shift_dict
['ie'])
240 |
(self
.puen
<< self
.shift_dict
['puen'])
241 |
(self
.pden
<< self
.shift_dict
['pden'])
242 |
(self
.io
<< self
.shift_dict
['io'])
243 |
(self
.bank
<< self
.shift_dict
['bank']))
245 #print("GPIO Packed CSR: {0:x}".format(self.packed))
247 # Object for storing each gpio's config state
250 def __init__(self
, dut
, layout
, wb_bus
):
253 # arrangement of config bits making up csr word
254 self
.csr_layout
= layout
255 self
.shift_dict
= self
._create
_shift
_dict
()
256 self
.n_gpios
= len(self
.dut
.gpio_ports
)
258 # Since GPIO HDL block already has wordsize parameter, use directly
259 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
260 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
261 self
.wordsize
= self
.dut
.wordsize
262 self
.n_rows
= ceil(self
.n_gpios
/ self
.wordsize
)
264 for i
in range(self
.n_gpios
):
265 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
267 def print_info(self
):
269 print("GPIO Block Info:")
270 print("Number of GPIOs: {}".format(self
.n_gpios
))
271 print("WB Data bus width (in bytes): {}".format(self
.wordsize
))
272 print("Number of rows: {}".format(self
.n_rows
))
275 # The shifting of control bits in the configuration word is dependent on the
276 # defined layout. To prevent maintaining the shift constants in a separate
277 # location, the same layout is used to generate a dictionary of bit shifts
278 # with which the configuration word can be produced!
279 def _create_shift_dict(self
):
282 for i
in range(0, len(self
.csr_layout
)):
283 shift_dict
[self
.csr_layout
[i
][0]] = shift
284 shift
+= self
.csr_layout
[i
][1]
288 def _parse_gpio_arg(self
, gpio_str
):
289 # TODO: No input checking!
290 print("Given GPIO/range string: {}".format(gpio_str
))
291 if gpio_str
== "all":
294 elif '-' in gpio_str
:
295 start
, end
= gpio_str
.split('-')
298 if (end
< start
) or (end
> self
.n_gpios
):
299 raise Exception("Second GPIO must be higher than first and"
300 + " must be lower or equal to last available GPIO.")
302 start
= int(gpio_str
)
303 if start
>= self
.n_gpios
:
304 raise Exception("GPIO must be less/equal to last GPIO.")
306 print("Parsed GPIOs {0} until {1}".format(start
, end
))
309 # Take a combined word and update shadow reg's
310 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
311 def update_single_shadow(self
, csr_byte
, gpio
):
312 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
313 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
314 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
315 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
316 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
317 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
319 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
320 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
322 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
323 return oe
, ie
, puen
, pden
, io
, bank
325 def rd_csr(self
, row_start
):
326 row_word
= yield from wb_read(self
.wb_bus
, row_start
)
327 print("Returned CSR: {0:x}".format(row_word
))
330 # Update a single row of configuration registers
331 def wr_row(self
, row_addr
, check
=False):
332 curr_gpio
= row_addr
* self
.wordsize
334 for byte
in range(0, self
.wordsize
):
335 if curr_gpio
>= self
.n_gpios
:
337 config_word
+= self
.shadow_csr
[curr_gpio
].packed
<< (8 * byte
)
338 #print("Reading GPIO{} shadow reg".format(curr_gpio))
340 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
341 .format(config_word
, row_addr
))
342 yield from wb_write(self
.wb_bus
, row_addr
, config_word
)
343 yield # Allow one clk cycle to propagate
346 read_word
= yield from self
.rd_row(row_addr
)
347 assert config_word
== read_word
349 # Read a single address row of GPIO CSRs, and update shadow
350 def rd_row(self
, row_addr
):
351 read_word
= yield from self
.rd_csr(row_addr
)
352 curr_gpio
= row_addr
* self
.wordsize
354 for byte
in range(0, self
.wordsize
):
355 if curr_gpio
>= self
.n_gpios
:
357 single_csr
= (read_word
>> (8 * byte
)) & 0xFF
358 #print("Updating GPIO{0} shadow reg to {1:x}"
359 # .format(curr_gpio, single_csr))
360 self
.update_single_shadow(single_csr
, curr_gpio
)
364 # Write all shadow registers to GPIO block
365 def wr_all(self
, check
=False):
366 for row
in range(0, self
.n_rows
):
367 yield from self
.wr_row(row
, check
)
369 # Read all GPIO block row addresses and update shadow reg's
370 def rd_all(self
, check
=False):
371 for row
in range(0, self
.n_rows
):
372 yield from self
.rd_row(row
, check
)
374 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
375 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
376 # Update the shadow configuration
377 for gpio
in range(start
, end
):
378 # print(oe, ie, puen, pden, outval, bank)
379 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
380 # TODO: only update the required rows?
381 yield from self
.wr_all()
383 # Set/Clear the output bit for single or group of GPIOs
384 def set_out(self
, gpio_str
, outval
):
385 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
386 for gpio
in range(start
, end
):
387 self
.shadow_csr
[gpio
].set_out(outval
)
390 print("Setting GPIO{0} output to {1}".format(start
, outval
))
392 print("Setting GPIOs {0}-{1} output to {2}"
393 .format(start
, end
-1, outval
))
395 yield from self
.wr_all()
397 def rd_input(self
, gpio_str
): # REWORK
398 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
400 # Too difficult to think about, just read all configs
401 #start_row = floor(start / self.wordsize)
402 # Hack because end corresponds to range limit, but maybe on same row
404 #end_row = floor( (end-1) / self.wordsize) + 1
405 read_data
= [0] * self
.n_rows
406 for row
in range(0, self
.n_rows
):
407 read_data
[row
] = yield from self
.rd_row(row
)
409 num_to_read
= (end
- start
)
410 read_in
= [0] * num_to_read
412 for i
in range(0, num_to_read
):
413 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
416 print("GPIOs {0} until {1}, i={2}".format(start
, end
, read_in
))
419 # TODO: There's probably a cleaner way to clear the bit...
420 def sim_set_in_pad(self
, gpio_str
, in_val
):
421 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
422 for gpio
in range(start
, end
):
423 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
425 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
426 .format(gpio
, old_in_val
, in_val
))
427 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
428 yield # Allow one clk cycle to propagate
431 shadow_csr
= [0] * self
.n_gpios
432 for gpio
in range(0, self
.n_gpios
):
433 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
436 for reg
in shadow_csr
:
437 hex_str
+= " "+hex(reg
)
438 print("Shadow reg's: ", hex_str
)
443 def sim_gpio(dut
, use_random
=True):
445 #print(dir(dut.gpio_ports))
446 #print(len(dut.gpio_ports))
448 gpios
= GPIOManager(dut
, csrbus_layout
)
450 # TODO: not working yet
452 #for i in range(0, (num_gpios * 2)):
453 # test_pattern.append(randint(0,1))
454 #yield from gpio_test_in_pattern(dut, test_pattern)
456 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
457 #reg_val = 0xC56271A2
458 #reg_val = 0xFFFFFFFF
459 #yield from reg_write(dut, 0, reg_val)
460 #yield from reg_write(dut, 0, reg_val)
463 #csr_val = yield from wb_read(dut.bus, 0)
464 #print("CSR Val: {0:x}".format(csr_val))
465 print("Finished the simple GPIO block test!")
467 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
468 # GTKWave doc generation
469 wb_data_width
= wordsize
*8
470 n_rows
= ceil(n_gpios
/wordsize
)
473 'in': {'color': 'orange'},
474 'out': {'color': 'yellow'},
475 'debug': {'module': 'top', 'color': 'red'}
478 # Create a trace list, each block expected to be a tuple()
480 wb_traces
= ('Wishbone Bus', [
481 ('gpio_wb__cyc', 'in'),
482 ('gpio_wb__stb', 'in'),
483 ('gpio_wb__we', 'in'),
484 ('gpio_wb__adr[27:0]', 'in'),
485 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
486 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
487 ('gpio_wb__ack', 'out'),
489 traces
.append(wb_traces
)
491 gpio_internal_traces
= ('Internal', [
497 traces
.append(gpio_internal_traces
)
499 traces
.append({'comment': 'Multi-byte GPIO config bus'})
500 for word
in range(0, wordsize
):
501 prefix
= "word{}__".format(word
)
504 single_word
.append('Word{}'.format(word
))
505 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
506 word_signals
.append((prefix
+'ie'))
507 word_signals
.append((prefix
+'io'))
508 word_signals
.append((prefix
+'oe'))
509 word_signals
.append((prefix
+'pden'))
510 word_signals
.append((prefix
+'puen'))
511 single_word
.append(word_signals
)
512 traces
.append(tuple(single_word
))
514 for gpio
in range(0, n_gpios
):
515 prefix
= "gpio{}__".format(gpio
)
518 single_gpio
.append('GPIO{} Port'.format(gpio
))
519 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
520 gpio_signals
.append( (prefix
+'i', 'in') )
521 gpio_signals
.append( (prefix
+'o', 'out') )
522 gpio_signals
.append( (prefix
+'oe', 'out') )
523 gpio_signals
.append( (prefix
+'pden', 'out') )
524 gpio_signals
.append( (prefix
+'puen', 'out') )
525 single_gpio
.append(gpio_signals
)
526 traces
.append(tuple(single_gpio
))
530 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
531 module
="top.xics_icp")
534 filename
= "test_gpio" # Doesn't include extension
536 wordsize
= 4 # Number of bytes in the WB data word
537 dut
= SimpleGPIO(wordsize
, n_gpios
)
538 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
539 with
open(filename
+".il", "w") as f
:
543 m
.submodules
.xics_icp
= dut
548 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
549 sim
.add_sync_process(wrap(test_gpioman(dut
)))
550 sim_writer
= sim
.write_vcd(filename
+".vcd")
554 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
556 def test_gpioman(dut
):
557 print("------START----------------------")
558 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
560 #gpios._parse_gpio_arg("all")
561 #gpios._parse_gpio_arg("0")
562 gpios
._parse
_gpio
_arg
("1-3")
563 #gpios._parse_gpio_arg("20")
571 yield from gpios
.config("0-3", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
573 yield from gpios
.config("4-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=2)
574 yield from gpios
.set_out("0-3", outval
=1)
576 #yield from gpios.rd_all()
577 yield from gpios
.sim_set_in_pad("4-7", 1)
578 print("----------------------------")
579 yield from gpios
.rd_input("4-7")
583 if __name__
== '__main__':