percolate ports for vga, ignore ddr2
[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 import static edu.berkeley.fleet.fpga.verilog.Verilog.PercolatedPort;
17
18
19 public class Fpga extends FleetTwoFleet {
20
21     public  Module top;
22     public  FabricElement top_horn;
23     Ship debugShip;
24
25     public LinkedHashMap<String,FpgaShip> ships = new LinkedHashMap<String,FpgaShip>();
26     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
27
28     public Ship getShip(String type, int ordinal) {
29         for(Ship s : this)
30             if (s.getType().equals(type))
31                 if (--ordinal < 0)
32                     return s;
33         return null;
34     }
35
36     public static void main(String[] s) throws Exception { 
37         new Fpga(new Module("root")).top.dump(s[0]);
38         PrintWriter pw;
39
40         pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(s[0]+"/timescale.v")));
41         pw.println("`timescale 1ns / 10ps");
42         pw.close();
43
44         pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(s[0]+"/bram14.v")));
45         pw.println("`define BRAM_ADDR_WIDTH 14");
46         pw.println("`define BRAM_DATA_WIDTH `WORDWIDTH");
47         pw.println("`define BRAM_SIZE (1<<(`BRAM_ADDR_WIDTH))");
48         pw.println("`define BRAM_NAME bram14");
49         pw.println("`include \"bram.inc\"");
50         pw.close();
51
52         pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(s[0]+"/vram.v")));
53         pw.println("`define BRAM_ADDR_WIDTH 19");
54         pw.println("`define BRAM_DATA_WIDTH 3");
55         pw.println("`define BRAM_SIZE (640*480)");
56         pw.println("`define BRAM_NAME vram");
57         pw.println("`include \"bram.inc\"");
58         pw.close();
59     }
60
61     public Module getVerilogModule() { return top; }
62
63     public FleetProcess run(Instruction[] instructions) {
64         try {
65             return new Client(this, "none", instructions);
66         } catch (Exception e) { throw new RuntimeException(e); }
67     }
68
69     public BitVector getDestAddr(Path path) {
70         return ((FpgaPath)path).toBitVector();
71     }
72
73     // Setup //////////////////////////////////////////////////////////////////////////////
74
75     public Ship createShip(String type, String name) throws IOException {
76         ShipDescription sd = new ShipDescription(type, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
77         FpgaShip ship = new FpgaShip(this, sd);
78         ships.put(name, ship);
79         return ship;
80     }
81
82     public Fpga() throws Exception { this(new Module("root")); }
83     public Fpga(Module top) throws Exception {
84         this.top = top;
85         debugShip = createShip("Debug",     "debug");
86
87         //boolean small = false;
88         boolean small = true;
89
90         createShip("Memory",      "memory1");
91
92         if (small) {
93             for(int i=0; i<2; i++)
94                 createShip("Fifo",           "fifo"+i);
95             for(int i=0; i<2; i++)
96                 createShip("Alu",            "alu"+i);
97             createShip("Counter",        "counter");
98             createShip("CarrySaveAdder", "csa1");
99             createShip("Rotator",        "rotator");
100             createShip("Lut3",           "lut");
101         } else {
102             createShip("Memory",    "memory2");
103             createShip("Memory",    "memory3");
104
105             for(int i=0; i<3; i++)
106                 createShip("Alu",       "alu"+i);
107
108             for(int i=0; i<1; i++)
109                 createShip("Fifo",      "fifo"+i);
110
111             for(int i=0; i<14; i++)
112                 createShip("Counter",  "counter"+i);
113
114             /*
115             createShip("CarrySaveAdder",  "csa1");
116             createShip("Rotator",         "rotator");
117             createShip("Lut3",            "lut");
118             */
119             //createShip("DDR2",    "ddr2");
120         }
121         createShip("DRAM",    "dram");
122         createShip("Video",   "video");
123
124         //Module.SourcePort  debug_in    = top.createWireSourcePort("debug_in", WIDTH_PACKET);
125         Module.SourcePort  debug_out   = null;
126         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
127             if (ship.getType().toLowerCase().equals("debug"))
128                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
129         }
130
131         // for FifoShip
132         new Module.InstantiatedModule(top, new FifoModule(8, WIDTH_WORD));
133
134         Module.SourcePort  in          = top.createInputPort("in", 8);
135         Module.SinkPort    out         = top.createOutputPort("out", 8, "");
136         Module.Latch       temp_in     = top.new Latch("temp", WIDTH_PACKET);
137         Module.Latch       count       = top.new Latch("count", 8);
138         Module.Latch       count_out   = top.new Latch("count_out", 8);
139
140         ArrayList inbox_sources = new ArrayList<FabricElement>();
141         ArrayList inbox_dests   = new ArrayList<FabricElement>();
142         ArrayList outbox_sources = new ArrayList<FabricElement>();
143         ArrayList outbox_dests   = new ArrayList<FabricElement>();
144         ArrayList instruction_dests   = new ArrayList<FabricElement>();
145         int numdocks = 0;
146         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
147             if (ship.getType().toLowerCase().equals("debug"))
148                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
149             for(Dock port : ship) {
150                 if (port.isInputDock()) {
151                     inbox_sources.add(((FpgaDock)port));
152                     instruction_dests.add(port.getInstructionDestination());
153                     inbox_dests.add(port.getDataDestination());
154                 } else {
155                     outbox_sources.add(((FpgaDock)port));
156                     instruction_dests.add(port.getInstructionDestination());
157                     outbox_dests.add(port.getDataDestination());
158                 }
159                 numdocks++;
160             }
161         }
162         ArrayList dests   = new ArrayList<FabricElement>();
163         ArrayList sources = new ArrayList<FabricElement>();
164         sources.addAll(inbox_sources);
165         sources.addAll(outbox_sources);
166         dests.addAll(inbox_dests);
167         dests.addAll(instruction_dests);
168         dests.addAll(outbox_dests);
169         top_horn = mkNode((FabricElement[])dests.toArray(new FabricElement[0]), true);
170         FabricElement   source  = mkNode((FabricElement[])sources.toArray(new FabricElement[0]), false);
171         FunnelModule.FunnelInstance top_funnel = new FunnelModule.FunnelInstance(this, top, null, source.getOutputPort());
172         ((FunnelModule.FunnelInstance)source).out = top_funnel;
173         top_funnel.addOutput(top_horn, top_horn.getInputPort());
174         Module.SinkPort debug_in = top_funnel.getInputPort("in1");
175
176         top.new Event(new Object[] { in, "count<=7" },
177                       new Object[] { new SimpleAction(temp_in.getVerilogName()+" <= {" + temp_in.getVerilogName() + "["+(WIDTH_PACKET-(1+8))+":0], in[7:0] };"),
178                                      new AssignAction(count, count.getVerilogName()+"+1"),
179                                      in
180                       });
181         top.new Event(new Object[] { debug_in, "count>7" },
182                       new Object[] { new AssignAction(count, "0"),
183                                      new AssignAction(debug_in, temp_in),
184                                      debug_in
185                       });
186         top.new Event(new Object[] { out, debug_out },
187                       new Object[] { new SimpleAction(out.getVerilogName()+" <= ("+debug_out.getVerilogName()+">> (count_out*8));"),
188                                      new ConditionalAction("count_out >= 5", debug_out),
189                                      new ConditionalAction("count_out >= 5", new AssignAction(count_out, "0")),
190                                      new ConditionalAction("count_out <  5", new AssignAction(count_out, "count_out+1")),
191                                      out });
192
193     }
194
195     public FabricElement mkNode(FabricElement[] ports, boolean is_horn) { return mkNode(ports, is_horn, 0, ports.length); }
196     public FabricElement mkNode(FabricElement[] ports, boolean is_horn, int start, int end) {
197         switch(end-start) {
198             case 0: return null;
199             case 1: return ports[start];
200             default: {
201                 FabricElement leftPort  = mkNode(ports, is_horn,  start,         (end+start)/2);
202                 FabricElement rightPort = mkNode(ports, is_horn,  (end+start)/2, end);
203                 return is_horn
204                     ? new HornModule.HornInstance(this, top,     leftPort, rightPort)
205                     : new FunnelModule.FunnelInstance(this, top, leftPort, rightPort);
206             }
207         }
208     }
209
210
211     // Expand //////////////////////////////////////////////////////////////////////////////
212
213     public void expand(ShipDescription sd) {
214         try {
215             if (sd.getSection("fpga")==null) return;
216             String filename = sd.getName().toLowerCase();
217             File outf = new File("build/fpga/"+filename+".v");
218             new File(outf.getParent()).mkdirs();
219             System.err.println("writing to " + outf);
220             FileOutputStream out = new FileOutputStream(outf);
221             PrintWriter pw = new PrintWriter(out);
222
223             boolean debug = "debug".equals(filename);
224
225             pw.println("`define WORDWIDTH                "+WIDTH_WORD);
226             pw.println("`define CODEBAG_SIZE_BITS        "+CBD_SIZE.valmaskwidth);
227             pw.println();
228
229             for(DockDescription dd : sd) {
230                 String name = dd.getName();
231                 pw.println("`define "+name+"_full    ("+name+"_r && !"+name+"_a)");
232                 pw.println("`define "+name+"_empty  (!"+name+"_r && !"+name+"_a)");
233                 if (dd.isInputDock()) {
234                     pw.println("`define drain_"+name+"  "+name+"_a <= 1;");
235                 } else {
236                     pw.println("`define fill_"+name+"  "+name+"_r <= 1;");
237                     pw.println("`define "+name+"_draining ("+name+"_r && "+name+"_a)");
238                 }
239             }
240             if (debug) {
241                 String name = "out";
242                 pw.println("`define "+name+"_full    ("+name+"_r && !"+name+"_a)");
243                 pw.println("`define "+name+"_empty  (!"+name+"_r && !"+name+"_a)");
244                 pw.println("`define fill_"+name+"  "+name+"_r <= 1;");
245                 pw.println("`define "+name+"_draining ("+name+"_r && "+name+"_a)");
246             }
247
248             pw.print("`define reset ");
249             for(DockDescription bb : sd) {
250                 String bb_name = bb.getName();
251                 if (bb.isInputDock()) pw.print(bb_name+"_a <= 1; "+bb_name+"_f <= 0; ");
252                 else                  pw.print(bb_name+"_r <= 0; ");
253             }
254             if (debug) {
255                 String bb_name = "out";
256                 pw.print(bb_name+"_r <= 0; ");
257             }
258             pw.println();
259
260             pw.print("`define cleanup ");
261             for(DockDescription bb : sd) {
262                 String bb_name = bb.getName();
263                 if (bb.isInputDock()) pw.print("if (!"+bb_name+"_r && "+bb_name+"_a) "+bb_name+"_a <= 0; ");
264                 else                  pw.print("if ( "+bb_name+"_r && "+bb_name+"_a) "+bb_name+"_r <= 0; ");
265             }
266             if (debug) {
267                 String bb_name = "out";
268                 pw.print("if ( "+bb_name+"_r && "+bb_name+"_a) "+bb_name+"_r <= 0; ");
269             }
270             pw.println();
271
272             // FIXME: this corresponds to something
273             /*
274             pw.print("`define flush_happening (1");
275             for(DockDescription bb : sd)
276                 if (bb.isInputDock())
277                     pw.print(" && "+bb.getName()+"_r_ && !"+bb.getName()+"_a && "+bb.getName()+"_d["+WIDTH_WORD+"]");
278             pw.println(")");
279             */
280
281             pw.print("`define flush ");
282             for(DockDescription bb : sd)
283                 if (bb.isInputDock())
284                     pw.print(" if (!"+bb.getName()+"_r_) "+bb.getName()+"_f <= 0; ");
285             pw.print("if (1");
286             for(DockDescription bb : sd)
287                 if (bb.isInputDock())
288                     pw.print(" && "+bb.getName()+"_r_ && !"+bb.getName()+"_a");
289             pw.print(") begin ");
290             if (true) {
291                 pw.print("if (1");
292                 for(DockDescription bb : sd)
293                     if (bb.isInputDock())
294                         pw.print(" && "+bb.getName()+"_d["+WIDTH_WORD+"] ");
295                 pw.print(") begin ");
296                 if (true) {
297                     for(DockDescription bb : sd)
298                         if (bb.isInputDock())
299                             pw.print(bb.getName()+"_f <= 1; ");
300                 }
301                 pw.print(" end else if (0");
302                 for(DockDescription bb : sd)
303                     if (bb.isInputDock())
304                         pw.print(" || "+bb.getName()+"_d["+WIDTH_WORD+"] ");
305                 pw.print(") begin ");
306                 if (true) {
307                     for(DockDescription bb : sd)
308                         if (bb.isInputDock())
309                             pw.print(" if (!"+bb.getName()+"_d["+WIDTH_WORD+"]) "+bb.getName()+"_f <= 1; ");
310                 }
311                 pw.print(" end ");
312             }
313             pw.print(" end ");
314             pw.println();
315             
316             pw.println("module " + filename + "( clk, rst ");
317             for(DockDescription bb : sd) {
318                 String bb_name = bb.getName();
319                 pw.print("        ");
320                 if (bb.isInputDock()) {
321                     pw.print(", " + bb_name+"_r_");
322                     pw.print(", " + bb_name+"_a_");
323                     pw.print(", " + bb_name+"_d");
324                 } else {
325                     pw.print(", " + bb_name+"_r_");
326                     pw.print(", " + bb_name+"_a");
327                     pw.print(", " + bb_name+"_d_");
328                 }
329                 pw.println();
330             }
331             if (filename.equals("debug")) {
332                 pw.println("    , out_r_");
333                 pw.println("    , out_a");
334                 pw.println("    , out_d_");
335             }
336             for(PercolatedPort pp : sd.percolatedPorts) {
337                 pw.print("    , ");
338                 pw.println(pp.name);
339             }
340             pw.println("        );");
341             pw.println();
342             pw.println("    input clk;");
343             pw.println("    input rst;");
344             for(PercolatedPort pp : sd.percolatedPorts) {
345                 pw.print(pp.up ? "output" : "input");
346                 pw.print("  ");
347                 if (pp.width > 1)
348                     pw.print("["+(pp.width-1)+":0]");
349                 pw.print(" ");
350                 pw.print(pp.name);
351                 pw.println(";");
352             }
353
354             for(DockDescription bb : sd) {
355                 String bb_name = bb.getName();
356                 if (bb.isInputDock()) {
357                     pw.println("        input   ["+WIDTH_WORD+":0] "+bb_name+"_d;");
358                     pw.println("        input   "+bb_name+"_r_;");
359                     pw.println("        wire    "+bb_name+"_r;");
360                     pw.println("        assign  "+bb_name+"_r = "+bb_name+"_r_ & ~"+bb_name+"_d["+WIDTH_WORD+"];");
361                     pw.println("        output  "+bb_name+"_a_;");
362                     pw.println("        reg     "+bb_name+"_a;");
363                     pw.println("        initial "+bb_name+"_a  = 0;");
364                     pw.println("        reg     "+bb_name+"_f;");
365                     pw.println("        initial "+bb_name+"_f  = 0;");
366                     pw.println("        assign  "+bb_name+"_a_ = "+bb_name+"_a || "+bb_name+"_f;");
367                 } else {
368                     pw.println("        output  ["+WIDTH_WORD+":0] "+bb_name+"_d_;");
369                     pw.println("        input   "+bb_name+"_a;");
370                     pw.println("        output  "+bb_name+"_r_;");
371                     pw.println("        reg     "+bb_name+"_r;");
372                     pw.println("        initial "+bb_name+"_r  = 0;");
373                     pw.println("        assign  "+bb_name+"_r_ = "+bb_name+"_r;");
374                 }
375                 pw.println();
376             }
377             if (filename.equals("debug")) {
378                 String bb_name = "out";
379                 pw.println("        output  ["+WIDTH_WORD+":0] "+bb_name+"_d_;");
380                 pw.println("        input   "+bb_name+"_a;");
381                 pw.println("        output  "+bb_name+"_r_;");
382                 pw.println("        reg     "+bb_name+"_r;");
383                 pw.println("        initial "+bb_name+"_r  = 0;");
384                 pw.println("        assign  "+bb_name+"_r_ = "+bb_name+"_r;");
385             }
386
387             if (filename.equals("fifo")) {
388                 pw.println("  wire in_a__;");
389                 pw.println("  wire out_r__;");
390                 pw.println("  fifo8x37 fifo8x37(clk, rst,");
391                 pw.println("                    in_r,    in_a__, in_d,");
392                 pw.println("                    out_r__, out_a,  out_d_);");
393                 pw.println("  always @(posedge clk) begin");
394                 pw.println("    if (!rst) begin");
395                 pw.println("      `reset");
396                 pw.println("    end else begin");
397                 pw.println("      `flush");
398                 pw.println("      out_r <= out_r__;");
399                 pw.println("      in_a  <= in_a__;");
400                 pw.println("    end");
401                 pw.println("  end");
402             } else {
403                 pw.println(sd.getSection("fpga"));
404             }
405
406             pw.println("endmodule");
407
408             pw.flush();
409             pw.close();
410         } catch (Exception e) { throw new RuntimeException(e); }
411     }
412
413 }