b739440a178cedbdfa2b881eb689b4b14b454086
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
))
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
+= new_transaction
.eq(1)
102 with m
.If(~bus
.we
): # read
103 # Update the read multi bus with current GPIO configs
104 # not ack'ing as we need to wait 1 clk cycle before data ready
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
+= rd_multi
[i
].oe
.eq(gpio_ports
[GPIO_num
].oe
)
110 sync
+= rd_multi
[i
].ie
.eq(~gpio_ports
[GPIO_num
].oe
)
111 sync
+= rd_multi
[i
].puen
.eq(gpio_ports
[GPIO_num
].puen
)
112 sync
+= rd_multi
[i
].pden
.eq(gpio_ports
[GPIO_num
].pden
)
113 with m
.If (gpio_ports
[GPIO_num
].oe
):
114 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].o
)
116 sync
+= rd_multi
[i
].io
.eq(gpio_ports
[GPIO_num
].i
)
117 sync
+= rd_multi
[i
].bank
.eq(gpio_ports
[GPIO_num
].bank
)
119 sync
+= rd_multi
[i
].oe
.eq(0)
120 sync
+= rd_multi
[i
].ie
.eq(0)
121 sync
+= rd_multi
[i
].puen
.eq(0)
122 sync
+= rd_multi
[i
].pden
.eq(0)
123 sync
+= rd_multi
[i
].io
.eq(0)
124 sync
+= rd_multi
[i
].bank
.eq(0)
125 sync
+= wb_ack
.eq(1) # ack after latching data
127 sync
+= new_transaction
.eq(0)
130 # Delayed from the start of transaction by 1 clk cycle
131 with m
.If(new_transaction
):
132 # Update the GPIO configs with sent parameters
134 for i
in range(len(bus
.sel
)):
135 GPIO_num
= Signal(16) # fixed for now
136 comb
+= GPIO_num
.eq(bus
.adr
*len(bus
.sel
)+i
)
137 with m
.If(bus
.sel
[i
]):
138 sync
+= gpio_ports
[GPIO_num
].oe
.eq(wr_multi
[i
].oe
)
139 sync
+= gpio_ports
[GPIO_num
].puen
.eq(wr_multi
[i
].puen
)
140 sync
+= gpio_ports
[GPIO_num
].pden
.eq(wr_multi
[i
].pden
)
141 with m
.If (wr_multi
[i
].oe
):
142 sync
+= gpio_ports
[GPIO_num
].o
.eq(wr_multi
[i
].io
)
144 sync
+= gpio_ports
[GPIO_num
].o
.eq(0)
145 sync
+= gpio_ports
[GPIO_num
].bank
.eq(wr_multi
[i
].bank
)
146 sync
+= wb_ack
.eq(1) # ack after latching data
147 # No need as rd data is can be outputed on the first clk
149 # sync += wb_ack.eq(1) # Delay ack until rd data is ready!
153 for field
in self
.bus
.fields
.values():
155 for gpio
in range(len(self
.gpio_ports
)):
156 for field
in self
.gpio_ports
[gpio
].fields
.values():
163 def gpio_test_in_pattern(dut, pattern):
164 num_gpios = len(dut.gpio_ports)
165 print("Test pattern:")
167 for pat in range(0, len(pattern)):
168 for gpio in range(0, num_gpios):
169 yield gpio_set_in_pad(dut, gpio, pattern[pat])
171 temp = yield from gpio_rd_input(dut, gpio)
172 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
173 assert (temp == pattern[pat])
175 if pat == len(pattern):
179 def test_gpio_single(dut
, gpio
, use_random
=True):
186 bank
= randint(0, (2**NUMBANKBITS
)-1)
187 print("Random bank select: {0:b}".format(bank
))
189 bank
= 3 # not special, chose for testing
191 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
195 gpio_csr
= yield from gpio_config(dut
, gpio
, oe
, ie
, puen
, pden
, output
,
198 # Shadow reg container class
199 class GPIOConfigReg():
200 def __init__(self
, shift_dict
):
201 self
.shift_dict
= shift_dict
203 self
.ie
=1 # By default gpio set as input
210 def set(self
, oe
=0, ie
=0, puen
=0, pden
=0, io
=0, bank
=0):
217 self
.pack() # Produce packed byte for sending
219 def set_out(self
, outval
):
221 self
.pack() # Produce packed byte for sending
223 # Take config parameters of specified GPIOs, and combine them to produce
224 # bytes for sending via WB bus
226 self
.packed
= ((self
.oe
<< self
.shift_dict
['oe'])
227 |
(self
.ie
<< self
.shift_dict
['ie'])
228 |
(self
.puen
<< self
.shift_dict
['puen'])
229 |
(self
.pden
<< self
.shift_dict
['pden'])
230 |
(self
.io
<< self
.shift_dict
['io'])
231 |
(self
.bank
<< self
.shift_dict
['bank']))
233 #print("GPIO Packed CSR: {0:x}".format(self.packed))
235 # Object for storing each gpio's config state
238 def __init__(self
, dut
, layout
, wb_bus
):
241 # arrangement of config bits making up csr word
242 self
.csr_layout
= layout
243 self
.shift_dict
= self
._create
_shift
_dict
()
244 self
.n_gpios
= len(self
.dut
.gpio_ports
)
246 # Get the number of bits of the WB sel signal
247 # indicates the number of gpios per address
248 self
.n_gp_per_adr
= len(self
.dut
.bus
.sel
)
249 # Shows if data is byte/half-word/word/qword addressable?
250 self
.granuality
= len(self
.dut
.bus
.dat_w
) // self
.n_gp_per_adr
251 self
.n_rows
= ceil(self
.n_gpios
/ self
.n_gp_per_adr
)
253 for i
in range(self
.n_gpios
):
254 self
.shadow_csr
.append(GPIOConfigReg(self
.shift_dict
))
256 def print_info(self
):
258 print("GPIO Block Info:")
259 print("Number of GPIOs: %d" % self
.n_gpios
)
260 print("GPIOs per WB data word: %d" % self
.n_gp_per_adr
)
261 print("WB data granuality: %d" % self
.granuality
)
262 print("Number of address rows: %d" % self
.n_rows
)
265 # The shifting of control bits in the configuration word is dependent on the
266 # defined layout. To prevent maintaining the shift constants in a separate
267 # location, the same layout is used to generate a dictionary of bit shifts
268 # with which the configuration word can be produced!
269 def _create_shift_dict(self
):
272 for i
in range(0, len(self
.csr_layout
)):
273 shift_dict
[self
.csr_layout
[i
][0]] = shift
274 shift
+= self
.csr_layout
[i
][1]
278 def _parse_gpio_arg(self
, gpio_str
):
279 # TODO: No input checking!
280 print("Given GPIO/range string: {}".format(gpio_str
))
281 if gpio_str
== "all":
284 elif '-' in gpio_str
:
285 start
, end
= gpio_str
.split('-')
288 if (end
< start
) or (end
> self
.n_gpios
):
289 raise Exception("Second GPIO must be higher than first and"
290 + " must be lower or equal to last available GPIO.")
292 start
= int(gpio_str
)
293 if start
>= self
.n_gpios
:
294 raise Exception("GPIO must be less/equal to last GPIO.")
296 print("Parsed GPIOs {0} until {1}".format(start
, end
))
299 # Take a combined word and update shadow reg's
300 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
301 def update_single_shadow(self
, csr_byte
, gpio
):
302 oe
= (csr_byte
>> self
.shift_dict
['oe']) & 0x1
303 ie
= (csr_byte
>> self
.shift_dict
['ie']) & 0x1
304 puen
= (csr_byte
>> self
.shift_dict
['puen']) & 0x1
305 pden
= (csr_byte
>> self
.shift_dict
['pden']) & 0x1
306 io
= (csr_byte
>> self
.shift_dict
['io']) & 0x1
307 bank
= (csr_byte
>> self
.shift_dict
['bank']) & 0x3
309 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
310 .format(csr_byte
, oe
, ie
, puen
, pden
, io
, bank
))
312 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, io
, bank
)
313 return oe
, ie
, puen
, pden
, io
, bank
315 # Update multiple configuration registers
316 def wr(self
, gp_start
, gp_end
, check
=False):
317 # Some maths to determine how many transactions, and at which
318 # address to start transmitting
319 n_gp_config
= gp_end
- gp_start
320 adr_start
= gp_start
// self
.n_gp_per_adr
321 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
324 # cycle through addresses, each iteration is a WB tx
325 for adr
in range(adr_start
, adr_start
+ n_adr
):
328 # cycle through every WB sel bit, and add configs of
329 # corresponding gpios
330 for i
in range(0, self
.n_gp_per_adr
):
331 # if current gpio's location in the WB data word matches sel bit
332 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
333 print("gpio%d" % curr_gpio
)
335 tx_word
+= (self
.shadow_csr
[curr_gpio
].packed
336 << (self
.granuality
* i
))
338 # stop if we processed all required gpios
339 if curr_gpio
>= gp_end
:
341 print("Adr: %x | Sel: %x | TX Word: %x" % (adr
, tx_sel
, tx_word
))
342 yield from wb_write(self
.wb_bus
, adr
, tx_word
, tx_sel
)
343 yield # Allow one clk cycle to propagate
346 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
347 assert config_word
== read_word
349 def rd(self
, gp_start
, gp_end
):
350 # Some maths to determine how many transactions, and at which
351 # address to start transmitting
352 n_gp_config
= gp_end
- gp_start
353 adr_start
= gp_start
// self
.n_gp_per_adr
354 n_adr
= ceil(n_gp_config
/ self
.n_gp_per_adr
)
357 # cycle through addresses, each iteration is a WB tx
358 for adr
in range(adr_start
, adr_start
+ n_adr
):
360 # cycle through every WB sel bit, and add configs of
361 # corresponding gpios
362 for i
in range(0, self
.n_gp_per_adr
):
363 # if current gpio's location in the WB data word matches sel bit
364 if (curr_gpio
% self
.n_gp_per_adr
) == i
:
365 print("gpio%d" % curr_gpio
)
368 # stop if we processed all required gpios
369 if curr_gpio
>= gp_end
:
371 print("Adr: %x | Sel: %x " % (adr
, tx_sel
))
372 row_word
= yield from wb_read(self
.wb_bus
, adr
, tx_sel
)
374 mask
= (2**self
.granuality
) - 1
375 for i
in range(self
.n_gp_per_adr
):
376 if ((tx_sel
>> i
) & 1) == 1:
377 single_csr
= (row_word
>> (i
*self
.granuality
)) & mask
378 curr_gpio
= adr
*self
.n_gp_per_adr
+ i
379 #print("rd gpio%d" % curr_gpio)
380 self
.update_single_shadow(single_csr
, curr_gpio
)
382 # Write all shadow registers to GPIO block
383 def wr_all(self
, check
=False):
384 for row
in range(0, self
.n_rows
):
385 yield from self
.wr(0, self
.n_gpios
, check
)
387 # Read all GPIO block row addresses and update shadow reg's
388 def rd_all(self
, check
=False):
389 for row
in range(0, self
.n_rows
):
390 yield from self
.rd(0, self
.n_gpios
)
392 def config(self
, gpio_str
, oe
, ie
, puen
, pden
, outval
, bank
, check
=False):
393 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
394 # Update the shadow configuration
395 for gpio
in range(start
, end
):
396 # print(oe, ie, puen, pden, outval, bank)
397 self
.shadow_csr
[gpio
].set(oe
, ie
, puen
, pden
, outval
, bank
)
398 # TODO: only update the required rows?
399 #yield from self.wr_all()
400 yield from self
.wr(start
, end
)
402 # Set/Clear the output bit for single or group of GPIOs
403 def set_out(self
, gpio_str
, outval
):
404 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
405 for gpio
in range(start
, end
):
406 self
.shadow_csr
[gpio
].set_out(outval
)
409 print("Setting GPIO{0} output to {1}".format(start
, outval
))
411 print("Setting GPIOs {0}-{1} output to {2}"
412 .format(start
, end
-1, outval
))
414 yield from self
.wr(start
, end
)
416 def rd_input(self
, gpio_str
):
417 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
418 #read_data = [0] * self.n_rows
419 #for row in range(0, self.n_rows):
420 # read_data[row] = yield from self.rd_row(row)
421 yield from self
.rd(start
, end
)
423 num_to_read
= (end
- start
)
424 read_in
= [0] * num_to_read
426 for i
in range(0, num_to_read
):
427 read_in
[i
] = self
.shadow_csr
[curr_gpio
].io
430 print("GPIOs %d until %d, i=%s".format(start
, end
, read_in
))
433 # TODO: There's probably a cleaner way to clear the bit...
434 def sim_set_in_pad(self
, gpio_str
, in_val
):
435 start
, end
= self
._parse
_gpio
_arg
(gpio_str
)
436 for gpio
in range(start
, end
):
437 old_in_val
= yield self
.dut
.gpio_ports
[gpio
].i
439 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
440 .format(gpio
, old_in_val
, in_val
))
441 yield self
.dut
.gpio_ports
[gpio
].i
.eq(in_val
)
442 yield # Allow one clk cycle to propagate
445 shadow_csr
= [0] * self
.n_gpios
446 for gpio
in range(0, self
.n_gpios
):
447 shadow_csr
[gpio
] = self
.shadow_csr
[gpio
].packed
450 for reg
in shadow_csr
:
451 hex_str
+= " "+hex(reg
)
452 print("Shadow reg's: ", hex_str
)
457 def sim_gpio(dut
, use_random
=True):
459 #print(dir(dut.gpio_ports))
460 #print(len(dut.gpio_ports))
462 gpios
= GPIOManager(dut
, csrbus_layout
)
464 # TODO: not working yet
466 #for i in range(0, (num_gpios * 2)):
467 # test_pattern.append(randint(0,1))
468 #yield from gpio_test_in_pattern(dut, test_pattern)
470 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
471 #reg_val = 0xC56271A2
472 #reg_val = 0xFFFFFFFF
473 #yield from reg_write(dut, 0, reg_val)
474 #yield from reg_write(dut, 0, reg_val)
477 #csr_val = yield from wb_read(dut.bus, 0)
478 #print("CSR Val: {0:x}".format(csr_val))
479 print("Finished the simple GPIO block test!")
481 def gen_gtkw_doc(n_gpios
, wordsize
, filename
):
482 # GTKWave doc generation
483 wb_data_width
= wordsize
*8
484 n_rows
= ceil(n_gpios
/wordsize
)
487 'in': {'color': 'orange'},
488 'out': {'color': 'yellow'},
489 'debug': {'module': 'top', 'color': 'red'}
492 # Create a trace list, each block expected to be a tuple()
494 wb_traces
= ('Wishbone Bus', [
495 ('gpio_wb__cyc', 'in'),
496 ('gpio_wb__stb', 'in'),
497 ('gpio_wb__we', 'in'),
498 ('gpio_wb__adr[27:0]', 'in'),
499 ('gpio_wb__sel[3:0]', 'in'),
500 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width
-1), 'in'),
501 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width
-1), 'out'),
502 ('gpio_wb__ack', 'out'),
504 traces
.append(wb_traces
)
506 gpio_internal_traces
= ('Internal', [
511 traces
.append(gpio_internal_traces
)
513 traces
.append({'comment': 'Multi-byte GPIO config read bus'})
514 for word
in range(0, wordsize
):
515 prefix
= "rd_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 traces
.append({'comment': 'Multi-byte GPIO config write bus'})
529 for word
in range(0, wordsize
):
530 prefix
= "wr_word{}__".format(word
)
533 single_word
.append('Word{}'.format(word
))
534 word_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1)))
535 word_signals
.append((prefix
+'ie'))
536 word_signals
.append((prefix
+'io'))
537 word_signals
.append((prefix
+'oe'))
538 word_signals
.append((prefix
+'pden'))
539 word_signals
.append((prefix
+'puen'))
540 single_word
.append(word_signals
)
541 traces
.append(tuple(single_word
))
543 for gpio
in range(0, n_gpios
):
544 prefix
= "gpio{}__".format(gpio
)
547 single_gpio
.append('GPIO{} Port'.format(gpio
))
548 gpio_signals
.append((prefix
+'bank[{}:0]'.format(NUMBANKBITS
-1), 'out'))
549 gpio_signals
.append( (prefix
+'i', 'in') )
550 gpio_signals
.append( (prefix
+'o', 'out') )
551 gpio_signals
.append( (prefix
+'oe', 'out') )
552 gpio_signals
.append( (prefix
+'pden', 'out') )
553 gpio_signals
.append( (prefix
+'puen', 'out') )
554 single_gpio
.append(gpio_signals
)
555 traces
.append(tuple(single_gpio
))
559 #module = "top.xics_icp"
560 module
= "bench.top.xics_icp"
561 write_gtkw(filename
+".gtkw", filename
+".vcd", traces
, style
,
565 filename
= "test_gpio" # Doesn't include extension
567 wordsize
= 4 # Number of bytes in the WB data word
568 dut
= SimpleGPIO(wordsize
, n_gpios
)
569 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
570 with
open(filename
+".il", "w") as f
:
574 m
.submodules
.xics_icp
= dut
579 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
580 sim
.add_sync_process(wrap(test_gpioman(dut
)))
581 sim_writer
= sim
.write_vcd(filename
+".vcd")
585 gen_gtkw_doc(n_gpios
, wordsize
, filename
)
587 def test_gpioman(dut
):
588 print("------START----------------------")
589 gpios
= GPIOManager(dut
, csrbus_layout
, dut
.bus
)
591 #gpios._parse_gpio_arg("all")
592 #gpios._parse_gpio_arg("0")
593 #gpios._parse_gpio_arg("1-3")
594 #gpios._parse_gpio_arg("20")
602 yield from gpios
.config("0-1", oe
=1, ie
=0, puen
=0, pden
=1, outval
=0, bank
=2)
604 yield from gpios
.config("5-7", oe
=0, ie
=1, puen
=0, pden
=1, outval
=0, bank
=6)
605 yield from gpios
.set_out("0-1", outval
=1)
607 #yield from gpios.rd_all()
608 yield from gpios
.sim_set_in_pad("6-7", 1)
609 print("----------------------------")
610 yield from gpios
.rd_input("4-7")
614 if __name__
== '__main__':