Fixed print formatting
[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: %d, #GPIOs: %d, Rows: %d" %
52 (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%d" % 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: %x, Reading %x" % (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: %x" % (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: %s" % (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 %d until %d" % (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=%02x | oe=%d, ie=%d, puen=%d, pden=%d, io=%d, bank=%x" %
297 (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 %d output to %d" % (start, outval))
397 else:
398 print("Setting GPIOs %d-%d output to %d" % (start, end-1, outval))
399
400 yield from self.wr(start, end)
401
402 def rd_input(self, gpio_str):
403 start, end = self._parse_gpio_arg(gpio_str)
404 #read_data = [0] * self.n_rows
405 #for row in range(0, self.n_rows):
406 # read_data[row] = yield from self.rd_row(row)
407 yield from self.rd(start, end)
408
409 num_to_read = (end - start)
410 read_in = [0] * num_to_read
411 curr_gpio = 0
412 for i in range(0, num_to_read):
413 read_in[i] = self.shadow_csr[curr_gpio].io
414 curr_gpio += 1
415
416 print("GPIOs %d until %d, i=%r" % (start, end, read_in))
417 return read_in
418
419 # TODO: There's probably a cleaner way to clear the bit...
420 def sim_set_in_pad(self, gpio_str, in_val):
421 start, end = self._parse_gpio_arg(gpio_str)
422 for gpio in range(start, end):
423 old_in_val = yield self.dut.gpio_ports[gpio].i
424 print(old_in_val)
425 print("GPIO %d Prev i: %x | New i: %x" % (gpio, old_in_val, in_val))
426 yield self.dut.gpio_ports[gpio].i.eq(in_val)
427 yield # Allow one clk cycle to propagate
428
429 def rd_shadow(self):
430 shadow_csr = [0] * self.n_gpios
431 for gpio in range(0, self.n_gpios):
432 shadow_csr[gpio] = self.shadow_csr[gpio].packed
433
434 hex_str = ""
435 for reg in shadow_csr:
436 hex_str += " "+hex(reg)
437 print("Shadow reg's: ", hex_str)
438
439 return shadow_csr
440
441
442 def sim_gpio(dut, use_random=True):
443 #print(dut)
444 #print(dir(dut.gpio_ports))
445 #print(len(dut.gpio_ports))
446
447 gpios = GPIOManager(dut, csrbus_layout)
448 gpios.print_info()
449 # TODO: not working yet
450 #test_pattern = []
451 #for i in range(0, (num_gpios * 2)):
452 # test_pattern.append(randint(0,1))
453 #yield from gpio_test_in_pattern(dut, test_pattern)
454
455 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
456 #reg_val = 0xC56271A2
457 #reg_val = 0xFFFFFFFF
458 #yield from reg_write(dut, 0, reg_val)
459 #yield from reg_write(dut, 0, reg_val)
460 #yield
461
462 #csr_val = yield from wb_read(dut.bus, 0)
463 #print("CSR Val: {0:x}".format(csr_val))
464 print("Finished the simple GPIO block test!")
465
466 def gen_gtkw_doc(n_gpios, wordsize, filename):
467 # GTKWave doc generation
468 wb_data_width = wordsize*8
469 n_rows = ceil(n_gpios/wordsize)
470 style = {
471 '': {'base': 'hex'},
472 'in': {'color': 'orange'},
473 'out': {'color': 'yellow'},
474 'debug': {'module': 'top', 'color': 'red'}
475 }
476
477 # Create a trace list, each block expected to be a tuple()
478 traces = []
479 wb_traces = ('Wishbone Bus', [
480 ('gpio_wb__cyc', 'in'),
481 ('gpio_wb__stb', 'in'),
482 ('gpio_wb__we', 'in'),
483 ('gpio_wb__adr[27:0]', 'in'),
484 ('gpio_wb__sel[3:0]', 'in'),
485 ('gpio_wb__dat_w[{}:0]'.format(wb_data_width-1), 'in'),
486 ('gpio_wb__dat_r[{}:0]'.format(wb_data_width-1), 'out'),
487 ('gpio_wb__ack', 'out'),
488 ])
489 traces.append(wb_traces)
490
491 gpio_internal_traces = ('Internal', [
492 ('clk', 'in'),
493 ('new_transaction'),
494 ('rst', 'in')
495 ])
496 traces.append(gpio_internal_traces)
497
498 traces.append({'comment': 'Multi-byte GPIO config read bus'})
499 for word in range(0, wordsize):
500 prefix = "rd_word{}__".format(word)
501 single_word = []
502 word_signals = []
503 single_word.append('Word{}'.format(word))
504 word_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1)))
505 word_signals.append((prefix+'ie'))
506 word_signals.append((prefix+'io'))
507 word_signals.append((prefix+'oe'))
508 word_signals.append((prefix+'pden'))
509 word_signals.append((prefix+'puen'))
510 single_word.append(word_signals)
511 traces.append(tuple(single_word))
512
513 traces.append({'comment': 'Multi-byte GPIO config write bus'})
514 for word in range(0, wordsize):
515 prefix = "wr_word{}__".format(word)
516 single_word = []
517 word_signals = []
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))
527
528 for gpio in range(0, n_gpios):
529 prefix = "gpio{}__".format(gpio)
530 single_gpio = []
531 gpio_signals = []
532 single_gpio.append('GPIO{} Port'.format(gpio))
533 gpio_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1), 'out'))
534 gpio_signals.append( (prefix+'i', 'in') )
535 gpio_signals.append( (prefix+'o', 'out') )
536 gpio_signals.append( (prefix+'oe', 'out') )
537 gpio_signals.append( (prefix+'pden', 'out') )
538 gpio_signals.append( (prefix+'puen', 'out') )
539 single_gpio.append(gpio_signals)
540 traces.append(tuple(single_gpio))
541
542 #print(traces)
543
544 #module = "top.xics_icp"
545 module = "bench.top.xics_icp"
546 write_gtkw(filename+".gtkw", filename+".vcd", traces, style,
547 module=module)
548
549 def test_gpio():
550 filename = "test_gpio" # Doesn't include extension
551 n_gpios = 8
552 wordsize = 4 # Number of bytes in the WB data word
553 dut = SimpleGPIO(wordsize, n_gpios)
554 vl = rtlil.convert(dut, ports=dut.ports())
555 with open(filename+".il", "w") as f:
556 f.write(vl)
557
558 m = Module()
559 m.submodules.xics_icp = dut
560
561 sim = Simulator(m)
562 sim.add_clock(1e-6)
563
564 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
565 sim.add_sync_process(wrap(test_gpioman(dut)))
566 sim_writer = sim.write_vcd(filename+".vcd")
567 with sim_writer:
568 sim.run()
569
570 gen_gtkw_doc(n_gpios, wordsize, filename)
571
572 def test_gpioman(dut):
573 print("------START----------------------")
574 gpios = GPIOManager(dut, csrbus_layout, dut.bus)
575 gpios.print_info()
576 #gpios._parse_gpio_arg("all")
577 #gpios._parse_gpio_arg("0")
578 #gpios._parse_gpio_arg("1-3")
579 #gpios._parse_gpio_arg("20")
580
581 oe = 1
582 ie = 0
583 puen = 0
584 pden = 1
585 outval = 0
586 bank = 3
587 yield from gpios.config("0-1", oe=1, ie=0, puen=0, pden=1, outval=0, bank=2)
588 ie = 1
589 yield from gpios.config("5-7", oe=0, ie=1, puen=0, pden=1, outval=0, bank=6)
590 yield from gpios.set_out("0-1", outval=1)
591
592 #yield from gpios.rd_all()
593 yield from gpios.sim_set_in_pad("6-7", 1)
594 print("----------------------------")
595 yield from gpios.rd_input("4-7")
596
597 gpios.rd_shadow()
598
599 if __name__ == '__main__':
600 test_gpio()
601