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
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 row_start
= Signal(log2_int(self
.n_gpio
))
88 # Flag for indicating rd/wr transactions
89 new_transaction
= Signal(1)
92 #print("gpio_addr: ", type(gpio_addr))
94 # One address used to configure CSR, set output, read input
95 with m
.If(bus
.cyc
& bus
.stb
):
96 comb
+= wb_ack
.eq(1) # always ack
98 sync
+= row_start
.eq(bus
.adr
* self
.wordsize
)
99 sync
+= new_transaction
.eq(1)
100 with m
.If(bus
.we
): # write
102 for byte
in range(0, self
.wordsize
):
103 sync
+= multi
[byte
].eq(wb_wr_data
[byte
*8:8+byte
*8])
104 with m
.Else(): # read
105 # Concatinate the GPIO configs that are on the same "row" or
108 for i
in range(0, self
.wordsize
):
109 multi_cat
.append(multi
[i
])
110 comb
+= wb_rd_data
.eq(Cat(multi_cat
))
112 sync
+= new_transaction
.eq(0)
113 # Update the state of "io" while no WB transactions
114 for byte
in range(0, self
.wordsize
):
115 with m
.If(gpio_ports
[row_start
+byte
].oe
):
116 sync
+= multi
[byte
].io
.eq(gpio_ports
[row_start
+byte
].o
)
118 sync
+= multi
[byte
].io
.eq(gpio_ports
[row_start
+byte
].i
)
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 for byte
in range(0, self
.wordsize
):
124 sync
+= gpio_ports
[row_start
+byte
].oe
.eq(multi
[byte
].oe
)
125 sync
+= gpio_ports
[row_start
+byte
].puen
.eq(multi
[byte
].puen
)
126 sync
+= gpio_ports
[row_start
+byte
].pden
.eq(multi
[byte
].pden
)
127 # Check to prevent output being set if GPIO configured as input
128 # TODO: No checking is done if ie/oe high together
129 with m
.If(gpio_ports
[row_start
+byte
].oe
):
130 sync
+= gpio_ports
[row_start
+byte
].o
.eq(multi
[byte
].io
)
131 sync
+= gpio_ports
[row_start
+byte
].bank
.eq(multi
[byte
].bank
)
135 for field
in self
.bus
.fields
.values():
137 for gpio
in range(len(self
.gpio_ports
)):
138 for field
in self
.gpio_ports
[gpio
].fields
.values():
144 def gpio_test_in_pattern(dut
, pattern
):
145 num_gpios
= len(dut
.gpio_ports
)
146 print("Test pattern:")
148 for pat
in range(0, len(pattern
)):
149 for gpio
in range(0, num_gpios
):
150 yield from gpio_set_in_pad(dut
, gpio
, pattern
[pat
])
152 temp
= yield from gpio_rd_input(dut
, gpio
)
153 print("Pattern: {0}, Reading {1}".format(pattern
[pat
], temp
))
154 assert (temp
== pattern
[pat
])
156 if pat
== len(pattern
):
159 def test_gpio_single(dut
, gpio
, use_random
=True):
166 bank
= randint(0, (2**NUMBANKBITS
)-1)
167 print("Random bank select: {0:b}".format(bank
))
169 bank
= 3 # not special, chose for testing
171 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
175 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
178 # Shadow reg container class
179 class GPIOConfigReg():
180 def __init__(self
, shift_dict
):
181 self
.shift_dict
= shift_dict
190 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
197 self
.pack() # Produce packed byte for sending
199 def set_out(self
, outval
):
201 self
.pack() # Produce packed byte for sending
203 # Take config parameters of specified GPIOs, and combine them to produce
204 # bytes for sending via WB bus
206 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
207 |
(self
.ie
<< self
.shift_dict
['ie'])
208 |
(self
.puen
<< self
.shift_dict
['puen'])
209 |
(self
.pden
<< self
.shift_dict
['pden'])
210 |
(self
.io
<< self
.shift_dict
['io'])
211 |
(self
.bank
<< self
.shift_dict
['bank']))
213 #print("GPIO Packed CSR: {0:x}".format(self.packed))
215 # Object for storing each gpio's config state
218 def __init__(self
, dut
, layout
, wb_bus
):
221 # arrangement of config bits making up csr word
222 self
.csr_layout
= layout
223 self
.shift_dict
= self
._create
_shift
_dict
()
224 self
.n_gpios
= len(self
.dut
.gpio_ports
)
226 # Since GPIO HDL block already has wordsize parameter, use directly
227 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
228 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
229 self
.wordsize
= self
.dut
.wordsize
230 self
.n_rows
= ceil(self
.n_gpios
/ self
.wordsize
)
232 for i
in range(self
.n_gpios
):
233 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
235 def print_info(self
):
237 print("GPIO Block Info:")
238 print("Number of GPIOs: {}".format(self
.n_gpios
))
239 print("WB Data bus width (in bytes): {}".format(self
.wordsize
))
240 print("Number of rows: {}".format(self
.n_rows
))
243 # The shifting of control bits in the configuration word is dependent on the
244 # defined layout. To prevent maintaining the shift constants in a separate
245 # location, the same layout is used to generate a dictionary of bit shifts
246 # with which the configuration word can be produced!
247 def _create_shift_dict(self
):
250 for i
in range(0, len(self
.csr_layout
)):
251 shift_dict
[self
.csr_layout
[i
][0]] = shift
252 shift
+= self
.csr_layout
[i
][1]
256 def _parse_gpio_arg(self
, gpio_str
):
257 # TODO: No input checking!
258 print("Given GPIO/range string: {}".format(gpio_str
))
259 if gpio_str
== "all":
262 elif '-' in gpio_str
:
263 start
, end
= gpio_str
.split('-')
266 if (end
< start
) or (end
> self
.n_gpios
):
267 raise Exception("Second GPIO must be higher than first and"
268 + " must be lower or equal to last available GPIO.")
270 start
= int(gpio_str
)
271 if start
>= self
.n_gpios
:
272 raise Exception("GPIO must be less/equal to last GPIO.")
274 print("Parsed GPIOs {0} until {1}".format(start
, end
))
277 # Take a combined word and update shadow reg's
278 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
279 def update_single_shadow(self
, csr_byte
, gpio
):
280 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
281 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
282 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
283 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
284 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
285 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
287 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
288 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
290 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
291 return oe
, ie
, puen
, pden
, io
, bank
293 def rd_csr(self
, row_start
):
294 row_word
= yield from wb_read(self
.wb_bus
, row_start
)
295 print("Returned CSR: {0:x}".format(row_word
))
298 # Update a single row of configuration registers
299 def wr_row(self
, row_addr
, check
=False):
300 curr_gpio
= row_addr
* self
.wordsize
302 for byte
in range(0, self
.wordsize
):
303 if curr_gpio
>= self
.n_gpios
:
305 config_word
+= self
.shadow_csr
[curr_gpio
].packed
<< (8 * byte
)
306 #print("Reading GPIO{} shadow reg".format(curr_gpio))
308 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
309 .format(config_word
, row_addr
))
310 yield from wb_write(self
.wb_bus
, row_addr
, config_word
)
311 yield # Allow one clk cycle to propagate
314 read_word
= yield from self
.rd_row(row_addr
)
315 assert config_word
== read_word
317 # Read a single address row of GPIO CSRs, and update shadow
318 def rd_row(self
, row_addr
):
319 read_word
= yield from self
.rd_csr(row_addr
)
320 curr_gpio
= row_addr
* self
.wordsize
322 for byte
in range(0, self
.wordsize
):
323 if curr_gpio
>= self
.n_gpios
:
325 single_csr
= (read_word
>> (8 * byte
)) & 0xFF
326 #print("Updating GPIO{0} shadow reg to {1:x}"
327 # .format(curr_gpio, single_csr))
328 self
.update_single_shadow(single_csr
, curr_gpio
)
332 # Write all shadow registers to GPIO block
333 def wr_all(self
, check
=False):
334 for row
in range(0, self
.n_rows
):
335 yield from self
.wr_row(row
, check
)
337 # Read all GPIO block row addresses and update shadow reg's
338 def rd_all(self
, check
=False):
339 for row
in range(0, self
.n_rows
):
340 yield from self
.rd_row(row
, check
)
342 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
343 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
344 # Update the shadow configuration
345 for gpio
in range(start
, end
):
346 # print(oe, ie, puen, pden, outval, bank)
347 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
348 # TODO: only update the required rows?
349 yield from self
.wr_all()
351 # Set/Clear the output bit for single or group of GPIOs
352 def set_out(self
, gpio_str
, outval
):
353 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
354 for gpio
in range(start
, end
):
355 self
.shadow_csr
[gpio
].set_out(outval
)
358 print("Setting GPIO{0} output to {1}".format(start
, outval
))
360 print("Setting GPIOs {0}-{1} output to {2}"
361 .format(start
, end
-1, outval
))
363 yield from self
.wr_all()
365 def rd_input(self
, gpio_str
): # REWORK
366 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
368 # Too difficult to think about, just read all configs
369 #start_row = floor(start / self.wordsize)
370 # Hack because end corresponds to range limit, but maybe on same row
372 #end_row = floor( (end-1) / self.wordsize) + 1
373 read_data
= [0] * self
.n_rows
374 for row
in range(0, self
.n_rows
):
375 read_data
[row
] = yield from self
.rd_row(row
)
377 num_to_read
= (end
- start
)
378 read_in
= [0] * num_to_read
380 for i
in range(0, num_to_read
):
381 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
384 print("GPIOs {0} until {1}, i={2}".format(start
, end
, read_in
))
387 # TODO: There's probably a cleaner way to clear the bit...
388 def sim_set_in_pad(self
, gpio_str
, in_val
):
389 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
390 for gpio
in range(start
, end
):
391 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
393 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
394 .format(gpio
, old_in_val
, in_val
))
395 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
396 yield # Allow one clk cycle to propagate
399 shadow_csr
= [0] * self
.n_gpios
400 for gpio
in range(0, self
.n_gpios
):
401 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
404 for reg
in shadow_csr
:
405 hex_str
+= " "+hex(reg
)
406 print("Shadow reg's: ", hex_str
)
411 def sim_gpio(dut
, use_random
=True):
413 #print(dir(dut.gpio_ports))
414 #print(len(dut.gpio_ports))
416 gpios
= GPIOManager(dut
, csrbus_layout
)
418 # TODO: not working yet
420 #for i in range(0, (num_gpios * 2)):
421 # test_pattern.append(randint(0,1))
422 #yield from gpio_test_in_pattern(dut, test_pattern)
424 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
425 #reg_val = 0xC56271A2
426 #reg_val = 0xFFFFFFFF
427 #yield from reg_write(dut, 0, reg_val)
428 #yield from reg_write(dut, 0, reg_val)
431 #csr_val = yield from wb_read(dut.bus, 0)
432 #print("CSR Val: {0:x}".format(csr_val))
433 print("Finished the simple GPIO block test!")
435 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
436 # GTKWave doc generation
437 wb_data_width
= wordsize
*8
438 n_rows
= ceil(n_gpios
/wordsize
)
441 'in': {'color': 'orange'},
442 'out': {'color': 'yellow'},
443 'debug': {'module': 'top', 'color': 'red'}
446 # Create a trace list, each block expected to be a tuple()
448 wb_traces
= ('Wishbone Bus', [
449 ('gpio_wb__cyc', 'in'),
450 ('gpio_wb__stb', 'in'),
451 ('gpio_wb__we', 'in'),
452 ('gpio_wb__adr[27:0]', 'in'),
453 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
454 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
455 ('gpio_wb__ack', 'out'),
457 traces
.append(wb_traces
)
459 gpio_internal_traces
= ('Internal', [
465 traces
.append(gpio_internal_traces
)
467 traces
.append({'comment': 'Multi-byte GPIO config bus'})
468 for word
in range(0, wordsize
):
469 prefix
= "word{}__".format(word
)
472 single_word
.append('Word{}'.format(word
))
473 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
474 word_signals
.append((prefix
+'ie'))
475 word_signals
.append((prefix
+'io'))
476 word_signals
.append((prefix
+'oe'))
477 word_signals
.append((prefix
+'pden'))
478 word_signals
.append((prefix
+'puen'))
479 single_word
.append(word_signals
)
480 traces
.append(tuple(single_word
))
482 for gpio
in range(0, n_gpios
):
483 prefix
= "gpio{}__".format(gpio
)
486 single_gpio
.append('GPIO{} Port'.format(gpio
))
487 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
488 gpio_signals
.append( (prefix
+'i', 'in') )
489 gpio_signals
.append( (prefix
+'o', 'out') )
490 gpio_signals
.append( (prefix
+'oe', 'out') )
491 gpio_signals
.append( (prefix
+'pden', 'out') )
492 gpio_signals
.append( (prefix
+'puen', 'out') )
493 single_gpio
.append(gpio_signals
)
494 traces
.append(tuple(single_gpio
))
498 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
499 module
="top.xics_icp")
502 filename
= "test_gpio" # Doesn't include extension
504 wordsize
= 4 # Number of bytes in the WB data word
505 dut
= SimpleGPIO(wordsize
, n_gpios
)
506 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
507 with
open(filename
+".il", "w") as f
:
511 m
.submodules
.xics_icp
= dut
516 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
517 sim
.add_sync_process(wrap(test_gpioman(dut
)))
518 sim_writer
= sim
.write_vcd(filename
+".vcd")
522 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
524 def test_gpioman(dut
):
525 print("------START----------------------")
526 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
528 #gpios._parse_gpio_arg("all")
529 #gpios._parse_gpio_arg("0")
530 gpios
._parse
_gpio
_arg
("1-3")
531 #gpios._parse_gpio_arg("20")
539 yield from gpios
.config("0-3", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
541 yield from gpios
.config("4-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=2)
542 yield from gpios
.set_out("0-3", outval
=1)
544 #yield from gpios.rd_all()
545 yield from gpios
.sim_set_in_pad("4-7", 1)
546 print("----------------------------")
547 yield from gpios
.rd_input("4-7")
551 if __name__
== '__main__':