cleanup of Marina test code
[fleet.git] / src / edu / berkeley / fleet / marina / ProperStopper.java
1 package edu.berkeley.fleet.marina;
2 import com.sun.electric.tool.simulation.test.*;
3 import java.util.ArrayList;
4 import java.util.List;
5 import edu.berkeley.fleet.marina.MarinaUtils.StateWireState;
6
7 public class ProperStopper {
8     // position of strobes in the control chain
9     private static final int BLOCK_STROBE_NDX = 0;
10     private static final int FILL_STROBE_NDX = 1;
11     private static final int GO_STROBE_NDX = 2;
12     private static final int SILENT_STROBE_NDX = 3;
13     private static final int CLEAR_STROBE_NDX = 4;
14     private static final int GENERAL_PURPOSE_STROBE_NDX = 5;
15         
16     // position of inputs in report chain
17     private static final int PREV_STATE_IN_NDX = 0;
18     private static final int FILL_STROBE_IN_NDX = 1;
19     private static final int FILL_STATE_IN_NDX = 2;
20     private static final int STOPPED_IN_NDX = 3;
21         
22     //private final String captureClockRelPath = "fillStag@1.gaspFill@0.fillScan@1";
23     private final String captureClockRelPath = "fillStag@1";
24     // test library direct write mode doesn't understand per register write 
25     // enables. We get simulation to work by toggling write clock.
26     private final boolean clockHack;
27     private final String captureClockName = "sx[4]";
28
29     /*
30     private boolean traceFill = true;
31     private boolean traceDrain = true;
32     */
33     private boolean traceFill = false;
34     private boolean traceDrain = false;
35         
36     private final String controlPath, dataPath, reportPath;
37     protected final ChainControl controlChain;
38     protected final ChainControl dataChain;
39     protected final ChainControl reportChain;
40     private final String captureClock;
41     private final ChipModel model;
42     private final Indenter indenter;
43
44     private final String pathToCounter;
45
46     protected static void fatal(boolean pred, String msg) { MarinaUtils.fatal(pred, msg); }
47     private void prln(String msg) { indenter.prln(msg); }
48     private void adjustIndent(int n) { indenter.adjustIndent(n); }
49         
50     /** NanosimModel.setNodeState() requires special path names.  
51      * Each instance name in the path must begin with the character 'x'.
52      * Return a path with the added X's. */
53     private String prefixInstNamesInPathWithX(String path) {
54         if (model==null) throw new RuntimeException();
55         if (!(model instanceof NanosimModel)) return path;
56         StringBuffer sb = new StringBuffer();
57         sb.append('x');
58         for (int i=0; i<path.length(); i++) {
59             char c = path.charAt(i);
60             sb.append(c);
61             if (c=='.')  sb.append('x');
62         }
63         return sb.toString();
64     }
65   
66     private void shiftControl(boolean readEnable, boolean writeEnable) {
67         controlChain.shift(Marina.CONTROL_CHAIN, readEnable, writeEnable);
68     }
69     private void shiftData(boolean readEnable, boolean writeEnable) {
70         dataChain.shift(Marina.DATA_CHAIN, readEnable, writeEnable);
71         if (writeEnable) {
72             if (clockHack && model instanceof NanosimModel) {
73                 NanosimModel nanoModel = (NanosimModel) model;
74                 nanoModel.setNodeState(captureClock, 1);
75                 nanoModel.waitNS(1);
76                 nanoModel.setNodeState(captureClock, 0);
77             } else if (clockHack && model instanceof VerilogModel) {
78                 VerilogModel nanoModel = (VerilogModel) model;
79                 nanoModel.setNodeState(captureClock, 1);
80                 nanoModel.waitNS(1);
81                 nanoModel.setNodeState(captureClock, 0);
82             }
83         }
84     }
85     private void shiftReport(boolean readEnable, boolean writeEnable) {
86         reportChain.shift(Marina.REPORT_CHAIN, readEnable, writeEnable);
87     }
88
89     private StateWireState boolToState(boolean b) {
90         return b ? StateWireState.FULL : StateWireState.EMPTY;
91     }
92
93     private CommandCodes fdcstate = null;
94
95     public void setCounterEnable(boolean enable) {
96         this.extra = enable;
97         setFillDrainControl(fdcstate);
98     }
99
100     public void setCounterValue(int val) {
101         SubchainNode chainNode = (SubchainNode) dataChain.findNode(pathToCounter);
102         int bitIndex = chainNode.getBitIndex();
103         ChainNode root = chainNode.getParentChain();
104         for(int i=0; i<31; i++)
105             root.getInBits().set(bitIndex+i, ((1<<i) & val)!=0);
106         shiftData(false, true);
107     }
108
109     // DOES NOT SHIFT THE CHAIN!!!!
110     public int getCounterValue() {
111         SubchainNode chainNode = (SubchainNode) dataChain.findNode(pathToCounter);
112         int bitIndex = chainNode.getBitIndex();
113         ChainNode root = chainNode.getParentChain();
114         return (int)root.getOutBits().get(bitIndex, 30).bitReverse().toLong();
115     }
116
117     // The first 5 bits of the control chain control the fill and drain stages
118     private void setFillDrainControl(CommandCodes ccc) {
119         BitVector fdCtl = ccc.bits(extra);
120         fdcstate = ccc;
121         fatal(fdCtl.getNumBits()!=6, "expect 6 proper stopper control bits");
122         BitVector val = controlChain.getInBits(controlPath);
123         for (int i=0; i<fdCtl.getNumBits(); i++) {
124             val.set(i, fdCtl.get(i));
125         }
126         controlChain.setInBits(controlPath, val);
127         shiftControl(false, true);
128     }
129     // The last bit of the control chain controls the general purpose
130     // output
131     public void setGeneralPurposeOutput(Boolean b) {
132         BitVector val = controlChain.getInBits(controlPath);
133         val.set(GENERAL_PURPOSE_STROBE_NDX,b);
134         shiftControl(false, true);
135     }
136     
137     //-------------------------- public methods ----------------------------
138
139     /** Put stopper in RUN state */
140     public void run() {
141         setFillDrainControl(CommandCodes.RUN);
142     }
143     /** Put stopper in IDLE state */
144     public void idle() {
145         setFillDrainControl(CommandCodes.IDLE);
146     }
147     /** Put stopper in FILL state */
148     private void fillMode() {
149         setFillDrainControl(CommandCodes.FILL);
150     }
151     /** Put stopper in BLOCK state */
152     public void block() {
153         setFillDrainControl(CommandCodes.BLOCK);
154     }
155     /** Put stopper in STOP state */
156     public void stop() {
157         setFillDrainControl(CommandCodes.STOP);
158     }
159     /** Put stopper in CLEAR state */
160     public void clear() {
161         setFillDrainControl(CommandCodes.CLEAR);
162     }
163     /** Put stopper in SOURCE state */
164     public void source() {
165         setFillDrainControl(CommandCodes.SOURCE);
166     }
167     /** Put stopper in STOPSOURCE state */
168     public void stopSource() {
169         setFillDrainControl(CommandCodes.STOPSOURCE);
170     }
171     /** Put stopper in SINK state */
172     public void sink() {
173         setFillDrainControl(CommandCodes.SINK);
174     }
175     /** Put stopper in STOPSINK state */
176     public void stopSink() {
177         setFillDrainControl(CommandCodes.STOPSINK);
178     }
179
180     public boolean extra = false;
181
182     /** Stop a running stopper in order to add items.  Ensure that we don't
183      * lose the item in the fill stage.  
184      * Exit state: block */
185     public void stopToFill() {
186         stop();                                 // go = 0
187         idle();                                 // block = 1
188         block();                                // go = 1
189         //      idle();                                 // go = 0
190     }
191
192     /** get value of the state wire preceding the fill stage */
193     public StateWireState getPrevStateWire() {
194         shiftReport(true, false);
195         BitVector b = reportChain.getOutBits(reportPath);
196         int n = b.getNumBits(); 
197         fatal(n!=4, "Bad number of Stopper report bits: "+n);
198         return boolToState(reportChain.getOutBits(reportPath).get(PREV_STATE_IN_NDX));
199     }
200
201     /** get the value of drain stage fill wire.
202      * The fill wire will be interesting if we doubt that the
203      * scan chain works. */
204     public boolean getFillStrobe() {
205         shiftReport(true, false);
206         return reportChain.getOutBits(reportPath).get(FILL_STROBE_IN_NDX);
207     }
208
209     /** get value of state wire between the fill and drain stages */
210     public StateWireState getFillStateWire() {
211         shiftReport(true, false);
212         return boolToState(reportChain.getOutBits(reportPath).get(FILL_STATE_IN_NDX));
213     }
214
215     /** get value of drain stage stopped wire */
216     public boolean getStopped() {
217         shiftReport(true, false);
218         return reportChain.getOutBits(reportPath).get(STOPPED_IN_NDX);
219     }
220
221     public String getReportString() {
222         StringBuffer sb = new StringBuffer();
223         sb.append("Stopper's prev state: ");
224         sb.append(getPrevStateWire()+"\n");
225         sb.append("Stopper's fill stage: ");
226         sb.append(getFillStateWire()+"\n");
227         sb.append("Stopper's stopped: ");
228         sb.append(getStopped()+"\n");
229         return sb.toString();
230     }
231
232     /** construct a ProperStopper */
233     public ProperStopper(String propInst,
234                          ChainControl controlChain,
235                          ChainControl dataChain,
236                          ChainControl reportChain,
237                          ChipModel model,
238                          boolean clockHack,
239                          Indenter indenter,
240                          String pathToCounter) {
241         propInst += ".properSt@1";
242         this.controlPath = Marina.CONTROL_CHAIN+'.'+propInst;
243         this.dataPath = Marina.DATA_CHAIN+'.'+propInst;
244         this.reportPath = Marina.REPORT_CHAIN+'.'+propInst;
245         this.model = model;
246         this.captureClock = 
247             prefixInstNamesInPathWithX(propInst+'.'+captureClockRelPath)
248             +'.'+captureClockName;
249         this.clockHack = clockHack;
250         this.indenter = indenter;
251         this.pathToCounter = Marina.DATA_CHAIN+'.'+pathToCounter;
252         this.controlChain = controlChain;
253         this.dataChain = dataChain;
254         this.reportChain = reportChain;
255     }
256
257     /** Reset ProperStopper after the JTAG TRST has been pulsed */
258     public void resetAfterMasterClear() {
259         BitVector we = new BitVector(2, "write enable");
260         BitVector packet = new BitVector(MarinaPacket.PACKET_WIDTH, "packet");
261         we.setFromLong(0);
262         packet.setFromLong(0);
263         BitVector wdta = we.cat(packet);
264         dataChain.setInBits(dataPath, wdta);
265     }
266     
267     /** Insert one item into the fill stage.
268      * Fill stage must be empty. 
269      * You must stop stopper before calling fill.
270      * exit state: block */
271     private void fill_(BitVector dta) {
272         adjustIndent(2);
273         
274         int n = dta.getNumBits();
275         fatal(n!=(37+1+14), "fill: wrong num bits: "+n);
276         
277         // make sure fill stage is empty
278         StateWireState myState = getFillStateWire();
279         fatal(myState!=StateWireState.EMPTY, "fill: fill stage already full");
280         
281         idle();                                 // block = 1, go = 0
282
283         BitVector wrEn = new BitVector(2, "write enable");
284         wrEn.setFromLong(3);
285         dataChain.setInBits(dataPath, wrEn.cat(dta));
286         shiftData(false, true);
287         
288         fillMode();                                 // fill = 1
289         idle();                                 // fill = 0
290         block();                                // go = 1
291         //      idle();
292         
293         model.waitNS(5);
294
295         // debugging
296         if (traceFill) prln(getReportString());
297         
298         // if data chain is shifted in the future, don't write!
299         wrEn.setFromLong(0);
300         dataChain.setInBits(dataPath, wrEn.cat(dta));
301         
302         adjustIndent(-2);
303         if (traceFill) prln("End fill");
304     }
305
306     public void fill() {
307         BitVector data = new BitVector(37, "empty");
308         BitVector addr = new BitVector(14, "empty");
309         for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
310         for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
311         fill(new MarinaPacket(data, false, addr));
312     }
313
314     public void fill(BitVector dat) {
315         if (traceFill) prln("Begin fill.");
316         if (traceFill) prln("writing data: "+new MarinaPacket(dat));
317         fill_(dat);
318     }
319
320     public void fill(MarinaPacket mp) {
321         if (traceFill) prln("Begin fill.");
322         if (traceFill) prln("writing data: "+mp);
323         fill_(mp.toSingleBitVector());
324     }
325
326     /** Insert items from a list, one by one. 
327      * You must stop stopper before calling fillMany()
328      * exit state: block */
329     public void fillMany(List<BitVector> data) {
330         prln("Begin fillMany. numWords="+data.size());
331         adjustIndent(2);
332         int cnt = 0;
333         for (BitVector bv : data) {
334             if (traceFill) prln("fillStopperMany: writing word number: "+cnt++);
335             fill(bv);
336         }
337         adjustIndent(-2);
338         prln("end fillMany");
339     }
340
341     /** Remove one item from fill stage. Return that item.
342      * An item must be available.
343      * drain() will stop cleanly.
344      * exit state: stop */
345     public BitVector drain() {
346         stop();                                 // all zero, block = 0, go = 0
347         
348         // make sure an item is available
349         StateWireState myState=getFillStateWire();
350         fatal(myState==StateWireState.EMPTY, "drain: fill stage empty");
351
352         return drainNoCheck();
353     }
354
355     /** Remove one item from fill stage. Return that item.
356      * Assume that an item is available. 
357      * entry state: stop
358      * exit state: stop */
359     private BitVector drainNoCheck() {
360         shiftData(true, false);
361
362         // strip the two write enable bits
363         BitVector ans = dataChain.getOutBits(dataPath).get(2, 52);
364
365         idle();                                 // block = 1
366         clear();                                // clear = 1
367         idle();                                 // clear = 0
368         stop();                                 // block = 0
369
370         if (traceDrain) prln("drain  data="+new MarinaPacket(ans));
371         return ans;
372     }
373
374     /** Remove as many items as possible from the fill stage.
375      * drainStopperMany() will stop cleanly.
376      * exit state: stop */
377     public List<BitVector> drainMany() {
378         return drainMany(Integer.MAX_VALUE);
379     }
380
381     /** Remove up to maxNbItems items from the fill stage.
382      * drainStopperMany() will stop cleanly.
383      * exit state: stop */
384     public List<BitVector> drainMany(int maxNbItems) {
385         adjustIndent(2);
386         
387         stop();
388         
389         List<BitVector> ans = new ArrayList<BitVector>();
390         
391         int cnt = 0;
392         while (true) {
393             StateWireState myState=getFillStateWire();
394
395             // debugging
396             if (traceDrain) prln(getReportString());
397
398             if (myState==StateWireState.EMPTY || cnt>=maxNbItems) break;
399                 
400             cnt++;
401             indenter.pr("  drain"+(maxNbItems==0?"":"Many")+
402                         ": reading word"+(maxNbItems==0?":":" number "+cnt+
403                         "/"+(maxNbItems==Integer.MAX_VALUE
404                              ?"unlimited":("at-most-"+maxNbItems))+": "));
405
406             BitVector d = drainNoCheck();
407             if (maxNbItems>1)
408                 prln("  got "+new MarinaPacket(d));
409
410             ans.add(d);
411         }
412         
413         prln("end drainMany, got "+ans.size()+" items");
414         adjustIndent(-2);
415         
416         return ans;
417     }
418
419     // proper stopper ring occupancy bits
420     //southFif@1.upDown8w@1.weakStag@18.scanEx1@0 REPORT chain
421     //18, 22, 19, 23, 20, 24, 21, 25
422     //northFif@1.upDown8w@2...
423     // south fifo tap stage:
424     //   southFif@1.tapPropS@1.tapStage@2.scanEx1@0 (also REPORT chain)
425
426     /**
427      * (Note by Bill and Adam: Ivan has struck again!)
428      * As of 05 March 2009 the new bits are:
429      *    Block Extra Fill Go Clear Silent
430      *      => Note: "Extra" gets fed to the mux in the counter
431      *         that selects the frequency output that goes off-chip
432      *
433      * Caution: Ivan changes the order of the ProperStopper control bits 
434      * from chip to chip.  Here is the current order for Marina
435      * as of 14 Aug 2008: 
436      *  Block, Fill, Go, Silent, Clear
437      *
438      *  The old bit order for Infinity was: Fill, Block, Clear, Silent, Go
439      */
440     private static enum CommandCodes {
441         RUN        ("000100","010100"),
442             IDLE       ("100000","110000"),
443             FILL       ("101000","111000"),
444             BLOCK      ("100100","110100"),
445             STOP       ("000000","010000"),
446             CLEAR      ("100010","110010"),
447             SOURCE     ("001100","011100"),
448             STOPSOURCE ("001000","011000"),
449             SINK       ("000101","010101"),
450             STOPSINK   ("000001","010001");
451         private BitVector scanBits0;
452         private BitVector scanBits1;
453         CommandCodes(String bits0,String bits1) {
454             scanBits0 = new BitVector(bits0,"CommandCodes");
455             scanBits1 = new BitVector(bits1,"CommandCodes");
456         }
457         public BitVector bits(boolean extra) {
458             return extra ? scanBits1 : scanBits0;
459         }
460     }
461
462 }