massive overhaul of fpga code
[fleet.git] / src / edu / berkeley / fleet / fpga / Fpga.java
1 package edu.berkeley.fleet.fpga;
2 import edu.berkeley.fleet.fpga.*;
3 import edu.berkeley.fleet.api.*;
4 import edu.berkeley.fleet.two.*;
5 import edu.berkeley.fleet.*;
6 import java.lang.reflect.*;
7 import edu.berkeley.sbp.chr.*;
8 import edu.berkeley.sbp.misc.*;
9 import edu.berkeley.sbp.meta.*;
10 import edu.berkeley.sbp.util.*;
11 import java.util.*;
12 import java.io.*;
13 import edu.berkeley.fleet.two.*;
14 import static edu.berkeley.fleet.two.FleetTwoFleet.*;
15 import static edu.berkeley.fleet.fpga.verilog.Verilog.*;
16
17
18 /*
19 => get rid of getInputPort(String) and instead use members
20 => clean up fabricelement methods
21 => get rid of addcrap
22 => automatic width-setting on ports
23 => nuke DATAWIDTH?
24   => serdes and fastclock/slowclock?
25 */
26
27 public class Fpga extends FleetTwoFleet {
28
29     public  Module top;
30     public  FabricElement top_horn;
31     Ship debugShip;
32
33     public LinkedHashMap<String,FpgaShip> ships = new LinkedHashMap<String,FpgaShip>();
34     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
35
36     public Ship getShip(String type, int ordinal) {
37         for(Ship s : this)
38             if (s.getType().equals(type))
39                 if (ordinal-- < 0)
40                     return s;
41         return null;
42     }
43
44     public static void main(String[] s) throws Exception { 
45         new Fpga(new Module("root")).top.dump(s[0]);
46     }
47
48     public FleetProcess run(Instruction[] instructions) {
49         try {
50             return new Client(this, "none", instructions);
51         } catch (Exception e) { throw new RuntimeException(e); }
52     }
53
54     // Setup //////////////////////////////////////////////////////////////////////////////
55
56     public Ship createShip(String type, String name) throws IOException {
57         ShipDescription sd = new ShipDescription(type, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
58         FpgaShip ship = new FpgaShip(this, sd);
59         ships.put(name, ship);
60         return ship;
61     }
62
63     public Fpga() throws Exception { this(new Module("root")); }
64     public Fpga(Module top) throws Exception {
65         this.top = top;
66         debugShip = createShip("Debug",     "debug");
67
68         int LANES = 6;
69
70         createShip("Memory",    "memory1");
71
72         if (LANES>1)
73             createShip("Memory",    "memory2");
74
75         for(int i=0; i<LANES; i++) {
76             createShip("Fifo",      "fifo"+i);
77             createShip("Fifo",      "fifo"+i+"x");
78             createShip("Alu2",      "alu"+i);
79             createShip("Alu2",      "alu"+i+"x");
80         }
81         createShip("Rotator",   "rotator");
82         createShip("Lut3",      "lut");
83
84         if (LANES<=1)
85             createShip("Fifo",      "fifo_extra");
86
87         createShip("DRAM",    "dram");
88         createShip("Video",   "video");
89
90         //Module.SourcePort  debug_in    = top.createWireSourcePort("debug_in", WIDTH_PACKET);
91         Module.SourcePort  debug_out   = null;
92         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
93             if (ship.getType().toLowerCase().equals("debug"))
94                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
95         }
96
97         // for FifoShip
98         new Module.InstantiatedModule(top, new FifoModule(8, WIDTH_WORD));
99
100         Module.SourcePort  in          = top.createInputPort("in", 8);
101         Module.SinkPort    out         = top.createOutputPort("out", 8, "");
102         Module.Latch       temp_in     = top.new Latch("temp", WIDTH_PACKET) { public String doReset() { return name+"=0;"; } };
103         Module.Latch       count       = top.new Latch("count", 8);
104         Module.Latch       count_out   = top.new Latch("count_out", 8);
105
106         ArrayList inbox_sources = new ArrayList<FabricElement>();
107         ArrayList inbox_dests   = new ArrayList<FabricElement>();
108         ArrayList outbox_sources = new ArrayList<FabricElement>();
109         ArrayList outbox_dests   = new ArrayList<FabricElement>();
110         ArrayList instruction_dests   = new ArrayList<FabricElement>();
111         int numdocks = 0;
112         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
113             if (ship.getType().toLowerCase().equals("debug"))
114                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
115             for(Dock port : ship) {
116                 if (port.isInputDock()) {
117                     inbox_sources.add(((FpgaDock)port));
118                     instruction_dests.add(port.getInstructionDestination());
119                     inbox_dests.add(port.getDataDestination());
120                 } else {
121                     outbox_sources.add(((FpgaDock)port));
122                     instruction_dests.add(port.getInstructionDestination());
123                     outbox_dests.add(port.getDataDestination());
124                 }
125                 numdocks++;
126             }
127         }
128         //System.err.println("dock count = " + numdocks);
129         ArrayList dests   = new ArrayList<FabricElement>();
130         ArrayList sources = new ArrayList<FabricElement>();
131         sources.addAll(inbox_sources);
132         sources.addAll(outbox_sources);
133         dests.addAll(inbox_dests);
134         dests.addAll(instruction_dests);
135         dests.addAll(outbox_dests);
136         top_horn = mkNode((FabricElement[])dests.toArray(new FabricElement[0]), true);
137         FabricElement   source  = mkNode((FabricElement[])sources.toArray(new FabricElement[0]), false);
138         FunnelModule.FunnelInstance top_funnel = new FunnelModule.FunnelInstance(top, null, source.getOutputPort());
139         ((FunnelModule.FunnelInstance)source).out = top_funnel;
140         //top_horn.addInput(top_funnel, top_funnel.getOutputPort());
141         top_funnel.addOutput(top_horn, top_horn.getInputPort());
142
143         //Module.SourcePort  debug_in    = top.createWireSourcePort("debug_in", WIDTH_PACKET);
144         Module.SinkPort debug_in = top_funnel.getInputPort("in1");
145
146         top.new Event(new Object[] { in, debug_in },
147                       new Object[] { new SimpleAction(temp_in.getVerilogName()+" = ("+temp_in.getVerilogName()+" << 8) | in;"),
148                                      new SimpleAction("if (count >= 5) begin"+
149                                                           " count <= 0; "+
150                                                           " `packet_token("+debug_in.getVerilogName()+") <= 0;"+
151                                                           " `packet_data("+debug_in.getVerilogName()+") <= "+temp_in.getVerilogName()+";"+
152                                                           " `packet_dest("+debug_in.getVerilogName()+") <= `instruction_dest("+temp_in.getVerilogName()+");"+
153                                                           " "+debug_in.getVerilogName()+"_r <= 1; "+
154                                                           "end else count <= count+1; "),
155                                      in
156                   });
157         top.new Event(new Object[] { out, debug_out },
158                       new Object[] { new SimpleAction(out.getVerilogName()+" <= ("+debug_out.getVerilogName()+">> (count_out*8));"),
159                                      new SimpleAction("if (count_out >= 5) begin "+
160                                                           "count_out <= 0; "+debug_out.getVerilogName()+"_a <= 1; end"+
161                                                           " else count_out <= count_out+1; "),
162                                      out });
163
164     }
165
166     public FabricElement mkNode(FabricElement[] ports, boolean is_horn) { return mkNode(ports, is_horn, 0, ports.length); }
167     public FabricElement mkNode(FabricElement[] ports, boolean is_horn, int start, int end) {
168         switch(end-start) {
169             case 0: return null;
170             case 1: return ports[start];
171             default: {
172                 FabricElement leftPort  = mkNode(ports, is_horn,  start,         (end+start)/2);
173                 FabricElement rightPort = mkNode(ports, is_horn,  (end+start)/2, end);
174                 return is_horn
175                     ? new HornModule.HornInstance(top,     leftPort, rightPort)
176                     : new FunnelModule.FunnelInstance(top, leftPort, rightPort);
177             }
178         }
179     }
180
181     public Module getVerilogModule() { return top; }
182
183
184     // Expand //////////////////////////////////////////////////////////////////////////////
185
186     public void expand(ShipDescription sd) {
187         try {
188             if (sd.getSection("fpga")==null) return;
189             String filename = sd.getName().toLowerCase();
190             File outf = new File("build/fpga/"+filename+".v");
191             new File(outf.getParent()).mkdirs();
192             System.err.println("writing to " + outf);
193             FileOutputStream out = new FileOutputStream(outf);
194             PrintWriter pw = new PrintWriter(out);
195
196             boolean auto = !"debug".equals(filename);
197
198             pw.println("`include \"bitfields.v\"");
199             pw.println("`define defreg(signame,width,regname) reg width regname; wire width signame;  assign signame = regname; initial regname = 0;");
200             pw.println("`define input(r, a, a_, w, d)  input r;  output a_; reg a; assign a_=a; input  w d; initial a=0;");
201             pw.println("`define output(r, r_, a, w, d) output r_; input a;  reg r; assign r_=r; output w d; initial r=0;");
202             pw.println("`define onread(req, ack)        if (!req && ack) ack <= 0;    else if (req && !ack)  begin ack <=1;");
203             pw.println("`define onwrite(req, ack)       if (!req && !ack) req <= 1; else if (req && ack)   begin req <= 0;");
204             pw.println();
205
206             if (auto) {
207                 pw.print("`define reset ");
208                 for(DockDescription bb : sd) {
209                     String bb_name = bb.getName();
210                     if (bb.isInputDock()) pw.print(bb_name+"_a <= 1; ");
211                     else              pw.print(bb_name+"_r <= 0; ");
212                 }
213                 pw.println();
214
215                 pw.println("module " + filename + "( clk, rst ");
216                 for(DockDescription bb : sd) {
217                     String bb_name = bb.getName();
218                     pw.print("        ");
219                     if (bb.isInputDock()) {
220                         pw.print(", " + bb_name+"_r");
221                         pw.print(", " + bb_name+"_a_");
222                         pw.print(", " + bb_name+"_d");
223                     } else {
224                         pw.print(", " + bb_name+"_r_");
225                         pw.print(", " + bb_name+"_a");
226                         pw.print(", " + bb_name+"_d_");
227                     }
228                     pw.println();
229                 }
230                 if (filename.equals("dram")) {
231                     pw.println("    , dram_addr_");
232                     pw.println("    , dram_addr_r_");
233                     pw.println("    , dram_addr_a");
234                     pw.println("    , dram_isread_");
235                     pw.println("    , dram_write_data_");
236                     pw.println("    , dram_write_data_push_");
237                     pw.println("    , dram_write_data_full");
238                     pw.println("    , dram_read_data");
239                     pw.println("    , dram_read_data_pop_");
240                     pw.println("    , dram_read_data_empty");
241                     pw.println("    , dram_read_data_latency");
242                 }
243                 if (filename.equals("video")) {
244                     pw.println("    , vga_clk");
245                     pw.println("    , vga_psave");
246                     pw.println("    , vga_hsync");
247                     pw.println("    , vga_vsync");
248                     pw.println("    , vga_sync");
249                     pw.println("    , vga_blank");
250                     pw.println("    , vga_r");
251                     pw.println("    , vga_g");
252                     pw.println("    , vga_b");
253                     pw.println("    , vga_clkout");
254                 }
255                 pw.println("        );");
256                 pw.println();
257                 pw.println("    input clk;");
258                 pw.println("    input rst;");
259                 if (filename.equals("dram")) {
260                     pw.println("output  [31:0] dram_addr_;");
261                     pw.println("output         dram_addr_r_;");
262                     pw.println("input          dram_addr_a;");
263                     pw.println("output         dram_isread_;");
264                     pw.println("output  [63:0] dram_write_data_;");
265                     pw.println("output         dram_write_data_push_;");
266                     pw.println("input          dram_write_data_full;");
267                     pw.println("input   [63:0] dram_read_data;");
268                     pw.println("output         dram_read_data_pop_;");
269                     pw.println("input          dram_read_data_empty;");
270                     pw.println("input   [1:0]  dram_read_data_latency;");
271                 }
272                 if (filename.equals("video")) {
273                     pw.println("input          vga_clk;");
274                     pw.println("output         vga_psave;");
275                     pw.println("output         vga_hsync;");
276                     pw.println("output         vga_vsync;");
277                     pw.println("output         vga_sync;");
278                     pw.println("output         vga_blank;");
279                     pw.println("output   [7:0] vga_r;");
280                     pw.println("output   [7:0] vga_g;");
281                     pw.println("output   [7:0] vga_b;");
282                     pw.println("output         vga_clkout;");
283                 }
284                 for(DockDescription bb : sd) {
285                     String bb_name = bb.getName();
286                     pw.print("        ");
287                     if ("fifo".equals(filename)) continue;
288                     if (bb.isInputDock()) {
289                         pw.println("`input(" +
290                                    bb_name+"_r,  "+
291                                    bb_name+"_a,  "+
292                                    bb_name+"_a_, "+
293                                    "[("+WIDTH_WORD+"-1):0],"+
294                                    bb_name+"_d)"
295                                    );
296                     } else {
297                         pw.println("`output(" +
298                                    bb_name+"_r,  "+
299                                    bb_name+"_r_, "+
300                                    bb_name+"_a,  "+
301                                    "[("+WIDTH_WORD+"):0],"+
302                                    bb_name+"_d_)"
303                                    );
304                         /*
305                         if (!bb_name.equals("out") || !"memory".equals(filename))
306                             pw.println("`defreg(" +
307                                        bb_name+"_d_,  "+
308                                        "[("+WIDTH_WORD+"-1):0],"+
309                                        bb_name+"_d)"
310                                        );
311                         */
312                     }
313                     pw.println();
314                 }
315             }
316
317             pw.println(sd.getSection("fpga"));
318
319             if (auto)
320                 pw.println("endmodule");
321
322             pw.flush();
323             pw.close();
324         } catch (Exception e) { throw new RuntimeException(e); }
325     }
326
327     public long getDestAddr(Path path) {
328         return ((FpgaPath)path).toLong();
329     }
330     public Dock getBoxByInstAddr(long dest) {
331         for(Ship ship : Fpga.this)
332             for(Dock bb : ship)
333                 if (((FpgaDestination)((FpgaDock)bb).getInstructionDestination()).getAddr() == dest)
334                     return bb;
335         return null;
336     }
337
338 }