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