hack LCD format of pinmux get/put on data bus
[pinmux.git] / src / bsv / interface_decl.py
1 import os.path
2
3 try:
4 from UserDict import UserDict
5 except ImportError:
6 from collections import UserDict
7
8 from bsv.wire_def import generic_io # special case
9 from bsv.wire_def import muxwire # special case
10 from ifacebase import InterfacesBase
11 from bsv.peripheral_gen import PeripheralIface
12 from bsv.peripheral_gen import PeripheralInterfaces
13
14
15 class Pin(object):
16 """ pin interface declaration.
17 * name is the name of the pin
18 * ready, enabled and io all create a (* .... *) prefix
19 * action changes it to an "in" if true
20 """
21
22 def __init__(self, name,
23 name_=None,
24 idx=None,
25 ready=True,
26 enabled=True,
27 io=False,
28 action=False,
29 bitspec=None,
30 outenmode=False):
31 self.name = name
32 self.name_ = name_
33 self.idx = idx
34 self.ready = ready
35 self.enabled = enabled
36 self.io = io
37 self.action = action
38 self.bitspec = bitspec if bitspec else 'Bit#(1)'
39 self.outenmode = outenmode
40
41 # bsv will look like this (method declaration):
42 """
43 (*always_ready,always_enabled*) method Bit#(1) io0_cell_outen;
44 (*always_ready,always_enabled,result="io"*) method
45 Action io0_inputval (Bit#(1) in);
46 """
47
48 def ifacepfmt(self, fmtfn):
49 res = ' '
50 status = []
51 res += "interface "
52 name = fmtfn(self.name_)
53 if self.action:
54 res += "Put"
55 else:
56 res += "Get"
57 res += "#(%s) %s;" % (self.bitspec, name)
58 return res
59
60 def ifacefmt(self, fmtfn):
61 res = ' '
62 status = []
63 if self.ready:
64 status.append('always_ready')
65 if self.enabled:
66 status.append('always_enabled')
67 if self.io:
68 status.append('result="io"')
69 if status:
70 res += '(*'
71 res += ','.join(status)
72 res += '*)'
73 res += " method "
74 if self.io:
75 res += "\n "
76 name = fmtfn(self.name)
77 if self.action:
78 res += " Action "
79 res += name
80 res += ' (%s in)' % self.bitspec
81 else:
82 res += " %s " % self.bitspec
83 res += name
84 res += ";"
85 return res
86
87 def ifacedef(self, fmtoutfn, fmtinfn, fmtdecfn):
88 res = ' method '
89 if self.action:
90 fmtname = fmtinfn(self.name)
91 res += "Action "
92 res += fmtdecfn(self.name)
93 res += '(%s in);\n' % self.bitspec
94 res += ' %s<=in;\n' % fmtname
95 res += ' endmethod'
96 else:
97 fmtname = fmtoutfn(self.name)
98 res += "%s=%s;" % (self.name, fmtname)
99 return res
100 # sample bsv method definition :
101 """
102 method Action cell0_mux(Bit#(2) in);
103 wrcell0_mux<=in;
104 endmethod
105 """
106
107 # sample bsv wire (wire definiton):
108 """
109 Wire#(Bit#(2)) wrcell0_mux<-mkDWire(0);
110 """
111
112 def wirefmt(self, fmtoutfn, fmtinfn, fmtdecfn):
113 res = ' Wire#(%s) ' % self.bitspec
114 if self.action:
115 res += '%s' % fmtinfn(self.name)
116 else:
117 res += '%s' % fmtoutfn(self.name)
118 res += "<-mkDWire(0);"
119 return res
120
121 def ifacedef2(self, fmtoutfn, fmtinfn, fmtdecfn):
122 if self.action:
123 fmtname = fmtinfn(self.name)
124 res = " interface %s = interface Put\n" % self.name_
125 res += ' method '
126 res += "Action put"
127 #res += fmtdecfn(self.name)
128 res += '(%s in);\n' % self.bitspec
129 res += ' %s<=in;\n' % fmtname
130 res += ' endmethod\n'
131 res += ' endinterface;'
132 else:
133 fmtname = fmtoutfn(self.name)
134 res = " interface %s = interface Get\n" % self.name_
135 res += ' method ActionValue#'
136 res += '(%s) get;\n' % self.bitspec
137 res += " return %s;\n" % (fmtname)
138 res += ' endmethod\n'
139 res += ' endinterface;'
140 return res
141
142 def ifacedef3(self, idx, fmtoutfn, fmtinfn, fmtdecfn):
143 if self.action:
144 fmtname = fmtinfn(self.name)
145 if self.name.endswith('outen'):
146 name = "tputen"
147 else:
148 name = "tput"
149 res = " %s <= in[%d];" % (fmtname, idx)
150 else:
151 fmtname = fmtoutfn(self.name)
152 res = " tget[%d] = %s;" % (idx, fmtname)
153 name = 'tget'
154 return (name, res)
155
156
157 class Interface(PeripheralIface):
158 """ create an interface from a list of pinspecs.
159 each pinspec is a dictionary, see Pin class arguments
160 single indicates that there is only one of these, and
161 so the name must *not* be extended numerically (see pname)
162 """
163 # sample interface object:
164 """
165 twiinterface_decl = Interface('twi',
166 [{'name': 'sda', 'outen': True},
167 {'name': 'scl', 'outen': True},
168 ])
169 """
170
171 def __init__(self, ifacename, pinspecs, ganged=None, single=False):
172 PeripheralIface.__init__(self, ifacename)
173 self.ifacename = ifacename
174 self.ganged = ganged or {}
175 self.pins = [] # a list of instances of class Pin
176 self.pinspecs = pinspecs # a list of dictionary
177 self.single = single
178
179 for idx, p in enumerate(pinspecs):
180 _p = {}
181 _p.update(p)
182 if 'type' in _p:
183 del _p['type']
184 if p.get('outen') is True: # special case, generate 3 pins
185 del _p['outen']
186 for psuffix in ['out', 'outen', 'in']:
187 # changing the name (like sda) to (twi_sda_out)
188 _p['name_'] = "%s_%s" % (p['name'], psuffix)
189 _p['name'] = "%s_%s" % (self.pname(p['name']), psuffix)
190 _p['action'] = psuffix != 'in'
191 _p['idx'] = idx
192 self.pins.append(Pin(**_p))
193 # will look like {'name': 'twi_sda_out', 'action': True}
194 # {'name': 'twi_sda_outen', 'action': True}
195 #{'name': 'twi_sda_in', 'action': False}
196 # NOTice - outen key is removed
197 else:
198 name = p['name']
199 if name.isdigit(): # HACK! deals with EINT case
200 name = self.pname(name)
201 _p['name_'] = name
202 _p['idx'] = idx
203 _p['name'] = self.pname(p['name'])
204 self.pins.append(Pin(**_p))
205
206 # sample interface object:
207 """
208 uartinterface_decl = Interface('uart',
209 [{'name': 'rx'},
210 {'name': 'tx', 'action': True},
211 ])
212 """
213 """
214 getifacetype is called multiple times in actual_pinmux.py
215 x = ifaces.getifacetype(temp), where temp is uart_rx, spi_mosi
216 Purpose is to identify is function : input/output/inout
217 """
218
219 def getifacetype(self, name):
220 for p in self.pinspecs:
221 fname = "%s_%s" % (self.ifacename, p['name'])
222 # print "search", self.ifacename, name, fname
223 if fname == name:
224 if p.get('action'):
225 return 'out'
226 elif p.get('outen'):
227 return 'inout'
228 return 'input'
229 return None
230
231 def iname(self):
232 """ generates the interface spec e.g. flexbus_ale
233 if there is only one flexbus interface, or
234 sd{0}_cmd if there are several. string format
235 function turns this into sd0_cmd, sd1_cmd as
236 appropriate. single mode stops the numerical extension.
237 """
238 if self.single:
239 return self.ifacename
240 return '%s{0}' % self.ifacename
241
242 def pname(self, name):
243 """ generates the interface spec e.g. flexbus_ale
244 if there is only one flexbus interface, or
245 sd{0}_cmd if there are several. string format
246 function turns this into sd0_cmd, sd1_cmd as
247 appropriate. single mode stops the numerical extension.
248 """
249 return "%s_%s" % (self.iname(), name)
250
251 def busfmt(self, *args):
252 """ this function creates a bus "ganging" system based
253 on input from the {interfacename}.txt file.
254 only inout pins that are under the control of the
255 interface may be "ganged" together.
256 """
257 if not self.ganged:
258 return '' # when self.ganged is None
259 # print self.ganged
260 res = []
261 for (k, pnames) in self.ganged.items():
262 name = self.pname('%senable' % k).format(*args)
263 decl = 'Bit#(1) %s = 0;' % name
264 res.append(decl)
265 ganged = []
266 for p in self.pinspecs:
267 if p['name'] not in pnames:
268 continue
269 pname = self.pname(p['name']).format(*args)
270 if p.get('outen') is True:
271 outname = self.ifacefmtoutfn(pname)
272 ganged.append("%s_outen" % outname) # match wirefmt
273
274 gangedfmt = '{%s} = duplicate(%s);'
275 res.append(gangedfmt % (',\n '.join(ganged), name))
276 return '\n'.join(res) + '\n\n'
277
278 def wirefmt(self, *args):
279 res = '\n'.join(map(self.wirefmtpin, self.pins)).format(*args)
280 res += '\n'
281 return '\n' + res
282
283 def ifacepfmt(self, *args):
284 res = '\n'.join(map(self.ifacepfmtdecpin, self.pins)).format(*args)
285 return '\n' + res # pins is a list
286
287 def ifacefmt(self, *args):
288 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
289 return '\n' + res # pins is a list
290
291 def ifacepfmtdecfn(self, name):
292 return name
293
294 def ifacefmtdecfn(self, name):
295 return name # like: uart
296
297 def ifacefmtdecfn2(self, name):
298 return name # like: uart
299
300 def ifacefmtdecfn3(self, name):
301 """ HACK! """
302 return "%s_outen" % name # like uart_outen
303
304 def ifacefmtoutfn(self, name):
305 return "wr%s" % name # like wruart
306
307 def ifacefmtinfn(self, name):
308 return "wr%s" % name
309
310 def wirefmtpin(self, pin):
311 return pin.wirefmt(self.ifacefmtoutfn, self.ifacefmtinfn,
312 self.ifacefmtdecfn2)
313
314 def ifacepfmtdecpin(self, pin):
315 return pin.ifacepfmt(self.ifacepfmtdecfn)
316
317 def ifacefmtdecpin(self, pin):
318 return pin.ifacefmt(self.ifacefmtdecfn)
319
320 def ifacefmtpin(self, pin):
321 decfn = self.ifacefmtdecfn2
322 outfn = self.ifacefmtoutfn
323 # print pin, pin.outenmode
324 if pin.outenmode:
325 decfn = self.ifacefmtdecfn3
326 outfn = self.ifacefmtoutenfn
327 return pin.ifacedef(outfn, self.ifacefmtinfn,
328 decfn)
329
330 def ifacedef2pin(self, pin):
331 decfn = self.ifacefmtdecfn2
332 outfn = self.ifacefmtoutfn
333 # print pin, pin.outenmode
334 if pin.outenmode:
335 decfn = self.ifacefmtdecfn3
336 outfn = self.ifacefmtoutenfn
337 return pin.ifacedef2(outfn, self.ifacefmtinfn,
338 decfn)
339
340 def ifacedef(self, *args):
341 res = '\n'.join(map(self.ifacefmtpin, self.pins))
342 res = res.format(*args)
343 return '\n' + res + '\n'
344
345 def ifacedef2(self, *args):
346 res = '\n'.join(map(self.ifacedef2pin, self.pins))
347 res = res.format(*args)
348 return '\n' + res + '\n'
349
350 def vectorifacedef2(self, pins, count, names, bitfmt, *args):
351 tput = []
352 tget = []
353 tputen = []
354 # XXX HACK! assume in, out and inout, create set of indices
355 # that are repeated three times.
356 plens = []
357 # ARG even worse hack for LCD *sigh*...
358 if names[1] is None and names[2] is None:
359 plens = range(len(pins))
360 else:
361 for i in range(0, len(pins), 3):
362 plens += [i/3, i/3, i/3]
363 for (typ, txt) in map(self.ifacedef3pin, plens, pins):
364 if typ == 'tput':
365 tput.append(txt)
366 elif typ == 'tget':
367 tget.append(txt)
368 elif typ == 'tputen':
369 tputen.append(txt)
370 tput = '\n'.join(tput).format(*args)
371 tget = '\n'.join(tget).format(*args)
372 tputen = '\n'.join(tputen).format(*args)
373 bitfmt = bitfmt.format(count)
374 template = ["""\
375 interface {3} = interface Put#({0})
376 method Action put({2} in);
377 {1}
378 endmethod
379 endinterface;
380 """,
381 """\
382 interface {3} = interface Put#({0})
383 method Action put({2} in);
384 {1}
385 endmethod
386 endinterface;
387 """,
388 """\
389 interface {3} = interface Get#({0})
390 method ActionValue#({2}) get;
391 {2} tget;
392 {1}
393 return tget;
394 endmethod
395 endinterface;
396 """]
397 res = ''
398 tlist = [tput, tputen, tget]
399 for i, n in enumerate(names):
400 if n:
401 res += template[i].format(count, tlist[i], bitfmt, n)
402 return '\n' + res + '\n'
403
404
405 class MuxInterface(Interface):
406
407 def wirefmt(self, *args):
408 return muxwire.format(*args)
409
410
411 class IOInterface(Interface):
412
413 def ifacefmtoutenfn(self, name):
414 return "cell{0}_mux_outen"
415
416 def ifacefmtoutfn(self, name):
417 """ for now strip off io{0}_ part """
418 return "cell{0}_mux_out"
419
420 def ifacefmtinfn(self, name):
421 return "cell{0}_mux_in"
422
423 def wirefmt(self, *args):
424 return generic_io.format(*args)
425
426
427 class InterfaceLCD(Interface):
428
429 def get_n_iopins(self, pins): # HACK! assume in/out/outen so div by 3
430 return len(pins)
431
432 def ifacepfmt(self, *args):
433 pins = filter(lambda x: not x.name_.startswith('out'), self.pins)
434 res = '\n'.join(map(self.ifacepfmtdecpin, pins)).format(*args)
435 res = res.format(*args)
436
437 pins = filter(lambda x: x.name_.startswith('out'), self.pins)
438 plen = self.get_n_iopins(pins)
439
440 return "\n" + res + """
441 interface Put#(Bit#({0})) data_out;
442 """.format(plen)
443
444 def ifacedef2(self, *args):
445 pins = filter(lambda x: not x.name_.startswith('out'), self.pins)
446 res = '\n'.join(map(self.ifacedef2pin, pins))
447 res = res.format(*args)
448
449 pins = filter(lambda x: x.name_.startswith('out'), self.pins)
450 plen = self.get_n_iopins(pins)
451 bitspec = "Bit#({0})".format(plen)
452 return '\n' + res + self.vectorifacedef2(pins, plen,
453 ['data', None, None],
454 bitspec, *args) + '\n'
455
456 def ifacedef3pin(self, idx, pin):
457 decfn = self.ifacefmtdecfn2
458 outfn = self.ifacefmtoutfn
459 # print pin, pin.outenmode
460 if pin.outenmode:
461 decfn = self.ifacefmtdecfn3
462 outfn = self.ifacefmtoutenfn
463 return pin.ifacedef3(idx, outfn, self.ifacefmtinfn,
464 decfn)
465
466 class InterfaceNSPI(Interface):
467
468 def get_n_iopins(self, pins): # HACK! assume in/out/outen so div by 3
469 return len(pins) / 3
470
471 def ifacepfmt(self, *args):
472 pins = filter(lambda x: not x.name_.startswith('io'), self.pins)
473 res = '\n'.join(map(self.ifacepfmtdecpin, pins)).format(*args)
474 res = res.format(*args)
475
476 pins = filter(lambda x: x.name_.startswith('io'), self.pins)
477 plen = self.get_n_iopins(pins)
478
479 return "\n" + res + """
480 interface Put#(Bit#({0})) io_out;
481 interface Put#(Bit#({0})) io_out_en;
482 interface Get#(Bit#({0})) io_in;
483 """.format(plen)
484
485 def ifacedef2(self, *args):
486 pins = filter(lambda x: not x.name_.startswith('io'), self.pins)
487 res = '\n'.join(map(self.ifacedef2pin, pins))
488 res = res.format(*args)
489
490 pins = filter(lambda x: x.name_.startswith('io'), self.pins)
491 plen = self.get_n_iopins(pins)
492 bitspec = "Bit#({0})".format(plen)
493 return '\n' + res + self.vectorifacedef2(pins, plen,
494 ['io_out', 'io_out_en', 'io_in'],
495 bitspec, *args) + '\n'
496
497 def ifacedef3pin(self, idx, pin):
498 decfn = self.ifacefmtdecfn2
499 outfn = self.ifacefmtoutfn
500 # print pin, pin.outenmode
501 if pin.outenmode:
502 decfn = self.ifacefmtdecfn3
503 outfn = self.ifacefmtoutenfn
504 return pin.ifacedef3(idx, outfn, self.ifacefmtinfn,
505 decfn)
506
507
508 class InterfaceEINT(Interface):
509 """ uses old-style (non-get/put) for now
510 """
511
512 def ifacepfmt(self, *args):
513 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
514 return '\n' + res # pins is a list
515
516 def ifacedef2(self, *args):
517 return self.ifacedef(*args)
518
519
520
521 class InterfaceGPIO(Interface):
522
523 def ifacepfmt(self, *args):
524 return """
525 interface Put#(Vector#({0}, Bit#(1))) out;
526 interface Put#(Vector#({0}, Bit#(1))) out_en;
527 interface Get#(Vector#({0}, Bit#(1))) in;
528 """.format(len(self.pinspecs))
529
530 def ifacedef2(self, *args):
531 return self.vectorifacedef2(self.pins, len(self.pinspecs),
532 ['out', 'out_en', 'in'],
533 "Vector#({0},Bit#(1))", *args)
534
535 def ifacedef3pin(self, idx, pin):
536 decfn = self.ifacefmtdecfn2
537 outfn = self.ifacefmtoutfn
538 # print pin, pin.outenmode
539 if pin.outenmode:
540 decfn = self.ifacefmtdecfn3
541 outfn = self.ifacefmtoutenfn
542 return pin.ifacedef3(idx, outfn, self.ifacefmtinfn,
543 decfn)
544
545
546 class Interfaces(InterfacesBase, PeripheralInterfaces):
547 """ contains a list of interface definitions
548 """
549
550 def __init__(self, pth=None):
551 InterfacesBase.__init__(self, Interface, pth,
552 {'gpio': InterfaceGPIO,
553 'spi': InterfaceNSPI,
554 'lcd': InterfaceLCD,
555 'qspi': InterfaceNSPI,
556 'eint': InterfaceEINT})
557 PeripheralInterfaces.__init__(self)
558
559 def ifacedef(self, f, *args):
560 for (name, count) in self.ifacecount:
561 for i in range(count):
562 f.write(self.data[name].ifacedef(i))
563
564 def ifacedef2(self, f, *args):
565 c = " interface {0} = interface PeripheralSide{1}"
566 for (name, count) in self.ifacecount:
567 for i in range(count):
568 iname = self.data[name].iname().format(i)
569 f.write(c.format(iname, name.upper()))
570 f.write(self.data[name].ifacedef2(i))
571 f.write(" endinterface;\n\n")
572
573 def busfmt(self, f, *args):
574 f.write("import BUtils::*;\n\n")
575 for (name, count) in self.ifacecount:
576 for i in range(count):
577 bf = self.data[name].busfmt(i)
578 f.write(bf)
579
580 def ifacepfmt(self, f, *args):
581 comment = '''
582 // interface declaration between {0} and pinmux
583 (*always_ready,always_enabled*)
584 interface PeripheralSide{0};'''
585 for (name, count) in self.ifacecount:
586 f.write(comment.format(name.upper()))
587 f.write(self.data[name].ifacepfmt(0))
588 f.write("\n endinterface\n")
589
590 def ifacefmt(self, f, *args):
591 comment = '''
592 // interface declaration between %s-{0} and pinmux'''
593 for (name, count) in self.ifacecount:
594 for i in range(count):
595 c = comment % name.upper()
596 f.write(c.format(i))
597 f.write(self.data[name].ifacefmt(i))
598
599 def ifacefmt2(self, f, *args):
600 comment = '''
601 interface PeripheralSide{0} {1};'''
602 for (name, count) in self.ifacecount:
603 for i in range(count):
604 iname = self.data[name].iname().format(i)
605 f.write(comment.format(name.upper(), iname))
606
607 def wirefmt(self, f, *args):
608 comment = '\n // following wires capture signals ' \
609 'to IO CELL if %s-{0} is\n' \
610 ' // allotted to it'
611 for (name, count) in self.ifacecount:
612 for i in range(count):
613 c = comment % name
614 f.write(c.format(i))
615 f.write(self.data[name].wirefmt(i))
616
617
618 # ========= Interface declarations ================ #
619
620 mux_interface = MuxInterface('cell',
621 [{'name': 'mux', 'ready': False, 'enabled': False,
622 'bitspec': '{1}', 'action': True}])
623
624 io_interface = IOInterface(
625 'io',
626 [{'name': 'cell_out', 'enabled': True, },
627 {'name': 'cell_outen', 'enabled': True, 'outenmode': True, },
628 {'name': 'cell_in', 'action': True, 'io': True}, ])
629
630 # == Peripheral Interface definitions == #
631 # these are the interface of the peripherals to the pin mux
632 # Outputs from the peripherals will be inputs to the pinmux
633 # module. Hence the change in direction for most pins
634
635 # ======================================= #
636
637 # basic test
638 if __name__ == '__main__':
639
640 uartinterface_decl = Interface('uart',
641 [{'name': 'rx'},
642 {'name': 'tx', 'action': True},
643 ])
644
645 twiinterface_decl = Interface('twi',
646 [{'name': 'sda', 'outen': True},
647 {'name': 'scl', 'outen': True},
648 ])
649
650 def _pinmunge(p, sep, repl, dedupe=True):
651 """ munges the text so it's easier to compare.
652 splits by separator, strips out blanks, re-joins.
653 """
654 p = p.strip()
655 p = p.split(sep)
656 if dedupe:
657 p = filter(lambda x: x, p) # filter out blanks
658 return repl.join(p)
659
660 def pinmunge(p):
661 """ munges the text so it's easier to compare.
662 """
663 # first join lines by semicolons, strip out returns
664 p = p.split(";")
665 p = map(lambda x: x.replace('\n', ''), p)
666 p = '\n'.join(p)
667 # now split first by brackets, then spaces (deduping on spaces)
668 p = _pinmunge(p, "(", " ( ", False)
669 p = _pinmunge(p, ")", " ) ", False)
670 p = _pinmunge(p, " ", " ")
671 return p
672
673 def zipcmp(l1, l2):
674 l1 = l1.split("\n")
675 l2 = l2.split("\n")
676 for p1, p2 in zip(l1, l2):
677 print (repr(p1))
678 print (repr(p2))
679 print ()
680 assert p1 == p2
681
682 ifaces = Interfaces()
683
684 ifaceuart = ifaces['uart']
685 print (ifaceuart.ifacedef(0))
686 print (uartinterface_decl.ifacedef(0))
687 assert ifaceuart.ifacedef(0) == uartinterface_decl.ifacedef(0)
688
689 ifacetwi = ifaces['twi']
690 print (ifacetwi.ifacedef(0))
691 print (twiinterface_decl.ifacedef(0))
692 assert ifacetwi.ifacedef(0) == twiinterface_decl.ifacedef(0)