ae699a88a9cf95abc8f13bfffb048532329835b3
[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 self.granuality = (len(self.bus.dat_w) // len(self.bus.sel))
67 print("Granuality: %d" % self.granuality)
68 assert self.granuality == 8, "Only byte granuality is supported atm!"
69
70 def elaborate(self, platform):
71 m = Module()
72 comb, sync = m.d.comb, m.d.sync
73
74 bus = self.bus
75 wb_rd_data = bus.dat_r
76 wb_wr_data = bus.dat_w
77 wb_ack = bus.ack
78
79 gpio_ports = self.gpio_ports
80
81 # MultiCSR read and write buses
82 rd_multi = []
83 for i in range(self.wordsize):
84 name = "rd_word%d" % i
85 rd_multi.append(Record(name=name, layout=csrbus_layout))
86
87 wr_multi = []
88 for i in range(self.wordsize):
89 name = "wr_word%d" % i
90 wr_multi.append(Record(name=name, layout=csrbus_layout))
91
92 # Connecting intermediate signals to the WB data buses
93 # allows the use of Records/Layouts
94 # Split the WB data into bytes for use with individual GPIOs
95 comb += Cat(*wr_multi).eq(wb_wr_data)
96 # Connect GPIO config bytes to form a single word
97 comb += wb_rd_data.eq(Cat(*rd_multi))
98 for i in range(len(bus.sel)):
99 sync += rd_multi[i].eq(0)
100
101 # One address used to configure CSR, set output, read input
102 with m.If(bus.cyc & bus.stb):
103 with m.If(bus.we): # write
104 # Update the GPIO configs with sent parameters
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 += gpio_ports[GPIO_num].oe.eq(wr_multi[i].oe)
110 sync += gpio_ports[GPIO_num].puen.eq(wr_multi[i].puen)
111 sync += gpio_ports[GPIO_num].pden.eq(wr_multi[i].pden)
112 with m.If (wr_multi[i].oe):
113 sync += gpio_ports[GPIO_num].o.eq(wr_multi[i].io)
114 with m.Else():
115 sync += gpio_ports[GPIO_num].o.eq(0)
116 sync += gpio_ports[GPIO_num].bank.eq(wr_multi[i].bank)
117 with m.Else(): # read
118 # Update the read multi bus with current GPIO configs
119 # not ack'ing as we need to wait 1 clk cycle before data ready
120 for i in range(len(bus.sel)):
121 GPIO_num = Signal(16) # fixed for now
122 comb += GPIO_num.eq(bus.adr*len(bus.sel)+i)
123 with m.If(bus.sel[i]):
124 sync += rd_multi[i].oe.eq(gpio_ports[GPIO_num].oe)
125 sync += rd_multi[i].ie.eq(~gpio_ports[GPIO_num].oe)
126 sync += rd_multi[i].puen.eq(gpio_ports[GPIO_num].puen)
127 sync += rd_multi[i].pden.eq(gpio_ports[GPIO_num].pden)
128 with m.If (gpio_ports[GPIO_num].oe):
129 sync += rd_multi[i].io.eq(gpio_ports[GPIO_num].o)
130 with m.Else():
131 sync += rd_multi[i].io.eq(gpio_ports[GPIO_num].i)
132 sync += rd_multi[i].bank.eq(gpio_ports[GPIO_num].bank)
133 sync += wb_ack.eq(1) # ack after latching data
134 with m.Else():
135 sync += wb_ack.eq(0)
136
137 return m
138
139 def __iter__(self):
140 for field in self.bus.fields.values():
141 yield field
142 for gpio in range(len(self.gpio_ports)):
143 for field in self.gpio_ports[gpio].fields.values():
144 yield field
145
146 def ports(self):
147 return list(self)
148
149 """
150 def gpio_test_in_pattern(dut, pattern):
151 num_gpios = len(dut.gpio_ports)
152 print("Test pattern:")
153 print(pattern)
154 for pat in range(0, len(pattern)):
155 for gpio in range(0, num_gpios):
156 yield gpio_set_in_pad(dut, gpio, pattern[pat])
157 yield
158 temp = yield from gpio_rd_input(dut, gpio)
159 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
160 assert (temp == pattern[pat])
161 pat += 1
162 if pat == len(pattern):
163 break
164 """
165
166 def test_gpio_single(dut, gpio, use_random=True):
167 oe = 1
168 ie = 0
169 output = 0
170 puen = 0
171 pden = 0
172 if use_random:
173 bank = randint(0, (2**NUMBANKBITS)-1)
174 print("Random bank select: {0:b}".format(bank))
175 else:
176 bank = 3 # not special, chose for testing
177
178 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
179 bank, check=True)
180 # Enable output
181 output = 1
182 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
183 bank, check=True)
184
185 # Shadow reg container class
186 class GPIOConfigReg():
187 def __init__(self, shift_dict):
188 self.shift_dict = shift_dict
189 self.oe=0
190 self.ie=1 # By default gpio set as input
191 self.puen=0
192 self.pden=0
193 self.io=0
194 self.bank=0
195 self.packed=0
196
197 def set(self, oe=0, ie=0, puen=0, pden=0, io=0, bank=0):
198 self.oe=oe
199 self.ie=ie
200 self.puen=puen
201 self.pden=pden
202 self.io=io
203 self.bank=bank
204 self.pack() # Produce packed byte for sending
205
206 def set_out(self, outval):
207 self.io=outval
208 self.pack() # Produce packed byte for sending
209
210 # Take config parameters of specified GPIOs, and combine them to produce
211 # bytes for sending via WB bus
212 def pack(self):
213 self.packed = ((self.oe << self.shift_dict['oe'])
214 | (self.ie << self.shift_dict['ie'])
215 | (self.puen << self.shift_dict['puen'])
216 | (self.pden << self.shift_dict['pden'])
217 | (self.io << self.shift_dict['io'])
218 | (self.bank << self.shift_dict['bank']))
219
220 #print("GPIO Packed CSR: {0:x}".format(self.packed))
221
222 # Object for storing each gpio's config state
223
224 class GPIOManager():
225 def __init__(self, dut, layout, wb_bus):
226 self.dut = dut
227 self.wb_bus = wb_bus
228 # arrangement of config bits making up csr word
229 self.csr_layout = layout
230 self.shift_dict = self._create_shift_dict()
231 self.n_gpios = len(self.dut.gpio_ports)
232 print(dir(self.dut))
233 # Get the number of bits of the WB sel signal
234 # indicates the number of gpios per address
235 self.n_gp_per_adr = len(self.dut.bus.sel)
236 # Shows if data is byte/half-word/word/qword addressable?
237 self.granuality = len(self.dut.bus.dat_w) // self.n_gp_per_adr
238 self.n_rows = ceil(self.n_gpios / self.n_gp_per_adr)
239 self.shadow_csr = []
240 for i in range(self.n_gpios):
241 self.shadow_csr.append(GPIOConfigReg(self.shift_dict))
242
243 def print_info(self):
244 print("----------")
245 print("GPIO Block Info:")
246 print("Number of GPIOs: %d" % self.n_gpios)
247 print("GPIOs per WB data word: %d" % self.n_gp_per_adr)
248 print("WB data granuality: %d" % self.granuality)
249 print("Number of address rows: %d" % self.n_rows)
250 print("----------")
251
252 # The shifting of control bits in the configuration word is dependent on the
253 # defined layout. To prevent maintaining the shift constants in a separate
254 # location, the same layout is used to generate a dictionary of bit shifts
255 # with which the configuration word can be produced!
256 def _create_shift_dict(self):
257 shift = 0
258 shift_dict = {}
259 for i in range(0, len(self.csr_layout)):
260 shift_dict[self.csr_layout[i][0]] = shift
261 shift += self.csr_layout[i][1]
262 print(shift_dict)
263 return shift_dict
264
265 def _parse_gpio_arg(self, gpio_str):
266 # TODO: No input checking!
267 print("Given GPIO/range string: {}".format(gpio_str))
268 if gpio_str == "all":
269 start = 0
270 end = self.n_gpios
271 elif '-' in gpio_str:
272 start, end = gpio_str.split('-')
273 start = int(start)
274 end = int(end) + 1
275 if (end < start) or (end > self.n_gpios):
276 raise Exception("Second GPIO must be higher than first and"
277 + " must be lower or equal to last available GPIO.")
278 else:
279 start = int(gpio_str)
280 if start >= self.n_gpios:
281 raise Exception("GPIO must be less/equal to last GPIO.")
282 end = start + 1
283 print("Parsed GPIOs {0} until {1}".format(start, end))
284 return start, end
285
286 # Take a combined word and update shadow reg's
287 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
288 def update_single_shadow(self, csr_byte, gpio):
289 oe = (csr_byte >> self.shift_dict['oe']) & 0x1
290 ie = (csr_byte >> self.shift_dict['ie']) & 0x1
291 puen = (csr_byte >> self.shift_dict['puen']) & 0x1
292 pden = (csr_byte >> self.shift_dict['pden']) & 0x1
293 io = (csr_byte >> self.shift_dict['io']) & 0x1
294 bank = (csr_byte >> self.shift_dict['bank']) & 0x3
295
296 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
297 .format(csr_byte, oe, ie, puen, pden, io, bank))
298
299 self.shadow_csr[gpio].set(oe, ie, puen, pden, io, bank)
300 return oe, ie, puen, pden, io, bank
301
302 # Update multiple configuration registers
303 def wr(self, gp_start, gp_end, check=False):
304 # Some maths to determine how many transactions, and at which
305 # address to start transmitting
306 n_gp_config = gp_end - gp_start
307 adr_start = gp_start // self.n_gp_per_adr
308 n_adr = ceil(n_gp_config / self.n_gp_per_adr)
309
310 curr_gpio = gp_start
311 # cycle through addresses, each iteration is a WB tx
312 for adr in range(adr_start, adr_start + n_adr):
313 tx_sel = 0
314 tx_word = 0
315 # cycle through every WB sel bit, and add configs of
316 # corresponding gpios
317 for i in range(0, self.n_gp_per_adr):
318 # if current gpio's location in the WB data word matches sel bit
319 if (curr_gpio % self.n_gp_per_adr) == i:
320 print("gpio%d" % curr_gpio)
321 tx_sel += 1 << i
322 tx_word += (self.shadow_csr[curr_gpio].packed
323 << (self.granuality * i))
324 curr_gpio += 1
325 # stop if we processed all required gpios
326 if curr_gpio >= gp_end:
327 break
328 print("Adr: %x | Sel: %x | TX Word: %x" % (adr, tx_sel, tx_word))
329 yield from wb_write(self.wb_bus, adr, tx_word, tx_sel)
330 yield # Allow one clk cycle to propagate
331
332 if(check):
333 row_word = yield from wb_read(self.wb_bus, adr, tx_sel)
334 assert config_word == read_word
335
336 def rd(self, gp_start, gp_end):
337 # Some maths to determine how many transactions, and at which
338 # address to start transmitting
339 n_gp_config = gp_end - gp_start
340 adr_start = gp_start // self.n_gp_per_adr
341 n_adr = ceil(n_gp_config / self.n_gp_per_adr)
342
343 curr_gpio = gp_start
344 # cycle through addresses, each iteration is a WB tx
345 for adr in range(adr_start, adr_start + n_adr):
346 tx_sel = 0
347 # cycle through every WB sel bit, and add configs of
348 # corresponding gpios
349 for i in range(0, self.n_gp_per_adr):
350 # if current gpio's location in the WB data word matches sel bit
351 if (curr_gpio % self.n_gp_per_adr) == i:
352 print("gpio%d" % curr_gpio)
353 tx_sel += 1 << i
354 curr_gpio += 1
355 # stop if we processed all required gpios
356 if curr_gpio >= gp_end:
357 break
358 print("Adr: %x | Sel: %x " % (adr, tx_sel))
359 row_word = yield from wb_read(self.wb_bus, adr, tx_sel)
360
361 mask = (2**self.granuality) - 1
362 for i in range(self.n_gp_per_adr):
363 if ((tx_sel >> i) & 1) == 1:
364 single_csr = (row_word >> (i*self.granuality)) & mask
365 curr_gpio = adr*self.n_gp_per_adr + i
366 #print("rd gpio%d" % curr_gpio)
367 self.update_single_shadow(single_csr, curr_gpio)
368
369 # Write all shadow registers to GPIO block
370 def wr_all(self, check=False):
371 for row in range(0, self.n_rows):
372 yield from self.wr(0, self.n_gpios, check)
373
374 # Read all GPIO block row addresses and update shadow reg's
375 def rd_all(self, check=False):
376 for row in range(0, self.n_rows):
377 yield from self.rd(0, self.n_gpios)
378
379 def config(self, gpio_str, oe, ie, puen, pden, outval, bank, check=False):
380 start, end = self._parse_gpio_arg(gpio_str)
381 # Update the shadow configuration
382 for gpio in range(start, end):
383 # print(oe, ie, puen, pden, outval, bank)
384 self.shadow_csr[gpio].set(oe, ie, puen, pden, outval, bank)
385 # TODO: only update the required rows?
386 #yield from self.wr_all()
387 yield from self.wr(start, end)
388
389 # Set/Clear the output bit for single or group of GPIOs
390 def set_out(self, gpio_str, outval):
391 start, end = self._parse_gpio_arg(gpio_str)
392 for gpio in range(start, end):
393 self.shadow_csr[gpio].set_out(outval)
394
395 if start == end:
396 print("Setting GPIO{0} output to {1}".format(start, outval))
397 else:
398 print("Setting GPIOs {0}-{1} output to {2}"
399 .format(start, end-1, outval))
400
401 yield from self.wr(start, end)
402
403 def rd_input(self, gpio_str):
404 start, end = self._parse_gpio_arg(gpio_str)
405 #read_data = [0] * self.n_rows
406 #for row in range(0, self.n_rows):
407 # read_data[row] = yield from self.rd_row(row)
408 yield from self.rd(start, end)
409
410 num_to_read = (end - start)
411 read_in = [0] * num_to_read
412 curr_gpio = 0
413 for i in range(0, num_to_read):
414 read_in[i] = self.shadow_csr[curr_gpio].io
415 curr_gpio += 1
416
417 print("GPIOs %d until %d, i=%s".format(start, end, read_in))
418 return read_in
419
420 # TODO: There's probably a cleaner way to clear the bit...
421 def sim_set_in_pad(self, gpio_str, in_val):
422 start, end = self._parse_gpio_arg(gpio_str)
423 for gpio in range(start, end):
424 old_in_val = yield self.dut.gpio_ports[gpio].i
425 print(old_in_val)
426 print("GPIO{0} Previous i: {1:b} | New i: {2:b}"
427 .format(gpio, old_in_val, in_val))
428 yield self.dut.gpio_ports[gpio].i.eq(in_val)
429 yield # Allow one clk cycle to propagate
430
431 def rd_shadow(self):
432 shadow_csr = [0] * self.n_gpios
433 for gpio in range(0, self.n_gpios):
434 shadow_csr[gpio] = self.shadow_csr[gpio].packed
435
436 hex_str = ""
437 for reg in shadow_csr:
438 hex_str += " "+hex(reg)
439 print("Shadow reg's: ", hex_str)
440
441 return shadow_csr
442
443
444 def sim_gpio(dut, use_random=True):
445 #print(dut)
446 #print(dir(dut.gpio_ports))
447 #print(len(dut.gpio_ports))
448
449 gpios = GPIOManager(dut, csrbus_layout)
450 gpios.print_info()
451 # TODO: not working yet
452 #test_pattern = []
453 #for i in range(0, (num_gpios * 2)):
454 # test_pattern.append(randint(0,1))
455 #yield from gpio_test_in_pattern(dut, test_pattern)
456
457 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
458 #reg_val = 0xC56271A2
459 #reg_val = 0xFFFFFFFF
460 #yield from reg_write(dut, 0, reg_val)
461 #yield from reg_write(dut, 0, reg_val)
462 #yield
463
464 #csr_val = yield from wb_read(dut.bus, 0)
465 #print("CSR Val: {0:x}".format(csr_val))
466 print("Finished the simple GPIO block test!")
467
468 def gen_gtkw_doc(n_gpios, wordsize, filename):
469 # GTKWave doc generation
470 wb_data_width = wordsize*8
471 n_rows = ceil(n_gpios/wordsize)
472 style = {
473 '': {'base': 'hex'},
474 'in': {'color': 'orange'},
475 'out': {'color': 'yellow'},
476 'debug': {'module': 'top', 'color': 'red'}
477 }
478
479 # Create a trace list, each block expected to be a tuple()
480 traces = []
481 wb_traces = ('Wishbone Bus', [
482 ('gpio_wb__cyc', 'in'),
483 ('gpio_wb__stb', 'in'),
484 ('gpio_wb__we', 'in'),
485 ('gpio_wb__adr[27:0]', 'in'),
486 ('gpio_wb__sel[3:0]', 'in'),
487 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width-1), 'in'),
488 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width-1), 'out'),
489 ('gpio_wb__ack', 'out'),
490 ])
491 traces.append(wb_traces)
492
493 gpio_internal_traces = ('Internal', [
494 ('clk', 'in'),
495 ('new_transaction'),
496 ('rst', 'in')
497 ])
498 traces.append(gpio_internal_traces)
499
500 traces.append({'comment': 'Multi-byte GPIO config read bus'})
501 for word in range(0, wordsize):
502 prefix = "rd_word{}__".format(word)
503 single_word = []
504 word_signals = []
505 single_word.append('Word{}'.format(word))
506 word_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1)))
507 word_signals.append((prefix+'ie'))
508 word_signals.append((prefix+'io'))
509 word_signals.append((prefix+'oe'))
510 word_signals.append((prefix+'pden'))
511 word_signals.append((prefix+'puen'))
512 single_word.append(word_signals)
513 traces.append(tuple(single_word))
514
515 traces.append({'comment': 'Multi-byte GPIO config write bus'})
516 for word in range(0, wordsize):
517 prefix = "wr_word{}__".format(word)
518 single_word = []
519 word_signals = []
520 single_word.append('Word{}'.format(word))
521 word_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1)))
522 word_signals.append((prefix+'ie'))
523 word_signals.append((prefix+'io'))
524 word_signals.append((prefix+'oe'))
525 word_signals.append((prefix+'pden'))
526 word_signals.append((prefix+'puen'))
527 single_word.append(word_signals)
528 traces.append(tuple(single_word))
529
530 for gpio in range(0, n_gpios):
531 prefix = "gpio{}__".format(gpio)
532 single_gpio = []
533 gpio_signals = []
534 single_gpio.append('GPIO{} Port'.format(gpio))
535 gpio_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1), 'out'))
536 gpio_signals.append( (prefix+'i', 'in') )
537 gpio_signals.append( (prefix+'o', 'out') )
538 gpio_signals.append( (prefix+'oe', 'out') )
539 gpio_signals.append( (prefix+'pden', 'out') )
540 gpio_signals.append( (prefix+'puen', 'out') )
541 single_gpio.append(gpio_signals)
542 traces.append(tuple(single_gpio))
543
544 #print(traces)
545
546 #module = "top.xics_icp"
547 module = "bench.top.xics_icp"
548 write_gtkw(filename+".gtkw", filename+".vcd", traces, style,
549 module=module)
550
551 def test_gpio():
552 filename = "test_gpio" # Doesn't include extension
553 n_gpios = 8
554 wordsize = 4 # Number of bytes in the WB data word
555 dut = SimpleGPIO(wordsize, n_gpios)
556 vl = rtlil.convert(dut, ports=dut.ports())
557 with open(filename+".il", "w") as f:
558 f.write(vl)
559
560 m = Module()
561 m.submodules.xics_icp = dut
562
563 sim = Simulator(m)
564 sim.add_clock(1e-6)
565
566 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
567 sim.add_sync_process(wrap(test_gpioman(dut)))
568 sim_writer = sim.write_vcd(filename+".vcd")
569 with sim_writer:
570 sim.run()
571
572 gen_gtkw_doc(n_gpios, wordsize, filename)
573
574 def test_gpioman(dut):
575 print("------START----------------------")
576 gpios = GPIOManager(dut, csrbus_layout, dut.bus)
577 gpios.print_info()
578 #gpios._parse_gpio_arg("all")
579 #gpios._parse_gpio_arg("0")
580 #gpios._parse_gpio_arg("1-3")
581 #gpios._parse_gpio_arg("20")
582
583 oe = 1
584 ie = 0
585 puen = 0
586 pden = 1
587 outval = 0
588 bank = 3
589 yield from gpios.config("0-1", oe=1, ie=0, puen=0, pden=1, outval=0, bank=2)
590 ie = 1
591 yield from gpios.config("5-7", oe=0, ie=1, puen=0, pden=1, outval=0, bank=6)
592 yield from gpios.set_out("0-1", outval=1)
593
594 #yield from gpios.rd_all()
595 yield from gpios.sim_set_in_pad("6-7", 1)
596 print("----------------------------")
597 yield from gpios.rd_input("4-7")
598
599 gpios.rd_shadow()
600
601 if __name__ == '__main__':
602 test_gpio()
603