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")
59 self
.wb_rd_data_reg
= Signal(self
.wordsize
*8) # same len as WB bus
61 #print("CSRBUS layout: ", csrbus_layout)
62 # MultiCSR read and write buses
64 for i
in range(self
.wordsize
):
65 temp_str
= "rd_word{}".format(i
)
66 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
67 self
.rd_multicsr
= Array(temp
)
70 for i
in range(self
.wordsize
):
71 temp_str
= "word{}".format(i
)
72 temp
.append(Record(name
=temp_str
, layout
=csrbus_layout
))
73 self
.multicsrbus
= Array(temp
)
76 for i
in range(self
.n_gpio
):
77 temp_str
= "gpio{}".format(i
)
78 temp
.append(Record(name
=temp_str
, layout
=gpio_layout
))
79 self
.gpio_ports
= Array(temp
)
81 def elaborate(self
, platform
):
83 comb
, sync
= m
.d
.comb
, m
.d
.sync
86 wb_rd_data
= bus
.dat_r
87 wb_wr_data
= bus
.dat_w
88 wb_rd_data_reg
= self
.wb_rd_data_reg
91 gpio_ports
= self
.gpio_ports
92 multi
= self
.multicsrbus
93 rd_multi
= self
.rd_multicsr
95 # Flag for indicating rd/wr transactions
96 new_transaction
= Signal(1)
98 # One address used to configure CSR, set output, read input
99 with m
.If(bus
.cyc
& bus
.stb
):
100 sync
+= wb_ack
.eq(1) # always ack, always delayed
101 # TODO: is this needed anymore?
102 sync
+= new_transaction
.eq(1)
103 # Concatinate the GPIO configs that are on the same "row" or
106 for i
in range(0, self
.wordsize
):
107 multi_cat
.append(rd_multi
[i
])
108 sync
+= wb_rd_data_reg
.eq(Cat(multi_cat
))
109 with m
.If(bus
.we
): # write
111 for byte
in range(0, self
.wordsize
):
112 # TODO: wasteful... convert to Cat(), somehow
113 sync
+= multi
[byte
].eq(wb_wr_data
[byte
*8:8+byte
*8])
115 sync
+= new_transaction
.eq(0)
118 with m
.If(wb_ack
): # read (and acked)
119 comb
+= wb_rd_data
.eq(wb_rd_data_reg
)
121 self
.connect_gpio_to_rd_bus(m
, sync
, bus
.adr
, gpio_ports
, rd_multi
)
123 # Only update GPIOs config if a new transaction happened last cycle
124 # (read or write). Always lags from multi csrbus by 1 clk cycle, most
125 # sane way I could think of while using Record().
126 with m
.If(new_transaction
):
127 self
.connect_wr_bus_to_gpio(m
, sync
, bus
.adr
, gpio_ports
, multi
)
131 def connect_wr_bus_to_gpio(self
, module
, domain
, addr
, gp
, multi
):
132 if self
.n_gpio
> self
.wordsize
:
133 print("#GPIOs is greater than, and is a multiple of WB wordsize")
134 # Case where all gpios fit within full words
135 if self
.n_gpio
% self
.wordsize
== 0:
136 for byte
in range(self
.wordsize
):
137 with module
.If(addr
[0]):
138 self
.wr_connect_one_byte(module
, domain
, gp
, multi
,
141 self
.wr_connect_one_byte(module
, domain
, gp
, multi
,
144 # TODO: This is a complex case, not needed atm
145 print("#GPIOs is greater than WB wordsize")
146 print("But not fully fitting in words...")
147 print("NOT IMPLEMENTED THIS CASE")
150 print("#GPIOs is less or equal to WB wordsize (in bytes)")
151 for byte
in range(self
.n_gpio
):
152 self
.wr_connect_one_byte(module
, domain
, gp
, multi
, byte
, 0)
154 def connect_gpio_to_rd_bus(self
, module
, domain
, addr
, gp
, multi
):
155 if self
.n_gpio
> self
.wordsize
:
156 print("#GPIOs is greater than, and is a multiple of WB wordsize")
157 # Case where all gpios fit within full words
158 if self
.n_gpio
% self
.wordsize
== 0:
159 for byte
in range(self
.wordsize
):
160 with module
.If(addr
[0]):
161 self
.rd_connect_one_byte(module
, domain
, gp
, multi
, byte
, self
.wordsize
)
163 self
.rd_connect_one_byte(module
, domain
, gp
, multi
, byte
, 0)
165 # TODO: This is a complex case, not needed atm
166 print("#GPIOs is greater than WB wordsize")
167 print("NOT IMPLEMENTED THIS CASE")
170 print("#GPIOs is less or equal to WB wordsize (in bytes)")
171 for byte
in range(self
.n_gpio
):
172 self
.rd_connect_one_byte(module
, domain
, gp
, multi
, byte
, 0)
174 def rd_connect_one_byte(self
, module
, domain
, gp
, multi
, byte
, offset
):
175 domain
+= multi
[byte
].oe
.eq(gp
[byte
+offset
].oe
)
176 domain
+= multi
[byte
].puen
.eq(gp
[byte
+offset
].puen
)
177 domain
+= multi
[byte
].pden
.eq(gp
[byte
+offset
].pden
)
178 with module
.If(gp
[byte
+offset
].oe
):
179 domain
+= multi
[byte
].ie
.eq(0)
180 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].o
)
182 domain
+= multi
[byte
].ie
.eq(1) # Return GPIO as i by default
183 domain
+= multi
[byte
].io
.eq(gp
[byte
+offset
].i
)
185 domain
+= multi
[byte
].bank
.eq(gp
[byte
+offset
].bank
)
187 def wr_connect_one_byte(self
, module
, domain
, gp
, multi
, byte
, offset
):
188 domain
+= gp
[byte
+offset
].oe
.eq(multi
[byte
].oe
)
189 domain
+= gp
[byte
+offset
].puen
.eq(multi
[byte
].puen
)
190 domain
+= gp
[byte
+offset
].pden
.eq(multi
[byte
].pden
)
191 # prevent output being set if GPIO configured as i
192 # TODO: No checking is done if ie/oe high together
193 with module
.If(multi
[byte
].oe
):
194 domain
+= gp
[byte
+offset
].o
.eq(multi
[byte
].io
)
196 domain
+= gp
[byte
+offset
].o
.eq(0)
197 domain
+= gp
[byte
+offset
].bank
.eq(multi
[byte
].bank
)
201 for field
in self
.bus
.fields
.values():
203 for gpio
in range(len(self
.gpio_ports
)):
204 for field
in self
.gpio_ports
[gpio
].fields
.values():
211 def gpio_test_in_pattern(dut, pattern):
212 num_gpios = len(dut.gpio_ports)
213 print("Test pattern:")
215 for pat in range(0, len(pattern)):
216 for gpio in range(0, num_gpios):
217 yield gpio_set_in_pad(dut, gpio, pattern[pat])
219 temp = yield from gpio_rd_input(dut, gpio)
220 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
221 assert (temp == pattern[pat])
223 if pat == len(pattern):
227 def test_gpio_single(dut
, gpio
, use_random
=True):
234 bank
= randint(0, (2**NUMBANKBITS
)-1)
235 print("Random bank select: {0:b}".format(bank
))
237 bank
= 3 # not special, chose for testing
239 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
243 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
246 # Shadow reg container class
247 class GPIOConfigReg():
248 def __init__(self
, shift_dict
):
249 self
.shift_dict
= shift_dict
258 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
265 self
.pack() # Produce packed byte for sending
267 def set_out(self
, outval
):
269 self
.pack() # Produce packed byte for sending
271 # Take config parameters of specified GPIOs, and combine them to produce
272 # bytes for sending via WB bus
274 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
275 |
(self
.ie
<< self
.shift_dict
['ie'])
276 |
(self
.puen
<< self
.shift_dict
['puen'])
277 |
(self
.pden
<< self
.shift_dict
['pden'])
278 |
(self
.io
<< self
.shift_dict
['io'])
279 |
(self
.bank
<< self
.shift_dict
['bank']))
281 #print("GPIO Packed CSR: {0:x}".format(self.packed))
283 # Object for storing each gpio's config state
286 def __init__(self
, dut
, layout
, wb_bus
):
289 # arrangement of config bits making up csr word
290 self
.csr_layout
= layout
291 self
.shift_dict
= self
._create
_shift
_dict
()
292 self
.n_gpios
= len(self
.dut
.gpio_ports
)
294 # Since GPIO HDL block already has wordsize parameter, use directly
295 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
296 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
297 self
.wordsize
= self
.dut
.wordsize
298 self
.n_rows
= ceil(self
.n_gpios
/ self
.wordsize
)
300 for i
in range(self
.n_gpios
):
301 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
303 def print_info(self
):
305 print("GPIO Block Info:")
306 print("Number of GPIOs: {}".format(self
.n_gpios
))
307 print("WB Data bus width (in bytes): {}".format(self
.wordsize
))
308 print("Number of rows: {}".format(self
.n_rows
))
311 # The shifting of control bits in the configuration word is dependent on the
312 # defined layout. To prevent maintaining the shift constants in a separate
313 # location, the same layout is used to generate a dictionary of bit shifts
314 # with which the configuration word can be produced!
315 def _create_shift_dict(self
):
318 for i
in range(0, len(self
.csr_layout
)):
319 shift_dict
[self
.csr_layout
[i
][0]] = shift
320 shift
+= self
.csr_layout
[i
][1]
324 def _parse_gpio_arg(self
, gpio_str
):
325 # TODO: No input checking!
326 print("Given GPIO/range string: {}".format(gpio_str
))
327 if gpio_str
== "all":
330 elif '-' in gpio_str
:
331 start
, end
= gpio_str
.split('-')
334 if (end
< start
) or (end
> self
.n_gpios
):
335 raise Exception("Second GPIO must be higher than first and"
336 + " must be lower or equal to last available GPIO.")
338 start
= int(gpio_str
)
339 if start
>= self
.n_gpios
:
340 raise Exception("GPIO must be less/equal to last GPIO.")
342 print("Parsed GPIOs {0} until {1}".format(start
, end
))
345 # Take a combined word and update shadow reg's
346 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
347 def update_single_shadow(self
, csr_byte
, gpio
):
348 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
349 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
350 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
351 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
352 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
353 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
355 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
356 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
358 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
359 return oe
, ie
, puen
, pden
, io
, bank
361 def rd_csr(self
, row_start
):
362 row_word
= yield from wb_read(self
.wb_bus
, row_start
)
363 print("Returned CSR: {0:x}".format(row_word
))
366 # Update a single row of configuration registers
367 def wr_row(self
, row_addr
, check
=False):
368 curr_gpio
= row_addr
* self
.wordsize
370 for byte
in range(0, self
.wordsize
):
371 if curr_gpio
>= self
.n_gpios
:
373 config_word
+= self
.shadow_csr
[curr_gpio
].packed
<< (8 * byte
)
374 #print("Reading GPIO{} shadow reg".format(curr_gpio))
376 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
377 .format(config_word
, row_addr
))
378 yield from wb_write(self
.wb_bus
, row_addr
, config_word
)
379 yield # Allow one clk cycle to propagate
382 read_word
= yield from self
.rd_row(row_addr
)
383 assert config_word
== read_word
385 # Read a single address row of GPIO CSRs, and update shadow
386 def rd_row(self
, row_addr
):
387 read_word
= yield from self
.rd_csr(row_addr
)
388 curr_gpio
= row_addr
* self
.wordsize
390 for byte
in range(0, self
.wordsize
):
391 if curr_gpio
>= self
.n_gpios
:
393 single_csr
= (read_word
>> (8 * byte
)) & 0xFF
394 #print("Updating GPIO{0} shadow reg to {1:x}"
395 # .format(curr_gpio, single_csr))
396 self
.update_single_shadow(single_csr
, curr_gpio
)
400 # Write all shadow registers to GPIO block
401 def wr_all(self
, check
=False):
402 for row
in range(0, self
.n_rows
):
403 yield from self
.wr_row(row
, check
)
405 # Read all GPIO block row addresses and update shadow reg's
406 def rd_all(self
, check
=False):
407 for row
in range(0, self
.n_rows
):
408 yield from self
.rd_row(row
, check
)
410 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
411 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
412 # Update the shadow configuration
413 for gpio
in range(start
, end
):
414 # print(oe, ie, puen, pden, outval, bank)
415 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
416 # TODO: only update the required rows?
417 yield from self
.wr_all()
419 # Set/Clear the output bit for single or group of GPIOs
420 def set_out(self
, gpio_str
, outval
):
421 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
422 for gpio
in range(start
, end
):
423 self
.shadow_csr
[gpio
].set_out(outval
)
426 print("Setting GPIO{0} output to {1}".format(start
, outval
))
428 print("Setting GPIOs {0}-{1} output to {2}"
429 .format(start
, end
-1, outval
))
431 yield from self
.wr_all()
433 def rd_input(self
, gpio_str
): # REWORK
434 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
436 # Too difficult to think about, just read all configs
437 #start_row = floor(start / self.wordsize)
438 # Hack because end corresponds to range limit, but maybe on same row
440 #end_row = floor( (end-1) / self.wordsize) + 1
441 read_data
= [0] * self
.n_rows
442 for row
in range(0, self
.n_rows
):
443 read_data
[row
] = yield from self
.rd_row(row
)
445 num_to_read
= (end
- start
)
446 read_in
= [0] * num_to_read
448 for i
in range(0, num_to_read
):
449 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
452 print("GPIOs {0} until {1}, i={2}".format(start
, end
, read_in
))
455 # TODO: There's probably a cleaner way to clear the bit...
456 def sim_set_in_pad(self
, gpio_str
, in_val
):
457 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
458 for gpio
in range(start
, end
):
459 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
461 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
462 .format(gpio
, old_in_val
, in_val
))
463 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
464 yield # Allow one clk cycle to propagate
467 shadow_csr
= [0] * self
.n_gpios
468 for gpio
in range(0, self
.n_gpios
):
469 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
472 for reg
in shadow_csr
:
473 hex_str
+= " "+hex(reg
)
474 print("Shadow reg's: ", hex_str
)
479 def sim_gpio(dut
, use_random
=True):
481 #print(dir(dut.gpio_ports))
482 #print(len(dut.gpio_ports))
484 gpios
= GPIOManager(dut
, csrbus_layout
)
486 # TODO: not working yet
488 #for i in range(0, (num_gpios * 2)):
489 # test_pattern.append(randint(0,1))
490 #yield from gpio_test_in_pattern(dut, test_pattern)
492 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
493 #reg_val = 0xC56271A2
494 #reg_val = 0xFFFFFFFF
495 #yield from reg_write(dut, 0, reg_val)
496 #yield from reg_write(dut, 0, reg_val)
499 #csr_val = yield from wb_read(dut.bus, 0)
500 #print("CSR Val: {0:x}".format(csr_val))
501 print("Finished the simple GPIO block test!")
503 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
504 # GTKWave doc generation
505 wb_data_width
= wordsize
*8
506 n_rows
= ceil(n_gpios
/wordsize
)
509 'in': {'color': 'orange'},
510 'out': {'color': 'yellow'},
511 'debug': {'module': 'top', 'color': 'red'}
514 # Create a trace list, each block expected to be a tuple()
516 wb_traces
= ('Wishbone Bus', [
517 ('gpio_wb__cyc', 'in'),
518 ('gpio_wb__stb', 'in'),
519 ('gpio_wb__we', 'in'),
520 ('gpio_wb__adr[27:0]', 'in'),
521 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
522 ('wb_rd_data_reg[{}:0]'.format(wb_data_width
-1), ''),
523 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
524 ('gpio_wb__ack', 'out'),
526 traces
.append(wb_traces
)
528 gpio_internal_traces
= ('Internal', [
533 traces
.append(gpio_internal_traces
)
535 traces
.append({'comment': 'Multi-byte GPIO config read bus'})
536 for word
in range(0, wordsize
):
537 prefix
= "rd_word{}__".format(word
)
540 single_word
.append('Word{}'.format(word
))
541 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
542 word_signals
.append((prefix
+'ie'))
543 word_signals
.append((prefix
+'io'))
544 word_signals
.append((prefix
+'oe'))
545 word_signals
.append((prefix
+'pden'))
546 word_signals
.append((prefix
+'puen'))
547 single_word
.append(word_signals
)
548 traces
.append(tuple(single_word
))
550 traces
.append({'comment': 'Multi-byte GPIO config bus'})
551 for word
in range(0, wordsize
):
552 prefix
= "word{}__".format(word
)
555 single_word
.append('Word{}'.format(word
))
556 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
557 word_signals
.append((prefix
+'ie'))
558 word_signals
.append((prefix
+'io'))
559 word_signals
.append((prefix
+'oe'))
560 word_signals
.append((prefix
+'pden'))
561 word_signals
.append((prefix
+'puen'))
562 single_word
.append(word_signals
)
563 traces
.append(tuple(single_word
))
565 for gpio
in range(0, n_gpios
):
566 prefix
= "gpio{}__".format(gpio
)
569 single_gpio
.append('GPIO{} Port'.format(gpio
))
570 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
571 gpio_signals
.append( (prefix
+'i', 'in') )
572 gpio_signals
.append( (prefix
+'o', 'out') )
573 gpio_signals
.append( (prefix
+'oe', 'out') )
574 gpio_signals
.append( (prefix
+'pden', 'out') )
575 gpio_signals
.append( (prefix
+'puen', 'out') )
576 single_gpio
.append(gpio_signals
)
577 traces
.append(tuple(single_gpio
))
581 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
582 module
="top.xics_icp")
585 filename
= "test_gpio" # Doesn't include extension
587 wordsize
= 4 # Number of bytes in the WB data word
588 dut
= SimpleGPIO(wordsize
, n_gpios
)
589 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
590 with
open(filename
+".il", "w") as f
:
594 m
.submodules
.xics_icp
= dut
599 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
600 sim
.add_sync_process(wrap(test_gpioman(dut
)))
601 sim_writer
= sim
.write_vcd(filename
+".vcd")
605 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
607 def test_gpioman(dut
):
608 print("------START----------------------")
609 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
611 #gpios._parse_gpio_arg("all")
612 #gpios._parse_gpio_arg("0")
613 #gpios._parse_gpio_arg("1-3")
614 #gpios._parse_gpio_arg("20")
622 yield from gpios
.config("0-3", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
624 yield from gpios
.config("4-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=6)
625 yield from gpios
.set_out("0-3", outval
=1)
627 #yield from gpios.rd_all()
628 yield from gpios
.sim_set_in_pad("4-7", 1)
629 print("----------------------------")
630 yield from gpios
.rd_input("4-7")
634 if __name__
== '__main__':