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: {0}, #GPIOs: {1}, Rows: {2}"
52 .format(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")
60 #print("CSRBUS layout: ", csrbus_layout)
61 # MultiCSR read and write buses
63 for i
in range(self
.wordsize
):
64 temp_str
= "rd_word{}".format(i
)
65 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
66 self
.rd_multicsr
= Array(temp
)
69 for i
in range(self
.wordsize
):
70 temp_str
= "wr_word{}".format(i
)
71 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
72 self
.wr_multicsr
= Array(temp
)
75 for i
in range(self
.n_gpio
):
76 temp_str
= "gpio{}".format(i
)
77 temp
.append(Record(name
=temp_str
, layout
=gpio_layout
))
78 self
.gpio_ports
= Array(temp
)
80 def elaborate(self
, platform
):
82 comb
, sync
= m
.d
.comb
, m
.d
.sync
85 wb_rd_data
= bus
.dat_r
86 wb_wr_data
= bus
.dat_w
89 gpio_ports
= self
.gpio_ports
90 wr_multi
= self
.wr_multicsr
91 rd_multi
= self
.rd_multicsr
93 # Flag for indicating rd/wr transactions
94 new_transaction
= Signal(1)
96 # One address used to configure CSR, set output, read input
97 with m
.If(bus
.cyc
& bus
.stb
):
98 # TODO: is this needed anymore?
99 sync
+= new_transaction
.eq(1)
101 with m
.If(bus
.we
): # write
102 sync
+= wb_ack
.eq(1) # always ack, always delayed
103 # Split the WB data into bytes for individual GPIOs
104 sync
+= Cat(*wr_multi
).eq(wb_wr_data
)
106 # Update the read multi bus with current GPIO configs
107 # not ack'ing as we need to wait 1 clk cycle before data ready
108 self
.connect_gpio_to_rd_bus(m
, sync
, bus
.adr
, gpio_ports
,
111 sync
+= new_transaction
.eq(0)
114 # Delayed from the start of transaction by 1 clk cycle
115 with m
.If(new_transaction
):
116 # Update the GPIO configs with sent parameters
118 self
.connect_wr_bus_to_gpio(m
, sync
, bus
.adr
, gpio_ports
,
120 sync
+= wb_ack
.eq(0) # stop ack'ing!
121 # Copy the GPIO config data in read multi bus to the WB data bus
125 for i
in range(0, self
.wordsize
):
126 multi_cat
.append(rd_multi
[i
])
127 sync
+= wb_rd_data
.eq(Cat(multi_cat
))
128 sync
+= wb_ack
.eq(1) # Delay ack until rd data is ready!
132 def connect_wr_bus_to_gpio(self
, module
, domain
, addr
, gp
, multi
):
133 if self
.n_gpio
> self
.wordsize
:
134 print("#GPIOs is greater than, and is a multiple of WB wordsize")
135 # Case where all gpios fit within full words
136 if self
.n_gpio
% self
.wordsize
== 0:
137 for byte
in range(self
.wordsize
):
138 with module
.If(addr
[0]):
139 self
.wr_connect_one_byte(module
, domain
, gp
, multi
,
142 self
.wr_connect_one_byte(module
, domain
, gp
, multi
,
145 # TODO: This is a complex case, not needed atm
146 print("#GPIOs is greater than WB wordsize")
147 print("But not fully fitting in words...")
148 print("NOT IMPLEMENTED THIS CASE")
151 print("#GPIOs is less or equal to WB wordsize (in bytes)")
152 for byte
in range(self
.n_gpio
):
153 self
.wr_connect_one_byte(module
, domain
, gp
, multi
, byte
, 0)
155 def connect_gpio_to_rd_bus(self
, module
, domain
, addr
, gp
, multi
):
156 if self
.n_gpio
> self
.wordsize
:
157 print("#GPIOs is greater than, and is a multiple of WB wordsize")
158 # Case where all gpios fit within full words
159 if self
.n_gpio
% self
.wordsize
== 0:
160 for byte
in range(self
.wordsize
):
161 with module
.If(addr
[0]):
162 self
.rd_connect_one_byte(module
, domain
, gp
, multi
,
165 self
.rd_connect_one_byte(module
, domain
, gp
, multi
,
168 # TODO: This is a complex case, not needed atm
169 print("#GPIOs is greater than WB wordsize")
170 print("NOT IMPLEMENTED THIS CASE")
173 print("#GPIOs is less or equal to WB wordsize (in bytes)")
174 for byte
in range(self
.n_gpio
):
175 self
.rd_connect_one_byte(module
, domain
, gp
, multi
, byte
, 0)
177 # Pass a single GPIO config to one byte of the read multi bus
178 # Offset parameter allows to connect multiple GPIO rows to same multi bus.
179 def rd_connect_one_byte(self
, module
, domain
, gp
, multi
, byte
, offset
):
180 domain
+= multi
[byte
].oe
.eq(gp
[byte
+offset
].oe
)
181 domain
+= multi
[byte
].puen
.eq(gp
[byte
+offset
].puen
)
182 domain
+= multi
[byte
].pden
.eq(gp
[byte
+offset
].pden
)
183 with module
.If(gp
[byte
+offset
].oe
):
184 domain
+= multi
[byte
].ie
.eq(0)
185 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].o
)
187 domain
+= multi
[byte
].ie
.eq(1) # Return GPIO as i by default
188 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].i
)
190 domain
+= multi
[byte
].bank
.eq(gp
[byte
+offset
].bank
)
192 # Pass a single CSR byte from write multi bus to one GPIO
193 def wr_connect_one_byte(self
, module
, domain
, gp
, multi
, byte
, offset
):
194 domain
+= gp
[byte
+offset
].oe
.eq(multi
[byte
].oe
)
195 domain
+= gp
[byte
+offset
].puen
.eq(multi
[byte
].puen
)
196 domain
+= gp
[byte
+offset
].pden
.eq(multi
[byte
].pden
)
197 # prevent output being set if GPIO configured as i
198 # TODO: No checking is done if ie/oe high together
199 with module
.If(multi
[byte
].oe
):
200 domain
+= gp
[byte
+offset
].o
.eq(multi
[byte
].io
)
202 domain
+= gp
[byte
+offset
].o
.eq(0) # Clear GPIO o by default
203 domain
+= gp
[byte
+offset
].bank
.eq(multi
[byte
].bank
)
207 for field
in self
.bus
.fields
.values():
209 for gpio
in range(len(self
.gpio_ports
)):
210 for field
in self
.gpio_ports
[gpio
].fields
.values():
217 def gpio_test_in_pattern(dut, pattern):
218 num_gpios = len(dut.gpio_ports)
219 print("Test pattern:")
221 for pat in range(0, len(pattern)):
222 for gpio in range(0, num_gpios):
223 yield gpio_set_in_pad(dut, gpio, pattern[pat])
225 temp = yield from gpio_rd_input(dut, gpio)
226 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
227 assert (temp == pattern[pat])
229 if pat == len(pattern):
233 def test_gpio_single(dut
, gpio
, use_random
=True):
240 bank
= randint(0, (2**NUMBANKBITS
)-1)
241 print("Random bank select: {0:b}".format(bank
))
243 bank
= 3 # not special, chose for testing
245 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
249 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
252 # Shadow reg container class
253 class GPIOConfigReg():
254 def __init__(self
, shift_dict
):
255 self
.shift_dict
= shift_dict
264 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
271 self
.pack() # Produce packed byte for sending
273 def set_out(self
, outval
):
275 self
.pack() # Produce packed byte for sending
277 # Take config parameters of specified GPIOs, and combine them to produce
278 # bytes for sending via WB bus
280 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
281 |
(self
.ie
<< self
.shift_dict
['ie'])
282 |
(self
.puen
<< self
.shift_dict
['puen'])
283 |
(self
.pden
<< self
.shift_dict
['pden'])
284 |
(self
.io
<< self
.shift_dict
['io'])
285 |
(self
.bank
<< self
.shift_dict
['bank']))
287 #print("GPIO Packed CSR: {0:x}".format(self.packed))
289 # Object for storing each gpio's config state
292 def __init__(self
, dut
, layout
, wb_bus
):
295 # arrangement of config bits making up csr word
296 self
.csr_layout
= layout
297 self
.shift_dict
= self
._create
_shift
_dict
()
298 self
.n_gpios
= len(self
.dut
.gpio_ports
)
300 # Since GPIO HDL block already has wordsize parameter, use directly
301 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
302 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
303 self
.wordsize
= self
.dut
.wordsize
304 self
.n_rows
= ceil(self
.n_gpios
/ self
.wordsize
)
306 for i
in range(self
.n_gpios
):
307 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
309 def print_info(self
):
311 print("GPIO Block Info:")
312 print("Number of GPIOs: {}".format(self
.n_gpios
))
313 print("WB Data bus width (in bytes): {}".format(self
.wordsize
))
314 print("Number of rows: {}".format(self
.n_rows
))
317 # The shifting of control bits in the configuration word is dependent on the
318 # defined layout. To prevent maintaining the shift constants in a separate
319 # location, the same layout is used to generate a dictionary of bit shifts
320 # with which the configuration word can be produced!
321 def _create_shift_dict(self
):
324 for i
in range(0, len(self
.csr_layout
)):
325 shift_dict
[self
.csr_layout
[i
][0]] = shift
326 shift
+= self
.csr_layout
[i
][1]
330 def _parse_gpio_arg(self
, gpio_str
):
331 # TODO: No input checking!
332 print("Given GPIO/range string: {}".format(gpio_str
))
333 if gpio_str
== "all":
336 elif '-' in gpio_str
:
337 start
, end
= gpio_str
.split('-')
340 if (end
< start
) or (end
> self
.n_gpios
):
341 raise Exception("Second GPIO must be higher than first and"
342 + " must be lower or equal to last available GPIO.")
344 start
= int(gpio_str
)
345 if start
>= self
.n_gpios
:
346 raise Exception("GPIO must be less/equal to last GPIO.")
348 print("Parsed GPIOs {0} until {1}".format(start
, end
))
351 # Take a combined word and update shadow reg's
352 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
353 def update_single_shadow(self
, csr_byte
, gpio
):
354 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
355 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
356 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
357 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
358 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
359 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
361 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
362 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
364 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
365 return oe
, ie
, puen
, pden
, io
, bank
367 def rd_csr(self
, row_start
):
368 row_word
= yield from wb_read(self
.wb_bus
, row_start
)
369 print("Returned CSR: {0:x}".format(row_word
))
372 # Update a single row of configuration registers
373 def wr_row(self
, row_addr
, check
=False):
374 curr_gpio
= row_addr
* self
.wordsize
376 for byte
in range(0, self
.wordsize
):
377 if curr_gpio
>= self
.n_gpios
:
379 config_word
+= self
.shadow_csr
[curr_gpio
].packed
<< (8 * byte
)
380 #print("Reading GPIO{} shadow reg".format(curr_gpio))
382 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
383 .format(config_word
, row_addr
))
384 yield from wb_write(self
.wb_bus
, row_addr
, config_word
)
385 yield # Allow one clk cycle to propagate
388 read_word
= yield from self
.rd_row(row_addr
)
389 assert config_word
== read_word
391 # Read a single address row of GPIO CSRs, and update shadow
392 def rd_row(self
, row_addr
):
393 read_word
= yield from self
.rd_csr(row_addr
)
394 curr_gpio
= row_addr
* self
.wordsize
396 for byte
in range(0, self
.wordsize
):
397 if curr_gpio
>= self
.n_gpios
:
399 single_csr
= (read_word
>> (8 * byte
)) & 0xFF
400 #print("Updating GPIO{0} shadow reg to {1:x}"
401 # .format(curr_gpio, single_csr))
402 self
.update_single_shadow(single_csr
, curr_gpio
)
406 # Write all shadow registers to GPIO block
407 def wr_all(self
, check
=False):
408 for row
in range(0, self
.n_rows
):
409 yield from self
.wr_row(row
, check
)
411 # Read all GPIO block row addresses and update shadow reg's
412 def rd_all(self
, check
=False):
413 for row
in range(0, self
.n_rows
):
414 yield from self
.rd_row(row
, check
)
416 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
417 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
418 # Update the shadow configuration
419 for gpio
in range(start
, end
):
420 # print(oe, ie, puen, pden, outval, bank)
421 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
422 # TODO: only update the required rows?
423 yield from self
.wr_all()
425 # Set/Clear the output bit for single or group of GPIOs
426 def set_out(self
, gpio_str
, outval
):
427 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
428 for gpio
in range(start
, end
):
429 self
.shadow_csr
[gpio
].set_out(outval
)
432 print("Setting GPIO{0} output to {1}".format(start
, outval
))
434 print("Setting GPIOs {0}-{1} output to {2}"
435 .format(start
, end
-1, outval
))
437 yield from self
.wr_all()
439 def rd_input(self
, gpio_str
): # REWORK
440 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
442 # Too difficult to think about, just read all configs
443 #start_row = floor(start / self.wordsize)
444 # Hack because end corresponds to range limit, but maybe on same row
446 #end_row = floor( (end-1) / self.wordsize) + 1
447 read_data
= [0] * self
.n_rows
448 for row
in range(0, self
.n_rows
):
449 read_data
[row
] = yield from self
.rd_row(row
)
451 num_to_read
= (end
- start
)
452 read_in
= [0] * num_to_read
454 for i
in range(0, num_to_read
):
455 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
458 print("GPIOs {0} until {1}, i={2}".format(start
, end
, read_in
))
461 # TODO: There's probably a cleaner way to clear the bit...
462 def sim_set_in_pad(self
, gpio_str
, in_val
):
463 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
464 for gpio
in range(start
, end
):
465 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
467 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
468 .format(gpio
, old_in_val
, in_val
))
469 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
470 yield # Allow one clk cycle to propagate
473 shadow_csr
= [0] * self
.n_gpios
474 for gpio
in range(0, self
.n_gpios
):
475 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
478 for reg
in shadow_csr
:
479 hex_str
+= " "+hex(reg
)
480 print("Shadow reg's: ", hex_str
)
485 def sim_gpio(dut
, use_random
=True):
487 #print(dir(dut.gpio_ports))
488 #print(len(dut.gpio_ports))
490 gpios
= GPIOManager(dut
, csrbus_layout
)
492 # TODO: not working yet
494 #for i in range(0, (num_gpios * 2)):
495 # test_pattern.append(randint(0,1))
496 #yield from gpio_test_in_pattern(dut, test_pattern)
498 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
499 #reg_val = 0xC56271A2
500 #reg_val = 0xFFFFFFFF
501 #yield from reg_write(dut, 0, reg_val)
502 #yield from reg_write(dut, 0, reg_val)
505 #csr_val = yield from wb_read(dut.bus, 0)
506 #print("CSR Val: {0:x}".format(csr_val))
507 print("Finished the simple GPIO block test!")
509 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
510 # GTKWave doc generation
511 wb_data_width
= wordsize
*8
512 n_rows
= ceil(n_gpios
/wordsize
)
515 'in': {'color': 'orange'},
516 'out': {'color': 'yellow'},
517 'debug': {'module': 'top', 'color': 'red'}
520 # Create a trace list, each block expected to be a tuple()
522 wb_traces
= ('Wishbone Bus', [
523 ('gpio_wb__cyc', 'in'),
524 ('gpio_wb__stb', 'in'),
525 ('gpio_wb__we', 'in'),
526 ('gpio_wb__adr[27:0]', 'in'),
527 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
528 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
529 ('gpio_wb__ack', 'out'),
531 traces
.append(wb_traces
)
533 gpio_internal_traces
= ('Internal', [
538 traces
.append(gpio_internal_traces
)
540 traces
.append({'comment': 'Multi-byte GPIO config read bus'})
541 for word
in range(0, wordsize
):
542 prefix
= "rd_word{}__".format(word
)
545 single_word
.append('Word{}'.format(word
))
546 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
547 word_signals
.append((prefix
+'ie'))
548 word_signals
.append((prefix
+'io'))
549 word_signals
.append((prefix
+'oe'))
550 word_signals
.append((prefix
+'pden'))
551 word_signals
.append((prefix
+'puen'))
552 single_word
.append(word_signals
)
553 traces
.append(tuple(single_word
))
555 traces
.append({'comment': 'Multi-byte GPIO config write bus'})
556 for word
in range(0, wordsize
):
557 prefix
= "wr_word{}__".format(word
)
560 single_word
.append('Word{}'.format(word
))
561 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
562 word_signals
.append((prefix
+'ie'))
563 word_signals
.append((prefix
+'io'))
564 word_signals
.append((prefix
+'oe'))
565 word_signals
.append((prefix
+'pden'))
566 word_signals
.append((prefix
+'puen'))
567 single_word
.append(word_signals
)
568 traces
.append(tuple(single_word
))
570 for gpio
in range(0, n_gpios
):
571 prefix
= "gpio{}__".format(gpio
)
574 single_gpio
.append('GPIO{} Port'.format(gpio
))
575 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
576 gpio_signals
.append( (prefix
+'i', 'in') )
577 gpio_signals
.append( (prefix
+'o', 'out') )
578 gpio_signals
.append( (prefix
+'oe', 'out') )
579 gpio_signals
.append( (prefix
+'pden', 'out') )
580 gpio_signals
.append( (prefix
+'puen', 'out') )
581 single_gpio
.append(gpio_signals
)
582 traces
.append(tuple(single_gpio
))
586 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
587 module
="top.xics_icp")
590 filename
= "test_gpio" # Doesn't include extension
592 wordsize
= 4 # Number of bytes in the WB data word
593 dut
= SimpleGPIO(wordsize
, n_gpios
)
594 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
595 with
open(filename
+".il", "w") as f
:
599 m
.submodules
.xics_icp
= dut
604 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
605 sim
.add_sync_process(wrap(test_gpioman(dut
)))
606 sim_writer
= sim
.write_vcd(filename
+".vcd")
610 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
612 def test_gpioman(dut
):
613 print("------START----------------------")
614 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
616 #gpios._parse_gpio_arg("all")
617 #gpios._parse_gpio_arg("0")
618 #gpios._parse_gpio_arg("1-3")
619 #gpios._parse_gpio_arg("20")
627 yield from gpios
.config("0-3", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
629 yield from gpios
.config("4-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=6)
630 yield from gpios
.set_out("0-1", outval
=1)
632 #yield from gpios.rd_all()
633 yield from gpios
.sim_set_in_pad("6-7", 1)
634 print("----------------------------")
635 yield from gpios
.rd_input("4-7")
639 if __name__
== '__main__':