use getifacetype to identify generation of xxxx_io objects
[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
11
12 class Pin(object):
13 """ pin interface declaration.
14 * name is the name of the pin
15 * ready, enabled and io all create a (* .... *) prefix
16 * action changes it to an "in" if true
17 """
18
19 def __init__(self, name,
20 ready=True,
21 enabled=True,
22 io=False,
23 action=False,
24 bitspec=None):
25 self.name = name
26 self.ready = ready
27 self.enabled = enabled
28 self.io = io
29 self.action = action
30 self.bitspec = bitspec if bitspec else 'Bit#(1)'
31
32 def ifacefmt(self, fmtfn=None):
33 res = ' '
34 status = []
35 if self.ready:
36 status.append('always_ready')
37 if self.enabled:
38 status.append('always_enabled')
39 if self.io:
40 status.append('result="io"')
41 if status:
42 res += '(*'
43 res += ','.join(status)
44 res += '*)'
45 res += " method "
46 if self.io:
47 res += "\n "
48 name = fmtfn(self.name)
49 if self.action:
50 res += " Action "
51 res += name
52 res += ' (%s in)' % self.bitspec
53 else:
54 res += " %s " % self.bitspec
55 res += name
56 res += ";"
57 return res
58
59 def ifacedef(self, fmtoutfn=None, fmtinfn=None, fmtdecfn=None):
60 res = ' method '
61 if self.action:
62 fmtname = fmtinfn(self.name)
63 res += "Action "
64 res += fmtdecfn(self.name)
65 res += '(%s in);\n' % self.bitspec
66 res += ' %s<=in;\n' % fmtname
67 res += ' endmethod'
68 else:
69 fmtname = fmtoutfn(self.name)
70 res += "%s=%s;" % (self.name, fmtname)
71 return res
72
73 def wirefmt(self, fmtoutfn=None, fmtinfn=None, fmtdecfn=None):
74 res = ' Wire#(%s) ' % self.bitspec
75 if self.action:
76 res += '%s' % fmtinfn(self.name)
77 else:
78 res += '%s' % fmtoutfn(self.name)
79 res += "<-mkDWire(0);"
80 return res
81
82
83 class Interface(object):
84 """ create an interface from a list of pinspecs.
85 each pinspec is a dictionary, see Pin class arguments
86 single indicates that there is only one of these, and
87 so the name must *not* be extended numerically (see pname)
88 """
89
90 def __init__(self, ifacename, pinspecs, ganged=None, single=False):
91 self.ifacename = ifacename
92 self.ganged = ganged or {}
93 self.pins = []
94 self.pinspecs = pinspecs
95 self.single = single
96 for p in pinspecs:
97 _p = {}
98 _p.update(p)
99 if p.get('outen') is True: # special case, generate 3 pins
100 del _p['outen']
101 for psuffix in ['out', 'outen', 'in']:
102 _p['name'] = "%s_%s" % (self.pname(p['name']), psuffix)
103 _p['action'] = psuffix != 'in'
104 self.pins.append(Pin(**_p))
105 else:
106 _p['name'] = self.pname(p['name'])
107 self.pins.append(Pin(**_p))
108
109 def getifacetype(self, name):
110 for p in self.pinspecs:
111 fname = "%s_%s" % (self.ifacename, p['name'])
112 #print "search", self.ifacename, name, fname
113 if fname == name:
114 if p.get('action'):
115 return 'out'
116 elif p.get('outen'):
117 return 'inout'
118 return 'input'
119 return None
120
121 def pname(self, name):
122 """ generates the interface spec e.g. flexbus_ale
123 if there is only one flexbus interface, or
124 sd{0}_cmd if there are several. string format
125 function turns this into sd0_cmd, sd1_cmd as
126 appropriate. single mode stops the numerical extension.
127 """
128 if self.single:
129 return '%s_%s' % (self.ifacename, name)
130 return '%s{0}_%s' % (self.ifacename, name)
131
132 def busfmt(self, *args):
133 """ this function creates a bus "ganging" system based
134 on input from the {interfacename}.txt file.
135 only inout pins that are under the control of the
136 interface may be "ganged" together.
137 """
138 if not self.ganged:
139 return ''
140 #print self.ganged
141 res = []
142 for (k, pnames) in self.ganged.items():
143 name = self.pname('%senable' % k).format(*args)
144 decl = 'Bit#(1) %s = 0;' % name
145 res.append(decl)
146 ganged = []
147 for p in self.pinspecs:
148 if p['name'] not in pnames:
149 continue
150 pname = self.pname(p['name']).format(*args)
151 if p.get('outen') is True:
152 outname = self.ifacefmtoutfn(pname)
153 ganged.append("%s_outen" % outname) # match wirefmt
154
155 gangedfmt = '{%s} = duplicate(%s);'
156 res.append(gangedfmt % (',\n '.join(ganged), name))
157 return '\n'.join(res) + '\n\n'
158
159 def wirefmt(self, *args):
160 res = '\n'.join(map(self.wirefmtpin, self.pins)).format(*args)
161 res += '\n'
162 for p in self.pinspecs:
163 name = self.pname(p['name'])
164 typ = self.getifacetype(name.format(""))
165 name = name.format(*args)
166 res += " # declare %s_io, set up as type '%s'\n" % (name, typ)
167 res += " GenericIOType %s_io = GenericIOType{\n" % name
168 params = []
169 if typ == 'inout':
170 outname = self.ifacefmtoutfn(name)
171 params.append('outputval:%s_out,' % outname)
172 params.append('output_en:%s_outen,' % outname) # match busfmt
173 params.append('input_en:~%s_outen,' % outname)
174 elif typ == 'out':
175 outname = self.ifacefmtoutfn(name)
176 params.append('outputval:%s,' % outname)
177 params.append('output_en:1,')
178 params.append('input_en:0,')
179 else: # input
180 params.append('outputval:0,')
181 params.append('output_en:0,')
182 params.append('input_en:1,')
183 params += ['pullup_en:0,', 'pulldown_en:0,',
184 'pushpull_en:0,', 'drivestrength:0,',
185 'opendrain_en:0']
186 for param in params:
187 res += ' %s\n' % param
188 res += ' };\n'
189 return '\n' + res
190
191 def ifacefmt(self, *args):
192 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
193 return '\n' + res
194
195 def ifacefmtdecfn(self, name):
196 return name
197
198 def ifacefmtdecfn2(self, name):
199 return name
200
201 def ifacefmtoutfn(self, name):
202 return "wr%s" % name
203
204 def ifacefmtinfn(self, name):
205 return "wr%s" % name
206
207 def wirefmtpin(self, pin):
208 return pin.wirefmt(self.ifacefmtoutfn, self.ifacefmtinfn,
209 self.ifacefmtdecfn2)
210
211 def ifacefmtdecpin(self, pin):
212 return pin.ifacefmt(self.ifacefmtdecfn)
213
214 def ifacefmtpin(self, pin):
215 return pin.ifacedef(self.ifacefmtoutfn, self.ifacefmtinfn,
216 self.ifacefmtdecfn2)
217
218 def ifacedef(self, *args):
219 res = '\n'.join(map(self.ifacefmtpin, self.pins))
220 res = res.format(*args)
221 return '\n' + res + '\n'
222
223
224 class MuxInterface(Interface):
225
226 def wirefmt(self, *args):
227 return muxwire.format(*args)
228
229
230 class IOInterface(Interface):
231
232 def ifacefmtoutfn(self, name):
233 """ for now strip off io{0}_ part """
234 return "cell{0}_mux_out"
235
236 def ifacefmtinfn(self, name):
237 return "cell{0}_mux_in"
238
239 def wirefmt(self, *args):
240 return generic_io.format(*args)
241
242
243 class Interfaces(UserDict):
244 """ contains a list of interface definitions
245 """
246
247 def __init__(self, pth):
248 self.pth = pth
249 self.ifacecount = []
250 UserDict.__init__(self, {})
251 ift = 'interfaces.txt'
252 if pth:
253 ift = os.path.join(pth, ift)
254 with open(ift, 'r') as ifile:
255 for ln in ifile.readlines():
256 ln = ln.strip()
257 ln = ln.split("\t")
258 name = ln[0]
259 count = int(ln[1])
260 spec, ganged = self.read_spec(pth, name)
261 iface = Interface(name, spec, ganged, count == 1)
262 self.ifaceadd(name, count, iface)
263
264 def getifacetype(self, fname):
265 # finds the interface type, e.g sd_d0 returns "inout"
266 for iface in self.values():
267 typ = iface.getifacetype(fname)
268 if typ:
269 return typ
270 return None
271
272 def ifaceadd(self, name, count, iface, at=None):
273 if at is None:
274 at = len(self.ifacecount)
275 self.ifacecount.insert(at, (name, count))
276 self[name] = iface
277
278 def read_spec(self, pth, name):
279 spec = []
280 ganged = {}
281 fname = '%s.txt' % name
282 if pth:
283 ift = os.path.join(pth, fname)
284 with open(ift, 'r') as sfile:
285 for ln in sfile.readlines():
286 ln = ln.strip()
287 ln = ln.split("\t")
288 name = ln[0]
289 d = {'name': name}
290 if ln[1] == 'out':
291 d['action'] = True
292 elif ln[1] == 'inout':
293 d['outen'] = True
294 if len(ln) == 3:
295 bus = ln[2]
296 if bus not in ganged:
297 ganged[bus] = []
298 ganged[bus].append(name)
299 spec.append(d)
300 return spec, ganged
301
302 def ifacedef(self, f, *args):
303 for (name, count) in self.ifacecount:
304 for i in range(count):
305 f.write(self.data[name].ifacedef(i))
306
307 def busfmt(self, f, *args):
308 f.write("import BUtils::*;\n\n")
309 for (name, count) in self.ifacecount:
310 for i in range(count):
311 bf = self.data[name].busfmt(i)
312 f.write(bf)
313
314 def ifacefmt(self, f, *args):
315 comment = '''
316 // interface declaration between %s-{0} and pinmux'''
317 for (name, count) in self.ifacecount:
318 for i in range(count):
319 c = comment % name.upper()
320 f.write(c.format(i))
321 f.write(self.data[name].ifacefmt(i))
322
323 def wirefmt(self, f, *args):
324 comment = '\n // following wires capture signals ' \
325 'to IO CELL if %s-{0} is\n' \
326 ' // allotted to it'
327 for (name, count) in self.ifacecount:
328 for i in range(count):
329 c = comment % name
330 f.write(c.format(i))
331 f.write(self.data[name].wirefmt(i))
332
333
334 # ========= Interface declarations ================ #
335
336 mux_interface = MuxInterface('cell', [{'name': 'mux', 'ready': False,
337 'enabled': False,
338 'bitspec': '{1}', 'action': True}])
339
340 io_interface = IOInterface(
341 'io',
342 [{'name': 'cell', 'enabled': False, 'bitspec': 'GenericIOType'},
343 {'name': 'inputval', 'action': True, 'io': True}, ])
344
345 # == Peripheral Interface definitions == #
346 # these are the interface of the peripherals to the pin mux
347 # Outputs from the peripherals will be inputs to the pinmux
348 # module. Hence the change in direction for most pins
349
350 # ======================================= #
351
352 # basic test
353 if __name__ == '__main__':
354
355 uartinterface_decl = Interface('uart',
356 [{'name': 'rx'},
357 {'name': 'tx', 'action': True},
358 ])
359
360 twiinterface_decl = Interface('twi',
361 [{'name': 'sda', 'outen': True},
362 {'name': 'scl', 'outen': True},
363 ])
364
365 def _pinmunge(p, sep, repl, dedupe=True):
366 """ munges the text so it's easier to compare.
367 splits by separator, strips out blanks, re-joins.
368 """
369 p = p.strip()
370 p = p.split(sep)
371 if dedupe:
372 p = filter(lambda x: x, p) # filter out blanks
373 return repl.join(p)
374
375 def pinmunge(p):
376 """ munges the text so it's easier to compare.
377 """
378 # first join lines by semicolons, strip out returns
379 p = p.split(";")
380 p = map(lambda x: x.replace('\n', ''), p)
381 p = '\n'.join(p)
382 # now split first by brackets, then spaces (deduping on spaces)
383 p = _pinmunge(p, "(", " ( ", False)
384 p = _pinmunge(p, ")", " ) ", False)
385 p = _pinmunge(p, " ", " ")
386 return p
387
388 def zipcmp(l1, l2):
389 l1 = l1.split("\n")
390 l2 = l2.split("\n")
391 for p1, p2 in zip(l1, l2):
392 print (repr(p1))
393 print (repr(p2))
394 print ()
395 assert p1 == p2
396
397 ifaces = Interfaces()
398
399 ifaceuart = ifaces['uart']
400 print (ifaceuart.ifacedef(0))
401 print (uartinterface_decl.ifacedef(0))
402 assert ifaceuart.ifacedef(0) == uartinterface_decl.ifacedef(0)
403
404 ifacetwi = ifaces['twi']
405 print (ifacetwi.ifacedef(0))
406 print (twiinterface_decl.ifacedef(0))
407 assert ifacetwi.ifacedef(0) == twiinterface_decl.ifacedef(0)