create new get/put interface pinmux declaration
[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 ready=True,
25 enabled=True,
26 io=False,
27 action=False,
28 bitspec=None,
29 outenmode=False):
30 self.name = name
31 self.name_ = name_
32 self.ready = ready
33 self.enabled = enabled
34 self.io = io
35 self.action = action
36 self.bitspec = bitspec if bitspec else 'Bit#(1)'
37 self.outenmode = outenmode
38
39 # bsv will look like this (method declaration):
40 """
41 (*always_ready,always_enabled*) method Bit#(1) io0_cell_outen;
42 (*always_ready,always_enabled,result="io"*) method
43 Action io0_inputval (Bit#(1) in);
44 """
45
46 def ifacepfmt(self, fmtfn):
47 res = ' '
48 status = []
49 res += "interface "
50 name = fmtfn(self.name_)
51 if self.action:
52 res += "Put"
53 else:
54 res += "Get"
55 res += "#(%s) %s;" % (self.bitspec, name)
56 return res
57
58 def ifacefmt(self, fmtfn):
59 res = ' '
60 status = []
61 if self.ready:
62 status.append('always_ready')
63 if self.enabled:
64 status.append('always_enabled')
65 if self.io:
66 status.append('result="io"')
67 if status:
68 res += '(*'
69 res += ','.join(status)
70 res += '*)'
71 res += " method "
72 if self.io:
73 res += "\n "
74 name = fmtfn(self.name)
75 if self.action:
76 res += " Action "
77 res += name
78 res += ' (%s in)' % self.bitspec
79 else:
80 res += " %s " % self.bitspec
81 res += name
82 res += ";"
83 return res
84
85 def ifacedef(self, fmtoutfn, fmtinfn, fmtdecfn):
86 res = ' method '
87 if self.action:
88 fmtname = fmtinfn(self.name)
89 res += "Action "
90 res += fmtdecfn(self.name)
91 res += '(%s in);\n' % self.bitspec
92 res += ' %s<=in;\n' % fmtname
93 res += ' endmethod'
94 else:
95 fmtname = fmtoutfn(self.name)
96 res += "%s=%s;" % (self.name, fmtname)
97 return res
98 # sample bsv method definition :
99 """
100 method Action cell0_mux(Bit#(2) in);
101 wrcell0_mux<=in;
102 endmethod
103 """
104
105 # sample bsv wire (wire definiton):
106 """
107 Wire#(Bit#(2)) wrcell0_mux<-mkDWire(0);
108 """
109
110 def wirefmt(self, fmtoutfn, fmtinfn, fmtdecfn):
111 res = ' Wire#(%s) ' % self.bitspec
112 if self.action:
113 res += '%s' % fmtinfn(self.name)
114 else:
115 res += '%s' % fmtoutfn(self.name)
116 res += "<-mkDWire(0);"
117 return res
118
119 def ifacedef2(self, fmtoutfn, fmtinfn, fmtdecfn):
120 if self.action:
121 fmtname = fmtinfn(self.name)
122 res = " interface %s = interface Put\n" % self.name_
123 res += ' method '
124 res += "Action put"
125 #res += fmtdecfn(self.name)
126 res += '(%s in);\n' % self.bitspec
127 res += ' %s<=in;\n' % fmtname
128 res += ' endmethod\n'
129 res += ' endinterface;'
130 else:
131 fmtname = fmtoutfn(self.name)
132 res = " interface %s = interface Get\n" % self.name_
133 res += ' method ActionValue#'
134 res += '(%s) get;\n' % self.bitspec
135 res += " return %s;\n" % (fmtname)
136 res += ' endmethod\n'
137 res += ' endinterface;'
138 return res
139
140 class Interface(PeripheralIface):
141 """ create an interface from a list of pinspecs.
142 each pinspec is a dictionary, see Pin class arguments
143 single indicates that there is only one of these, and
144 so the name must *not* be extended numerically (see pname)
145 """
146 # sample interface object:
147 """
148 twiinterface_decl = Interface('twi',
149 [{'name': 'sda', 'outen': True},
150 {'name': 'scl', 'outen': True},
151 ])
152 """
153
154 def __init__(self, ifacename, pinspecs, ganged=None, single=False):
155 PeripheralIface.__init__(self, ifacename)
156 self.ifacename = ifacename
157 self.ganged = ganged or {}
158 self.pins = [] # a list of instances of class Pin
159 self.pinspecs = pinspecs # a list of dictionary
160 self.single = single
161
162 for p in pinspecs:
163 _p = {}
164 _p.update(p)
165 if 'type' in _p:
166 del _p['type']
167 if p.get('outen') is True: # special case, generate 3 pins
168 del _p['outen']
169 for psuffix in ['out', 'outen', 'in']:
170 # changing the name (like sda) to (twi_sda_out)
171 _p['name_'] = "%s_%s" % (p['name'], psuffix)
172 _p['name'] = "%s_%s" % (self.pname(p['name']), psuffix)
173 _p['action'] = psuffix != 'in'
174 self.pins.append(Pin(**_p))
175 # will look like {'name': 'twi_sda_out', 'action': True}
176 # {'name': 'twi_sda_outen', 'action': True}
177 #{'name': 'twi_sda_in', 'action': False}
178 # NOTice - outen key is removed
179 else:
180 _p['name_'] = p['name']
181 _p['name'] = self.pname(p['name'])
182 self.pins.append(Pin(**_p))
183
184 # sample interface object:
185 """
186 uartinterface_decl = Interface('uart',
187 [{'name': 'rx'},
188 {'name': 'tx', 'action': True},
189 ])
190 """
191 """
192 getifacetype is called multiple times in actual_pinmux.py
193 x = ifaces.getifacetype(temp), where temp is uart_rx, spi_mosi
194 Purpose is to identify is function : input/output/inout
195 """
196
197 def getifacetype(self, name):
198 for p in self.pinspecs:
199 fname = "%s_%s" % (self.ifacename, p['name'])
200 # print "search", self.ifacename, name, fname
201 if fname == name:
202 if p.get('action'):
203 return 'out'
204 elif p.get('outen'):
205 return 'inout'
206 return 'input'
207 return None
208
209 def iname(self):
210 """ generates the interface spec e.g. flexbus_ale
211 if there is only one flexbus interface, or
212 sd{0}_cmd if there are several. string format
213 function turns this into sd0_cmd, sd1_cmd as
214 appropriate. single mode stops the numerical extension.
215 """
216 if self.single:
217 return self.ifacename
218 return '%s{0}' % self.ifacename
219
220 def pname(self, name):
221 """ generates the interface spec e.g. flexbus_ale
222 if there is only one flexbus interface, or
223 sd{0}_cmd if there are several. string format
224 function turns this into sd0_cmd, sd1_cmd as
225 appropriate. single mode stops the numerical extension.
226 """
227 return "%s_%s" % (self.iname(), name)
228
229 def busfmt(self, *args):
230 """ this function creates a bus "ganging" system based
231 on input from the {interfacename}.txt file.
232 only inout pins that are under the control of the
233 interface may be "ganged" together.
234 """
235 if not self.ganged:
236 return '' # when self.ganged is None
237 # print self.ganged
238 res = []
239 for (k, pnames) in self.ganged.items():
240 name = self.pname('%senable' % k).format(*args)
241 decl = 'Bit#(1) %s = 0;' % name
242 res.append(decl)
243 ganged = []
244 for p in self.pinspecs:
245 if p['name'] not in pnames:
246 continue
247 pname = self.pname(p['name']).format(*args)
248 if p.get('outen') is True:
249 outname = self.ifacefmtoutfn(pname)
250 ganged.append("%s_outen" % outname) # match wirefmt
251
252 gangedfmt = '{%s} = duplicate(%s);'
253 res.append(gangedfmt % (',\n '.join(ganged), name))
254 return '\n'.join(res) + '\n\n'
255
256 def wirefmt(self, *args):
257 res = '\n'.join(map(self.wirefmtpin, self.pins)).format(*args)
258 res += '\n'
259 return '\n' + res
260
261 def ifacepfmt(self, *args):
262 res = '\n'.join(map(self.ifacepfmtdecpin, self.pins)).format(*args)
263 return '\n' + res # pins is a list
264
265 def ifacefmt(self, *args):
266 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
267 return '\n' + res # pins is a list
268
269 def ifacepfmtdecfn(self, name):
270 return name
271
272 def ifacefmtdecfn(self, name):
273 return name # like: uart
274
275 def ifacefmtdecfn2(self, name):
276 return name # like: uart
277
278 def ifacefmtdecfn3(self, name):
279 """ HACK! """
280 return "%s_outen" % name # like uart_outen
281
282 def ifacefmtoutfn(self, name):
283 return "wr%s" % name # like wruart
284
285 def ifacefmtinfn(self, name):
286 return "wr%s" % name
287
288 def wirefmtpin(self, pin):
289 return pin.wirefmt(self.ifacefmtoutfn, self.ifacefmtinfn,
290 self.ifacefmtdecfn2)
291
292 def ifacepfmtdecpin(self, pin):
293 return pin.ifacepfmt(self.ifacepfmtdecfn)
294
295 def ifacefmtdecpin(self, pin):
296 return pin.ifacefmt(self.ifacefmtdecfn)
297
298 def ifacefmtpin(self, pin):
299 decfn = self.ifacefmtdecfn2
300 outfn = self.ifacefmtoutfn
301 # print pin, pin.outenmode
302 if pin.outenmode:
303 decfn = self.ifacefmtdecfn3
304 outfn = self.ifacefmtoutenfn
305 return pin.ifacedef(outfn, self.ifacefmtinfn,
306 decfn)
307
308 def ifacedef2pin(self, pin):
309 decfn = self.ifacefmtdecfn2
310 outfn = self.ifacefmtoutfn
311 # print pin, pin.outenmode
312 if pin.outenmode:
313 decfn = self.ifacefmtdecfn3
314 outfn = self.ifacefmtoutenfn
315 return pin.ifacedef2(outfn, self.ifacefmtinfn,
316 decfn)
317
318 def ifacedef(self, *args):
319 res = '\n'.join(map(self.ifacefmtpin, self.pins))
320 res = res.format(*args)
321 return '\n' + res + '\n'
322
323 def ifacedef2(self, *args):
324 res = '\n'.join(map(self.ifacedef2pin, self.pins))
325 res = res.format(*args)
326 return '\n' + res + '\n'
327
328
329 class MuxInterface(Interface):
330
331 def wirefmt(self, *args):
332 return muxwire.format(*args)
333
334
335 class IOInterface(Interface):
336
337 def ifacefmtoutenfn(self, name):
338 return "cell{0}_mux_outen"
339
340 def ifacefmtoutfn(self, name):
341 """ for now strip off io{0}_ part """
342 return "cell{0}_mux_out"
343
344 def ifacefmtinfn(self, name):
345 return "cell{0}_mux_in"
346
347 def wirefmt(self, *args):
348 return generic_io.format(*args)
349
350
351 class Interfaces(InterfacesBase, PeripheralInterfaces):
352 """ contains a list of interface definitions
353 """
354
355 def __init__(self, pth=None):
356 InterfacesBase.__init__(self, Interface, pth)
357 PeripheralInterfaces.__init__(self)
358
359 def ifacedef(self, f, *args):
360 for (name, count) in self.ifacecount:
361 for i in range(count):
362 f.write(self.data[name].ifacedef(i))
363
364 def ifacedef2(self, f, *args):
365 c = " interface {0} = interface PeripheralSide{1}"
366 for (name, count) in self.ifacecount:
367 for i in range(count):
368 iname = self.data[name].iname().format(i)
369 f.write(c.format(iname, name.upper()))
370 f.write(self.data[name].ifacedef2(i))
371 f.write(" endinterface;\n\n")
372
373 def busfmt(self, f, *args):
374 f.write("import BUtils::*;\n\n")
375 for (name, count) in self.ifacecount:
376 for i in range(count):
377 bf = self.data[name].busfmt(i)
378 f.write(bf)
379
380 def ifacepfmt(self, f, *args):
381 comment = '''
382 // interface declaration between {0} and pinmux
383 (*always_ready,always_enabled*)
384 interface PeripheralSide{0};'''
385 for (name, count) in self.ifacecount:
386 f.write(comment.format(name.upper()))
387 f.write(self.data[name].ifacepfmt(0))
388 f.write("\n endinterface\n")
389
390 def ifacefmt(self, f, *args):
391 comment = '''
392 // interface declaration between %s-{0} and pinmux'''
393 for (name, count) in self.ifacecount:
394 for i in range(count):
395 c = comment % name.upper()
396 f.write(c.format(i))
397 f.write(self.data[name].ifacefmt(i))
398
399 def ifacefmt2(self, f, *args):
400 comment = '''
401 interface PeripheralSide{0} {1};'''
402 for (name, count) in self.ifacecount:
403 for i in range(count):
404 iname = self.data[name].iname().format(i)
405 f.write(comment.format(name.upper(), iname))
406
407 def wirefmt(self, f, *args):
408 comment = '\n // following wires capture signals ' \
409 'to IO CELL if %s-{0} is\n' \
410 ' // allotted to it'
411 for (name, count) in self.ifacecount:
412 for i in range(count):
413 c = comment % name
414 f.write(c.format(i))
415 f.write(self.data[name].wirefmt(i))
416
417
418 # ========= Interface declarations ================ #
419
420 mux_interface = MuxInterface('cell',
421 [{'name': 'mux', 'ready': False, 'enabled': False,
422 'bitspec': '{1}', 'action': True}])
423
424 io_interface = IOInterface(
425 'io',
426 [{'name': 'cell_out', 'enabled': True, },
427 {'name': 'cell_outen', 'enabled': True, 'outenmode': True, },
428 {'name': 'cell_in', 'action': True, 'io': True}, ])
429
430 # == Peripheral Interface definitions == #
431 # these are the interface of the peripherals to the pin mux
432 # Outputs from the peripherals will be inputs to the pinmux
433 # module. Hence the change in direction for most pins
434
435 # ======================================= #
436
437 # basic test
438 if __name__ == '__main__':
439
440 uartinterface_decl = Interface('uart',
441 [{'name': 'rx'},
442 {'name': 'tx', 'action': True},
443 ])
444
445 twiinterface_decl = Interface('twi',
446 [{'name': 'sda', 'outen': True},
447 {'name': 'scl', 'outen': True},
448 ])
449
450 def _pinmunge(p, sep, repl, dedupe=True):
451 """ munges the text so it's easier to compare.
452 splits by separator, strips out blanks, re-joins.
453 """
454 p = p.strip()
455 p = p.split(sep)
456 if dedupe:
457 p = filter(lambda x: x, p) # filter out blanks
458 return repl.join(p)
459
460 def pinmunge(p):
461 """ munges the text so it's easier to compare.
462 """
463 # first join lines by semicolons, strip out returns
464 p = p.split(";")
465 p = map(lambda x: x.replace('\n', ''), p)
466 p = '\n'.join(p)
467 # now split first by brackets, then spaces (deduping on spaces)
468 p = _pinmunge(p, "(", " ( ", False)
469 p = _pinmunge(p, ")", " ) ", False)
470 p = _pinmunge(p, " ", " ")
471 return p
472
473 def zipcmp(l1, l2):
474 l1 = l1.split("\n")
475 l2 = l2.split("\n")
476 for p1, p2 in zip(l1, l2):
477 print (repr(p1))
478 print (repr(p2))
479 print ()
480 assert p1 == p2
481
482 ifaces = Interfaces()
483
484 ifaceuart = ifaces['uart']
485 print (ifaceuart.ifacedef(0))
486 print (uartinterface_decl.ifacedef(0))
487 assert ifaceuart.ifacedef(0) == uartinterface_decl.ifacedef(0)
488
489 ifacetwi = ifaces['twi']
490 print (ifacetwi.ifacedef(0))
491 print (twiinterface_decl.ifacedef(0))
492 assert ifacetwi.ifacedef(0) == twiinterface_decl.ifacedef(0)