rename Alu2->Alu
[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 = 12;
69         //int LANES = 1;
70
71         createShip("Memory",            "memory1");
72         createShip("CarrySaveAdder",    "csa1");
73
74         if (LANES>1)
75             createShip("Memory",    "memory2");
76
77         for(int i=0; i<LANES; i++) {
78             createShip("Fifo",      "fifo"+i);
79             createShip("Alu",       "alu"+i);
80         }
81         createShip("Rotator",   "rotator");
82         createShip("Lut3",      "lut");
83         /*
84         createShip("Rotator",   "rotator_");
85         createShip("Lut3",      "lut_");
86         */
87
88         if (LANES<=1)
89             createShip("Fifo",      "fifo_extra");
90
91         createShip("DRAM",    "dram");
92         createShip("Video",   "video");
93
94         //Module.SourcePort  debug_in    = top.createWireSourcePort("debug_in", WIDTH_PACKET);
95         Module.SourcePort  debug_out   = null;
96         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
97             if (ship.getType().toLowerCase().equals("debug"))
98                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
99         }
100
101         // for FifoShip
102         new Module.InstantiatedModule(top, new FifoModule(8, WIDTH_WORD));
103
104         Module.SourcePort  in          = top.createInputPort("in", 8);
105         Module.SinkPort    out         = top.createOutputPort("out", 8, "");
106         Module.Latch       temp_in     = top.new Latch("temp", WIDTH_PACKET) { public String doReset() { return name+"=0;"; } };
107         Module.Latch       count       = top.new Latch("count", 8);
108         Module.Latch       count_out   = top.new Latch("count_out", 8);
109
110         ArrayList inbox_sources = new ArrayList<FabricElement>();
111         ArrayList inbox_dests   = new ArrayList<FabricElement>();
112         ArrayList outbox_sources = new ArrayList<FabricElement>();
113         ArrayList outbox_dests   = new ArrayList<FabricElement>();
114         ArrayList instruction_dests   = new ArrayList<FabricElement>();
115         int numdocks = 0;
116         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
117             if (ship.getType().toLowerCase().equals("debug"))
118                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
119             for(Dock port : ship) {
120                 if (port.isInputDock()) {
121                     inbox_sources.add(((FpgaDock)port));
122                     instruction_dests.add(port.getInstructionDestination());
123                     inbox_dests.add(port.getDataDestination());
124                 } else {
125                     outbox_sources.add(((FpgaDock)port));
126                     instruction_dests.add(port.getInstructionDestination());
127                     outbox_dests.add(port.getDataDestination());
128                 }
129                 numdocks++;
130             }
131         }
132         //System.err.println("dock count = " + numdocks);
133         ArrayList dests   = new ArrayList<FabricElement>();
134         ArrayList sources = new ArrayList<FabricElement>();
135         sources.addAll(inbox_sources);
136         sources.addAll(outbox_sources);
137         dests.addAll(inbox_dests);
138         dests.addAll(instruction_dests);
139         dests.addAll(outbox_dests);
140         top_horn = mkNode((FabricElement[])dests.toArray(new FabricElement[0]), true);
141         FabricElement   source  = mkNode((FabricElement[])sources.toArray(new FabricElement[0]), false);
142         FunnelModule.FunnelInstance top_funnel = new FunnelModule.FunnelInstance(top, null, source.getOutputPort());
143         ((FunnelModule.FunnelInstance)source).out = top_funnel;
144         //top_horn.addInput(top_funnel, top_funnel.getOutputPort());
145         top_funnel.addOutput(top_horn, top_horn.getInputPort());
146
147         //Module.SourcePort  debug_in    = top.createWireSourcePort("debug_in", WIDTH_PACKET);
148         Module.SinkPort debug_in = top_funnel.getInputPort("in1");
149
150         top.new Event(new Object[] { in, debug_in },
151                       new Object[] { new SimpleAction(temp_in.getVerilogName()+" = ("+temp_in.getVerilogName()+" << 8) | in;"),
152                                      new SimpleAction("if (count >= 5) begin"+
153                                                           " count <= 0; "+
154                                                           " `packet_token("+debug_in.getVerilogName()+") <= 0;"+
155                                                           " `packet_data("+debug_in.getVerilogName()+") <= "+temp_in.getVerilogName()+";"+
156                                                           " `packet_dest("+debug_in.getVerilogName()+") <= `instruction_dest("+temp_in.getVerilogName()+");"+
157                                                           " "+debug_in.getVerilogName()+"_r <= 1; "+
158                                                           "end else count <= count+1; "),
159                                      in
160                   });
161         top.new Event(new Object[] { out, debug_out },
162                       new Object[] { new SimpleAction(out.getVerilogName()+" <= ("+debug_out.getVerilogName()+">> (count_out*8));"),
163                                      new SimpleAction("if (count_out >= 5) begin "+
164                                                           "count_out <= 0; "+debug_out.getVerilogName()+"_a <= 1; end"+
165                                                           " else count_out <= count_out+1; "),
166                                      out });
167
168     }
169
170     public FabricElement mkNode(FabricElement[] ports, boolean is_horn) { return mkNode(ports, is_horn, 0, ports.length); }
171     public FabricElement mkNode(FabricElement[] ports, boolean is_horn, int start, int end) {
172         switch(end-start) {
173             case 0: return null;
174             case 1: return ports[start];
175             default: {
176                 FabricElement leftPort  = mkNode(ports, is_horn,  start,         (end+start)/2);
177                 FabricElement rightPort = mkNode(ports, is_horn,  (end+start)/2, end);
178                 return is_horn
179                     ? new HornModule.HornInstance(top,     leftPort, rightPort)
180                     : new FunnelModule.FunnelInstance(top, leftPort, rightPort);
181             }
182         }
183     }
184
185     public Module getVerilogModule() { return top; }
186
187
188     // Expand //////////////////////////////////////////////////////////////////////////////
189
190     public void expand(ShipDescription sd) {
191         try {
192             if (sd.getSection("fpga")==null) return;
193             String filename = sd.getName().toLowerCase();
194             File outf = new File("build/fpga/"+filename+".v");
195             new File(outf.getParent()).mkdirs();
196             System.err.println("writing to " + outf);
197             FileOutputStream out = new FileOutputStream(outf);
198             PrintWriter pw = new PrintWriter(out);
199
200             boolean auto = !"debug".equals(filename);
201
202             pw.println("`include \"bitfields.v\"");
203             pw.println("`define defreg(signame,width,regname) reg width regname; wire width signame;  assign signame = regname; initial regname = 0;");
204             pw.println("`define input(r, a, a_, w, d)  input r;  output a_; reg a; assign a_=a; input  w d; initial a=0;");
205             pw.println("`define output(r, r_, a, w, d) output r_; input a;  reg r; assign r_=r; output w d; initial r=0;");
206             pw.println("`define onread(req, ack)        if (!req && ack) ack <= 0;    else if (req && !ack)  begin ack <=1;");
207             pw.println("`define onwrite(req, ack)       if (!req && !ack) req <= 1; else if (req && ack)   begin req <= 0;");
208             pw.println();
209
210             if (auto) {
211                 pw.print("`define reset ");
212                 for(DockDescription bb : sd) {
213                     String bb_name = bb.getName();
214                     if (bb.isInputDock()) pw.print(bb_name+"_a <= 1; ");
215                     else              pw.print(bb_name+"_r <= 0; ");
216                 }
217                 pw.println();
218
219                 pw.println("module " + filename + "( clk, rst ");
220                 for(DockDescription bb : sd) {
221                     String bb_name = bb.getName();
222                     pw.print("        ");
223                     if (bb.isInputDock()) {
224                         pw.print(", " + bb_name+"_r");
225                         pw.print(", " + bb_name+"_a_");
226                         pw.print(", " + bb_name+"_d");
227                     } else {
228                         pw.print(", " + bb_name+"_r_");
229                         pw.print(", " + bb_name+"_a");
230                         pw.print(", " + bb_name+"_d_");
231                     }
232                     pw.println();
233                 }
234                 if (filename.equals("dram")) {
235                     pw.println("    , dram_addr_");
236                     pw.println("    , dram_addr_r_");
237                     pw.println("    , dram_addr_a");
238                     pw.println("    , dram_isread_");
239                     pw.println("    , dram_write_data_");
240                     pw.println("    , dram_write_data_push_");
241                     pw.println("    , dram_write_data_full");
242                     pw.println("    , dram_read_data");
243                     pw.println("    , dram_read_data_pop_");
244                     pw.println("    , dram_read_data_empty");
245                     pw.println("    , dram_read_data_latency");
246                 }
247                 if (filename.equals("video")) {
248                     pw.println("    , vga_clk");
249                     pw.println("    , vga_psave");
250                     pw.println("    , vga_hsync");
251                     pw.println("    , vga_vsync");
252                     pw.println("    , vga_sync");
253                     pw.println("    , vga_blank");
254                     pw.println("    , vga_r");
255                     pw.println("    , vga_g");
256                     pw.println("    , vga_b");
257                     pw.println("    , vga_clkout");
258                 }
259                 pw.println("        );");
260                 pw.println();
261                 pw.println("    input clk;");
262                 pw.println("    input rst;");
263                 if (filename.equals("dram")) {
264                     pw.println("output  [31:0] dram_addr_;");
265                     pw.println("output         dram_addr_r_;");
266                     pw.println("input          dram_addr_a;");
267                     pw.println("output         dram_isread_;");
268                     pw.println("output  [63:0] dram_write_data_;");
269                     pw.println("output         dram_write_data_push_;");
270                     pw.println("input          dram_write_data_full;");
271                     pw.println("input   [63:0] dram_read_data;");
272                     pw.println("output         dram_read_data_pop_;");
273                     pw.println("input          dram_read_data_empty;");
274                     pw.println("input   [1:0]  dram_read_data_latency;");
275                 }
276                 if (filename.equals("video")) {
277                     pw.println("input          vga_clk;");
278                     pw.println("output         vga_psave;");
279                     pw.println("output         vga_hsync;");
280                     pw.println("output         vga_vsync;");
281                     pw.println("output         vga_sync;");
282                     pw.println("output         vga_blank;");
283                     pw.println("output   [7:0] vga_r;");
284                     pw.println("output   [7:0] vga_g;");
285                     pw.println("output   [7:0] vga_b;");
286                     pw.println("output         vga_clkout;");
287                 }
288                 for(DockDescription bb : sd) {
289                     String bb_name = bb.getName();
290                     pw.print("        ");
291                     if ("fifo".equals(filename)) continue;
292                     if (bb.isInputDock()) {
293                         pw.println("`input(" +
294                                    bb_name+"_r,  "+
295                                    bb_name+"_a,  "+
296                                    bb_name+"_a_, "+
297                                    "[("+WIDTH_WORD+"-1):0],"+
298                                    bb_name+"_d)"
299                                    );
300                     } else {
301                         pw.println("`output(" +
302                                    bb_name+"_r,  "+
303                                    bb_name+"_r_, "+
304                                    bb_name+"_a,  "+
305                                    "[("+WIDTH_WORD+"):0],"+
306                                    bb_name+"_d_)"
307                                    );
308                         /*
309                         if (!bb_name.equals("out") || !"memory".equals(filename))
310                             pw.println("`defreg(" +
311                                        bb_name+"_d_,  "+
312                                        "[("+WIDTH_WORD+"-1):0],"+
313                                        bb_name+"_d)"
314                                        );
315                         */
316                     }
317                     pw.println();
318                 }
319             }
320
321             pw.println(sd.getSection("fpga"));
322
323             if (auto)
324                 pw.println("endmodule");
325
326             pw.flush();
327             pw.close();
328         } catch (Exception e) { throw new RuntimeException(e); }
329     }
330
331     public long getDestAddr(Path path) {
332         return ((FpgaPath)path).toLong();
333     }
334     public Dock getBoxByInstAddr(long dest) {
335         for(Ship ship : Fpga.this)
336             for(Dock bb : ship)
337                 if (((FpgaDestination)((FpgaDock)bb).getInstructionDestination()).getAddr() == dest)
338                     return bb;
339         return null;
340     }
341
342 }