a543edcfcd7cc8f7cf26abf89b1508a2d425b06e
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
= "word{}".format(i
)
71 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
72 self
.multicsrbus
= 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 multi
= self
.multicsrbus
91 rd_multi
= self
.rd_multicsr
96 for row
in range(self
.n_rows
):
97 row_const
.append(Const(row
))
99 # log2_int(1) will give 0, which wouldn't work?
100 if (self
.n_gpio
== 1):
101 row_start
= Signal(1)
103 row_start
= Signal(log2_int(self
.n_gpio
))
105 # Flag for indicating rd/wr transactions
106 new_transaction
= Signal(1)
109 #print("gpio_addr: ", type(gpio_addr))
111 # One address used to configure CSR, set output, read input
112 with m
.If(bus
.cyc
& bus
.stb
):
113 comb
+= wb_ack
.eq(1) # always ack
115 sync
+= row_start
.eq(bus
.adr
* self
.wordsize
)
116 sync
+= new_transaction
.eq(1)
117 with m
.If(bus
.we
): # write
119 for byte
in range(0, self
.wordsize
):
120 sync
+= multi
[byte
].eq(wb_wr_data
[byte
*8:8+byte
*8])
121 with m
.Else(): # read
122 # Concatinate the GPIO configs that are on the same "row" or
125 for i
in range(0, self
.wordsize
):
126 multi_cat
.append(rd_multi
[i
])
127 comb
+= wb_rd_data
.eq(Cat(multi_cat
))
129 sync
+= new_transaction
.eq(0)
131 # Only update GPIOs config if a new transaction happened last cycle
132 # (read or write). Always lags from multi csrbus by 1 clk cycle, most
133 # sane way I could think of while using Record().
134 with m
.If(new_transaction
):
135 self
.connect_wr_bus_to_gpio(m
, sync
, bus
.adr
, gpio_ports
, multi
)
136 self
.connect_gpio_to_rd_bus(m
, sync
, bus
.adr
, gpio_ports
, rd_multi
)
138 # print("Copy gpio_ports to multi...")
142 def connect_wr_bus_to_gpio(self
, module
, domain
, addr
, gp
, multi
):
143 if self
.n_gpio
> self
.wordsize
:
144 print("#GPIOs is greater than, and is a multiple of WB wordsize")
145 # Case where all gpios fit within full words
146 if self
.n_gpio
% self
.wordsize
== 0:
147 for row
in range(self
.n_rows
):
148 with module
.If(addr
== Const(row
)):
149 offset
= row
*self
.wordsize
150 for byte
in range(self
.wordsize
):
151 domain
+= gp
[byte
+offset
].oe
.eq(multi
[byte
].oe
)
152 domain
+= gp
[byte
+offset
].puen
.eq(multi
[byte
].puen
)
153 domain
+= gp
[byte
+offset
].pden
.eq(multi
[byte
].pden
)
154 # prevent output being set if GPIO configured as i
155 # TODO: No checking is done if ie/oe high together
156 with module
.If(multi
[byte
].oe
):
157 domain
+= gp
[byte
+offset
].o
.eq(multi
[byte
].io
)
159 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].i
)
160 domain
+= gp
[byte
+offset
].bank
.eq(multi
[byte
].bank
)
162 # TODO: This is a complex case, not needed atm
163 print("#GPIOs is greater than WB wordsize")
164 print("But not fully fitting in words...")
165 print("NOT IMPLEMENTED THIS CASE")
168 print("#GPIOs is less or equal to WB wordsize (in bytes)")
169 for byte
in range(self
.n_gpio
):
170 domain
+= gp
[byte
].oe
.eq(multi
[byte
].oe
)
171 domain
+= gp
[byte
].puen
.eq(multi
[byte
].puen
)
172 domain
+= gp
[byte
].pden
.eq(multi
[byte
].pden
)
173 # Check to prevent output being set if GPIO configured as i
174 # TODO: No checking is done if ie/oe high together
175 with module
.If(multi
[byte
].oe
):
176 domain
+= gp
[byte
].o
.eq(multi
[byte
].io
)
178 domain
+= gp
[byte
].o
.eq(0)
179 domain
+= gp
[byte
].bank
.eq(multi
[byte
].bank
)
181 def connect_gpio_to_rd_bus(self
, module
, domain
, addr
, gp
, multi
):
182 if self
.n_gpio
> self
.wordsize
:
183 print("#GPIOs is greater than, and is a multiple of WB wordsize")
184 # Case where all gpios fit within full words
185 if self
.n_gpio
% self
.wordsize
== 0:
186 for row
in range(self
.n_rows
):
187 with module
.If(addr
== Const(row
)):
188 offset
= row
*self
.wordsize
189 for byte
in range(self
.wordsize
):
190 domain
+= multi
[byte
].oe
.eq(gp
[byte
+offset
].oe
)
191 domain
+= multi
[byte
].puen
.eq(gp
[byte
+offset
].puen
)
192 domain
+= multi
[byte
].pden
.eq(gp
[byte
+offset
].pden
)
193 # prevent output being set if GPIO configured as i
194 # TODO: No checking is done if ie/oe high together
195 with module
.If(gp
[byte
+offset
].oe
):
196 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].o
)
198 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].i
)
199 domain
+= multi
[byte
].bank
.eq(gp
[byte
+offset
].bank
)
201 # TODO: This is a complex case, not needed atm
202 print("#GPIOs is greater than WB wordsize")
203 print("NOT IMPLEMENTED THIS CASE")
206 print("#GPIOs is less or equal to WB wordsize (in bytes)")
207 for byte
in range(self
.n_gpio
):
208 domain
+= multi
[byte
].oe
.eq(gp
[gpio
].oe
)
209 domain
+= multi
[byte
].puen
.eq(gp
[gpio
].puen
)
210 domain
+= multi
[byte
].pden
.eq(gp
[gpio
].pden
)
211 # Check to prevent output being set if GPIO configured as i
212 # TODO: No checking is done if ie/oe high together
213 with module
.If(multi
[byte
].oe
):
214 domain
+= multi
[byte
].io
.eq(gp
[gpio
].o
)
216 domain
+= multi
[byte
].io
.eq(gp
[byte
].i
)
217 domain
+= multi
[byte
].bank
.eq(gp
[gpio
].bank
)
221 for field
in self
.bus
.fields
.values():
223 for gpio
in range(len(self
.gpio_ports
)):
224 for field
in self
.gpio_ports
[gpio
].fields
.values():
231 def gpio_test_in_pattern(dut, pattern):
232 num_gpios = len(dut.gpio_ports)
233 print("Test pattern:")
235 for pat in range(0, len(pattern)):
236 for gpio in range(0, num_gpios):
237 yield gpio_set_in_pad(dut, gpio, pattern[pat])
239 temp = yield from gpio_rd_input(dut, gpio)
240 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
241 assert (temp == pattern[pat])
243 if pat == len(pattern):
247 def test_gpio_single(dut
, gpio
, use_random
=True):
254 bank
= randint(0, (2**NUMBANKBITS
)-1)
255 print("Random bank select: {0:b}".format(bank
))
257 bank
= 3 # not special, chose for testing
259 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
263 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
266 # Shadow reg container class
267 class GPIOConfigReg():
268 def __init__(self
, shift_dict
):
269 self
.shift_dict
= shift_dict
278 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
285 self
.pack() # Produce packed byte for sending
287 def set_out(self
, outval
):
289 self
.pack() # Produce packed byte for sending
291 # Take config parameters of specified GPIOs, and combine them to produce
292 # bytes for sending via WB bus
294 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
295 |
(self
.ie
<< self
.shift_dict
['ie'])
296 |
(self
.puen
<< self
.shift_dict
['puen'])
297 |
(self
.pden
<< self
.shift_dict
['pden'])
298 |
(self
.io
<< self
.shift_dict
['io'])
299 |
(self
.bank
<< self
.shift_dict
['bank']))
301 #print("GPIO Packed CSR: {0:x}".format(self.packed))
303 # Object for storing each gpio's config state
306 def __init__(self
, dut
, layout
, wb_bus
):
309 # arrangement of config bits making up csr word
310 self
.csr_layout
= layout
311 self
.shift_dict
= self
._create
_shift
_dict
()
312 self
.n_gpios
= len(self
.dut
.gpio_ports
)
314 # Since GPIO HDL block already has wordsize parameter, use directly
315 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
316 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
317 self
.wordsize
= self
.dut
.wordsize
318 self
.n_rows
= ceil(self
.n_gpios
/ self
.wordsize
)
320 for i
in range(self
.n_gpios
):
321 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
323 def print_info(self
):
325 print("GPIO Block Info:")
326 print("Number of GPIOs: {}".format(self
.n_gpios
))
327 print("WB Data bus width (in bytes): {}".format(self
.wordsize
))
328 print("Number of rows: {}".format(self
.n_rows
))
331 # The shifting of control bits in the configuration word is dependent on the
332 # defined layout. To prevent maintaining the shift constants in a separate
333 # location, the same layout is used to generate a dictionary of bit shifts
334 # with which the configuration word can be produced!
335 def _create_shift_dict(self
):
338 for i
in range(0, len(self
.csr_layout
)):
339 shift_dict
[self
.csr_layout
[i
][0]] = shift
340 shift
+= self
.csr_layout
[i
][1]
344 def _parse_gpio_arg(self
, gpio_str
):
345 # TODO: No input checking!
346 print("Given GPIO/range string: {}".format(gpio_str
))
347 if gpio_str
== "all":
350 elif '-' in gpio_str
:
351 start
, end
= gpio_str
.split('-')
354 if (end
< start
) or (end
> self
.n_gpios
):
355 raise Exception("Second GPIO must be higher than first and"
356 + " must be lower or equal to last available GPIO.")
358 start
= int(gpio_str
)
359 if start
>= self
.n_gpios
:
360 raise Exception("GPIO must be less/equal to last GPIO.")
362 print("Parsed GPIOs {0} until {1}".format(start
, end
))
365 # Take a combined word and update shadow reg's
366 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
367 def update_single_shadow(self
, csr_byte
, gpio
):
368 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
369 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
370 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
371 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
372 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
373 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
375 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
376 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
378 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
379 return oe
, ie
, puen
, pden
, io
, bank
381 def rd_csr(self
, row_start
):
382 row_word
= yield from wb_read(self
.wb_bus
, row_start
)
383 print("Returned CSR: {0:x}".format(row_word
))
386 # Update a single row of configuration registers
387 def wr_row(self
, row_addr
, check
=False):
388 curr_gpio
= row_addr
* self
.wordsize
390 for byte
in range(0, self
.wordsize
):
391 if curr_gpio
>= self
.n_gpios
:
393 config_word
+= self
.shadow_csr
[curr_gpio
].packed
<< (8 * byte
)
394 #print("Reading GPIO{} shadow reg".format(curr_gpio))
396 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
397 .format(config_word
, row_addr
))
398 yield from wb_write(self
.wb_bus
, row_addr
, config_word
)
399 yield # Allow one clk cycle to propagate
402 read_word
= yield from self
.rd_row(row_addr
)
403 assert config_word
== read_word
405 # Read a single address row of GPIO CSRs, and update shadow
406 def rd_row(self
, row_addr
):
407 read_word
= yield from self
.rd_csr(row_addr
)
408 curr_gpio
= row_addr
* self
.wordsize
410 for byte
in range(0, self
.wordsize
):
411 if curr_gpio
>= self
.n_gpios
:
413 single_csr
= (read_word
>> (8 * byte
)) & 0xFF
414 #print("Updating GPIO{0} shadow reg to {1:x}"
415 # .format(curr_gpio, single_csr))
416 self
.update_single_shadow(single_csr
, curr_gpio
)
420 # Write all shadow registers to GPIO block
421 def wr_all(self
, check
=False):
422 for row
in range(0, self
.n_rows
):
423 yield from self
.wr_row(row
, check
)
425 # Read all GPIO block row addresses and update shadow reg's
426 def rd_all(self
, check
=False):
427 for row
in range(0, self
.n_rows
):
428 yield from self
.rd_row(row
, check
)
430 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
431 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
432 # Update the shadow configuration
433 for gpio
in range(start
, end
):
434 # print(oe, ie, puen, pden, outval, bank)
435 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
436 # TODO: only update the required rows?
437 yield from self
.wr_all()
439 # Set/Clear the output bit for single or group of GPIOs
440 def set_out(self
, gpio_str
, outval
):
441 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
442 for gpio
in range(start
, end
):
443 self
.shadow_csr
[gpio
].set_out(outval
)
446 print("Setting GPIO{0} output to {1}".format(start
, outval
))
448 print("Setting GPIOs {0}-{1} output to {2}"
449 .format(start
, end
-1, outval
))
451 yield from self
.wr_all()
453 def rd_input(self
, gpio_str
): # REWORK
454 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
456 # Too difficult to think about, just read all configs
457 #start_row = floor(start / self.wordsize)
458 # Hack because end corresponds to range limit, but maybe on same row
460 #end_row = floor( (end-1) / self.wordsize) + 1
461 read_data
= [0] * self
.n_rows
462 for row
in range(0, self
.n_rows
):
463 read_data
[row
] = yield from self
.rd_row(row
)
465 num_to_read
= (end
- start
)
466 read_in
= [0] * num_to_read
468 for i
in range(0, num_to_read
):
469 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
472 print("GPIOs {0} until {1}, i={2}".format(start
, end
, read_in
))
475 # TODO: There's probably a cleaner way to clear the bit...
476 def sim_set_in_pad(self
, gpio_str
, in_val
):
477 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
478 for gpio
in range(start
, end
):
479 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
481 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
482 .format(gpio
, old_in_val
, in_val
))
483 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
484 yield # Allow one clk cycle to propagate
487 shadow_csr
= [0] * self
.n_gpios
488 for gpio
in range(0, self
.n_gpios
):
489 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
492 for reg
in shadow_csr
:
493 hex_str
+= " "+hex(reg
)
494 print("Shadow reg's: ", hex_str
)
499 def sim_gpio(dut
, use_random
=True):
501 #print(dir(dut.gpio_ports))
502 #print(len(dut.gpio_ports))
504 gpios
= GPIOManager(dut
, csrbus_layout
)
506 # TODO: not working yet
508 #for i in range(0, (num_gpios * 2)):
509 # test_pattern.append(randint(0,1))
510 #yield from gpio_test_in_pattern(dut, test_pattern)
512 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
513 #reg_val = 0xC56271A2
514 #reg_val = 0xFFFFFFFF
515 #yield from reg_write(dut, 0, reg_val)
516 #yield from reg_write(dut, 0, reg_val)
519 #csr_val = yield from wb_read(dut.bus, 0)
520 #print("CSR Val: {0:x}".format(csr_val))
521 print("Finished the simple GPIO block test!")
523 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
524 # GTKWave doc generation
525 wb_data_width
= wordsize
*8
526 n_rows
= ceil(n_gpios
/wordsize
)
529 'in': {'color': 'orange'},
530 'out': {'color': 'yellow'},
531 'debug': {'module': 'top', 'color': 'red'}
534 # Create a trace list, each block expected to be a tuple()
536 wb_traces
= ('Wishbone Bus', [
537 ('gpio_wb__cyc', 'in'),
538 ('gpio_wb__stb', 'in'),
539 ('gpio_wb__we', 'in'),
540 ('gpio_wb__adr[27:0]', 'in'),
541 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
542 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
543 ('gpio_wb__ack', 'out'),
545 traces
.append(wb_traces
)
547 gpio_internal_traces
= ('Internal', [
553 traces
.append(gpio_internal_traces
)
555 traces
.append({'comment': 'Multi-byte GPIO config bus'})
556 for word
in range(0, wordsize
):
557 prefix
= "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
=2)
630 yield from gpios
.set_out("0-3", outval
=1)
632 #yield from gpios.rd_all()
633 yield from gpios
.sim_set_in_pad("4-7", 1)
634 print("----------------------------")
635 yield from gpios
.rd_input("4-7")
639 if __name__
== '__main__':