Added some gpio logic, still need reading implemented
[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 print("#GPIOs is greater than, and is a multiple of WB wordsize")
124 # Case where all gpios fit within full words
125 if self.n_gpio % self.wordsize == 0:
126 gpio = 0
127 while (gpio < self.n_gpio):
128 for byte in range(self.wordsize):
129 sync += gpio_ports[gpio].oe.eq(multi[byte].oe)
130 sync += gpio_ports[gpio].puen.eq(multi[byte].puen)
131 sync += gpio_ports[gpio].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(multi[byte].oe):
135 sync += gpio_ports[gpio].o.eq(multi[byte].io)
136 with m.Else():
137 sync += multi[byte].io.eq(gpio_ports[gpio].i)
138 sync += gpio_ports[gpio].bank.eq(multi[byte].bank)
139 gpio += 1
140 elif self.n_gpio > self.wordsize:
141 # This is a complex case, not needed atm
142 print("#GPIOs is greater than WB wordsize")
143 print("NOT IMPLEMENTED THIS CASE")
144 raise
145 else:
146 print("#GPIOs is less or equal to WB wordsize (in bytes)")
147 for byte in range(self.n_gpio):
148 sync += gpio_ports[byte].oe.eq(multi[byte].oe)
149 sync += gpio_ports[byte].puen.eq(multi[byte].puen)
150 sync += gpio_ports[byte].pden.eq(multi[byte].pden)
151 # Check to prevent output being set if GPIO configured as i
152 # TODO: No checking is done if ie/oe high together
153 with m.If(multi[byte].oe): # gpio_ports[byte].oe):
154 sync += gpio_ports[byte].o.eq(multi[byte].io)
155 with m.Else():
156 sync += multi[byte].io.eq(gpio_ports[byte].i)
157 sync += gpio_ports[byte].bank.eq(multi[byte].bank)
158 # TODO: need logic for reading gpio config...
159 #with m.Else():
160 # print("Copy gpio_ports to multi...")
161 # sync += multi[]
162 return m
163
164 def __iter__(self):
165 for field in self.bus.fields.values():
166 yield field
167 for gpio in range(len(self.gpio_ports)):
168 for field in self.gpio_ports[gpio].fields.values():
169 yield field
170
171 def ports(self):
172 return list(self)
173
174 """
175 def gpio_test_in_pattern(dut, pattern):
176 num_gpios = len(dut.gpio_ports)
177 print("Test pattern:")
178 print(pattern)
179 for pat in range(0, len(pattern)):
180 for gpio in range(0, num_gpios):
181 yield gpio_set_in_pad(dut, gpio, pattern[pat])
182 yield
183 temp = yield from gpio_rd_input(dut, gpio)
184 print("Pattern: {0}, Reading {1}".format(pattern[pat], temp))
185 assert (temp == pattern[pat])
186 pat += 1
187 if pat == len(pattern):
188 break
189 """
190
191 def test_gpio_single(dut, gpio, use_random=True):
192 oe = 1
193 ie = 0
194 output = 0
195 puen = 0
196 pden = 0
197 if use_random:
198 bank = randint(0, (2**NUMBANKBITS)-1)
199 print("Random bank select: {0:b}".format(bank))
200 else:
201 bank = 3 # not special, chose for testing
202
203 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
204 bank, check=True)
205 # Enable output
206 output = 1
207 gpio_csr = yield from gpio_config(dut, gpio, oe, ie, puen, pden, output,
208 bank, check=True)
209
210 # Shadow reg container class
211 class GPIOConfigReg():
212 def __init__(self, shift_dict):
213 self.shift_dict = shift_dict
214 self.oe=0
215 self.ie=0
216 self.puen=0
217 self.pden=0
218 self.io=0
219 self.bank=0
220 self.packed=0
221
222 def set(self, oe=0, ie=0, puen=0, pden=0, io=0, bank=0):
223 self.oe=oe
224 self.ie=ie
225 self.puen=puen
226 self.pden=pden
227 self.io=io
228 self.bank=bank
229 self.pack() # Produce packed byte for sending
230
231 def set_out(self, outval):
232 self.io=outval
233 self.pack() # Produce packed byte for sending
234
235 # Take config parameters of specified GPIOs, and combine them to produce
236 # bytes for sending via WB bus
237 def pack(self):
238 self.packed = ((self.oe << self.shift_dict['oe'])
239 | (self.ie << self.shift_dict['ie'])
240 | (self.puen << self.shift_dict['puen'])
241 | (self.pden << self.shift_dict['pden'])
242 | (self.io << self.shift_dict['io'])
243 | (self.bank << self.shift_dict['bank']))
244
245 #print("GPIO Packed CSR: {0:x}".format(self.packed))
246
247 # Object for storing each gpio's config state
248
249 class GPIOManager():
250 def __init__(self, dut, layout, wb_bus):
251 self.dut = dut
252 self.wb_bus = wb_bus
253 # arrangement of config bits making up csr word
254 self.csr_layout = layout
255 self.shift_dict = self._create_shift_dict()
256 self.n_gpios = len(self.dut.gpio_ports)
257 print(dir(self.dut))
258 # Since GPIO HDL block already has wordsize parameter, use directly
259 # Alternatively, can derive from WB data r/w buses (div by 8 for bytes)
260 #self.wordsize = len(self.dut.gpio_wb__dat_w) / 8
261 self.wordsize = self.dut.wordsize
262 self.n_rows = ceil(self.n_gpios / self.wordsize)
263 self.shadow_csr = []
264 for i in range(self.n_gpios):
265 self.shadow_csr.append(GPIOConfigReg(self.shift_dict))
266
267 def print_info(self):
268 print("----------")
269 print("GPIO Block Info:")
270 print("Number of GPIOs: {}".format(self.n_gpios))
271 print("WB Data bus width (in bytes): {}".format(self.wordsize))
272 print("Number of rows: {}".format(self.n_rows))
273 print("----------")
274
275 # The shifting of control bits in the configuration word is dependent on the
276 # defined layout. To prevent maintaining the shift constants in a separate
277 # location, the same layout is used to generate a dictionary of bit shifts
278 # with which the configuration word can be produced!
279 def _create_shift_dict(self):
280 shift = 0
281 shift_dict = {}
282 for i in range(0, len(self.csr_layout)):
283 shift_dict[self.csr_layout[i][0]] = shift
284 shift += self.csr_layout[i][1]
285 print(shift_dict)
286 return shift_dict
287
288 def _parse_gpio_arg(self, gpio_str):
289 # TODO: No input checking!
290 print("Given GPIO/range string: {}".format(gpio_str))
291 if gpio_str == "all":
292 start = 0
293 end = self.n_gpios
294 elif '-' in gpio_str:
295 start, end = gpio_str.split('-')
296 start = int(start)
297 end = int(end) + 1
298 if (end < start) or (end > self.n_gpios):
299 raise Exception("Second GPIO must be higher than first and"
300 + " must be lower or equal to last available GPIO.")
301 else:
302 start = int(gpio_str)
303 if start >= self.n_gpios:
304 raise Exception("GPIO must be less/equal to last GPIO.")
305 end = start + 1
306 print("Parsed GPIOs {0} until {1}".format(start, end))
307 return start, end
308
309 # Take a combined word and update shadow reg's
310 # TODO: convert hard-coded sizes to use the csrbus_layout (or dict?)
311 def update_single_shadow(self, csr_byte, gpio):
312 oe = (csr_byte >> self.shift_dict['oe']) & 0x1
313 ie = (csr_byte >> self.shift_dict['ie']) & 0x1
314 puen = (csr_byte >> self.shift_dict['puen']) & 0x1
315 pden = (csr_byte >> self.shift_dict['pden']) & 0x1
316 io = (csr_byte >> self.shift_dict['io']) & 0x1
317 bank = (csr_byte >> self.shift_dict['bank']) & 0x3
318
319 print("csr={0:x} | oe={1}, ie={2}, puen={3}, pden={4}, io={5}, bank={6}"
320 .format(csr_byte, oe, ie, puen, pden, io, bank))
321
322 self.shadow_csr[gpio].set(oe, ie, puen, pden, io, bank)
323 return oe, ie, puen, pden, io, bank
324
325 def rd_csr(self, row_start):
326 row_word = yield from wb_read(self.wb_bus, row_start)
327 print("Returned CSR: {0:x}".format(row_word))
328 return row_word
329
330 # Update a single row of configuration registers
331 def wr_row(self, row_addr, check=False):
332 curr_gpio = row_addr * self.wordsize
333 config_word = 0
334 for byte in range(0, self.wordsize):
335 if curr_gpio >= self.n_gpios:
336 break
337 config_word += self.shadow_csr[curr_gpio].packed << (8 * byte)
338 #print("Reading GPIO{} shadow reg".format(curr_gpio))
339 curr_gpio += 1
340 print("Writing shadow CSRs val {0:x} to row addr {1:x}"
341 .format(config_word, row_addr))
342 yield from wb_write(self.wb_bus, row_addr, config_word)
343 yield # Allow one clk cycle to propagate
344
345 if(check):
346 read_word = yield from self.rd_row(row_addr)
347 assert config_word == read_word
348
349 # Read a single address row of GPIO CSRs, and update shadow
350 def rd_row(self, row_addr):
351 read_word = yield from self.rd_csr(row_addr)
352 curr_gpio = row_addr * self.wordsize
353 single_csr = 0
354 for byte in range(0, self.wordsize):
355 if curr_gpio >= self.n_gpios:
356 break
357 single_csr = (read_word >> (8 * byte)) & 0xFF
358 #print("Updating GPIO{0} shadow reg to {1:x}"
359 # .format(curr_gpio, single_csr))
360 self.update_single_shadow(single_csr, curr_gpio)
361 curr_gpio += 1
362 return read_word
363
364 # Write all shadow registers to GPIO block
365 def wr_all(self, check=False):
366 for row in range(0, self.n_rows):
367 yield from self.wr_row(row, check)
368
369 # Read all GPIO block row addresses and update shadow reg's
370 def rd_all(self, check=False):
371 for row in range(0, self.n_rows):
372 yield from self.rd_row(row, check)
373
374 def config(self, gpio_str, oe, ie, puen, pden, outval, bank, check=False):
375 start, end = self._parse_gpio_arg(gpio_str)
376 # Update the shadow configuration
377 for gpio in range(start, end):
378 # print(oe, ie, puen, pden, outval, bank)
379 self.shadow_csr[gpio].set(oe, ie, puen, pden, outval, bank)
380 # TODO: only update the required rows?
381 yield from self.wr_all()
382
383 # Set/Clear the output bit for single or group of GPIOs
384 def set_out(self, gpio_str, outval):
385 start, end = self._parse_gpio_arg(gpio_str)
386 for gpio in range(start, end):
387 self.shadow_csr[gpio].set_out(outval)
388
389 if start == end:
390 print("Setting GPIO{0} output to {1}".format(start, outval))
391 else:
392 print("Setting GPIOs {0}-{1} output to {2}"
393 .format(start, end-1, outval))
394
395 yield from self.wr_all()
396
397 def rd_input(self, gpio_str): # REWORK
398 start, end = self._parse_gpio_arg(gpio_str)
399 curr_gpio = 0
400 # Too difficult to think about, just read all configs
401 #start_row = floor(start / self.wordsize)
402 # Hack because end corresponds to range limit, but maybe on same row
403 # TODO: clean
404 #end_row = floor( (end-1) / self.wordsize) + 1
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
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 {0} until {1}, i={2}".format(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{0} Previous i: {1:b} | New i: {2:b}"
426 .format(gpio, old_in_val, in_val))
427 yield self.dut.gpio_ports[gpio].i.eq(in_val)
428 yield # Allow one clk cycle to propagate
429
430 def rd_shadow(self):
431 shadow_csr = [0] * self.n_gpios
432 for gpio in range(0, self.n_gpios):
433 shadow_csr[gpio] = self.shadow_csr[gpio].packed
434
435 hex_str = ""
436 for reg in shadow_csr:
437 hex_str += " "+hex(reg)
438 print("Shadow reg's: ", hex_str)
439
440 return shadow_csr
441
442
443 def sim_gpio(dut, use_random=True):
444 #print(dut)
445 #print(dir(dut.gpio_ports))
446 #print(len(dut.gpio_ports))
447
448 gpios = GPIOManager(dut, csrbus_layout)
449 gpios.print_info()
450 # TODO: not working yet
451 #test_pattern = []
452 #for i in range(0, (num_gpios * 2)):
453 # test_pattern.append(randint(0,1))
454 #yield from gpio_test_in_pattern(dut, test_pattern)
455
456 #yield from gpio_config(dut, start_gpio, oe, ie, puen, pden, outval, bank, end_gpio, check=False, wordsize=4)
457 #reg_val = 0xC56271A2
458 #reg_val = 0xFFFFFFFF
459 #yield from reg_write(dut, 0, reg_val)
460 #yield from reg_write(dut, 0, reg_val)
461 #yield
462
463 #csr_val = yield from wb_read(dut.bus, 0)
464 #print("CSR Val: {0:x}".format(csr_val))
465 print("Finished the simple GPIO block test!")
466
467 def gen_gtkw_doc(n_gpios, wordsize, filename):
468 # GTKWave doc generation
469 wb_data_width = wordsize*8
470 n_rows = ceil(n_gpios/wordsize)
471 style = {
472 '': {'base': 'hex'},
473 'in': {'color': 'orange'},
474 'out': {'color': 'yellow'},
475 'debug': {'module': 'top', 'color': 'red'}
476 }
477
478 # Create a trace list, each block expected to be a tuple()
479 traces = []
480 wb_traces = ('Wishbone Bus', [
481 ('gpio_wb__cyc', 'in'),
482 ('gpio_wb__stb', 'in'),
483 ('gpio_wb__we', 'in'),
484 ('gpio_wb__adr[27: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 ('row_start[2:0]'),
495 ('rst', 'in')
496 ])
497 traces.append(gpio_internal_traces)
498
499 traces.append({'comment': 'Multi-byte GPIO config bus'})
500 for word in range(0, wordsize):
501 prefix = "word{}__".format(word)
502 single_word = []
503 word_signals = []
504 single_word.append('Word{}'.format(word))
505 word_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1)))
506 word_signals.append((prefix+'ie'))
507 word_signals.append((prefix+'io'))
508 word_signals.append((prefix+'oe'))
509 word_signals.append((prefix+'pden'))
510 word_signals.append((prefix+'puen'))
511 single_word.append(word_signals)
512 traces.append(tuple(single_word))
513
514 for gpio in range(0, n_gpios):
515 prefix = "gpio{}__".format(gpio)
516 single_gpio = []
517 gpio_signals = []
518 single_gpio.append('GPIO{} Port'.format(gpio))
519 gpio_signals.append((prefix+'bank[{}:0]'.format(NUMBANKBITS-1), 'out'))
520 gpio_signals.append( (prefix+'i', 'in') )
521 gpio_signals.append( (prefix+'o', 'out') )
522 gpio_signals.append( (prefix+'oe', 'out') )
523 gpio_signals.append( (prefix+'pden', 'out') )
524 gpio_signals.append( (prefix+'puen', 'out') )
525 single_gpio.append(gpio_signals)
526 traces.append(tuple(single_gpio))
527
528 #print(traces)
529
530 write_gtkw(filename+".gtkw", filename+".vcd", traces, style,
531 module="top.xics_icp")
532
533 def test_gpio():
534 filename = "test_gpio" # Doesn't include extension
535 n_gpios = 8
536 wordsize = 4 # Number of bytes in the WB data word
537 dut = SimpleGPIO(wordsize, n_gpios)
538 vl = rtlil.convert(dut, ports=dut.ports())
539 with open(filename+".il", "w") as f:
540 f.write(vl)
541
542 m = Module()
543 m.submodules.xics_icp = dut
544
545 sim = Simulator(m)
546 sim.add_clock(1e-6)
547
548 #sim.add_sync_process(wrap(sim_gpio(dut, use_random=False)))
549 sim.add_sync_process(wrap(test_gpioman(dut)))
550 sim_writer = sim.write_vcd(filename+".vcd")
551 with sim_writer:
552 sim.run()
553
554 gen_gtkw_doc(n_gpios, wordsize, filename)
555
556 def test_gpioman(dut):
557 print("------START----------------------")
558 gpios = GPIOManager(dut, csrbus_layout, dut.bus)
559 gpios.print_info()
560 #gpios._parse_gpio_arg("all")
561 #gpios._parse_gpio_arg("0")
562 gpios._parse_gpio_arg("1-3")
563 #gpios._parse_gpio_arg("20")
564
565 oe = 1
566 ie = 0
567 puen = 0
568 pden = 1
569 outval = 0
570 bank = 3
571 yield from gpios.config("0-3", oe=1, ie=0, puen=0, pden=1, outval=0, bank=2)
572 ie = 1
573 yield from gpios.config("4-7", oe=0, ie=1, puen=0, pden=1, outval=0, bank=2)
574 yield from gpios.set_out("0-3", outval=1)
575
576 #yield from gpios.rd_all()
577 yield from gpios.sim_set_in_pad("4-7", 1)
578 print("----------------------------")
579 yield from gpios.rd_input("4-7")
580
581 gpios.rd_shadow()
582
583 if __name__ == '__main__':
584 test_gpio()
585