f8e1f20f00d0577426b09aaf2ee17cca4caffbd3
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")
61 for i
in range(self
.n_gpio
):
62 name
= "gpio{}".format(i
)
63 temp
.append(Record(name
=name
, layout
=gpio_layout
))
64 self
.gpio_ports
= Array(temp
)
66 def elaborate(self
, platform
):
68 comb
, sync
= m
.d
.comb
, m
.d
.sync
71 wb_rd_data
= bus
.dat_r
72 wb_wr_data
= bus
.dat_w
75 gpio_ports
= self
.gpio_ports
77 # MultiCSR read and write buses
79 for i
in range(self
.wordsize
):
80 name
= "rd_word%d" % i
81 rd_multi
.append(Record(name
=name
, layout
=csrbus_layout
))
84 for i
in range(self
.wordsize
):
85 name
= "wr_word%d" % i
86 wr_multi
.append(Record(name
=name
, layout
=csrbus_layout
))
88 # Connecting intermediate signals to the WB data buses
89 # allows the use of Records/Layouts
90 # Split the WB data into bytes for use with individual GPIOs
91 comb
+= Cat(*wr_multi
).eq(wb_wr_data
)
92 # Connect GPIO config bytes to form a single word
93 comb
+= wb_rd_data
.eq(Cat(*rd_multi
))
94 for i
in range(len(bus
.sel
)):
95 sync
+= rd_multi
[i
].eq(0)
97 # One address used to configure CSR, set output, read input
98 with m
.If(bus
.cyc
& bus
.stb
):
99 with m
.If(bus
.we
): # write
100 # Update the GPIO configs with sent parameters
101 for i
in range(len(bus
.sel
)):
102 GPIO_num
= Signal(16) # fixed for now
103 comb
+= GPIO_num
.eq(bus
.adr
*len(bus
.sel
)+i
)
104 with m
.If(bus
.sel
[i
]):
105 sync
+= gpio_ports
[GPIO_num
].oe
.eq(wr_multi
[i
].oe
)
106 sync
+= gpio_ports
[GPIO_num
].puen
.eq(wr_multi
[i
].puen
)
107 sync
+= gpio_ports
[GPIO_num
].pden
.eq(wr_multi
[i
].pden
)
108 with m
.If (wr_multi
[i
].oe
):
109 sync
+= gpio_ports
[GPIO_num
].o
.eq(wr_multi
[i
].io
)
111 sync
+= gpio_ports
[GPIO_num
].o
.eq(0)
112 sync
+= gpio_ports
[GPIO_num
].bank
.eq(wr_multi
[i
].bank
)
113 with m
.Else(): # read
114 # Update the read multi bus with current GPIO configs
115 # not ack'ing as we need to wait 1 clk cycle before data ready
116 for i
in range(len(bus
.sel
)):
117 GPIO_num
= Signal(16) # fixed for now
118 comb
+= GPIO_num
.eq(bus
.adr
*len(bus
.sel
)+i
)
119 with m
.If(bus
.sel
[i
]):
120 sync
+= rd_multi
[i
].oe
.eq(gpio_ports
[GPIO_num
].oe
)
121 sync
+= rd_multi
[i
].ie
.eq(~gpio_ports
[GPIO_num
].oe
)
122 sync
+= rd_multi
[i
].puen
.eq(gpio_ports
[GPIO_num
].puen
)
123 sync
+= rd_multi
[i
].pden
.eq(gpio_ports
[GPIO_num
].pden
)
124 with m
.If (gpio_ports
[GPIO_num
].oe
):
125 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].o
)
127 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].i
)
128 sync
+= rd_multi
[i
].bank
.eq(gpio_ports
[GPIO_num
].bank
)
129 sync
+= wb_ack
.eq(1) # ack after latching data
136 for field
in self
.bus
.fields
.values():
138 for gpio
in range(len(self
.gpio_ports
)):
139 for field
in self
.gpio_ports
[gpio
].fields
.values():
146 def gpio_test_in_pattern(dut, pattern):
147 num_gpios = len(dut.gpio_ports)
148 print("Test pattern:")
150 for pat in range(0, len(pattern)):
151 for gpio in range(0, num_gpios):
152 yield gpio_set_in_pad(dut, gpio, pattern[pat])
154 temp = yield from gpio_rd_input(dut, gpio)
155 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
156 assert (temp == pattern[pat])
158 if pat == len(pattern):
162 def test_gpio_single(dut
, gpio
, use_random
=True):
169 bank
= randint(0, (2**NUMBANKBITS
)-1)
170 print("Random bank select: {0:b}".format(bank
))
172 bank
= 3 # not special, chose for testing
174 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
178 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
181 # Shadow reg container class
182 class GPIOConfigReg():
183 def __init__(self
, shift_dict
):
184 self
.shift_dict
= shift_dict
186 self
.ie
=1 # By default gpio set as input
193 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
200 self
.pack() # Produce packed byte for sending
202 def set_out(self
, outval
):
204 self
.pack() # Produce packed byte for sending
206 # Take config parameters of specified GPIOs, and combine them to produce
207 # bytes for sending via WB bus
209 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
210 |
(self
.ie
<< self
.shift_dict
['ie'])
211 |
(self
.puen
<< self
.shift_dict
['puen'])
212 |
(self
.pden
<< self
.shift_dict
['pden'])
213 |
(self
.io
<< self
.shift_dict
['io'])
214 |
(self
.bank
<< self
.shift_dict
['bank']))
216 #print("GPIO Packed CSR: {0:x}".format(self.packed))
218 # Object for storing each gpio's config state
221 def __init__(self
, dut
, layout
, wb_bus
):
224 # arrangement of config bits making up csr word
225 self
.csr_layout
= layout
226 self
.shift_dict
= self
._create
_shift
_dict
()
227 self
.n_gpios
= len(self
.dut
.gpio_ports
)
229 # Get the number of bits of the WB sel signal
230 # indicates the number of gpios per address
231 self
.n_gp_per_adr
= len(self
.dut
.bus
.sel
)
232 # Shows if data is byte/half-word/word/qword addressable?
233 self
.granuality
= len(self
.dut
.bus
.dat_w
) // self
.n_gp_per_adr
234 self
.n_rows
= ceil(self
.n_gpios
/ self
.n_gp_per_adr
)
236 for i
in range(self
.n_gpios
):
237 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
239 def print_info(self
):
241 print("GPIO Block Info:")
242 print("Number of GPIOs: %d" % self
.n_gpios
)
243 print("GPIOs per WB data word: %d" % self
.n_gp_per_adr
)
244 print("WB data granuality: %d" % self
.granuality
)
245 print("Number of address rows: %d" % self
.n_rows
)
248 # The shifting of control bits in the configuration word is dependent on the
249 # defined layout. To prevent maintaining the shift constants in a separate
250 # location, the same layout is used to generate a dictionary of bit shifts
251 # with which the configuration word can be produced!
252 def _create_shift_dict(self
):
255 for i
in range(0, len(self
.csr_layout
)):
256 shift_dict
[self
.csr_layout
[i
][0]] = shift
257 shift
+= self
.csr_layout
[i
][1]
261 def _parse_gpio_arg(self
, gpio_str
):
262 # TODO: No input checking!
263 print("Given GPIO/range string: {}".format(gpio_str
))
264 if gpio_str
== "all":
267 elif '-' in gpio_str
:
268 start
, end
= gpio_str
.split('-')
271 if (end
< start
) or (end
> self
.n_gpios
):
272 raise Exception("Second GPIO must be higher than first and"
273 + " must be lower or equal to last available GPIO.")
275 start
= int(gpio_str
)
276 if start
>= self
.n_gpios
:
277 raise Exception("GPIO must be less/equal to last GPIO.")
279 print("Parsed GPIOs {0} until {1}".format(start
, end
))
282 # Take a combined word and update shadow reg's
283 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
284 def update_single_shadow(self
, csr_byte
, gpio
):
285 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
286 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
287 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
288 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
289 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
290 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
292 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
293 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
295 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
296 return oe
, ie
, puen
, pden
, io
, bank
298 # Update multiple configuration registers
299 def wr(self
, gp_start
, gp_end
, check
=False):
300 # Some maths to determine how many transactions, and at which
301 # address to start transmitting
302 n_gp_config
= gp_end
- gp_start
303 adr_start
= gp_start
// self
.n_gp_per_adr
304 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
307 # cycle through addresses, each iteration is a WB tx
308 for adr
in range(adr_start
, adr_start
+ n_adr
):
311 # cycle through every WB sel bit, and add configs of
312 # corresponding gpios
313 for i
in range(0, self
.n_gp_per_adr
):
314 # if current gpio's location in the WB data word matches sel bit
315 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
316 print("gpio%d" % curr_gpio
)
318 tx_word
+= (self
.shadow_csr
[curr_gpio
].packed
319 << (self
.granuality
* i
))
321 # stop if we processed all required gpios
322 if curr_gpio
>= gp_end
:
324 print("Adr: %x | Sel: %x | TX Word: %x" % (adr
, tx_sel
, tx_word
))
325 yield from wb_write(self
.wb_bus
, adr
, tx_word
, tx_sel
)
326 yield # Allow one clk cycle to propagate
329 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
330 assert config_word
== read_word
332 def rd(self
, gp_start
, gp_end
):
333 # Some maths to determine how many transactions, and at which
334 # address to start transmitting
335 n_gp_config
= gp_end
- gp_start
336 adr_start
= gp_start
// self
.n_gp_per_adr
337 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
340 # cycle through addresses, each iteration is a WB tx
341 for adr
in range(adr_start
, adr_start
+ n_adr
):
343 # cycle through every WB sel bit, and add configs of
344 # corresponding gpios
345 for i
in range(0, self
.n_gp_per_adr
):
346 # if current gpio's location in the WB data word matches sel bit
347 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
348 print("gpio%d" % curr_gpio
)
351 # stop if we processed all required gpios
352 if curr_gpio
>= gp_end
:
354 print("Adr: %x | Sel: %x " % (adr
, tx_sel
))
355 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
357 mask
= (2**self
.granuality
) - 1
358 for i
in range(self
.n_gp_per_adr
):
359 if ((tx_sel
>> i
) & 1) == 1:
360 single_csr
= (row_word
>> (i
*self
.granuality
)) & mask
361 curr_gpio
= adr
*self
.n_gp_per_adr
+ i
362 #print("rd gpio%d" % curr_gpio)
363 self
.update_single_shadow(single_csr
, curr_gpio
)
365 # Write all shadow registers to GPIO block
366 def wr_all(self
, check
=False):
367 for row
in range(0, self
.n_rows
):
368 yield from self
.wr(0, self
.n_gpios
, check
)
370 # Read all GPIO block row addresses and update shadow reg's
371 def rd_all(self
, check
=False):
372 for row
in range(0, self
.n_rows
):
373 yield from self
.rd(0, self
.n_gpios
)
375 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
376 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
377 # Update the shadow configuration
378 for gpio
in range(start
, end
):
379 # print(oe, ie, puen, pden, outval, bank)
380 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
381 # TODO: only update the required rows?
382 #yield from self.wr_all()
383 yield from self
.wr(start
, end
)
385 # Set/Clear the output bit for single or group of GPIOs
386 def set_out(self
, gpio_str
, outval
):
387 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
388 for gpio
in range(start
, end
):
389 self
.shadow_csr
[gpio
].set_out(outval
)
392 print("Setting GPIO{0} output to {1}".format(start
, outval
))
394 print("Setting GPIOs {0}-{1} output to {2}"
395 .format(start
, end
-1, outval
))
397 yield from self
.wr(start
, end
)
399 def rd_input(self
, gpio_str
):
400 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
401 #read_data = [0] * self.n_rows
402 #for row in range(0, self.n_rows):
403 # read_data[row] = yield from self.rd_row(row)
404 yield from self
.rd(start
, end
)
406 num_to_read
= (end
- start
)
407 read_in
= [0] * num_to_read
409 for i
in range(0, num_to_read
):
410 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
413 print("GPIOs %d until %d, i=%s".format(start
, end
, read_in
))
416 # TODO: There's probably a cleaner way to clear the bit...
417 def sim_set_in_pad(self
, gpio_str
, in_val
):
418 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
419 for gpio
in range(start
, end
):
420 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
422 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
423 .format(gpio
, old_in_val
, in_val
))
424 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
425 yield # Allow one clk cycle to propagate
428 shadow_csr
= [0] * self
.n_gpios
429 for gpio
in range(0, self
.n_gpios
):
430 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
433 for reg
in shadow_csr
:
434 hex_str
+= " "+hex(reg
)
435 print("Shadow reg's: ", hex_str
)
440 def sim_gpio(dut
, use_random
=True):
442 #print(dir(dut.gpio_ports))
443 #print(len(dut.gpio_ports))
445 gpios
= GPIOManager(dut
, csrbus_layout
)
447 # TODO: not working yet
449 #for i in range(0, (num_gpios * 2)):
450 # test_pattern.append(randint(0,1))
451 #yield from gpio_test_in_pattern(dut, test_pattern)
453 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
454 #reg_val = 0xC56271A2
455 #reg_val = 0xFFFFFFFF
456 #yield from reg_write(dut, 0, reg_val)
457 #yield from reg_write(dut, 0, reg_val)
460 #csr_val = yield from wb_read(dut.bus, 0)
461 #print("CSR Val: {0:x}".format(csr_val))
462 print("Finished the simple GPIO block test!")
464 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
465 # GTKWave doc generation
466 wb_data_width
= wordsize
*8
467 n_rows
= ceil(n_gpios
/wordsize
)
470 'in': {'color': 'orange'},
471 'out': {'color': 'yellow'},
472 'debug': {'module': 'top', 'color': 'red'}
475 # Create a trace list, each block expected to be a tuple()
477 wb_traces
= ('Wishbone Bus', [
478 ('gpio_wb__cyc', 'in'),
479 ('gpio_wb__stb', 'in'),
480 ('gpio_wb__we', 'in'),
481 ('gpio_wb__adr[27:0]', 'in'),
482 ('gpio_wb__sel[3:0]', 'in'),
483 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
484 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
485 ('gpio_wb__ack', 'out'),
487 traces
.append(wb_traces
)
489 gpio_internal_traces
= ('Internal', [
494 traces
.append(gpio_internal_traces
)
496 traces
.append({'comment': 'Multi-byte GPIO config read bus'})
497 for word
in range(0, wordsize
):
498 prefix
= "rd_word{}__".format(word
)
501 single_word
.append('Word{}'.format(word
))
502 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
503 word_signals
.append((prefix
+'ie'))
504 word_signals
.append((prefix
+'io'))
505 word_signals
.append((prefix
+'oe'))
506 word_signals
.append((prefix
+'pden'))
507 word_signals
.append((prefix
+'puen'))
508 single_word
.append(word_signals
)
509 traces
.append(tuple(single_word
))
511 traces
.append({'comment': 'Multi-byte GPIO config write bus'})
512 for word
in range(0, wordsize
):
513 prefix
= "wr_word{}__".format(word
)
516 single_word
.append('Word{}'.format(word
))
517 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
518 word_signals
.append((prefix
+'ie'))
519 word_signals
.append((prefix
+'io'))
520 word_signals
.append((prefix
+'oe'))
521 word_signals
.append((prefix
+'pden'))
522 word_signals
.append((prefix
+'puen'))
523 single_word
.append(word_signals
)
524 traces
.append(tuple(single_word
))
526 for gpio
in range(0, n_gpios
):
527 prefix
= "gpio{}__".format(gpio
)
530 single_gpio
.append('GPIO{} Port'.format(gpio
))
531 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
532 gpio_signals
.append( (prefix
+'i', 'in') )
533 gpio_signals
.append( (prefix
+'o', 'out') )
534 gpio_signals
.append( (prefix
+'oe', 'out') )
535 gpio_signals
.append( (prefix
+'pden', 'out') )
536 gpio_signals
.append( (prefix
+'puen', 'out') )
537 single_gpio
.append(gpio_signals
)
538 traces
.append(tuple(single_gpio
))
542 #module = "top.xics_icp"
543 module
= "bench.top.xics_icp"
544 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
548 filename
= "test_gpio" # Doesn't include extension
550 wordsize
= 4 # Number of bytes in the WB data word
551 dut
= SimpleGPIO(wordsize
, n_gpios
)
552 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
553 with
open(filename
+".il", "w") as f
:
557 m
.submodules
.xics_icp
= dut
562 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
563 sim
.add_sync_process(wrap(test_gpioman(dut
)))
564 sim_writer
= sim
.write_vcd(filename
+".vcd")
568 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
570 def test_gpioman(dut
):
571 print("------START----------------------")
572 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
574 #gpios._parse_gpio_arg("all")
575 #gpios._parse_gpio_arg("0")
576 #gpios._parse_gpio_arg("1-3")
577 #gpios._parse_gpio_arg("20")
585 yield from gpios
.config("0-1", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
587 yield from gpios
.config("5-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=6)
588 yield from gpios
.set_out("0-1", outval
=1)
590 #yield from gpios.rd_all()
591 yield from gpios
.sim_set_in_pad("6-7", 1)
592 print("----------------------------")
593 yield from gpios
.rd_input("4-7")
597 if __name__
== '__main__':