add qspi auto-gen
[pinmux.git] / src / bsv / peripheral_gen.py
1 import types
2 from copy import deepcopy
3
4
5 class PBase(object):
6 def __init__(self, name):
7 self.name = name
8
9 def axibase(self, name, ifacenum):
10 name = name.upper()
11 return "%(name)s%(ifacenum)dBase" % locals()
12
13 def axiend(self, name, ifacenum):
14 name = name.upper()
15 return "%(name)s%(ifacenum)dEnd" % locals()
16
17 def axi_reg_def(self, start, name, ifacenum):
18 name = name.upper()
19 offs = self.num_axi_regs32() * 4 * 16
20 end = start + offs - 1
21 bname = self.axibase(name, ifacenum)
22 bend = self.axiend(name, ifacenum)
23 comment = "%d 32-bit regs" % self.num_axi_regs32()
24 return (" `define%(bname)s 'h%(start)08X\n"
25 " `define%(bend)s 'h%(end)08X // %(comment)s" % locals(),
26 offs)
27
28 def axi_slave_name(self, name, ifacenum):
29 name = name.upper()
30 return "{0}{1}_slave_num".format(name, ifacenum)
31
32 def axi_slave_idx(self, idx, name, ifacenum):
33 name = self.axi_slave_name(name, ifacenum)
34 return ("typedef {0} {1};".format(idx, name), 1)
35
36 def axi_addr_map(self, name, ifacenum):
37 bname = self.axibase(name, ifacenum)
38 bend = self.axiend(name, ifacenum)
39 name = self.axi_slave_name(name, ifacenum)
40 return """\
41 if(addr>=`{0} && addr<=`{1})
42 return tuple2(True,fromInteger(valueOf({2})));
43 else""".format(bname, bend, name)
44
45 def mk_pincon(self, name, count):
46 # TODO: really should be using bsv.interface_decl.Interfaces
47 # pin-naming rules.... logic here is hard-coded to duplicate
48 # it (see Interface.__init__ outen)
49 ret = []
50 for p in self.peripheral.pinspecs:
51 typ = p['type']
52 pname = p['name']
53 #n = "{0}{1}".format(self.name, self.mksuffix(name, count))
54 n = name # "{0}{1}".format(self.name, self.mksuffix(name, count))
55 ret.append(" //%s %s" % (n, str(p)))
56 sname = self.peripheral.pname(pname).format(count)
57 ps = "pinmux.peripheral_side.%s" % sname
58 if typ == 'out' or typ == 'inout':
59 ret.append(" rule con_%s%d_%s_out" % (name, count, pname))
60 fname = self.pinname_out(pname)
61 if fname:
62 if p.get('outen'):
63 ps_ = ps + '_out'
64 else:
65 ps_ = ps
66 n_ = "{0}{1}".format(n, count)
67 ret.append(" {0}({1}.{2});".format(ps_, n_, fname))
68 fname = None
69 if p.get('outen'):
70 fname = self.pinname_outen(pname)
71 if fname:
72 if isinstance(fname, str):
73 fname = "{0}{1}.{2}".format(n, count, fname)
74 fname = self.pinname_tweak(pname, 'outen', fname)
75 ret.append(" {0}_outen({1});".format(ps, fname))
76 ret.append(" endrule")
77 if typ == 'in' or typ == 'inout':
78 fname = self.pinname_in(pname)
79 if fname:
80 if p.get('outen'):
81 ps_ = ps + '_in'
82 else:
83 ps_ = ps
84 ret.append(
85 " rule con_%s%d_%s_in" %
86 (name, count, pname))
87 ret.append(" {1}.{2}({0});".format(ps_, n, fname))
88 ret.append(" endrule")
89 return '\n'.join(ret)
90
91 def mk_cellconn(self, *args):
92 return ''
93
94 def mkslow_peripheral(self):
95 return ''
96
97 def mksuffix(self, name, i):
98 return i
99
100 def __mk_connection(self, con, aname):
101 txt = " mkConnection (slow_fabric.v_to_slaves\n" + \
102 " [fromInteger(valueOf({1}))],\n" + \
103 " {0});"
104
105 print "PBase __mk_connection", self.name, aname
106 if not con:
107 return ''
108 return txt.format(con, aname)
109
110 def mk_connection(self, count, name=None):
111 if name is None:
112 name = self.name
113 print "PBase mk_conn", self.name, count
114 aname = self.axi_slave_name(name, count)
115 #dname = self.mksuffix(name, count)
116 #dname = "{0}{1}".format(name, dname)
117 con = self._mk_connection(name, count).format(count, aname)
118 return self.__mk_connection(con, aname)
119
120 def _mk_connection(self, name=None, count=0):
121 return ''
122
123 def pinname_out(self, pname):
124 return ''
125
126 def pinname_in(self, pname):
127 return ''
128
129 def pinname_outen(self, pname):
130 return ''
131
132 def pinname_tweak(self, pname, typ, txt):
133 return txt
134
135
136 class uart(PBase):
137
138 def slowimport(self):
139 return " import Uart16550 :: *;"
140
141 def slowifdecl(self):
142 return " interface RS232_PHY_Ifc uart{0}_coe;\n" + \
143 " method Bit#(1) uart{0}_intr;"
144
145 def num_axi_regs32(self):
146 return 8
147
148 def mkslow_peripheral(self):
149 return " Uart16550_AXI4_Lite_Ifc uart{0} <- \n" + \
150 " mkUart16550(clocked_by uart_clock,\n" + \
151 " reset_by uart_reset, sp_clock, sp_reset);"
152
153 def _mk_connection(self, name=None, count=0):
154 return "uart{0}.slave_axi_uart"
155
156 def pinname_out(self, pname):
157 return {'tx': 'coe_rs232.sout'}.get(pname, '')
158
159 def pinname_in(self, pname):
160 return {'rx': 'coe_rs232.sin'}.get(pname, '')
161
162
163 class rs232(PBase):
164
165 def slowimport(self):
166 return " import Uart_bs::*;\n" + \
167 " import RS232_modified::*;"
168
169 def slowifdecl(self):
170 return " interface RS232 uart{0}_coe;"
171
172 def num_axi_regs32(self):
173 return 2
174
175 def mkslow_peripheral(self):
176 return " //Ifc_Uart_bs uart{0} <-" + \
177 " // mkUart_bs(clocked_by uart_clock,\n" + \
178 " // reset_by uart_reset,sp_clock, sp_reset);" +\
179 " Ifc_Uart_bs uart{0} <-" + \
180 " mkUart_bs(clocked_by sp_clock,\n" + \
181 " reset_by sp_reset, sp_clock, sp_reset);"
182
183 def _mk_connection(self, name=None, count=0):
184 return "uart{0}.slave_axi_uart"
185
186 def pinname_out(self, pname):
187 return {'tx': 'coe_rs232.sout'}.get(pname, '')
188
189 def pinname_in(self, pname):
190 return {'rx': 'coe_rs232.sin'}.get(pname, '')
191
192
193 class twi(PBase):
194
195 def slowimport(self):
196 return " import I2C_top :: *;"
197
198 def slowifdecl(self):
199 return " interface I2C_out twi{0}_out;\n" + \
200 " method Bit#(1) twi{0}_isint;"
201
202 def num_axi_regs32(self):
203 return 8
204
205 def mkslow_peripheral(self):
206 return " I2C_IFC twi{0} <- mkI2CController();"
207
208 def _mk_connection(self, name=None, count=0):
209 return "twi{0}.slave_i2c_axi"
210
211 def pinname_out(self, pname):
212 return {'sda': 'out.sda_out',
213 'scl': 'out.scl_out'}.get(pname, '')
214
215 def pinname_in(self, pname):
216 return {'sda': 'out.sda_in',
217 'scl': 'out.scl_in'}.get(pname, '')
218
219 def pinname_outen(self, pname):
220 return {'sda': 'out.sda_outen',
221 'scl': 'out.scl_outen'}.get(pname, '')
222
223 def pinname_tweak(self, pname, typ, txt):
224 if typ == 'outen':
225 return "pack({0})".format(txt)
226 return txt
227
228
229 class qspi(PBase):
230
231 def slowimport(self):
232 return " import qspi :: *;"
233
234 def slowifdecl(self):
235 return " interface QSPI_out qspi{0}_out;\n" + \
236 " method Bit#(1) qspi{0}_isint;"
237
238 def num_axi_regs32(self):
239 return 13
240
241 def mkslow_peripheral(self):
242 return " Ifc_qspi qspi{0} <- mkqspi();"
243
244 def _mk_connection(self, name=None, count=0):
245 return "qspi{0}.slave"
246
247 def pinname_out(self, pname):
248 return {'ck': 'out.clk_o',
249 'nss': 'out.ncs_o',
250 'io0': 'out.io_o[0]',
251 'io1': 'out.io_o[1]',
252 'io2': 'out.io_o[2]',
253 'io3': 'out.io_o[3]',
254 }.get(pname, '')
255
256 def pinname_outen(self, pname):
257 return {'ck': 1,
258 'nss': 1,
259 'io0': 'out.io_enable[0]',
260 'io1': 'out.io_enable[1]',
261 'io2': 'out.io_enable[2]',
262 'io3': 'out.io_enable[3]',
263 }.get(pname, '')
264
265 def mk_pincon(self, name, count):
266 ret = [PBase.mk_pincon(self, name, count)]
267 # special-case for gpio in, store in a temporary vector
268 plen = len(self.peripheral.pinspecs)
269 ret.append(" // XXX NSS and CLK are hard-coded master")
270 ret.append(" // TODO: must add qspi slave-mode")
271 ret.append(" rule con_%s%d_io_in" % (name, count))
272 ret.append(" {0}{1}.out.io_i(".format(name, count))
273 for p in self.peripheral.pinspecs:
274 typ = p['type']
275 pname = p['name']
276 if not pname.startswith('io'):
277 continue
278 idx = pname[1:]
279 n = name
280 sname = self.peripheral.pname(pname).format(count)
281 ps = "pinmux.peripheral_side.%s_in" % sname
282 ret.append(" {0},".format(ps))
283 ret.append(" });")
284 ret.append(" endrule")
285 return '\n'.join(ret)
286
287
288 class pwm(PBase):
289
290 def slowimport(self):
291 return " import pwm::*;"
292
293 def slowifdecl(self):
294 return " interface PWMIO pwm{0}_o;"
295
296 def num_axi_regs32(self):
297 return 4
298
299 def mkslow_peripheral(self):
300 return " Ifc_PWM_bus pwm{0}_bus <- mkPWM_bus(sp_clock);"
301
302 def _mk_connection(self, name=None, count=0):
303 return "pwm{0}_bus.axi4_slave"
304
305 def pinname_out(self, pname):
306 return {'out': 'pwm_io.pwm_o'}.get(pname, '')
307
308
309 class gpio(PBase):
310
311 def slowimport(self):
312 return " import pinmux::*;\n" + \
313 " import mux::*;\n" + \
314 " import gpio::*;\n"
315
316 def slowifdecl(self):
317 return " interface GPIO_config#({1}) pad_config{0};"
318
319 def num_axi_regs32(self):
320 return 2
321
322 def axi_slave_idx(self, idx, name, ifacenum):
323 """ generates AXI slave number definition, except
324 GPIO also has a muxer per bank
325 """
326 name = name.upper()
327 (ret, x) = PBase.axi_slave_idx(self, idx, name, ifacenum)
328 (ret2, x) = PBase.axi_slave_idx(self, idx, "mux", ifacenum)
329 return ("%s\n%s" % (ret, ret2), 2)
330
331 def mkslow_peripheral(self):
332 return " MUX#(%(name)s) mux{0} <- mkmux();\n" + \
333 " GPIO#(%(name)s) gpio{0} <- mkgpio();" % \
334 {'name': self.name}
335
336 def mk_connection(self, count):
337 print "GPIO mk_conn", self.name, count
338 res = []
339 dname = self.mksuffix(self.name, count)
340 for i, n in enumerate(['gpio' + dname, 'mux' + dname]):
341 res.append(PBase.mk_connection(self, count, n))
342 return '\n'.join(res)
343
344 def _mk_connection(self, name=None, count=0):
345 n = self.mksuffix(name, count)
346 if name.startswith('gpio'):
347 return "gpio{0}.axi_slave".format(n)
348 if name.startswith('mux'):
349 return "mux{0}.axi_slave".format(n)
350
351 def mksuffix(self, name, i):
352 if name.startswith('mux'):
353 return name[3:]
354 return name[4:]
355
356 def mk_cellconn(self, cellnum, name, count):
357 ret = []
358 bank = self.mksuffix(name, count)
359 txt = " pinmux.mux_lines.cell{0}_mux(mux{1}.mux_config.mux[{2}]);"
360 for p in self.peripheral.pinspecs:
361 ret.append(txt.format(cellnum, bank, p['name'][1:]))
362 cellnum += 1
363 return ("\n".join(ret), cellnum)
364
365 def pinname_out(self, pname):
366 return "func.gpio_out[{0}]".format(pname[1:])
367
368 def pinname_outen(self, pname):
369 return {'sda': 'out.sda_outen',
370 'scl': 'out.scl_outen'}.get(pname, '')
371
372 def mk_pincon(self, name, count):
373 ret = [PBase.mk_pincon(self, name, count)]
374 # special-case for gpio in, store in a temporary vector
375 plen = len(self.peripheral.pinspecs)
376 ret.append(" rule con_%s%d_in" % (name, count))
377 ret.append(" Vector#({0},Bit#(1)) temp;".format(plen))
378 for p in self.peripheral.pinspecs:
379 typ = p['type']
380 pname = p['name']
381 idx = pname[1:]
382 n = name
383 sname = self.peripheral.pname(pname).format(count)
384 ps = "pinmux.peripheral_side.%s_in" % sname
385 ret.append(" temp[{0}]={1};".format(idx, ps))
386 ret.append(" {0}.func.gpio_in(temp);".format(name))
387 ret.append(" endrule")
388 return '\n'.join(ret)
389
390
391 axi_slave_declarations = """\
392 typedef 0 SlowMaster;
393 {0}
394 typedef TAdd#(LastGen_slave_num,`ifdef CLINT 1 `else 0 `endif )
395 CLINT_slave_num;
396 typedef TAdd#(CLINT_slave_num ,`ifdef PLIC 1 `else 0 `endif )
397 Plic_slave_num;
398 typedef TAdd#(Plic_slave_num ,`ifdef AXIEXP 1 `else 0 `endif )
399 AxiExp1_slave_num;
400 typedef TAdd#(AxiExp1_slave_num,1) Num_Slow_Slaves;
401 """
402
403 pinmux_cellrule = """\
404 rule connect_select_lines_pinmux;
405 {0}
406 endrule
407 """
408
409
410 class CallFn(object):
411 def __init__(self, peripheral, name):
412 self.peripheral = peripheral
413 self.name = name
414
415 def __call__(self, *args):
416 #print "__call__", self.name, self.peripheral.slow, args
417 if not self.peripheral.slow:
418 return ''
419 return getattr(self.peripheral.slow, self.name)(*args[1:])
420
421
422 class PeripheralIface(object):
423 def __init__(self, ifacename):
424 self.slow = None
425 slow = slowfactory.getcls(ifacename)
426 print "Iface", ifacename, slow
427 if slow:
428 self.slow = slow(ifacename)
429 self.slow.peripheral = self
430 for fname in ['slowimport', 'slowifdecl', 'mkslow_peripheral',
431 'mk_connection', 'mk_cellconn', 'mk_pincon']:
432 fn = CallFn(self, fname)
433 setattr(self, fname, types.MethodType(fn, self))
434
435 #print "PeripheralIface"
436 #print dir(self)
437
438 def mksuffix(self, name, i):
439 if self.slow is None:
440 return i
441 return self.slow.mksuffix(name, i)
442
443 def axi_reg_def(self, start, count):
444 if not self.slow:
445 return ('', 0)
446 return self.slow.axi_reg_def(start, self.ifacename, count)
447
448 def axi_slave_idx(self, start, count):
449 if not self.slow:
450 return ('', 0)
451 return self.slow.axi_slave_idx(start, self.ifacename, count)
452
453 def axi_addr_map(self, count):
454 if not self.slow:
455 return ''
456 return self.slow.axi_addr_map(self.ifacename, count)
457
458
459 class PeripheralInterfaces(object):
460 def __init__(self):
461 pass
462
463 def slowimport(self, *args):
464 ret = []
465 for (name, count) in self.ifacecount:
466 #print "slowimport", name, self.data[name].slowimport
467 ret.append(self.data[name].slowimport())
468 return '\n'.join(list(filter(None, ret)))
469
470 def slowifdecl(self, *args):
471 ret = []
472 for (name, count) in self.ifacecount:
473 for i in range(count):
474 ret.append(self.data[name].slowifdecl().format(i, name))
475 return '\n'.join(list(filter(None, ret)))
476
477 def axi_reg_def(self, *args):
478 ret = []
479 start = 0x00011100 # start of AXI peripherals address
480 for (name, count) in self.ifacecount:
481 for i in range(count):
482 x = self.data[name].axi_reg_def(start, i)
483 #print ("ifc", name, x)
484 (rdef, offs) = x
485 ret.append(rdef)
486 start += offs
487 return '\n'.join(list(filter(None, ret)))
488
489 def axi_slave_idx(self, *args):
490 ret = []
491 start = 0
492 for (name, count) in self.ifacecount:
493 for i in range(count):
494 (rdef, offs) = self.data[name].axi_slave_idx(start, i)
495 #print ("ifc", name, rdef, offs)
496 ret.append(rdef)
497 start += offs
498 ret.append("typedef %d LastGen_slave_num" % (start - 1))
499 decls = '\n'.join(list(filter(None, ret)))
500 return axi_slave_declarations.format(decls)
501
502 def axi_addr_map(self, *args):
503 ret = []
504 for (name, count) in self.ifacecount:
505 for i in range(count):
506 ret.append(self.data[name].axi_addr_map(i))
507 return '\n'.join(list(filter(None, ret)))
508
509 def mkslow_peripheral(self, *args):
510 ret = []
511 for (name, count) in self.ifacecount:
512 for i in range(count):
513 print "mkslow", name, count
514 x = self.data[name].mkslow_peripheral()
515 print name, count, x
516 suffix = self.data[name].mksuffix(name, i)
517 ret.append(x.format(suffix))
518 return '\n'.join(list(filter(None, ret)))
519
520 def mk_connection(self, *args):
521 ret = []
522 for (name, count) in self.ifacecount:
523 for i in range(count):
524 print "mk_conn", name, i
525 txt = self.data[name].mk_connection(i)
526 if name == 'gpioa':
527 print "txt", txt
528 print self.data[name].mk_connection
529 ret.append(txt)
530 return '\n'.join(list(filter(None, ret)))
531
532 def mk_cellconn(self):
533 ret = []
534 cellcount = 0
535 for (name, count) in self.ifacecount:
536 for i in range(count):
537 res = self.data[name].mk_cellconn(cellcount, name, i)
538 if not res:
539 continue
540 (txt, cellcount) = res
541 ret.append(txt)
542 ret = '\n'.join(list(filter(None, ret)))
543 return pinmux_cellrule.format(ret)
544
545 def mk_pincon(self):
546 ret = []
547 for (name, count) in self.ifacecount:
548 for i in range(count):
549 txt = self.data[name].mk_pincon(name, i)
550 ret.append(txt)
551 return '\n'.join(list(filter(None, ret)))
552
553
554 class PFactory(object):
555 def getcls(self, name):
556 for k, v in {'uart': uart,
557 'rs232': rs232,
558 'twi': twi,
559 'qspi': qspi,
560 'pwm': pwm,
561 'gpio': gpio
562 }.items():
563 if name.startswith(k):
564 return v
565 return None
566
567
568 slowfactory = PFactory()
569
570 if __name__ == '__main__':
571 p = uart('uart')
572 print p.slowimport()
573 print p.slowifdecl()
574 i = PeripheralIface('uart')
575 print i, i.slow
576 i = PeripheralIface('gpioa')
577 print i, i.slow