add first attempt at vector-version of getput interface
[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, fmtoutfn, fmtinfn, fmtdecfn):
143 if self.action:
144 if self.name.endswith('outen'):
145 name = "tputen"
146 else:
147 name = "tput"
148 fmtname = fmtinfn(self.name)
149 res = " %s <= %s[%d];" % (fmtname, name, self.idx)
150 else:
151 fmtname = fmtoutfn(self.name)
152 res = " tget[%d] = %s;" % (self.idx, fmtname)
153 return res
154
155 class Interface(PeripheralIface):
156 """ create an interface from a list of pinspecs.
157 each pinspec is a dictionary, see Pin class arguments
158 single indicates that there is only one of these, and
159 so the name must *not* be extended numerically (see pname)
160 """
161 # sample interface object:
162 """
163 twiinterface_decl = Interface('twi',
164 [{'name': 'sda', 'outen': True},
165 {'name': 'scl', 'outen': True},
166 ])
167 """
168
169 def __init__(self, ifacename, pinspecs, ganged=None, single=False):
170 PeripheralIface.__init__(self, ifacename)
171 self.ifacename = ifacename
172 self.ganged = ganged or {}
173 self.pins = [] # a list of instances of class Pin
174 self.pinspecs = pinspecs # a list of dictionary
175 self.single = single
176
177 for idx, p in enumerate(pinspecs):
178 _p = {}
179 _p.update(p)
180 if 'type' in _p:
181 del _p['type']
182 if p.get('outen') is True: # special case, generate 3 pins
183 del _p['outen']
184 for psuffix in ['out', 'outen', 'in']:
185 # changing the name (like sda) to (twi_sda_out)
186 _p['name_'] = "%s_%s" % (p['name'], psuffix)
187 _p['name'] = "%s_%s" % (self.pname(p['name']), psuffix)
188 _p['action'] = psuffix != 'in'
189 _p['idx'] = idx
190 self.pins.append(Pin(**_p))
191 # will look like {'name': 'twi_sda_out', 'action': True}
192 # {'name': 'twi_sda_outen', 'action': True}
193 #{'name': 'twi_sda_in', 'action': False}
194 # NOTice - outen key is removed
195 else:
196 name = p['name']
197 if name.isdigit(): # HACK! deals with EINT case
198 name = self.pname(name)
199 _p['name_'] = name
200 _p['idx'] = idx
201 _p['name'] = self.pname(p['name'])
202 self.pins.append(Pin(**_p))
203
204 # sample interface object:
205 """
206 uartinterface_decl = Interface('uart',
207 [{'name': 'rx'},
208 {'name': 'tx', 'action': True},
209 ])
210 """
211 """
212 getifacetype is called multiple times in actual_pinmux.py
213 x = ifaces.getifacetype(temp), where temp is uart_rx, spi_mosi
214 Purpose is to identify is function : input/output/inout
215 """
216
217 def getifacetype(self, name):
218 for p in self.pinspecs:
219 fname = "%s_%s" % (self.ifacename, p['name'])
220 # print "search", self.ifacename, name, fname
221 if fname == name:
222 if p.get('action'):
223 return 'out'
224 elif p.get('outen'):
225 return 'inout'
226 return 'input'
227 return None
228
229 def iname(self):
230 """ generates the interface spec e.g. flexbus_ale
231 if there is only one flexbus interface, or
232 sd{0}_cmd if there are several. string format
233 function turns this into sd0_cmd, sd1_cmd as
234 appropriate. single mode stops the numerical extension.
235 """
236 if self.single:
237 return self.ifacename
238 return '%s{0}' % self.ifacename
239
240 def pname(self, name):
241 """ generates the interface spec e.g. flexbus_ale
242 if there is only one flexbus interface, or
243 sd{0}_cmd if there are several. string format
244 function turns this into sd0_cmd, sd1_cmd as
245 appropriate. single mode stops the numerical extension.
246 """
247 return "%s_%s" % (self.iname(), name)
248
249 def busfmt(self, *args):
250 """ this function creates a bus "ganging" system based
251 on input from the {interfacename}.txt file.
252 only inout pins that are under the control of the
253 interface may be "ganged" together.
254 """
255 if not self.ganged:
256 return '' # when self.ganged is None
257 # print self.ganged
258 res = []
259 for (k, pnames) in self.ganged.items():
260 name = self.pname('%senable' % k).format(*args)
261 decl = 'Bit#(1) %s = 0;' % name
262 res.append(decl)
263 ganged = []
264 for p in self.pinspecs:
265 if p['name'] not in pnames:
266 continue
267 pname = self.pname(p['name']).format(*args)
268 if p.get('outen') is True:
269 outname = self.ifacefmtoutfn(pname)
270 ganged.append("%s_outen" % outname) # match wirefmt
271
272 gangedfmt = '{%s} = duplicate(%s);'
273 res.append(gangedfmt % (',\n '.join(ganged), name))
274 return '\n'.join(res) + '\n\n'
275
276 def wirefmt(self, *args):
277 res = '\n'.join(map(self.wirefmtpin, self.pins)).format(*args)
278 res += '\n'
279 return '\n' + res
280
281 def ifacepfmt(self, *args):
282 res = '\n'.join(map(self.ifacepfmtdecpin, self.pins)).format(*args)
283 return '\n' + res # pins is a list
284
285 def ifacefmt(self, *args):
286 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
287 return '\n' + res # pins is a list
288
289 def ifacepfmtdecfn(self, name):
290 return name
291
292 def ifacefmtdecfn(self, name):
293 return name # like: uart
294
295 def ifacefmtdecfn2(self, name):
296 return name # like: uart
297
298 def ifacefmtdecfn3(self, name):
299 """ HACK! """
300 return "%s_outen" % name # like uart_outen
301
302 def ifacefmtoutfn(self, name):
303 return "wr%s" % name # like wruart
304
305 def ifacefmtinfn(self, name):
306 return "wr%s" % name
307
308 def wirefmtpin(self, pin):
309 return pin.wirefmt(self.ifacefmtoutfn, self.ifacefmtinfn,
310 self.ifacefmtdecfn2)
311
312 def ifacepfmtdecpin(self, pin):
313 return pin.ifacepfmt(self.ifacepfmtdecfn)
314
315 def ifacefmtdecpin(self, pin):
316 return pin.ifacefmt(self.ifacefmtdecfn)
317
318 def ifacefmtpin(self, pin):
319 decfn = self.ifacefmtdecfn2
320 outfn = self.ifacefmtoutfn
321 # print pin, pin.outenmode
322 if pin.outenmode:
323 decfn = self.ifacefmtdecfn3
324 outfn = self.ifacefmtoutenfn
325 return pin.ifacedef(outfn, self.ifacefmtinfn,
326 decfn)
327
328 def ifacedef2pin(self, pin):
329 decfn = self.ifacefmtdecfn2
330 outfn = self.ifacefmtoutfn
331 # print pin, pin.outenmode
332 if pin.outenmode:
333 decfn = self.ifacefmtdecfn3
334 outfn = self.ifacefmtoutenfn
335 return pin.ifacedef2(outfn, self.ifacefmtinfn,
336 decfn)
337
338 def ifacedef(self, *args):
339 res = '\n'.join(map(self.ifacefmtpin, self.pins))
340 res = res.format(*args)
341 return '\n' + res + '\n'
342
343 def ifacedef2(self, *args):
344 res = '\n'.join(map(self.ifacedef2pin, self.pins))
345 res = res.format(*args)
346 return '\n' + res + '\n'
347
348
349 class MuxInterface(Interface):
350
351 def wirefmt(self, *args):
352 return muxwire.format(*args)
353
354
355 class IOInterface(Interface):
356
357 def ifacefmtoutenfn(self, name):
358 return "cell{0}_mux_outen"
359
360 def ifacefmtoutfn(self, name):
361 """ for now strip off io{0}_ part """
362 return "cell{0}_mux_out"
363
364 def ifacefmtinfn(self, name):
365 return "cell{0}_mux_in"
366
367 def wirefmt(self, *args):
368 return generic_io.format(*args)
369
370 class InterfaceGPIO(Interface):
371
372 def ifacedef2(self, *args):
373 res = '\n'.join(map(self.ifacedef2pin, self.pins))
374 res = res.format(*args)
375
376 tdecl = """\
377 Vector#({0},Bit#(1)) tput;
378 Vector#({0},Bit#(1)) tputen;
379 Vector#({0},Bit#(1)) tget;
380 """.format(len(self.pinspecs))
381 template = """\
382 interface gpio_out = interface Put#
383 method Action put(Vector#({0},Bit#(1)) in);
384 tput<=in;
385 endmethod
386 endinterface;
387 interface gpio_outen = interface Put#
388 method Action put(Vector#({0},Bit#(1)) in);
389 tputen<=in;
390 endmethod
391 endinterface;
392 interface gpio_in = interface Get#
393 method ActionValue#(Vector#({0},Bit#(1))) get;
394 return tget;
395 endmethod
396 endinterface;
397 """.format(len(self.pinspecs))
398 return '\n' + tdecl + res + '\n' + template + '\n'
399
400 def ifacedef2pin(self, pin):
401 decfn = self.ifacefmtdecfn2
402 outfn = self.ifacefmtoutfn
403 # print pin, pin.outenmode
404 if pin.outenmode:
405 decfn = self.ifacefmtdecfn3
406 outfn = self.ifacefmtoutenfn
407 return pin.ifacedef3(outfn, self.ifacefmtinfn,
408 decfn)
409
410
411 class Interfaces(InterfacesBase, PeripheralInterfaces):
412 """ contains a list of interface definitions
413 """
414
415 def __init__(self, pth=None):
416 InterfacesBase.__init__(self, Interface, pth,
417 {'gpio': InterfaceGPIO })
418 PeripheralInterfaces.__init__(self)
419
420 def ifacedef(self, f, *args):
421 for (name, count) in self.ifacecount:
422 for i in range(count):
423 f.write(self.data[name].ifacedef(i))
424
425 def ifacedef2(self, f, *args):
426 c = " interface {0} = interface PeripheralSide{1}"
427 for (name, count) in self.ifacecount:
428 for i in range(count):
429 iname = self.data[name].iname().format(i)
430 f.write(c.format(iname, name.upper()))
431 f.write(self.data[name].ifacedef2(i))
432 f.write(" endinterface;\n\n")
433
434 def busfmt(self, f, *args):
435 f.write("import BUtils::*;\n\n")
436 for (name, count) in self.ifacecount:
437 for i in range(count):
438 bf = self.data[name].busfmt(i)
439 f.write(bf)
440
441 def ifacepfmt(self, f, *args):
442 comment = '''
443 // interface declaration between {0} and pinmux
444 (*always_ready,always_enabled*)
445 interface PeripheralSide{0};'''
446 for (name, count) in self.ifacecount:
447 f.write(comment.format(name.upper()))
448 f.write(self.data[name].ifacepfmt(0))
449 f.write("\n endinterface\n")
450
451 def ifacefmt(self, f, *args):
452 comment = '''
453 // interface declaration between %s-{0} and pinmux'''
454 for (name, count) in self.ifacecount:
455 for i in range(count):
456 c = comment % name.upper()
457 f.write(c.format(i))
458 f.write(self.data[name].ifacefmt(i))
459
460 def ifacefmt2(self, f, *args):
461 comment = '''
462 interface PeripheralSide{0} {1};'''
463 for (name, count) in self.ifacecount:
464 for i in range(count):
465 iname = self.data[name].iname().format(i)
466 f.write(comment.format(name.upper(), iname))
467
468 def wirefmt(self, f, *args):
469 comment = '\n // following wires capture signals ' \
470 'to IO CELL if %s-{0} is\n' \
471 ' // allotted to it'
472 for (name, count) in self.ifacecount:
473 for i in range(count):
474 c = comment % name
475 f.write(c.format(i))
476 f.write(self.data[name].wirefmt(i))
477
478
479 # ========= Interface declarations ================ #
480
481 mux_interface = MuxInterface('cell',
482 [{'name': 'mux', 'ready': False, 'enabled': False,
483 'bitspec': '{1}', 'action': True}])
484
485 io_interface = IOInterface(
486 'io',
487 [{'name': 'cell_out', 'enabled': True, },
488 {'name': 'cell_outen', 'enabled': True, 'outenmode': True, },
489 {'name': 'cell_in', 'action': True, 'io': True}, ])
490
491 # == Peripheral Interface definitions == #
492 # these are the interface of the peripherals to the pin mux
493 # Outputs from the peripherals will be inputs to the pinmux
494 # module. Hence the change in direction for most pins
495
496 # ======================================= #
497
498 # basic test
499 if __name__ == '__main__':
500
501 uartinterface_decl = Interface('uart',
502 [{'name': 'rx'},
503 {'name': 'tx', 'action': True},
504 ])
505
506 twiinterface_decl = Interface('twi',
507 [{'name': 'sda', 'outen': True},
508 {'name': 'scl', 'outen': True},
509 ])
510
511 def _pinmunge(p, sep, repl, dedupe=True):
512 """ munges the text so it's easier to compare.
513 splits by separator, strips out blanks, re-joins.
514 """
515 p = p.strip()
516 p = p.split(sep)
517 if dedupe:
518 p = filter(lambda x: x, p) # filter out blanks
519 return repl.join(p)
520
521 def pinmunge(p):
522 """ munges the text so it's easier to compare.
523 """
524 # first join lines by semicolons, strip out returns
525 p = p.split(";")
526 p = map(lambda x: x.replace('\n', ''), p)
527 p = '\n'.join(p)
528 # now split first by brackets, then spaces (deduping on spaces)
529 p = _pinmunge(p, "(", " ( ", False)
530 p = _pinmunge(p, ")", " ) ", False)
531 p = _pinmunge(p, " ", " ")
532 return p
533
534 def zipcmp(l1, l2):
535 l1 = l1.split("\n")
536 l2 = l2.split("\n")
537 for p1, p2 in zip(l1, l2):
538 print (repr(p1))
539 print (repr(p2))
540 print ()
541 assert p1 == p2
542
543 ifaces = Interfaces()
544
545 ifaceuart = ifaces['uart']
546 print (ifaceuart.ifacedef(0))
547 print (uartinterface_decl.ifacedef(0))
548 assert ifaceuart.ifacedef(0) == uartinterface_decl.ifacedef(0)
549
550 ifacetwi = ifaces['twi']
551 print (ifacetwi.ifacedef(0))
552 print (twiinterface_decl.ifacedef(0))
553 assert ifacetwi.ifacedef(0) == twiinterface_decl.ifacedef(0)