7ff19cca0cc13623f570728ac54f44f3b69d9de4
[fleet.git] / src / edu / berkeley / fleet / interpreter / Interpreter.java
1 package edu.berkeley.fleet.interpreter;
2 import java.io.*;
3 import java.util.*;
4 import java.util.concurrent.*;
5 import java.lang.reflect.*;
6 import edu.berkeley.sbp.util.ANSI;
7 import edu.berkeley.fleet.api.*;
8 import edu.berkeley.fleet.two.*;
9 import edu.berkeley.fleet.assembler.*;
10 import edu.berkeley.fleet.util.*;
11
12 public class Interpreter extends FleetTwoFleet {
13
14     /** used to allocate serial numbers; see InterpreterDestination for further detail */
15     int maxAllocatedDestinationSerialNumber = 0;
16
17     private InterpreterShip debugShip = null;
18     private BlockingQueue<BitVector> debugStream = new LinkedBlockingQueue<BitVector>();
19     private LinkedHashMap<String,InterpreterShip> ships = new LinkedHashMap<String,InterpreterShip>();
20     public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
21     public Ship getShip(String type, int ordinal) {
22         for(Ship s : this)
23             if (s.getType().equals(type))
24                 if (ordinal-- <= 0)
25                     return s;
26         return null;
27     }
28
29     /** do not use this; it is going to go away */
30     public Interpreter() { this(true); }
31     public Interpreter(boolean logging) {
32         this(new String[] {
33                 "Debug",
34                 "Memory",
35                 "Memory",
36                 "Memory",
37                 "Alu",
38                 "Alu",
39                 "Alu",
40                 "Alu",
41                 "Alu",
42                 "Alu",
43                 "Alu",
44                 "Fifo",
45                 "Fifo",
46                 "Counter",
47                 "Counter",
48                 "Counter",
49                 "Counter",
50                 "Counter",
51                 "Counter",
52                 "Counter",
53                 "Counter",
54                 "Counter",
55                 "Counter",
56                 "Counter",
57                 "Counter",
58                 "Counter",
59                 "Counter",
60                 "Lut3",
61                 "CarrySaveAdder",
62                 "Rotator",
63                 "Dvi",
64                 "Button",
65                 "Timer",
66             }, logging);
67     }
68
69     public Interpreter(String[] ships, boolean logging) {
70         int i=0;
71         Log.quiet = !logging;
72         for(String s : ships) {
73             createShip(ships[i], ships[i]+"_"+i);
74             i++;
75         }
76     }
77
78     private Ship createShip(String shipType, String shipname) {
79         try {
80             if (ships.get(shipname)!=null) return ships.get(shipname);
81             Class c = Class.forName("edu.berkeley.fleet.interpreter."+shipType);
82             Constructor con = c.getConstructor(new Class[] { Interpreter.class, String.class, ShipDescription.class });
83             String src = "/ships/" + shipType + ".ship";
84             InputStream is = getClass().getResourceAsStream(src);
85             BufferedReader br = new BufferedReader(new InputStreamReader(is));
86             ShipDescription sd = new ShipDescription(this, shipType, br);
87             InterpreterShip ret = (InterpreterShip)con.newInstance(new Object[] { this, shipname, sd });
88             ships.put(shipname, ret);
89             if (shipType.equals("Debug") && debugShip == null)
90                 debugShip = ret;
91             return ret;
92         } catch (Exception e) {
93             e.printStackTrace();
94             return null;
95         }
96     }
97
98     void debug(long d) { debug(new BitVector(getWordWidth()).set(d)); }
99     void debug(BitVector data) {
100         try {
101             if (debugStream != null) debugStream.put(data);
102             else Log.println(ANSI.invert("   DEBUG: got a datum: " +  data+ANSI.clreol()));
103         } catch (Exception e) {
104             throw new RuntimeException(e);
105         }
106     }
107
108     // Instruction Encoding /////////////////////////////////////////////////////////////////////////
109
110     public BitVector getDestAddr(Path path) {
111         long ret = ((InterpreterDestination)path.getDestination()).getSerialNumber();
112         BitVector sig = path.getSignal();
113         BitVector bv = new BitVector(DISPATCH_PATH.valmaskwidth+1);
114         bv.set(ret);
115         if (sig != null) {
116             if (sig.length() > 1) throw new RuntimeException("signal was " + sig.length() + " bits long!");
117             if (sig.length() > 0 && sig.get(0)) bv.set(bv.length()-1,true);
118         }
119         return bv;
120     }
121
122
123     // ShipDescription //////////////////////////////////////////////////////////////////////////////
124
125     public void expand(ShipDescription sd) {
126         try {
127             String filename = sd.getName();
128             //String filename = (sd.getName().charAt(0)+"").toUpperCase() + sd.getName().substring(1).toLowerCase();
129             File outf = new File("build/java/edu/berkeley/fleet/interpreter/"+filename+".java");
130             new File(outf.getParent()).mkdirs();
131             System.err.println("writing to " + outf);
132             FileOutputStream out = new FileOutputStream(outf);
133             PrintWriter pw = new PrintWriter(out);
134
135             pw.println("package edu.berkeley.fleet.interpreter;");
136             pw.println("import edu.berkeley.sbp.util.ANSI;");
137             pw.println("import edu.berkeley.fleet.api.*;");
138             pw.println("import edu.berkeley.fleet.two.*;");
139             pw.println("import edu.berkeley.fleet.*;");
140             pw.println("import java.util.*;");
141             pw.println("import java.io.*;");
142             pw.println("");
143             pw.println("public class "+filename+" extends InterpreterShip {");
144             pw.println("");
145             pw.println("    public "+filename+"(Interpreter fleet, String name, ShipDescription sd) {");
146             pw.println("       super(fleet, sd);");
147             pw.println("    }");
148             pw.println("");
149             for(DockDescription b : sd) {
150                 String name = b.getName();
151                 pw.print("    InterpreterDock box_");
152                 pw.print(name);
153                 pw.print(" = new InterpreterDock(this, shipDescription.getDockDescription(\""+name+"\"));");
154             }
155             pw.println("");
156             pw.println(sd.getSection("fleeterpreter"));
157             pw.println("}");
158             pw.flush();
159             pw.close();
160         } catch (Exception e) { throw new RuntimeException(e); }
161     }
162
163     // Run //////////////////////////////////////////////////////////////////////////////
164
165     public FleetProcess run(final Instruction[] instructions) {
166         InterpreterProcess ip = initialize(instructions);
167         Thread ipt = new Thread(ip);
168         ipt.setDaemon(true);
169         ipt.start();
170         return ip;
171     }
172
173     public InterpreterProcess initialize(Instruction[] instr) {
174         return new InterpreterProcess(instr);
175     }
176
177     public class InterpreterProcess extends FleetProcess implements Runnable {
178         private Instruction[] instructions;
179         public synchronized void sendWord(Destination d, BitVector word) { sendWord(d, word, null); }
180         public synchronized void sendWord(Destination d, BitVector word, BitVector signal) {
181             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, signal==null?new BitVector(1):signal);
182             new Packet(path, word, false).send();
183         }
184         public synchronized void sendToken(Destination d) {
185             InterpreterPath path = (InterpreterPath)debugShip.getDock("in").getPath(d, new BitVector(1));
186             new Packet(path, new BitVector(getWordWidth()), true).send();
187         }
188         public InterpreterProcess(Instruction[] instructions) {
189             this.instructions = instructions;
190             for(Instruction i : instructions)
191                 sendInstruction(i);
192         }
193         public Fleet getFleet() { return Interpreter.this; }
194         public synchronized void sendInstruction(Instruction i) {
195             long il = writeInstruction(i, debugShip.getDock("in"));
196             Path path = debugShip.getDock("in").getPath(i.dock.getInstructionDestination(), null);
197             new Packet((InterpreterPath)path, new BitVector(getWordWidth()).set(il), false).send();
198         }
199         public Dock getDebugInputDock() { return debugShip.getDock("in"); }
200         public BitVector recvWord() {
201             try {
202                 return debugStream.take();
203             } catch (Exception e) { throw new RuntimeException(e); }
204         }
205         protected void _terminate() { }
206         public void run() {
207             try {
208                 long lastStatus = System.currentTimeMillis();
209                 while(!isTerminated()) {
210                     flush();
211                     long now = System.currentTimeMillis();
212                     if (now - lastStatus > 2000 && !Log.quiet &&
213                         !"false".equals(System.getProperty("fleet.log.state","false"))) {
214                         System.out.println("== State Dump ===================================================");
215                         for(InterpreterShip ship : ships.values())
216                             for(Dock d : ship)
217                                 synchronized(this) {
218                                     ((InterpreterDock)d).dumpState();
219                                 }
220                         lastStatus = now;
221                     }
222                 }
223                 for(InterpreterShip ship : ships.values())
224                     ship.reset();
225                 debugStream.clear();
226             } catch (Exception e) {
227                 if (isTerminated()) return;
228                 throw new RuntimeException(e);
229             }
230         }
231
232         public void flush() {
233             // FIXME: should this run until we detect some sort of "quiescence"?  OTOH that might never happen.
234             for(InterpreterShip ship : ships.values())
235                 for(int j=0; j<10; j++)
236                     if (!isTerminated())
237                         synchronized(this) {
238                             ship._service();
239                         }
240         }
241
242         public synchronized void step(Dock d) {
243             ((InterpreterDock)d).service();
244         }
245         
246         public synchronized void step(Ship s) {
247             ((InterpreterShip)s).service();
248         }
249
250     }
251 }