Fixed GPIO block issue that accessed out of bounds Array()
[pinmux.git] / src / spec / simple_gpio.py
1 """Simple GPIO peripheral on wishbone
2
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
5
6 Modified for use with pinmux, will probably change the class name later.
7 """
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
17
18 from nmutil.gtkw import write_gtkw
19
20 cxxsim = False
21 if cxxsim:
22 from nmigen.sim.cxxsim import Simulator, Settle
23 else:
24 from nmigen.sim import Simulator, Settle
25
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),
30 ("ie", 1),
31 ("puen", 1),
32 ("pden", 1),
33 ("io", 1),
34 ("bank", NUMBANKBITS)
35 )
36
37 gpio_layout = (("i", 1),
38 ("oe", 1),
39 ("o", 1),
40 ("puen", 1),
41 ("pden", 1),
42 ("bank", NUMBANKBITS)
43 )
44
45 class SimpleGPIO(Elaboratable):
46
47 def __init__(self, wordsize=4, n_gpio=16):
48 print("SimpleGPIO: WB Data # of bytes: {0}, # of GPIOs: {1}"
49 .format(wordsize, n_gpio))
50 self.wordsize = wordsize
51 self.n_gpio = n_gpio
52 class Spec: pass
53 spec = Spec()
54 spec.addr_wid = 30
55 spec.mask_wid = 4
56 spec.reg_wid = wordsize*8 # 32
57 self.bus = Record(make_wb_layout(spec), name="gpio_wb")
58
59 #print("CSRBUS layout: ", csrbus_layout)
60 # create array - probably a cleaner way to do this...
61 temp = []
62 for i in range(self.wordsize):
63 temp_str = "word{}".format(i)
64 temp.append(Record(name=temp_str, layout=csrbus_layout))
65 self.multicsrbus = Array(temp)
66
67 temp = []
68 for i in range(self.n_gpio):
69 temp_str = "gpio{}".format(i)
70 temp.append(Record(name=temp_str, layout=gpio_layout))
71 self.gpio_ports = Array(temp)
72
73 def elaborate(self, platform):
74 m = Module()
75 comb, sync = m.d.comb, m.d.sync
76
77 bus = self.bus
78 wb_rd_data = bus.dat_r
79 wb_wr_data = bus.dat_w
80 wb_ack = bus.ack
81
82 gpio_ports = self.gpio_ports
83 multi = self.multicsrbus
84
85 comb += wb_ack.eq(0)
86
87 # log2_int(1) will give 0, which wouldn't work?
88 if (self.n_gpio == 1):
89 row_start = Signal(1)
90 else:
91 row_start = Signal(log2_int(self.n_gpio))
92
93 # Flag for indicating rd/wr transactions
94 new_transaction = Signal(1)
95
96 #print("Types:")
97 #print("gpio_addr: ", type(gpio_addr))
98
99 # One address used to configure CSR, set output, read input
100 with m.If(bus.cyc & bus.stb):
101 comb += wb_ack.eq(1) # always ack
102 # Probably wasteful
103 sync += row_start.eq(bus.adr * self.wordsize)
104 sync += new_transaction.eq(1)
105 with m.If(bus.we): # write
106 # Configure CSR
107 for byte in range(0, self.wordsize):
108 sync += multi[byte].eq(wb_wr_data[byte*8:8+byte*8])
109 with m.Else(): # read
110 # Concatinate the GPIO configs that are on the same "row" or
111 # address and send
112 multi_cat = []
113 for i in range(0, self.wordsize):
114 multi_cat.append(multi[i])
115 comb += wb_rd_data.eq(Cat(multi_cat))
116 with m.Else():
117 sync += new_transaction.eq(0)
118
119 # Only update GPIOs config if a new transaction happened last cycle
120 # (read or write). Always lags from multi csrbus by 1 clk cycle, most
121 # sane way I could think of while using Record().
122 with m.If(new_transaction):
123 # This is a complex case, not needed atm
124 if self.n_gpio > self.wordsize:
125 print("NOT IMPLEMENTED THIS CASE")
126 """
127 for byte in range(0, self.wordsize):
128 if ((row_start+byte) < Const(self.n_gpio)):
129 sync += gpio_ports[row+byte].oe.eq(multi[byte].oe)
130 sync += gpio_ports[row+byte].puen.eq(multi[byte].puen)
131 sync += gpio_ports[row+byte].pden.eq(multi[byte].pden)
132 # prevent output being set if GPIO configured as i
133 # TODO: No checking is done if ie/oe high together
134 with m.If(gpio_ports[row+byte].oe):
135 sync += gpio_ports[row+byte].o.eq(multi[byte].io)
136 with m.Else():
137 sync += multi[byte].io.eq(gpio_ports[row+byte].i)
138 sync += gpio_ports[row+byte].bank.eq(multi[byte].bank)
139 """
140 raise
141 else:
142 for byte in range(self.n_gpio):
143 sync += gpio_ports[byte].oe.eq(multi[byte].oe)
144 sync += gpio_ports[byte].puen.eq(multi[byte].puen)
145 sync += gpio_ports[byte].pden.eq(multi[byte].pden)
146 # Check to prevent output being set if GPIO configured as i
147 # TODO: No checking is done if ie/oe high together
148 with m.If(multi[byte].oe): # gpio_ports[byte].oe):
149 sync += gpio_ports[byte].o.eq(multi[byte].io)
150 with m.Else():
151 sync += multi[byte].io.eq(gpio_ports[byte].i)
152 sync += gpio_ports[byte].bank.eq(multi[byte].bank)
153 return m
154
155 def __iter__(self):
156 for field in self.bus.fields.values():
157 yield field
158 for gpio in range(len(self.gpio_ports)):
159 for field in self.gpio_ports[gpio].fields.values():
160 yield field
161
162 def ports(self):
163 return list(self)
164
165 def gpio_test_in_pattern(dut, pattern):
166 num_gpios = len(dut.gpio_ports)
167 print("Test pattern:")
168 print(pattern)
169 for pat in range(0, len(pattern)):
170 for gpio in range(0, num_gpios):
171 yield from gpio_set_in_pad(dut, gpio, pattern[pat])
172 yield
173 temp = yield from gpio_rd_input(dut, gpio)
174 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
175 assert (temp == pattern[pat])
176 pat += 1
177 if pat == len(pattern):
178 break
179
180 def test_gpio_single(dut, gpio, use_random=True):
181 oe = 1
182 ie = 0
183 output = 0
184 puen = 0
185 pden = 0
186 if use_random:
187 bank = randint(0, (2**NUMBANKBITS)-1)
188 print("Random bank select: {0:b}".format(bank))
189 else:
190 bank = 3 # not special, chose for testing
191
192 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
193 bank, check=True)
194 # Enable output
195 output = 1
196 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
197 bank, check=True)
198
199 # Shadow reg container class
200 class GPIOConfigReg():
201 def __init__(self, shift_dict):
202 self.shift_dict = shift_dict
203 self.oe=0
204 self.ie=0
205 self.puen=0
206 self.pden=0
207 self.io=0
208 self.bank=0
209 self.packed=0
210
211 def set(self, oe=0, ie=0, puen=0, pden=0, io=0, bank=0):
212 self.oe=oe
213 self.ie=ie
214 self.puen=puen
215 self.pden=pden
216 self.io=io
217 self.bank=bank
218 self.pack() # Produce packed byte for sending
219
220 def set_out(self, outval):
221 self.io=outval
222 self.pack() # Produce packed byte for sending
223
224 # Take config parameters of specified GPIOs, and combine them to produce
225 # bytes for sending via WB bus
226 def pack(self):
227 self.packed = ((self.oe << self.shift_dict['oe'])
228 | (self.ie << self.shift_dict['ie'])
229 | (self.puen << self.shift_dict['puen'])
230 | (self.pden << self.shift_dict['pden'])
231 | (self.io << self.shift_dict['io'])
232 | (self.bank << self.shift_dict['bank']))
233
234 #print("GPIO Packed CSR: {0:x}".format(self.packed))
235
236 # Object for storing each gpio's config state
237
238 class GPIOManager():
239 def __init__(self, dut, layout, wb_bus):
240 self.dut = dut
241 self.wb_bus = wb_bus
242 # arrangement of config bits making up csr word
243 self.csr_layout = layout
244 self.shift_dict = self._create_shift_dict()
245 self.n_gpios = len(self.dut.gpio_ports)
246 print(dir(self.dut))
247 # Since GPIO HDL block already has wordsize parameter, use directly
248 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
249 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
250 self.wordsize = self.dut.wordsize
251 self.n_rows = ceil(self.n_gpios / self.wordsize)
252 self.shadow_csr = []
253 for i in range(self.n_gpios):
254 self.shadow_csr.append(GPIOConfigReg(self.shift_dict))
255
256 def print_info(self):
257 print("----------")
258 print("GPIO Block Info:")
259 print("Number of GPIOs: {}".format(self.n_gpios))
260 print("WB Data bus width (in bytes): {}".format(self.wordsize))
261 print("Number of rows: {}".format(self.n_rows))
262 print("----------")
263
264 # The shifting of control bits in the configuration word is dependent on the
265 # defined layout. To prevent maintaining the shift constants in a separate
266 # location, the same layout is used to generate a dictionary of bit shifts
267 # with which the configuration word can be produced!
268 def _create_shift_dict(self):
269 shift = 0
270 shift_dict = {}
271 for i in range(0, len(self.csr_layout)):
272 shift_dict[self.csr_layout[i][0]] = shift
273 shift += self.csr_layout[i][1]
274 print(shift_dict)
275 return shift_dict
276
277 def _parse_gpio_arg(self, gpio_str):
278 # TODO: No input checking!
279 print("Given GPIO/range string: {}".format(gpio_str))
280 if gpio_str == "all":
281 start = 0
282 end = self.n_gpios
283 elif '-' in gpio_str:
284 start, end = gpio_str.split('-')
285 start = int(start)
286 end = int(end) + 1
287 if (end < start) or (end > self.n_gpios):
288 raise Exception("Second GPIO must be higher than first and"
289 + " must be lower or equal to last available GPIO.")
290 else:
291 start = int(gpio_str)
292 if start >= self.n_gpios:
293 raise Exception("GPIO must be less/equal to last GPIO.")
294 end = start + 1
295 print("Parsed GPIOs {0} until {1}".format(start, end))
296 return start, end
297
298 # Take a combined word and update shadow reg's
299 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
300 def update_single_shadow(self, csr_byte, gpio):
301 oe = (csr_byte >> self.shift_dict['oe']) & 0x1
302 ie = (csr_byte >> self.shift_dict['ie']) & 0x1
303 puen = (csr_byte >> self.shift_dict['puen']) & 0x1
304 pden = (csr_byte >> self.shift_dict['pden']) & 0x1
305 io = (csr_byte >> self.shift_dict['io']) & 0x1
306 bank = (csr_byte >> self.shift_dict['bank']) & 0x3
307
308 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
309 .format(csr_byte, oe, ie, puen, pden, io, bank))
310
311 self.shadow_csr[gpio].set(oe, ie, puen, pden, io, bank)
312 return oe, ie, puen, pden, io, bank
313
314 def rd_csr(self, row_start):
315 row_word = yield from wb_read(self.wb_bus, row_start)
316 print("Returned CSR: {0:x}".format(row_word))
317 return row_word
318
319 # Update a single row of configuration registers
320 def wr_row(self, row_addr, check=False):
321 curr_gpio = row_addr * self.wordsize
322 config_word = 0
323 for byte in range(0, self.wordsize):
324 if curr_gpio >= self.n_gpios:
325 break
326 config_word += self.shadow_csr[curr_gpio].packed << (8 * byte)
327 #print("Reading GPIO{} shadow reg".format(curr_gpio))
328 curr_gpio += 1
329 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
330 .format(config_word, row_addr))
331 yield from wb_write(self.wb_bus, row_addr, config_word)
332 yield # Allow one clk cycle to propagate
333
334 if(check):
335 read_word = yield from self.rd_row(row_addr)
336 assert config_word == read_word
337
338 # Read a single address row of GPIO CSRs, and update shadow
339 def rd_row(self, row_addr):
340 read_word = yield from self.rd_csr(row_addr)
341 curr_gpio = row_addr * self.wordsize
342 single_csr = 0
343 for byte in range(0, self.wordsize):
344 if curr_gpio >= self.n_gpios:
345 break
346 single_csr = (read_word >> (8 * byte)) & 0xFF
347 #print("Updating GPIO{0} shadow reg to {1:x}"
348 # .format(curr_gpio, single_csr))
349 self.update_single_shadow(single_csr, curr_gpio)
350 curr_gpio += 1
351 return read_word
352
353 # Write all shadow registers to GPIO block
354 def wr_all(self, check=False):
355 for row in range(0, self.n_rows):
356 yield from self.wr_row(row, check)
357
358 # Read all GPIO block row addresses and update shadow reg's
359 def rd_all(self, check=False):
360 for row in range(0, self.n_rows):
361 yield from self.rd_row(row, check)
362
363 def config(self, gpio_str, oe, ie, puen, pden, outval, bank, check=False):
364 start, end = self._parse_gpio_arg(gpio_str)
365 # Update the shadow configuration
366 for gpio in range(start, end):
367 # print(oe, ie, puen, pden, outval, bank)
368 self.shadow_csr[gpio].set(oe, ie, puen, pden, outval, bank)
369 # TODO: only update the required rows?
370 yield from self.wr_all()
371
372 # Set/Clear the output bit for single or group of GPIOs
373 def set_out(self, gpio_str, outval):
374 start, end = self._parse_gpio_arg(gpio_str)
375 for gpio in range(start, end):
376 self.shadow_csr[gpio].set_out(outval)
377
378 if start == end:
379 print("Setting GPIO{0} output to {1}".format(start, outval))
380 else:
381 print("Setting GPIOs {0}-{1} output to {2}"
382 .format(start, end-1, outval))
383
384 yield from self.wr_all()
385
386 def rd_input(self, gpio_str): # REWORK
387 start, end = self._parse_gpio_arg(gpio_str)
388 curr_gpio = 0
389 # Too difficult to think about, just read all configs
390 #start_row = floor(start / self.wordsize)
391 # Hack because end corresponds to range limit, but maybe on same row
392 # TODO: clean
393 #end_row = floor( (end-1) / self.wordsize) + 1
394 read_data = [0] * self.n_rows
395 for row in range(0, self.n_rows):
396 read_data[row] = yield from self.rd_row(row)
397
398 num_to_read = (end - start)
399 read_in = [0] * num_to_read
400 curr_gpio = 0
401 for i in range(0, num_to_read):
402 read_in[i] = self.shadow_csr[curr_gpio].io
403 curr_gpio += 1
404
405 print("GPIOs {0} until {1}, i={2}".format(start, end, read_in))
406 return read_in
407
408 # TODO: There's probably a cleaner way to clear the bit...
409 def sim_set_in_pad(self, gpio_str, in_val):
410 start, end = self._parse_gpio_arg(gpio_str)
411 for gpio in range(start, end):
412 old_in_val = yield self.dut.gpio_ports[gpio].i
413 print(old_in_val)
414 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
415 .format(gpio, old_in_val, in_val))
416 yield self.dut.gpio_ports[gpio].i.eq(in_val)
417 yield # Allow one clk cycle to propagate
418
419 def rd_shadow(self):
420 shadow_csr = [0] * self.n_gpios
421 for gpio in range(0, self.n_gpios):
422 shadow_csr[gpio] = self.shadow_csr[gpio].packed
423
424 hex_str = ""
425 for reg in shadow_csr:
426 hex_str += " "+hex(reg)
427 print("Shadow reg's: ", hex_str)
428
429 return shadow_csr
430
431
432 def sim_gpio(dut, use_random=True):
433 #print(dut)
434 #print(dir(dut.gpio_ports))
435 #print(len(dut.gpio_ports))
436
437 gpios = GPIOManager(dut, csrbus_layout)
438 gpios.print_info()
439 # TODO: not working yet
440 #test_pattern = []
441 #for i in range(0, (num_gpios * 2)):
442 # test_pattern.append(randint(0,1))
443 #yield from gpio_test_in_pattern(dut, test_pattern)
444
445 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
446 #reg_val = 0xC56271A2
447 #reg_val = 0xFFFFFFFF
448 #yield from reg_write(dut, 0, reg_val)
449 #yield from reg_write(dut, 0, reg_val)
450 #yield
451
452 #csr_val = yield from wb_read(dut.bus, 0)
453 #print("CSR Val: {0:x}".format(csr_val))
454 print("Finished the simple GPIO block test!")
455
456 def gen_gtkw_doc(n_gpios, wordsize, filename):
457 # GTKWave doc generation
458 wb_data_width = wordsize*8
459 n_rows = ceil(n_gpios/wordsize)
460 style = {
461 '': {'base': 'hex'},
462 'in': {'color': 'orange'},
463 'out': {'color': 'yellow'},
464 'debug': {'module': 'top', 'color': 'red'}
465 }
466
467 # Create a trace list, each block expected to be a tuple()
468 traces = []
469 wb_traces = ('Wishbone Bus', [
470 ('gpio_wb__cyc', 'in'),
471 ('gpio_wb__stb', 'in'),
472 ('gpio_wb__we', 'in'),
473 ('gpio_wb__adr[27:0]', 'in'),
474 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width-1), 'in'),
475 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width-1), 'out'),
476 ('gpio_wb__ack', 'out'),
477 ])
478 traces.append(wb_traces)
479
480 gpio_internal_traces = ('Internal', [
481 ('clk', 'in'),
482 ('new_transaction'),
483 ('row_start[2:0]'),
484 ('rst', 'in')
485 ])
486 traces.append(gpio_internal_traces)
487
488 traces.append({'comment': 'Multi-byte GPIO config bus'})
489 for word in range(0, wordsize):
490 prefix = "word{}__".format(word)
491 single_word = []
492 word_signals = []
493 single_word.append('Word{}'.format(word))
494 word_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1)))
495 word_signals.append((prefix+'ie'))
496 word_signals.append((prefix+'io'))
497 word_signals.append((prefix+'oe'))
498 word_signals.append((prefix+'pden'))
499 word_signals.append((prefix+'puen'))
500 single_word.append(word_signals)
501 traces.append(tuple(single_word))
502
503 for gpio in range(0, n_gpios):
504 prefix = "gpio{}__".format(gpio)
505 single_gpio = []
506 gpio_signals = []
507 single_gpio.append('GPIO{} Port'.format(gpio))
508 gpio_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1), 'out'))
509 gpio_signals.append( (prefix+'i', 'in') )
510 gpio_signals.append( (prefix+'o', 'out') )
511 gpio_signals.append( (prefix+'oe', 'out') )
512 gpio_signals.append( (prefix+'pden', 'out') )
513 gpio_signals.append( (prefix+'puen', 'out') )
514 single_gpio.append(gpio_signals)
515 traces.append(tuple(single_gpio))
516
517 #print(traces)
518
519 write_gtkw(filename+".gtkw", filename+".vcd", traces, style,
520 module="top.xics_icp")
521
522 def test_gpio():
523 filename = "test_gpio" # Doesn't include extension
524 n_gpios = 8
525 wordsize = 4 # Number of bytes in the WB data word
526 dut = SimpleGPIO(wordsize, n_gpios)
527 vl = rtlil.convert(dut, ports=dut.ports())
528 with open(filename+".il", "w") as f:
529 f.write(vl)
530
531 m = Module()
532 m.submodules.xics_icp = dut
533
534 sim = Simulator(m)
535 sim.add_clock(1e-6)
536
537 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
538 sim.add_sync_process(wrap(test_gpioman(dut)))
539 sim_writer = sim.write_vcd(filename+".vcd")
540 with sim_writer:
541 sim.run()
542
543 gen_gtkw_doc(n_gpios, wordsize, filename)
544
545 def test_gpioman(dut):
546 print("------START----------------------")
547 gpios = GPIOManager(dut, csrbus_layout, dut.bus)
548 gpios.print_info()
549 #gpios._parse_gpio_arg("all")
550 #gpios._parse_gpio_arg("0")
551 gpios._parse_gpio_arg("1-3")
552 #gpios._parse_gpio_arg("20")
553
554 oe = 1
555 ie = 0
556 puen = 0
557 pden = 1
558 outval = 0
559 bank = 3
560 yield from gpios.config("0-3", oe=1, ie=0, puen=0, pden=1, outval=0, bank=2)
561 ie = 1
562 yield from gpios.config("4-7", oe=0, ie=1, puen=0, pden=1, outval=0, bank=2)
563 yield from gpios.set_out("0-3", outval=1)
564
565 #yield from gpios.rd_all()
566 yield from gpios.sim_set_in_pad("4-7", 1)
567 print("----------------------------")
568 yield from gpios.rd_input("4-7")
569
570 gpios.rd_shadow()
571
572 if __name__ == '__main__':
573 test_gpio()
574