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 self
.wordsize
= wordsize
50 self
.n_rows
= ceil(self
.n_gpio
/ self
.wordsize
)
51 print("SimpleGPIO: WB Data # of bytes: %d, #GPIOs: %d, Rows: %d" %
52 (self
.wordsize
, self
.n_gpio
, self
.n_rows
))
57 spec
.reg_wid
= wordsize
*8 # 32
58 self
.bus
= Record(make_wb_layout(spec
), name
="gpio_wb")
61 for i
in range(self
.n_gpio
):
63 temp
.append(Record(name
=name
, layout
=gpio_layout
))
64 self
.gpio_ports
= Array(temp
)
66 self
.granuality
= (len(self
.bus
.dat_w
) // len(self
.bus
.sel
))
67 print("Granuality: %d" % self
.granuality
)
68 assert self
.granuality
== 8, "Only byte granuality is supported atm!"
70 def elaborate(self
, platform
):
72 comb
, sync
= m
.d
.comb
, m
.d
.sync
75 wb_rd_data
= bus
.dat_r
76 wb_wr_data
= bus
.dat_w
79 gpio_ports
= self
.gpio_ports
81 # MultiCSR read and write buses
83 for i
in range(self
.wordsize
):
84 name
= "rd_word%d" % i
85 rd_multi
.append(Record(name
=name
, layout
=csrbus_layout
))
88 for i
in range(self
.wordsize
):
89 name
= "wr_word%d" % i
90 wr_multi
.append(Record(name
=name
, layout
=csrbus_layout
))
92 # Connecting intermediate signals to the WB data buses
93 # allows the use of Records/Layouts
94 # Split the WB data into bytes for use with individual GPIOs
95 comb
+= Cat(*wr_multi
).eq(wb_wr_data
)
96 # Connect GPIO config bytes to form a single word
97 comb
+= wb_rd_data
.eq(Cat(*rd_multi
))
98 for i
in range(len(bus
.sel
)):
99 sync
+= rd_multi
[i
].eq(0)
101 # One address used to configure CSR, set output, read input
102 with m
.If(bus
.cyc
& bus
.stb
):
103 with m
.If(bus
.we
): # write
104 # Update the GPIO configs with sent parameters
105 for i
in range(len(bus
.sel
)):
106 GPIO_num
= Signal(16) # fixed for now
107 comb
+= GPIO_num
.eq(bus
.adr
*len(bus
.sel
)+i
)
108 with m
.If(bus
.sel
[i
]):
109 sync
+= gpio_ports
[GPIO_num
].oe
.eq(wr_multi
[i
].oe
)
110 sync
+= gpio_ports
[GPIO_num
].puen
.eq(wr_multi
[i
].puen
)
111 sync
+= gpio_ports
[GPIO_num
].pden
.eq(wr_multi
[i
].pden
)
112 with m
.If (wr_multi
[i
].oe
):
113 sync
+= gpio_ports
[GPIO_num
].o
.eq(wr_multi
[i
].io
)
115 sync
+= gpio_ports
[GPIO_num
].o
.eq(0)
116 sync
+= gpio_ports
[GPIO_num
].bank
.eq(wr_multi
[i
].bank
)
117 with m
.Else(): # read
118 # Update the read multi bus with current GPIO configs
119 # not ack'ing as we need to wait 1 clk cycle before data ready
120 for i
in range(len(bus
.sel
)):
121 GPIO_num
= Signal(16) # fixed for now
122 comb
+= GPIO_num
.eq(bus
.adr
*len(bus
.sel
)+i
)
123 with m
.If(bus
.sel
[i
]):
124 sync
+= rd_multi
[i
].oe
.eq(gpio_ports
[GPIO_num
].oe
)
125 sync
+= rd_multi
[i
].ie
.eq(~gpio_ports
[GPIO_num
].oe
)
126 sync
+= rd_multi
[i
].puen
.eq(gpio_ports
[GPIO_num
].puen
)
127 sync
+= rd_multi
[i
].pden
.eq(gpio_ports
[GPIO_num
].pden
)
128 with m
.If (gpio_ports
[GPIO_num
].oe
):
129 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].o
)
131 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].i
)
132 sync
+= rd_multi
[i
].bank
.eq(gpio_ports
[GPIO_num
].bank
)
133 sync
+= wb_ack
.eq(1) # ack after latching data
140 for field
in self
.bus
.fields
.values():
142 for gpio
in range(len(self
.gpio_ports
)):
143 for field
in self
.gpio_ports
[gpio
].fields
.values():
150 def gpio_test_in_pattern(dut, pattern):
151 num_gpios = len(dut.gpio_ports)
152 print("Test pattern:")
154 for pat in range(0, len(pattern)):
155 for gpio in range(0, num_gpios):
156 yield gpio_set_in_pad(dut, gpio, pattern[pat])
158 temp = yield from gpio_rd_input(dut, gpio)
159 print("Pattern: %x, Reading %x" % (pattern[pat], temp))
160 assert (temp == pattern[pat])
162 if pat == len(pattern):
166 def test_gpio_single(dut
, gpio
, use_random
=True):
173 bank
= randint(0, (2**NUMBANKBITS
)-1)
174 print("Random bank select: %x" % (bank
))
176 bank
= 3 # not special, chose for testing
178 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
182 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
185 # Shadow reg container class
186 class GPIOConfigReg():
187 def __init__(self
, shift_dict
):
188 self
.shift_dict
= shift_dict
190 self
.ie
=1 # By default gpio set as input
197 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
204 self
.pack() # Produce packed byte for sending
206 def set_out(self
, outval
):
208 self
.pack() # Produce packed byte for sending
210 # Take config parameters of specified GPIOs, and combine them to produce
211 # bytes for sending via WB bus
213 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
214 |
(self
.ie
<< self
.shift_dict
['ie'])
215 |
(self
.puen
<< self
.shift_dict
['puen'])
216 |
(self
.pden
<< self
.shift_dict
['pden'])
217 |
(self
.io
<< self
.shift_dict
['io'])
218 |
(self
.bank
<< self
.shift_dict
['bank']))
220 #print("GPIO Packed CSR: {0:x}".format(self.packed))
222 # Object for storing each gpio's config state
225 def __init__(self
, dut
, layout
, wb_bus
):
228 # arrangement of config bits making up csr word
229 self
.csr_layout
= layout
230 self
.shift_dict
= self
._create
_shift
_dict
()
231 self
.n_gpios
= len(self
.dut
.gpio_ports
)
233 # Get the number of bits of the WB sel signal
234 # indicates the number of gpios per address
235 self
.n_gp_per_adr
= len(self
.dut
.bus
.sel
)
236 # Shows if data is byte/half-word/word/qword addressable?
237 self
.granuality
= len(self
.dut
.bus
.dat_w
) // self
.n_gp_per_adr
238 self
.n_rows
= ceil(self
.n_gpios
/ self
.n_gp_per_adr
)
240 for i
in range(self
.n_gpios
):
241 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
243 def print_info(self
):
245 print("GPIO Block Info:")
246 print("Number of GPIOs: %d" % self
.n_gpios
)
247 print("GPIOs per WB data word: %d" % self
.n_gp_per_adr
)
248 print("WB data granuality: %d" % self
.granuality
)
249 print("Number of address rows: %d" % self
.n_rows
)
252 # The shifting of control bits in the configuration word is dependent on the
253 # defined layout. To prevent maintaining the shift constants in a separate
254 # location, the same layout is used to generate a dictionary of bit shifts
255 # with which the configuration word can be produced!
256 def _create_shift_dict(self
):
259 for i
in range(0, len(self
.csr_layout
)):
260 shift_dict
[self
.csr_layout
[i
][0]] = shift
261 shift
+= self
.csr_layout
[i
][1]
265 def _parse_gpio_arg(self
, gpio_str
):
266 # TODO: No input checking!
267 print("Given GPIO/range string: %s" % (gpio_str
))
268 if gpio_str
== "all":
271 elif '-' in gpio_str
:
272 start
, end
= gpio_str
.split('-')
275 if (end
< start
) or (end
> self
.n_gpios
):
276 raise Exception("Second GPIO must be higher than first and"
277 + " must be lower or equal to last available GPIO.")
279 start
= int(gpio_str
)
280 if start
>= self
.n_gpios
:
281 raise Exception("GPIO must be less/equal to last GPIO.")
283 print("Parsed GPIOs %d until %d" % (start
, end
))
286 # Take a combined word and update shadow reg's
287 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
288 def update_single_shadow(self
, csr_byte
, gpio
):
289 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
290 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
291 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
292 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
293 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
294 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
296 print("csr=%02x | oe=%d, ie=%d, puen=%d, pden=%d, io=%d, bank=%x" %
297 (csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
299 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
300 return oe
, ie
, puen
, pden
, io
, bank
302 # Update multiple configuration registers
303 def wr(self
, gp_start
, gp_end
, check
=False):
304 # Some maths to determine how many transactions, and at which
305 # address to start transmitting
306 n_gp_config
= gp_end
- gp_start
307 adr_start
= gp_start
// self
.n_gp_per_adr
308 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
311 # cycle through addresses, each iteration is a WB tx
312 for adr
in range(adr_start
, adr_start
+ n_adr
):
315 # cycle through every WB sel bit, and add configs of
316 # corresponding gpios
317 for i
in range(0, self
.n_gp_per_adr
):
318 # if current gpio's location in the WB data word matches sel bit
319 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
320 print("gpio%d" % curr_gpio
)
322 tx_word
+= (self
.shadow_csr
[curr_gpio
].packed
323 << (self
.granuality
* i
))
325 # stop if we processed all required gpios
326 if curr_gpio
>= gp_end
:
328 print("Adr: %x | Sel: %x | TX Word: %x" % (adr
, tx_sel
, tx_word
))
329 yield from wb_write(self
.wb_bus
, adr
, tx_word
, tx_sel
)
330 yield # Allow one clk cycle to propagate
333 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
334 assert config_word
== read_word
336 def rd(self
, gp_start
, gp_end
):
337 # Some maths to determine how many transactions, and at which
338 # address to start transmitting
339 n_gp_config
= gp_end
- gp_start
340 adr_start
= gp_start
// self
.n_gp_per_adr
341 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
344 # cycle through addresses, each iteration is a WB tx
345 for adr
in range(adr_start
, adr_start
+ n_adr
):
347 # cycle through every WB sel bit, and add configs of
348 # corresponding gpios
349 for i
in range(0, self
.n_gp_per_adr
):
350 # if current gpio's location in the WB data word matches sel bit
351 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
352 print("gpio%d" % curr_gpio
)
355 # stop if we processed all required gpios
356 if curr_gpio
>= gp_end
:
358 print("Adr: %x | Sel: %x " % (adr
, tx_sel
))
359 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
361 mask
= (2**self
.granuality
) - 1
362 for i
in range(self
.n_gp_per_adr
):
363 if ((tx_sel
>> i
) & 1) == 1:
364 single_csr
= (row_word
>> (i
*self
.granuality
)) & mask
365 curr_gpio
= adr
*self
.n_gp_per_adr
+ i
366 #print("rd gpio%d" % curr_gpio)
367 self
.update_single_shadow(single_csr
, curr_gpio
)
369 # Write all shadow registers to GPIO block
370 def wr_all(self
, check
=False):
371 for row
in range(0, self
.n_rows
):
372 yield from self
.wr(0, self
.n_gpios
, check
)
374 # Read all GPIO block row addresses and update shadow reg's
375 def rd_all(self
, check
=False):
376 for row
in range(0, self
.n_rows
):
377 yield from self
.rd(0, self
.n_gpios
)
379 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
380 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
381 # Update the shadow configuration
382 for gpio
in range(start
, end
):
383 # print(oe, ie, puen, pden, outval, bank)
384 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
385 # TODO: only update the required rows?
386 #yield from self.wr_all()
387 yield from self
.wr(start
, end
)
389 # Set/Clear the output bit for single or group of GPIOs
390 def set_out(self
, gpio_str
, outval
):
391 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
392 for gpio
in range(start
, end
):
393 self
.shadow_csr
[gpio
].set_out(outval
)
396 print("Setting GPIO %d output to %d" % (start
, outval
))
398 print("Setting GPIOs %d-%d output to %d" % (start
, end
-1, outval
))
400 yield from self
.wr(start
, end
)
402 def rd_input(self
, gpio_str
):
403 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
404 #read_data = [0] * self.n_rows
405 #for row in range(0, self.n_rows):
406 # read_data[row] = yield from self.rd_row(row)
407 yield from self
.rd(start
, end
)
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 %d until %d, i=%r" % (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 %d Prev i: %x | New i: %x" % (gpio
, old_in_val
, in_val
))
426 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
427 yield # Allow one clk cycle to propagate
430 shadow_csr
= [0] * self
.n_gpios
431 for gpio
in range(0, self
.n_gpios
):
432 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
435 for reg
in shadow_csr
:
436 hex_str
+= " "+hex(reg
)
437 print("Shadow reg's: ", hex_str
)
442 def sim_gpio(dut
, use_random
=True):
444 #print(dir(dut.gpio_ports))
445 #print(len(dut.gpio_ports))
447 gpios
= GPIOManager(dut
, csrbus_layout
)
449 # TODO: not working yet
451 #for i in range(0, (num_gpios * 2)):
452 # test_pattern.append(randint(0,1))
453 #yield from gpio_test_in_pattern(dut, test_pattern)
455 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
456 #reg_val = 0xC56271A2
457 #reg_val = 0xFFFFFFFF
458 #yield from reg_write(dut, 0, reg_val)
459 #yield from reg_write(dut, 0, reg_val)
462 #csr_val = yield from wb_read(dut.bus, 0)
463 #print("CSR Val: {0:x}".format(csr_val))
464 print("Finished the simple GPIO block test!")
466 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
467 # GTKWave doc generation
468 wb_data_width
= wordsize
*8
469 n_rows
= ceil(n_gpios
/wordsize
)
472 'in': {'color': 'orange'},
473 'out': {'color': 'yellow'},
474 'debug': {'module': 'top', 'color': 'red'}
477 # Create a trace list, each block expected to be a tuple()
479 wb_traces
= ('Wishbone Bus', [
480 ('gpio_wb__cyc', 'in'),
481 ('gpio_wb__stb', 'in'),
482 ('gpio_wb__we', 'in'),
483 ('gpio_wb__adr[27:0]', 'in'),
484 ('gpio_wb__sel[3: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', [
496 traces
.append(gpio_internal_traces
)
498 traces
.append({'comment': 'Multi-byte GPIO config read bus'})
499 for word
in range(0, wordsize
):
500 prefix
= "rd_word{}__".format(word
)
503 single_word
.append('Word{}'.format(word
))
504 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
505 word_signals
.append((prefix
+'ie'))
506 word_signals
.append((prefix
+'io'))
507 word_signals
.append((prefix
+'oe'))
508 word_signals
.append((prefix
+'pden'))
509 word_signals
.append((prefix
+'puen'))
510 single_word
.append(word_signals
)
511 traces
.append(tuple(single_word
))
513 traces
.append({'comment': 'Multi-byte GPIO config write bus'})
514 for word
in range(0, wordsize
):
515 prefix
= "wr_word{}__".format(word
)
518 single_word
.append('Word{}'.format(word
))
519 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
520 word_signals
.append((prefix
+'ie'))
521 word_signals
.append((prefix
+'io'))
522 word_signals
.append((prefix
+'oe'))
523 word_signals
.append((prefix
+'pden'))
524 word_signals
.append((prefix
+'puen'))
525 single_word
.append(word_signals
)
526 traces
.append(tuple(single_word
))
528 for gpio
in range(0, n_gpios
):
529 prefix
= "gpio{}__".format(gpio
)
532 single_gpio
.append('GPIO{} Port'.format(gpio
))
533 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
534 gpio_signals
.append( (prefix
+'i', 'in') )
535 gpio_signals
.append( (prefix
+'o', 'out') )
536 gpio_signals
.append( (prefix
+'oe', 'out') )
537 gpio_signals
.append( (prefix
+'pden', 'out') )
538 gpio_signals
.append( (prefix
+'puen', 'out') )
539 single_gpio
.append(gpio_signals
)
540 traces
.append(tuple(single_gpio
))
544 #module = "top.xics_icp"
545 module
= "bench.top.xics_icp"
546 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
550 filename
= "test_gpio" # Doesn't include extension
552 wordsize
= 4 # Number of bytes in the WB data word
553 dut
= SimpleGPIO(wordsize
, n_gpios
)
554 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
555 with
open(filename
+".il", "w") as f
:
559 m
.submodules
.xics_icp
= dut
564 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
565 sim
.add_sync_process(wrap(test_gpioman(dut
)))
566 sim_writer
= sim
.write_vcd(filename
+".vcd")
570 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
572 def test_gpioman(dut
):
573 print("------START----------------------")
574 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
576 #gpios._parse_gpio_arg("all")
577 #gpios._parse_gpio_arg("0")
578 #gpios._parse_gpio_arg("1-3")
579 #gpios._parse_gpio_arg("20")
587 yield from gpios
.config("0-1", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
589 yield from gpios
.config("5-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=6)
590 yield from gpios
.set_out("0-1", outval
=1)
592 #yield from gpios.rd_all()
593 yield from gpios
.sim_set_in_pad("6-7", 1)
594 print("----------------------------")
595 yield from gpios
.rd_input("4-7")
599 if __name__
== '__main__':