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