add rst wire (but do not do anything with it)
[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.doc.*;
4 import edu.berkeley.fleet.api.*;
5 import edu.berkeley.fleet.ies44.*;
6 import edu.berkeley.fleet.*;
7 import java.lang.reflect.*;
8 import edu.berkeley.sbp.chr.*;
9 import edu.berkeley.sbp.misc.*;
10 import edu.berkeley.sbp.meta.*;
11 import edu.berkeley.sbp.util.*;
12 import java.util.*;
13 import java.io.*;
14
15 public class Fpga extends Fleet {
16
17     public ArrayList<FpgaShip> shiplist   = new ArrayList<FpgaShip>();
18     public HashMap<String,FpgaShip> ships = new HashMap<String,FpgaShip>();
19     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)shiplist.iterator(); }
20
21     private String bitfile;
22
23     public static void main(String[] s) throws Exception {
24         new Fpga().dumpFabric(false);
25     }
26
27     public Fpga() { this("gaspified.bit"); }
28     public Fpga(String bitfile) {
29         this.bitfile = bitfile;
30         createShip("Debug",   "debug");
31         createShip("Memory",    "memory");
32         createShip("Memory",    "memory2");  // need this to avoid a bug
33         createShip("Fifo",    "fifo1");
34         createShip("Fifo",    "fifo2");
35         createShip("Alu2",    "alu2a");
36         createShip("BitFifo",   "bitfifo");
37         // above is the minimal ship set needed to run the regression suite, excluding "ships" tests
38         /*
39         createShip("Fifo",    "fifo3");
40         createShip("Alu1",    "alu1");
41         createShip("Lut3",      "lut3");
42         createShip("Choice",    "Choice");
43         createShip("Stack",     "Stack");
44         createShip("Alu3",      "alu3");
45         */
46         // above is the minimal ship set needed to run the regression suite, including "ships" tests
47
48         // below are extra bonus ships
49         /*
50         createShip("Alu2",    "alu2b");
51         createShip("Alu2",    "alu2c");
52         createShip("Alu2",    "alu2d");
53         createShip("Fifo",    "fifo4");
54         createShip("Memory",    "Memory");
55         createShip("Choice",    "Choice");
56         createShip("Choice",    "Choice");
57         createShip("Choice",    "Choice");
58         */
59         dumpFabric(true);
60     }
61
62     public Ship createShip(String type, String name) {
63         try {
64             ShipDescription sd = new ShipDescription(name, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
65             FpgaShip ship = new FpgaShip(this, name, type, sd);
66             ships.put(name, ship);
67             shiplist.add(ship);
68             return ship;
69         } catch (IOException e) { throw new RuntimeException(e); }
70     }
71
72     public FleetProcess run(final byte[] instructions) {
73         try {
74             return new Client(bitfile, instructions);
75         } catch (IOException e) { throw new RuntimeException(e); }
76     }
77
78     public void dumpFabric(boolean quiet) {
79         // FIXME: this is really ugly: the order of port declarations in
80         //        the XXXShip.java file must match the order in the .balsa file!
81
82         ArrayList instructionports = new ArrayList<FpgaPump>();
83         for(FpgaShip ship : shiplist)
84             for(Pump port : ship.getPumps())
85                 if (!((FpgaPump)port).special())
86                     instructionports.add(port);
87         FabricTree instructions =
88             new FabricTree((FpgaPump[])instructionports.toArray(new FpgaPump[0]),
89                            "ihorn",
90                            "instruction");
91
92         ArrayList inputports = new ArrayList<FpgaPump>();
93         for(FpgaShip ship : shiplist)
94             for(Pump port : ship.getPumps())
95                 if (!((FpgaPump)port).special())
96                     inputports.add(port);
97         FabricTree inputs =
98             new FabricTree((FpgaPump[])inputports.toArray(new FpgaPump[0]),
99                            "horn",
100                            "dest");
101
102         ArrayList outputports = new ArrayList<FpgaPump>();
103         for(FpgaShip ship : shiplist)
104             for(Pump port : ship.getPumps())
105                 if (!((FpgaPump)port).special() || ((FpgaPump)port).dhorn())
106                     outputports.add(port);
107         FabricTree outputs =
108             new FabricTree((FpgaPump[])outputports.toArray(new FpgaPump[0]),
109                            "funnel",
110                            "source");
111
112         ArrayList ihornports = new ArrayList<FpgaPump>();
113         for(FpgaShip ship : shiplist)
114             for(Pump port : ship.getPumps())
115                 if (((FpgaPump)port).ihorn())
116                     ihornports.add(port);
117         FabricTree ihorns =
118             new FabricTree((FpgaPump[])ihornports.toArray(new FpgaPump[0]),
119                            "funnel",
120                            "ihorn");
121
122         if (quiet) return;
123         System.out.println("`include \"macros.v\"");
124         System.out.println("module fabric(clk, rst, data_Memory0_command_r, data_Memory0_command_a, data_Memory0_command,");
125         System.out.println("                   data_Debug0_out_r, data_Debug0_out_a, data_Debug0_out);");
126         System.out.println("  input  clk;");
127         System.out.println("  input  rst;");
128         System.out.println("  input  data_Memory0_command_r;");
129         System.out.println("  output data_Memory0_command_a;");
130         System.out.println("  output data_Debug0_out_r;");
131         System.out.println("  input  data_Debug0_out_a;");
132         System.out.println("  output [(`PACKET_WIDTH-1):0]      data_Debug0_out;");
133         System.out.println("  input  [(`PACKET_WIDTH-1):0]      data_Memory0_command;");
134         //System.out.println("  wire   [(`INSTRUCTION_WIDTH-1):0] data_Memory0_ihorn;");
135         //System.out.println("  wire   [(`PACKET_WIDTH-1):0]      data_Memory0_dhorn;");
136         System.out.println();
137         
138         System.out.println();
139
140         instructions.dumpChannels(true);
141         outputs.dumpChannels(true);
142         inputs.dumpChannels(true);
143         ihorns.dumpChannels(true);
144         for(FpgaShip ship : shiplist)
145             for(Pump port : ship.getPumps())
146                 if (!((FpgaPump)port).special() || ((FpgaPump)port).dhorn())
147                     System.out.println("  wire [(`PACKET_WIDTH-1):0] data_"
148                                        +getUniqueName(ship)+"_"+port.getName()+";");
149
150         System.out.println("wire [(`PACKET_WIDTH-1):0] ihornleft;");
151
152         System.out.println("");
153         instructions.dumpChannels(false);
154         System.out.println("");
155         outputs.dumpChannels(false);
156         System.out.println("");
157         inputs.dumpChannels(false);
158         System.out.println("");
159         ihorns.dumpChannels(false);
160         System.out.println("");
161         for(FpgaShip ship : shiplist) {
162             System.out.print(ship.getType().toLowerCase());
163             System.out.print(" ");
164             System.out.print("krunk"+(krunk++));
165             System.out.print("(clk, rst, ");
166             boolean first = true;
167             for(Pump port : ship.getPumps()) {
168                 if (!first) System.out.print(", ");
169                 first = false;
170                 String prefix = "data_";
171                 if (((FpgaPump)port).ihorn()) prefix = "ihorn_";
172                 if (((FpgaPump)port).dhorn()) prefix = "source_";
173                 System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
174                 System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
175                 System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName());
176                 System.out.print(" ");
177             }
178             System.out.println(");");
179
180             for(Pump port : ship.getPumps()) {
181                 if (((FpgaPump)port).special()) continue;
182                 if (((FpgaPump)port).inbox) {
183                     System.out.print("inbox");
184                 } else {
185                     System.out.print("outbox");
186                 }
187                 System.out.print(" krunk"+(krunk++)+"(clk, rst, ");
188                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
189                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
190                 System.out.print("`packet_data(instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"), ");
191                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
192                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
193                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
194                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
195                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
196                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
197                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
198                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
199                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
200                 System.out.print(");");
201                 System.out.println();
202             }
203
204         }
205
206         System.out.println("funnel ihornfun(clk, rst, "+
207                            "             ihornleft_r, ihornleft_a, ihornleft,"+
208                            "             ihorn_r, ihorn_a, ihorn,"+
209                            "             source_r, source_a, source);");
210         System.out.println("horn tophorn(clk, rst, "+
211                            "             ihornleft_r, ihornleft_a, ihornleft,"+
212                            "             instruction_r, instruction_a, instruction,"+
213                            "             dest_r, dest_a, dest);");
214         /*
215         System.out.println("assign instruction_r = ihorn_r;");
216         System.out.println("assign ihorn_a = instruction_a;");
217         System.out.println("assign instruction = ihorn;");
218         System.out.println("assign dest_r = source_r;");
219         System.out.println("assign source_a = dest_a;");
220         System.out.println("assign dest = source;");
221         */
222         System.out.println("endmodule");
223     }
224
225     private static class FabricTree {
226         int master_idx = 1;
227         String prefix;
228         Node root;
229         public void dumpChannels(boolean decl) { root.dumpChannels(0, decl); }
230         public FabricTree(FpgaPump[] ports, String component, String prefix) {
231             this.prefix = prefix;
232             root = (Node)mkNode("", component, ports, 0, ports.length, 0, 0);
233         }
234         private Object mkNode(String name, String component, FpgaPump[] ports,
235                               int start, int end, int addr, int bits) {
236             if (end-start == 0) return null;
237             if (end-start == 1) {
238                 FpgaPump p = ports[start];
239                 if (prefix.equals("instruction")) {
240                     p.instr_addr = (addr<<1);
241                     p.instr_bits = bits+1;
242                 } else if (prefix.equals("dest")) {
243                     p.addr = (addr << 1) | 1;
244                     p.bits = bits+1;
245                     if (bits >= 11)
246                         throw new RuntimeException("too many pumps!");
247                     int count = 0;
248                     for(Destination d : p.getDestinations()) {
249                         if (!(d instanceof FpgaPump.VirtualPort)) continue;
250                         FpgaPump.VirtualPort vp = (FpgaPump.VirtualPort)d;
251                         vp.addr = p.addr | (count << bits);
252                         count++;
253                     }
254                 }
255                 return p;
256             }
257             int len = end-start;
258             int count   = 0;
259             int count2  = 0;
260             int breakpt = 0;
261             if (end-start <= 2) {
262                 breakpt = (start+end)/2;
263             } else {
264                 for(int i=start; i<end; i++)
265                     count += count(ports[i].getDestinations());
266                 for(int i=start; i<end-1; i++) {
267                     count2 += count(ports[i].getDestinations());
268                     breakpt = i;
269                     if (i>start && count2 >= count/2) break;
270                 }
271             }
272             return new Node(name,
273                             component,
274                             mkNode(name+"_0", component, ports, start, breakpt, addr,               bits+1),
275                             mkNode(name+"_1", component, ports, breakpt, end,   addr | (1 << bits), bits+1),
276                             addr,
277                             bits);
278         }
279         private String describe(String prefix, Object o) {
280             if (o==null) return null;
281             if (o instanceof FpgaPump) {
282                 FpgaPump p = (FpgaPump)o;
283                 return prefix+"_"+getUniqueName(p.getShip())+"_"+p.getName();
284             }
285             if (o instanceof Node) {
286                 return ((Node)o).describe(prefix);
287             }
288             return null;
289         }
290         private class Node {
291             Object left;
292             Object right;
293             String name;
294             String component;
295             int addr;
296             int bits;
297             public Node(String name, String component, Object left, Object right, int addr, int bits) {
298                 this.left = left;
299                 this.right = right;
300                 this.name = name;
301                 this.component = component;
302                 this.addr = addr;
303                 this.bits = bits;
304             }
305             public void dumpChannels(int indentamount, boolean decl) {
306                 String indent = "";
307                 for(int i=0; i<indentamount; i++) indent += "  ";
308                 if (decl) {
309                     String n = describe(prefix).startsWith("instruction")
310                         ? "[(`PACKET_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
311                     System.out.println("  wire "+n+" "+indent+describe(prefix)+";");
312                 } else {
313                     System.out.println("     "+indent+
314                                        component+" "+
315                                        "krunk"+(krunk++)+"(clk, rst, "+
316                                        describe(prefix)+"_r, "+
317                                        describe(prefix)+"_a, "+
318                                        describe(prefix)+", "+
319                                        FabricTree.this.describe(prefix, left)+"_r, "+
320                                        FabricTree.this.describe(prefix, left)+"_a, "+
321                                        FabricTree.this.describe(prefix, left)+", "+
322                                        FabricTree.this.describe(prefix, right)+"_r, "+
323                                        FabricTree.this.describe(prefix, right)+"_a, "+
324                                        FabricTree.this.describe(prefix, right)+
325                                        ");");
326                 }
327                 dumpChannels(left, indentamount+1, decl);
328                 dumpChannels(right, indentamount+1, decl);
329             }
330             public void dumpChannels(Object o, int indentamount, boolean decl) {
331                 if (o==null) return;
332                 if (o instanceof Node) {
333                     ((Node)o).dumpChannels(indentamount, decl);
334                 } else {
335                     String indent = "";
336                     for(int i=0; i<indentamount; i++) indent += "  ";
337                     if (decl) {
338                         String n = FabricTree.this.describe(prefix,o).startsWith("instruction")
339                             ? "[(`PACKET_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
340                         System.out.println("  wire "+n+" "+indent+FabricTree.this.describe(prefix,o)+";");
341                     }
342                 }
343             }
344             public String describe(String prefix) {
345                 return prefix+name;
346             }
347         }
348     }
349     public static int krunk=0;
350
351     private static String getUniqueName(Ship ship) {
352         return ship.getType() + ship.getOrdinal();
353     }
354
355     private static int count(Iterable<Destination> it) {
356         int ret = 0;
357         for(Destination d : it)
358             ret++;
359         return ret;
360     }
361
362     public void expand(ShipDescription sd) {
363         try {
364             if (sd.getSection("fpga")==null) return;
365             String filename = sd.getName().toLowerCase();
366             File outf = new File("build/fpga/"+filename+".v");
367             new File(outf.getParent()).mkdirs();
368             System.err.println("writing to " + outf);
369             FileOutputStream out = new FileOutputStream(outf);
370             PrintWriter pw = new PrintWriter(out);
371
372             boolean auto =
373                 !"debug".equals(filename) &&
374                 !"execute".equals(filename) &&
375                 !"memory".equals(filename) &&
376                 !"fifo".equals(filename);
377             if (auto) {
378                 pw.println("`include \"macros.v\"");
379                 pw.println();
380                 pw.println("module " + filename + "( clk, rst ");
381                 for(PumpDescription bb : sd) {
382                     String bb_name = bb.getName();
383                     pw.print("        ");
384                     if (bb.isInbox()) {
385                         pw.print(", " + bb_name+"_r");
386                         pw.print(", " + bb_name+"_a_");
387                         pw.print(", " + bb_name+"_d");
388                     } else {
389                         pw.print(", " + bb_name+"_r_");
390                         pw.print(", " + bb_name+"_a");
391                         pw.print(", " + bb_name+"_d_");
392                     }
393                     pw.println();
394                 }
395                 pw.println("        );");
396                 pw.println();
397                 pw.println("    input clk;");
398                 pw.println("    input rst;");
399                 for(PumpDescription bb : sd) {
400                     String bb_name = bb.getName();
401                     pw.print("        ");
402                     if (bb.isInbox()) {
403                         pw.println("`input(" +
404                                    bb_name+"_r,  "+
405                                    bb_name+"_a,  "+
406                                    bb_name+"_a_, "+
407                                    "[(`PACKET_WIDTH-1):0],"+
408                                    bb_name+"_d)"
409                                    );
410                     } else {
411                         pw.println("`output(" +
412                                    bb_name+"_r,  "+
413                                    bb_name+"_r_, "+
414                                    bb_name+"_a,  "+
415                                    "[(`PACKET_WIDTH-1):0],"+
416                                    bb_name+"_d_)"
417                                    );
418                         pw.println("`defreg(" +
419                                    bb_name+"_d_,  "+
420                                    "[(`PACKET_WIDTH-1):0],"+
421                                    bb_name+"_d)"
422                                    );
423                     }
424                     pw.println();
425                 }
426             }
427
428             pw.println(sd.getSection("fpga"));
429
430             if (auto)
431                 pw.println("endmodule");
432
433             pw.flush();
434             pw.close();
435         } catch (Exception e) { throw new RuntimeException(e); }
436     }
437
438     public int computeOffset(int origin, int target) { return (target - origin)/6; }
439     public int computeTarget(int origin, int offset) { return origin + (offset*6); }
440
441     private FpgaInstructionEncoder iie = new FpgaInstructionEncoder();
442     public Instruction readInstruction(DataInputStream is) throws IOException { return iie.readInstruction(is); }
443     public Instruction readInstruction(long instr) { return iie.readInstruction(instr); }
444     public long writeInstruction(Instruction d) { return writeInstruction(d); }
445     public void writeInstruction(DataOutputStream os, Instruction d) throws IOException { iie.writeInstruction(os, d); }
446
447     private class FpgaInstructionEncoder extends InstructionEncoder {
448         public long getDestAddr(Destination box) { return ((FpgaPump.VirtualPort)box).addr; }
449         public long getBoxInstAddr(Pump box) { return ((FpgaPump)box).instr_addr; }
450         public Destination getDestByAddr(long dest) {
451             for(Ship ship : Fpga.this)
452                 for(Pump bb : ship.getPumps())
453                     for(Destination d : bb.getDestinations())
454                         if (getDestAddr(d)==dest)
455                             return d;
456             return null;
457         }
458         public Pump getBoxByInstAddr(long dest) {
459             for(Ship ship : Fpga.this)
460                 for(Pump bb : ship.getPumps())
461                     if (((FpgaPump)bb).instr_addr == dest)
462                         return bb;
463             return null;
464         }
465     }
466
467 }