use function abstraction, reduce code a bit
[pinmux.git] / src / bsv / pinmux_generator.py
1 # ================================== Steps to add peripherals ============
2 # Step-1: create interface declaration for the peripheral to be added.
3 # Remember these are interfaces defined for the pinmux and hence
4 # will be opposite to those defined at the peripheral.
5 # For eg. the output TX from the UART will be input (method Action)
6 # for the pinmux.
7 # These changes will have to be done in interface_decl.py
8 # Step-2 define the wires that will be required to transfer data from the
9 # peripheral interface to the IO cell and vice-versa. Create a
10 # mkDWire for each input/output between the peripheral and the
11 # pinmux. Also create an implicit wire of GenericIOType for each cell
12 # that can be connected to a each bit from the peripheral.
13 # These changes will have to be done in wire_def.py
14 # Step-3: create the definitions for each of the methods defined above.
15 # These changes will have to be done in interface_decl.py
16 # ========================================================================
17
18 # default module imports
19 import shutil
20 import os
21 import os.path
22 import time
23
24 # project module imports
25 from bsv.interface_decl import Interfaces, mux_interface, io_interface
26 from parse import Parse
27 from bsv.actual_pinmux import init
28 from bsv.bus_transactors import axi4_lite
29
30 copyright = '''
31 /*
32 This BSV file has been generated by the PinMux tool available at:
33 https://bitbucket.org/casl/pinmux.
34
35 Authors: Neel Gala, Luke
36 Date of generation: ''' + time.strftime("%c") + '''
37 */
38 '''
39 header = copyright + '''
40 package pinmux;
41
42 '''
43 footer = '''
44 endmodule
45 endpackage
46 '''
47
48
49 def pinmuxgen(pth=None, verify=True):
50 """ populating the file with the code
51 """
52
53 p = Parse(pth, verify)
54 iocells = Interfaces()
55 iocells.ifaceadd('io', p.N_IO, io_interface, 0)
56 ifaces = Interfaces(pth)
57 #ifaces.ifaceadd('io', p.N_IO, io_interface, 0)
58 init(p, ifaces)
59
60 bp = 'bsv_src'
61 if pth:
62 bp = os.path.join(pth, bp)
63 if not os.path.exists(bp):
64 os.makedirs(bp)
65 bl = os.path.join(bp, 'bsv_lib')
66 if not os.path.exists(bl):
67 os.makedirs(bl)
68
69 cwd = os.path.split(__file__)[0]
70
71 # copy over template and library files
72 shutil.copyfile(os.path.join(cwd, 'Makefile.template'),
73 os.path.join(bp, 'Makefile'))
74 cwd = os.path.join(cwd, 'bsv_lib')
75 for fname in ['AXI4_Lite_Types.bsv', 'Semi_FIFOF.bsv',
76 'gpio.bsv', 'mux.bsv']:
77 shutil.copyfile(os.path.join(cwd, fname),
78 os.path.join(bl, fname))
79
80 bus = os.path.join(bp, 'busenable.bsv')
81 pmp = os.path.join(bp, 'pinmux.bsv')
82 ptp = os.path.join(bp, 'PinTop.bsv')
83 bvp = os.path.join(bp, 'bus.bsv')
84 idef = os.path.join(bp, 'instance_defines.bsv')
85 slow = os.path.join(bp, 'slow_peripherals.bsv')
86 slowt = os.path.join(cwd, 'slow_peripherals_template.bsv')
87
88 write_pmp(pmp, p, ifaces, iocells)
89 write_ptp(ptp, p, ifaces)
90 write_bvp(bvp, p, ifaces)
91 write_bus(bus, p, ifaces)
92 write_instances(idef, p, ifaces)
93 write_slow(slow, slowt, p, ifaces)
94
95
96 def write_slow(slow, template, p, ifaces):
97 """ write out the slow_peripherals.bsv file.
98 joins all the peripherals together into one AXI Lite interface
99 """
100 with open(template) as bsv_file:
101 template = bsv_file.read()
102 imports = ifaces.slowimport()
103 ifdecl = ifaces.slowifdecl()
104 regdef = ifaces.axi_reg_def()
105 slavedecl = ifaces.axi_slave_idx()
106 fnaddrmap = ifaces.axi_addr_map()
107 mkslow = ifaces.mkslow_peripheral()
108 with open(slow, "w") as bsv_file:
109 bsv_file.write(template.format(imports, ifdecl, regdef, slavedecl,
110 fnaddrmap, mkslow))
111
112
113 def write_bus(bus, p, ifaces):
114 # package and interface declaration followed by
115 # the generic io_cell definition
116 with open(bus, "w") as bsv_file:
117 ifaces.busfmt(bsv_file)
118
119
120 def write_pmp(pmp, p, ifaces, iocells):
121 # package and interface declaration followed by
122 # the generic io_cell definition
123 with open(pmp, "w") as bsv_file:
124 bsv_file.write(header)
125
126 cell_bit_width = 'Bit#(%d)' % p.cell_bitwidth
127 bsv_file.write('''\
128 interface MuxSelectionLines;
129
130 // declare the method which will capture the user pin-mux
131 // selection values.The width of the input is dependent on the number
132 // of muxes happening per IO. For now we have a generalized width
133 // where each IO will have the same number of muxes.''')
134
135 for cell in p.muxed_cells:
136 bsv_file.write(mux_interface.ifacefmt(cell[0], cell_bit_width))
137
138 bsv_file.write("\n endinterface\n")
139
140 bsv_file.write('''
141
142 interface IOCellSide;
143 // declare the interface to the IO cells.
144 // Each IO cell will have 1 input field (output from pin mux)
145 // and an output and out-enable field (input to pinmux)''')
146
147 # == create method definitions for all iocell interfaces ==#
148 iocells.ifacefmt(bsv_file)
149
150 # ===== finish interface definition and start module definition=======
151 bsv_file.write("\n endinterface\n")
152
153 # ===== io cell definition =======
154 bsv_file.write('''
155
156 interface PeripheralSide;
157 // declare the interface to the peripherals
158 // Each peripheral's function will be either an input, output
159 // or be bi-directional. an input field will be an output from the
160 // peripheral and an output field will be an input to the peripheral.
161 // Bi-directional functions also have an output-enable (which
162 // again comes *in* from the peripheral)''')
163 # ==============================================================
164
165 # == create method definitions for all peripheral interfaces ==#
166 ifaces.ifacefmt(bsv_file)
167 bsv_file.write("\n endinterface\n")
168
169 # ===== finish interface definition and start module definition=======
170 bsv_file.write('''
171
172 interface Ifc_pinmux;
173 // this interface controls how each IO cell is routed. setting
174 // any given IO cell's mux control value will result in redirection
175 // of not just the input or output to different peripheral functions
176 // but also the *direction* control - if appropriate - as well.
177 interface MuxSelectionLines mux_lines;
178
179 // this interface contains the inputs, outputs and direction-control
180 // lines for all peripherals. GPIO is considered to also be just
181 // a peripheral because it also has in, out and direction-control.
182 interface PeripheralSide peripheral_side;
183
184 // this interface is to be linked to the individual IO cells.
185 // if looking at a "non-muxed" GPIO design, basically the
186 // IO cell input, output and direction-control wires are cut
187 // (giving six pairs of dangling wires, named left and right)
188 // these iocells are routed in their place on one side ("left")
189 // and the matching *GPIO* peripheral interfaces in/out/dir
190 // connect to the OTHER side ("right"). the result is that
191 // the muxer settings end up controlling the routing of where
192 // the I/O from the IOcell actually goes.
193 interface IOCellSide iocell_side;
194 endinterface
195 (*synthesize*)
196 module mkpinmux(Ifc_pinmux);
197 ''')
198 # ====================================================================
199
200 # ======================= create wire and registers =================#
201 bsv_file.write('''
202 // the followins wires capture the pin-mux selection
203 // values for each mux assigned to a CELL
204 ''')
205 for cell in p.muxed_cells:
206 bsv_file.write(mux_interface.wirefmt(
207 cell[0], cell_bit_width))
208
209 iocells.wirefmt(bsv_file)
210 ifaces.wirefmt(bsv_file)
211
212 bsv_file.write("\n")
213 # ====================================================================
214 # ========================= Actual pinmuxing ========================#
215 bsv_file.write('''
216 /*====== This where the muxing starts for each io-cell======*/
217 Wire#(Bit#(1)) val0<-mkDWire(0); // need a zero
218 ''')
219 bsv_file.write(p.pinmux)
220 bsv_file.write('''
221 /*============================================================*/
222 ''')
223 # ====================================================================
224 # ================= interface definitions for each method =============#
225 bsv_file.write('''
226 interface mux_lines = interface MuxSelectionLines
227 ''')
228 for cell in p.muxed_cells:
229 bsv_file.write(
230 mux_interface.ifacedef(
231 cell[0], cell_bit_width))
232 bsv_file.write("\n endinterface;")
233
234 bsv_file.write('''
235 interface iocell_side = interface IOCellSide
236 ''')
237 iocells.ifacedef(bsv_file)
238 bsv_file.write("\n endinterface;")
239
240 bsv_file.write('''
241 interface peripheral_side = interface PeripheralSide
242 ''')
243 ifaces.ifacedef(bsv_file)
244 bsv_file.write("\n endinterface;")
245
246 bsv_file.write(footer)
247 print("BSV file successfully generated: bsv_src/pinmux.bsv")
248 # ======================================================================
249
250
251 def write_ptp(ptp, p, ifaces):
252 with open(ptp, 'w') as bsv_file:
253 bsv_file.write(copyright + '''
254 package PinTop;
255 import pinmux::*;
256 interface Ifc_PintTop;
257 method ActionValue#(Bool) write(Bit#({0}) addr, Bit#({1}) data);
258 method Tuple2#(Bool,Bit#({1})) read(Bit#({0}) addr);
259 interface PeripheralSide peripheral_side;
260 endinterface
261
262 module mkPinTop(Ifc_PintTop);
263 // instantiate the pin-mux module here
264 Ifc_pinmux pinmux <-mkpinmux;
265
266 // declare the registers which will be used to mux the IOs
267 '''.format(p.ADDR_WIDTH, p.DATA_WIDTH))
268
269 cell_bit_width = str(p.cell_bitwidth)
270 for cell in p.muxed_cells:
271 bsv_file.write('''
272 Reg#(Bit#({0})) rg_muxio_{1} <-mkReg(0);'''.format(
273 cell_bit_width, cell[0]))
274
275 bsv_file.write('''
276 // rule to connect the registers to the selection lines of the
277 // pin-mux module
278 rule connect_selection_registers;''')
279
280 for cell in p.muxed_cells:
281 bsv_file.write('''
282 pinmux.mux_lines.cell{0}_mux(rg_muxio_{0});'''.format(cell[0]))
283
284 bsv_file.write('''
285 endrule
286 // method definitions for the write user interface
287 method ActionValue#(Bool) write(Bit#({2}) addr, Bit#({3}) data);
288 Bool err=False;
289 case (addr[{0}:{1}])'''.format(p.upper_offset, p.lower_offset,
290 p.ADDR_WIDTH, p.DATA_WIDTH))
291 index = 0
292 for cell in p.muxed_cells:
293 bsv_file.write('''
294 {0}: rg_muxio_{1}<=truncate(data);'''.format(index, cell[0]))
295 index = index + 1
296
297 bsv_file.write('''
298 default: err=True;
299 endcase
300 return err;
301 endmethod''')
302
303 bsv_file.write('''
304 // method definitions for the read user interface
305 method Tuple2#(Bool,Bit#({3})) read(Bit#({2}) addr);
306 Bool err=False;
307 Bit#(32) data=0;
308 case (addr[{0}:{1}])'''.format(p.upper_offset, p.lower_offset,
309 p.ADDR_WIDTH, p.DATA_WIDTH))
310 index = 0
311 for cell in p.muxed_cells:
312 bsv_file.write('''
313 {0}: data=zeroExtend(rg_muxio_{1});'''.format(index, cell[0]))
314 index = index + 1
315
316 bsv_file.write('''
317 default:err=True;
318 endcase
319 return tuple2(err,data);
320 endmethod
321 interface peripheral_side=pinmux.peripheral_side;
322 endmodule
323 endpackage
324 ''')
325
326
327 def write_bvp(bvp, p, ifaces):
328 # ######## Generate bus transactors ################
329 gpiocfg = '\t\tinterface GPIO_config#({4}) bank{3}_config;\n' \
330 '\t\tinterface AXI4_Lite_Slave_IFC#({0},{1},{2}) bank{3}_slave;'
331 muxcfg = '\t\tinterface MUX_config#({4}) muxb{3}_config;\n' \
332 '\t\tinterface AXI4_Lite_Slave_IFC#({0},{1},{2}) muxb{3}_slave;'
333
334 gpiodec = '\tGPIO#({0}) mygpio{1} <- mkgpio();'
335 muxdec = '\tMUX#({0}) mymux{1} <- mkmux();'
336 gpioifc = '\tinterface bank{0}_config=mygpio{0}.pad_config;\n' \
337 '\tinterface bank{0}_slave=mygpio{0}.axi_slave;'
338 muxifc = '\tinterface muxb{0}_config=mymux{0}.mux_config;\n' \
339 '\tinterface muxb{0}_slave=mymux{0}.axi_slave;'
340 with open(bvp, 'w') as bsv_file:
341 # assume here that all muxes have a 1:1 gpio
342 cfg = []
343 decl = []
344 idec = []
345 iks = sorted(ifaces.keys())
346 for iname in iks:
347 if not iname.startswith('gpio'): # TODO: declare other interfaces
348 continue
349 bank = iname[4:]
350 ifc = ifaces[iname]
351 npins = len(ifc.pinspecs)
352 cfg.append(gpiocfg.format(p.ADDR_WIDTH, p.DATA_WIDTH,
353 0, # USERSPACE
354 bank, npins))
355 cfg.append(muxcfg.format(p.ADDR_WIDTH, p.DATA_WIDTH,
356 0, # USERSPACE
357 bank, npins))
358 decl.append(gpiodec.format(npins, bank))
359 decl.append(muxdec .format(npins, bank))
360 idec.append(gpioifc.format(bank))
361 idec.append(muxifc.format(bank))
362 print dir(ifaces)
363 print ifaces.items()
364 print dir(ifaces['gpioa'])
365 print ifaces['gpioa'].pinspecs
366 gpiodecl = '\n'.join(decl) + '\n' + '\n'.join(idec)
367 gpiocfg = '\n'.join(cfg)
368 bsv_file.write(axi4_lite.format(gpiodecl, gpiocfg))
369 # ##################################################
370
371
372 def write_instances(idef, p, ifaces):
373 with open(idef, 'w') as bsv_file:
374 txt = '''\
375 `define ADDR {0}
376 `define DATA {1}
377 `define USERSPACE 0
378 '''
379 bsv_file.write(txt.format(p.ADDR_WIDTH, p.DATA_WIDTH))