total overhaul: fleetcode-1.0 api finished
[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.ies44.*;
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.ies44.InstructionEncoder.*;
15 import static edu.berkeley.fleet.verilog.Verilog.*;
16
17
18 public class Fpga extends Fleet {
19
20     public Ship getShip(String type, int ordinal) {
21         for(Ship s : this)
22             if (s.getType().equals(type))
23                 if (ordinal-- < 0)
24                     return s;
25         return null;
26     }
27
28     public int getWordWidth() { return 37; }
29     private static final BitVector SIGNAL_ZERO = new BitVector(1);
30     private static final BitVector SIGNAL_ONE  = new BitVector(1);
31     static {
32         SIGNAL_ONE.set(0,true);
33     }
34
35     public Module top;
36     public FabricElement top_horn;
37
38     public LinkedHashMap<String,FpgaShip> ships = new LinkedHashMap<String,FpgaShip>();
39     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
40
41     public static void main(String[] s) throws Exception { 
42         String prefix = s[0];
43
44         new FunnelModule().dump(prefix);
45         new HornModule().dump(prefix);
46
47         new FifoModule(0).dump(prefix);
48         new FifoModule(4).dump(prefix);
49         new FifoModule(8).dump(prefix);
50         new FpgaDock.DockModule(false).dump(prefix);
51         new FpgaDock.DockModule(true).dump(prefix);
52
53         Module top = new Module("root");
54         new Fpga(top).top.dump(prefix);
55     }
56
57     public FleetProcess run(Instruction[] instructions) {
58         try {
59             ByteArrayOutputStream baos = new ByteArrayOutputStream();
60             DataOutputStream dos = new DataOutputStream(baos);
61             for(Instruction i : instructions)
62                 writeInstruction(dos, getUniversalSource(), i);
63             dos.flush();
64             return new Client("none", baos.toByteArray());
65         } catch (Exception e) { throw new RuntimeException(e); }
66     }
67
68     // Setup //////////////////////////////////////////////////////////////////////////////
69
70     public Ship createShip(String type, String name) throws IOException {
71         ShipDescription sd = new ShipDescription(type, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
72         FpgaShip ship = new FpgaShip(this, sd);
73         ships.put(name, ship);
74         return ship;
75     }
76
77     public Fpga() throws Exception { this(new Module("root")); }
78     public Fpga(Module top) throws Exception {
79         this.top = top;
80         debugShip = createShip("Debug",     "debug");
81         createShip("Memory",    "memory");
82         createShip("Fifo",      "fifo1");
83         createShip("Fifo",      "fifo2");
84         createShip("Alu2",      "alu2a");
85         createShip("Rotator",   "rotator");
86         //createShip("Alu1",      "alu1");
87         createShip("Lut3",      "lut3");
88         createShip("Alu3",      "alu3");
89
90         Module fifostage = new FifoModule(0);
91         Module fifo4     = new FifoModule(4);
92         Module fifo8     = new FifoModule(8);
93         Module horn      = new HornModule();
94         Module funnel    = new FunnelModule();
95         Module outbox    = new FpgaDock.DockModule(false);
96         Module inbox     = new FpgaDock.DockModule(true);
97
98         Module.SinkPort    debug_in    = top.createWirePort("debug_in", WIDTH_PACKET);
99         Module.SourcePort  debug_out   = null;
100         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
101             if (ship.getType().toLowerCase().equals("debug"))
102                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
103         }
104
105         Module.SourcePort  in          = top.createInputPort("in", 8);
106         Module.SinkPort    out         = top.createOutputPort("out", 8, "");
107         Module.Latch       temp_in     = top.new Latch("temp", WIDTH_PACKET) { public String doReset() { return name+"=0;"; } };
108         Module.Latch       count       = top.new Latch("count", 8);
109         Module.Latch       count_out   = top.new Latch("count_out", 8);
110         top.new Event(new Object[] { in, debug_in },
111                       new Object[] { new SimpleAction(temp_in.getVerilogName()+" = ("+temp_in.getVerilogName()+" << 8) | in;"),
112                                      new SimpleAction("if (count >= 5) begin"+
113                                                           " count <= 0; "+
114                                                           " `packet_token("+debug_in.getVerilogName()+") <= 0;"+
115                                                           " `packet_data("+debug_in.getVerilogName()+") <= "+temp_in.getVerilogName()+";"+
116                                                           " `packet_dest("+debug_in.getVerilogName()+") <= `instruction_dest("+temp_in.getVerilogName()+");"+
117                                                           " "+debug_in.getVerilogName()+"_r <= 1; "+
118                                                           "end else count <= count+1; "),
119                                      in
120                   });
121         top.new Event(new Object[] { out, debug_out },
122                       new Object[] { new SimpleAction(out.getVerilogName()+" <= ("+debug_out.getVerilogName()+">> (count_out*8));"),
123                                      new SimpleAction("if (count_out >= 5) begin "+
124                                                           "count_out <= 0; "+debug_out.getVerilogName()+"_a <= 1; end"+
125                                                           " else count_out <= count_out+1; "),
126                                      out });
127
128         ArrayList sources = new ArrayList<FabricElement>();
129         ArrayList dests   = new ArrayList<FabricElement>();
130         for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
131             if (ship.getType().toLowerCase().equals("debug"))
132                 debug_out = ship.getVerilogModule().getOutputPort("debug_out");
133             for(Dock port : ship) {
134                 sources.add(((FpgaDock)port));
135                 dests.add(port.getInstructionDestination());
136                 dests.add(port.getDataDestination());
137             }
138         }
139         top_horn = mkNode((FabricElement[])dests.toArray(new FabricElement[0]), true);
140         FabricElement   source  = mkNode((FabricElement[])sources.toArray(new FabricElement[0]), false);
141         FunnelModule.FunnelInstance top_funnel = new FunnelModule.FunnelInstance(top, debug_in, source.getOutputPort());
142         ((FunnelModule.FunnelInstance)source).out = top_funnel;
143         //top_horn.addInput(top_funnel, top_funnel.getOutputPort());
144         top_funnel.addOutput(top_horn, top_horn.getInputPort());
145     }
146
147     public FabricElement mkNode(FabricElement[] ports, boolean is_horn) { return mkNode(ports, is_horn, 0, ports.length); }
148     public FabricElement mkNode(FabricElement[] ports, boolean is_horn, int start, int end) {
149         switch(end-start) {
150             case 0: return null;
151             case 1: return ports[start];
152             default: {
153                 FabricElement leftPort  = mkNode(ports, is_horn,  start,         (end+start)/2);
154                 FabricElement rightPort = mkNode(ports, is_horn,  (end+start)/2, end);
155                 return is_horn
156                     ? new HornModule.HornInstance(top,     leftPort, rightPort)
157                     : new FunnelModule.FunnelInstance(top, leftPort, rightPort);
158             }
159         }
160     }
161
162     public Module getVerilogModule() { return top; }
163
164
165     // Expand //////////////////////////////////////////////////////////////////////////////
166
167     public void expand(ShipDescription sd) {
168         try {
169             if (sd.getSection("fpga")==null) return;
170             String filename = sd.getName().toLowerCase();
171             File outf = new File("build/fpga/"+filename+".v");
172             new File(outf.getParent()).mkdirs();
173             System.err.println("writing to " + outf);
174             FileOutputStream out = new FileOutputStream(outf);
175             PrintWriter pw = new PrintWriter(out);
176
177             boolean auto = !"debug".equals(filename);
178
179             if (auto) {
180                 pw.println("`include \"macros.v\"");
181                 pw.println();
182
183                 pw.print("`define reset ");
184                 for(DockDescription bb : sd) {
185                     String bb_name = bb.getName();
186                     if (bb.isInputDock()) pw.print(bb_name+"_a <= 1; ");
187                     else              pw.print(bb_name+"_r <= 0; ");
188                 }
189                 pw.println();
190
191                 pw.println("module " + filename + "( clk, rst ");
192                 for(DockDescription bb : sd) {
193                     String bb_name = bb.getName();
194                     pw.print("        ");
195                     if (bb.isInputDock()) {
196                         pw.print(", " + bb_name+"_r");
197                         pw.print(", " + bb_name+"_a_");
198                         pw.print(", " + bb_name+"_d");
199                     } else {
200                         pw.print(", " + bb_name+"_r_");
201                         pw.print(", " + bb_name+"_a");
202                         pw.print(", " + bb_name+"_d_");
203                     }
204                     pw.println();
205                 }
206                 pw.println("        );");
207                 pw.println();
208                 pw.println("    input clk;");
209                 pw.println("    input rst;");
210                 for(DockDescription bb : sd) {
211                     String bb_name = bb.getName();
212                     pw.print("        ");
213                     if (bb.isInputDock()) {
214                         pw.println("`input(" +
215                                    bb_name+"_r,  "+
216                                    bb_name+"_a,  "+
217                                    bb_name+"_a_, "+
218                                    "[("+WIDTH_WORD+"-1):0],"+
219                                    bb_name+"_d)"
220                                    );
221                     } else {
222                         pw.println("`output(" +
223                                    bb_name+"_r,  "+
224                                    bb_name+"_r_, "+
225                                    bb_name+"_a,  "+
226                                    "[("+WIDTH_WORD+"-1):0],"+
227                                    bb_name+"_d_)"
228                                    );
229                         if (!bb_name.equals("out") || !"memory".equals(filename))
230                             pw.println("`defreg(" +
231                                        bb_name+"_d_,  "+
232                                        "[("+WIDTH_WORD+"-1):0],"+
233                                        bb_name+"_d)"
234                                        );
235                     }
236                     pw.println();
237                 }
238             }
239
240             pw.println(sd.getSection("fpga"));
241
242             if (auto)
243                 pw.println("endmodule");
244
245             pw.flush();
246             pw.close();
247         } catch (Exception e) { throw new RuntimeException(e); }
248     }
249
250     private FpgaInstructionEncoder iie = new FpgaInstructionEncoder();
251     public Instruction readInstruction(DataInputStream is, Dock dispatchFrom) throws IOException { return iie.readInstruction(dispatchFrom, is); }
252     public Instruction readInstruction(Dock dispatchFrom, long instr) { return iie.readInstruction(dispatchFrom, instr); }
253     public long writeInstruction(Dock dispatchFrom, Instruction d) { return iie.writeInstruction(dispatchFrom, d); }
254     public void writeInstruction(DataOutputStream os, Dock dispatchFrom, Instruction d) throws IOException { iie.writeInstruction(os, dispatchFrom, d); }
255
256     private Ship debugShip;
257
258
259     public Dock getUniversalSource() { return debugShip.getDock("in"); }
260     private class FpgaInstructionEncoder extends InstructionEncoder {
261         public Dock getUniversalSource() { return debugShip.getDock("in"); }
262         public long getDestAddr(Path path) {
263             return ((FpgaPath)path).toLong();
264         }
265         public Path getPathByAddr(Dock source, long dest) {
266             for(Ship ship : Fpga.this)
267                 for(Dock bb : ship) {
268                     for(Destination d : new Destination[] { bb.getInstructionDestination(), bb.getDataDestination() }) {
269                         for(BitVector signal : new BitVector[] { SIGNAL_ZERO, SIGNAL_ONE }) {
270                             FpgaPath p = (FpgaPath)source.getPath(d, signal);
271                             if (p.toLong() == dest) return p;
272                         }
273                     }
274                 }
275             return null;
276         }
277         public Dock getBoxByInstAddr(long dest) {
278             for(Ship ship : Fpga.this)
279                 for(Dock bb : ship)
280                     if (((FpgaDestination)((FpgaDock)bb).getInstructionDestination()).getAddr() == dest)
281                         return bb;
282             return null;
283         }
284     }
285 }