support for fpga client/server network access
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
1 package edu.berkeley.fleet.interpreter;
2 import edu.berkeley.fleet.api.*;
3
4 import edu.berkeley.fleet.api.*;
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.bind.*;
11 import edu.berkeley.sbp.util.*;
12 import java.util.*;
13 import java.io.*;
14 import edu.berkeley.fleet.ships.*;
15
16 public class Interpreter extends Fleet implements Iterable<Ship> {
17
18     public InterpreterBenkoBox resolve(edu.berkeley.fleet.api.BenkoBox bb) { return (InterpreterBenkoBox)bb; }
19
20     public void dumpCode(Instruction[] instructions) throws IOException {
21         DataOutputStream dos = new DataOutputStream(new FileOutputStream("build/fleet.bin"));
22         for(int i=1; i<instructions.length; i++) {
23             Instruction inst = instructions[i];
24             writeInstruction(dos, inst);
25         }
26         dos.flush();
27         dos.close();
28     }
29
30     public void dispatch(Instruction i, long address) {
31
32         if (i instanceof Instruction.Executable) {
33             InterpreterBenkoBox sourceBenkoBox = resolve(((Instruction.Executable)i).benkoBox);
34             if (!(sourceBenkoBox instanceof InstructionPort))
35                 throw new RuntimeException(sourceBenkoBox + " is not an InstructionPort!");
36             ((InstructionPort)sourceBenkoBox).addInstruction(((Instruction.Executable)i));
37
38         } else if (i instanceof Instruction.Literal.CodeBagDescriptor) {
39             Log.dispatch(i);
40             Instruction.Literal.CodeBagDescriptor cbd = (Instruction.Literal.CodeBagDescriptor)i;
41             dispatchCodeBag(cbd.offset+address, cbd.size);
42             
43         } else if (i instanceof Instruction.Literal.Absolute) {
44             InterpreterBenkoBox destBenkoBox = resolve(((Instruction.Literal.Absolute)i).dest);
45             Log.data(((Instruction.Literal.Absolute)i).value+"", null, destBenkoBox);
46             destBenkoBox.addDataFromFabric((int)((Instruction.Literal.Absolute)i).value);
47
48         } else if (i instanceof Instruction.Kill) {
49             InterpreterBenkoBox benkoBox = resolve(((Instruction.Kill)i).benkoBox);
50             if (!(benkoBox instanceof InstructionPort))
51                 throw new RuntimeException(benkoBox + " is not an InstructionPort!");
52             ((InstructionPort)benkoBox).kill(((Instruction.Kill)i).count);
53
54         } else {
55             throw new Error("unsupported: " + i.getClass().getName());
56         }
57     }
58
59     /** some "halt ship" can turn this on to stop the interpreter */
60     public boolean halt = false;
61
62     public int[] mem = new int[0];
63
64     public Instruction[] instructions = null;
65     public ArrayList<String> imports = new ArrayList<String>();
66
67     private static String getUniqueName(Ship ship) {
68         return ship.getType() + ship.getOrdinal();
69     }
70
71     public ArrayList<InterpreterShip> shiplist = new ArrayList<InterpreterShip>();
72     public HashMap<String,InterpreterShip> ships = new HashMap<String,InterpreterShip>();
73
74     /** read a machine-formatted instruction from a file (into a Java object) */
75     public Instruction readInstruction(DataInputStream is) throws IOException {
76         // FIXME
77         return null;
78     }
79
80     public void writeInstruction(DataOutputStream os, Instruction d) throws IOException {
81         long instr = 0;
82
83         // Kill is encoded as Execute with the illegal combination (Latch & ~DataIn)
84         if (d instanceof Instruction.Kill) {
85             Instruction.Kill k = (Instruction.Kill)d;
86             d = new Instruction.Executable(k.benkoBox, null, k.count, false, false, true, false, false, false);
87         }
88
89         if (d instanceof Instruction.Executable) {
90             Instruction.Executable inst = (Instruction.Executable)d;
91             InterpreterBenkoBox dest = resolve(inst.dest);
92             instr = dest==null ? 0 : (dest.addr << 1);
93             if (inst.count >= (1<<8))
94                 throw new RuntimeException("count field must be less than 128");
95             instr |= (((long)inst.count) << (11+1));
96             if (inst.tokenIn)  instr |= (1L << (11+1+7+0));
97             if (inst.dataIn)   instr |= (1L << (11+1+7+1));
98             if (inst.latch)    instr |= (1L << (11+1+7+2));
99             if (inst.dataOut)  instr |= (1L << (11+1+7+3));
100             if (inst.tokenOut) instr |= (1L << (11+1+7+4));
101             if (inst.recycle)  instr |= (1L);
102             instr |= ((long)resolve(inst.benkoBox).instr_addr) << (11+5+7+1);
103
104         } else if (d instanceof Instruction.Literal.Absolute) {
105             Instruction.Literal.Absolute ld = (Instruction.Literal.Absolute)d;
106             instr = (2L << (11+24));
107             instr |= (resolve(ld.dest).addr) << 24;
108             if (ld.value >= (1<<25))
109                 throw new RuntimeException("literals must be less than 2^24");
110             instr |= ((long)ld.value);
111         }
112
113         dump(os, (instr >> (5*8)) & 0xff);
114         dump(os, (instr >> (4*8)) & 0xff);
115         dump(os, (instr >> (3*8)) & 0xff);
116         dump(os, (instr >> (2*8)) & 0xff);
117         dump(os, (instr >> (1*8)) & 0xff);
118         dump(os, (instr >> (0*8)) & 0xff);
119     }
120     public void dump(OutputStream os, long data_) throws IOException {
121         int data = (int)data_;
122         os.write((byte)data);
123         //System.out.println(data);
124     }
125
126     public Iterator<Ship> iterator() {
127         return (Iterator<Ship>)(Object)shiplist.iterator();
128     }
129
130     public void dispatchCodeBag(long base, long size) {
131         for(long i=base; i<base+size; i++)
132             dispatch(instructions[(int)i], i);
133     }
134
135     public void go() {
136         Instruction.Literal.CodeBagDescriptor cbl =
137             (Instruction.Literal.CodeBagDescriptor)instructions[0];
138         dispatchCodeBag(cbl.offset+0, cbl.size);
139
140         while(!halt)
141             for(InterpreterShip ship : ships.values())
142                 for(int j=0; j<10; j++)
143                     ship._service();
144
145         // run the ships a bit longer for good measure
146         for(int i=0; i<100; i++)
147             for(InterpreterShip ship : ships.values())
148                 for(int j=0; j<10; j++)
149                     ship._service();
150
151         // check the state of the ships
152         for(InterpreterShip ship : ships.values())
153             ship.shutdown();
154
155         Log.println(Log.yellow("    DONE: ====== FLEET is halted.  Have a nice day.  ======"));
156     }
157
158     public void dumpMem() {
159         Log.print(Log.cyan("  MEMORY: "));
160         for(int i=0; i<mem.length; i++) {
161             if ((i%10)==0 && i!=0) Log.print(Log.cyan("          "));
162             Log.print(Log.cyan(mem[i] + " "));
163             if ((i%10)==9 && i!=mem.length-1) Log.println("");
164         }
165         Log.println();
166     }
167
168     public void writeMem(int addr, int data) {
169         if (addr >= mem.length) {
170             int[] mem2 = new int[addr*2+1];
171             System.arraycopy(mem, 0, mem2, 0, mem2.length);
172             mem = mem2;
173         }
174         mem[addr] = data;
175     }
176
177     public InterpreterShip getShip(String name) {
178         InterpreterShip s = ships.get(name);
179         if (s == null) throw new RuntimeException("unknown ship \""+name+"\"");
180         return s;
181     }
182
183     public InterpreterShip tryCreate(String classname, String shipname) {
184         try {
185             Class c = Class.forName(classname);
186             Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class });
187             InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname });
188             ships.put(shipname, ret);
189             shiplist.add(ret);
190             return ret;
191         } catch (Exception e) {
192             return null;
193         }
194     }
195
196     public void sendToken(InterpreterBenkoBox source, InterpreterBenkoBox dest) {
197         Log.token(source, dest);
198         dest.addTokenFromFabric();
199     }
200
201     public void sendData(InterpreterBenkoBox source, int data, InterpreterBenkoBox dest) {
202         Log.data(data+"", source, dest);
203         dest.addDataFromFabric(data);
204     }
205
206     public void dumpFabric(boolean quiet) {
207         // FIXME: this is really ugly: the order of port declarations in
208         //        the XXXShip.java file must match the order in the .balsa file!
209
210         ArrayList instructionports = new ArrayList<InterpreterBenkoBox>();
211         for(InterpreterShip ship : shiplist)
212             for(BenkoBox port : ship.getBenkoBoxes())
213                 if (!((InterpreterBenkoBox)port).special())
214                     instructionports.add(port);
215         FabricTree instructions =
216             new FabricTree((InterpreterBenkoBox[])instructionports.toArray(new InterpreterBenkoBox[0]),
217                            "ihorn",
218                            "instruction");
219
220         ArrayList inputports = new ArrayList<InterpreterBenkoBox>();
221         for(InterpreterShip ship : shiplist)
222             for(BenkoBox port : ship.getBenkoBoxes())
223                 if (!((InterpreterBenkoBox)port).special())
224                     inputports.add(port);
225         FabricTree inputs =
226             new FabricTree((InterpreterBenkoBox[])inputports.toArray(new InterpreterBenkoBox[0]),
227                            "horn",
228                            "dest");
229
230         ArrayList outputports = new ArrayList<InterpreterBenkoBox>();
231         for(InterpreterShip ship : shiplist)
232             for(BenkoBox port : ship.getBenkoBoxes())
233                 if (!((InterpreterBenkoBox)port).special())
234                     outputports.add(port);
235         FabricTree outputs =
236             new FabricTree((InterpreterBenkoBox[])outputports.toArray(new InterpreterBenkoBox[0]),
237                            "funnel",
238                            "source");
239
240         if (quiet) return;
241         System.out.println("`include \"macros.v\"");
242         /*
243           HashSet<Class> added = new HashSet<Class>();
244           for(Ship ship : shiplist)
245           if (!added.contains(ship.getClass())) {
246           added.add(ship.getClass());
247           System.out.println("import ["+ship.getBalsaName()+"]");
248           }
249         */
250         System.out.println("module fabric(clk, data_Execute0_in_r, data_Execute0_in_a, data_Execute0_in,");
251         System.out.println("                   data_Debug0_out_r, data_Debug0_out_a, data_Debug0_out);");
252         System.out.println("  input  clk;");
253         System.out.println("  input  data_Execute0_in_r;");
254         System.out.println("  output data_Execute0_in_a;");
255         System.out.println("  input  [(`PACKET_WIDTH-1):0] data_Execute0_in;");
256         System.out.println("  output data_Debug0_out_r;");
257         System.out.println("  input  data_Debug0_out_a;");
258         System.out.println("  output [(`PACKET_WIDTH-1):0] data_Debug0_out;");
259         System.out.println("  wire   [(`INSTRUCTION_WIDTH-1):0] data_Execute0_ihorn;");
260         System.out.println("  wire   [(`PACKET_WIDTH-1):0] data_Execute0_dhorn;");
261         System.out.println();
262         
263         System.out.println();
264
265         instructions.dumpChannels(true);
266         outputs.dumpChannels(true);
267         inputs.dumpChannels(true);
268         for(InterpreterShip ship : shiplist)
269             for(BenkoBox port : ship.getBenkoBoxes()) {
270                 if (ship instanceof Execute && port instanceof Outbox) continue;
271                 System.out.println("  wire [(`PACKET_WIDTH-1):0] data_"+getUniqueName(ship)+"_"+port.getName()+";");
272             }
273
274         System.out.println("");
275         instructions.dumpChannels(false);
276         System.out.println("");
277         outputs.dumpChannels(false);
278         System.out.println("");
279         inputs.dumpChannels(false);
280         System.out.println("");
281         for(InterpreterShip ship : shiplist) {
282             System.out.print(ship.getClass().getSimpleName().toLowerCase());
283             System.out.print(" ");
284             System.out.print("krunk"+(krunk++));
285             System.out.print("(clk, ");
286             boolean first = true;
287             for(BenkoBox port : ship.getBenkoBoxes()) {
288                 if (!first) System.out.print(", ");
289                 first = false;
290                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
291                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
292                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
293                 System.out.print(" ");
294             }
295             System.out.println(");");
296
297             for(BenkoBox port : ship.getBenkoBoxes()) {
298                 if (((InterpreterBenkoBox)port).special()) continue;
299                 if (port instanceof Inbox) {
300                     /*
301                     if (((InterpreterBenkoBox)port).noInbox())
302                         System.out.print("stupidinbox");
303                     else
304                     */
305                     System.out.print("inbox");
306                 } else {
307                     System.out.print("outbox");
308                 }
309                 System.out.print(" krunk"+(krunk++)+"(clk, ");
310                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
311                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
312                 System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
313                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
314                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
315                 System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
316                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
317                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
318                 System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
319                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
320                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
321                 System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
322                 System.out.print(");");
323                 System.out.println();
324             }
325
326         }
327         System.out.println("funnel topfun(clk,"+
328                            "              dest_r, dest_a, dest,"+
329                            "              source_r, source_a, source,"+
330                            "              data_Execute0_dhorn_r, data_Execute0_dhorn_a, data_Execute0_dhorn);");
331         System.out.println("assign instruction_r = data_Execute0_ihorn_r;");
332         System.out.println("assign data_Execute0_ihorn_a = instruction_a;");
333         System.out.println("assign instruction = data_Execute0_ihorn;");
334         System.out.println("endmodule");
335     }
336
337     private static class FabricTree {
338         int master_idx = 1;
339         String prefix;
340         Node root;
341         public void dumpChannels(boolean decl) { root.dumpChannels(0, decl); }
342         public FabricTree(InterpreterBenkoBox[] ports, String component, String prefix) {
343             this.prefix = prefix;
344             root = (Node)mkNode("", component, ports, 0, ports.length, 0, 0);
345         }
346         private Object mkNode(String name, String component, InterpreterBenkoBox[] ports,
347                               int start, int end, int addr, int bits) {
348             if (end-start == 0) return null;
349             if (end-start == 1) {
350                 InterpreterBenkoBox p = ports[start];
351                 if (prefix.equals("instruction")) {
352                     p.instr_addr = addr;
353                     p.instr_bits = bits;
354                 } else {
355                     p.addr = addr;
356                     p.bits = bits;
357                 }
358                 return p;
359             }
360             int len = end-start;
361             return new Node(name,
362                             component,
363                             mkNode(name+"_0", component, ports, start, start+len/2, addr, bits+1),
364                             mkNode(name+"_1", component, ports, start+len/2, end,   addr | (1 << bits), bits+1),
365                             addr,
366                             bits);
367         }
368         private String describe(String prefix, Object o) {
369             if (o==null) return null;
370             if (o instanceof InterpreterBenkoBox) {
371                 InterpreterBenkoBox p = (InterpreterBenkoBox)o;
372                 return prefix+"_"+getUniqueName(p.getShip())+"_"+p.getName();
373             }
374             if (o instanceof Node) {
375                 return ((Node)o).describe(prefix);
376             }
377             return null;
378         }
379         private class Node {
380             Object left;
381             Object right;
382             String name;
383             String component;
384             int addr;
385             int bits;
386             public Node(String name, String component, Object left, Object right, int addr, int bits) {
387                 this.left = left;
388                 this.right = right;
389                 this.name = name;
390                 this.component = component;
391                 this.addr = addr;
392                 this.bits = bits;
393             }
394             public void dumpChannels(int indentamount, boolean decl) {
395                 String indent = "";
396                 for(int i=0; i<indentamount; i++) indent += "  ";
397                 if (decl) {
398                     String n = describe(prefix).startsWith("instruction")
399                         ? "[(`INSTRUCTION_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
400                     System.out.println("  wire "+n+" "+indent+describe(prefix)+";");
401                 } else {
402                     System.out.println("     "+indent+
403                                        component+" "+
404                                        "krunk"+(krunk++)+"(clk, "+
405                                        describe(prefix)+"_r, "+
406                                        describe(prefix)+"_a, "+
407                                        describe(prefix)+", "+
408                                        FabricTree.this.describe(prefix, left)+"_r, "+
409                                        FabricTree.this.describe(prefix, left)+"_a, "+
410                                        FabricTree.this.describe(prefix, left)+", "+
411                                        FabricTree.this.describe(prefix, right)+"_r, "+
412                                        FabricTree.this.describe(prefix, right)+"_a, "+
413                                        FabricTree.this.describe(prefix, right)+
414                                        ");");
415                 }
416                 dumpChannels(left, indentamount+1, decl);
417                 dumpChannels(right, indentamount+1, decl);
418             }
419             public void dumpChannels(Object o, int indentamount, boolean decl) {
420                 if (o==null) return;
421                 if (o instanceof Node) {
422                     ((Node)o).dumpChannels(indentamount, decl);
423                 } else {
424                     String indent = "";
425                     for(int i=0; i<indentamount; i++) indent += "  ";
426                     if (decl) {
427                         String n = FabricTree.this.describe(prefix,o).startsWith("instruction")
428                             ? "[(`INSTRUCTION_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
429                         System.out.println("  wire "+n+" "+indent+FabricTree.this.describe(prefix,o)+";");
430                     }
431                 }
432             }
433             public String describe(String prefix) {
434                 return prefix+name;
435             }
436         }
437     }
438     public static int krunk=0;
439
440     public int computeOffset(int origin, int target) { return target - origin; }
441     public int computeTarget(int origin, int offset) { return origin + offset; }
442 }