23d103089bf3de05adb85c52c4d08cc0ed0bf4df
[fleet.git] / marina / testCode / com / sun / vlsi / chips / marina / test / MarinaTest.java
1 package com.sun.vlsi.chips.marina.test;
2 /* -*- tab-width: 4 -*- */
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import com.sun.async.test.BitVector;
7 import com.sun.async.test.ChainControl;
8 import com.sun.async.test.ChainG;
9 import com.sun.async.test.ChainTest;
10 import com.sun.async.test.ChipModel;
11 import com.sun.async.test.HP34401A;
12 import com.sun.async.test.Infrastructure;
13 import com.sun.async.test.JtagSubchainTesterModel;
14 import com.sun.async.test.JtagTester;
15 import com.sun.async.test.ManualPowerChannel;
16 import com.sun.async.test.NanosimModel;
17 import com.sun.async.test.HsimModel;
18 import com.sun.async.test.VerilogModel;
19 import com.sun.async.test.Netscan4;
20 import com.sun.async.test.PowerChannel;
21 import com.sun.async.test.Pst3202Channel;
22 import com.sun.async.test.SiliconChip;
23 import com.sun.async.test.SimulationModel;
24 import com.sun.async.test.VoltageReadable;
25 import com.sun.vlsi.chips.marina.test.Marina.Ilc;
26 import com.sun.vlsi.chips.marina.test.CmdArgs;
27 import com.sun.vlsi.chips.marina.test.CmdArgs.Mode;
28
29 import edu.berkeley.fleet.api.Dock;
30 import edu.berkeley.fleet.api.Instruction;
31 import edu.berkeley.fleet.api.Predicate;
32 import edu.berkeley.fleet.api.Instruction.Set.SetDest;
33 import edu.berkeley.fleet.api.Instruction.Set.SetSource;
34 import edu.berkeley.fleet.marina.MarinaFleet;
35 import edu.berkeley.fleet.marina.MarinaPath;
36
37 /**
38  * Tests for Marina
39  */
40 public class MarinaTest {
41     public static final MarinaFleet marinaFleet = new MarinaFleet();
42     public static final Dock dock = marinaFleet.getOnlyInputDock();
43
44     //--------------------------  constants -----------------------------------
45     private static final String SCAN_CHAIN_XML = "marina.xml";
46     private static final String NET_LIST = "marina.spi";
47
48     public static final int INSTR_SZ = 36;
49
50        
51     public static final Instruction.Set.FlagFunction CLEAR_FLAG 
52         = Instruction.Set.FlagFunction.ZERO;
53     public static final Instruction.Set.FlagFunction SET_FLAG 
54         = Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagA)
55         .add(Predicate.NotFlagA);
56     public static final Instruction.Set.FlagFunction A_FLAG 
57         = Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagA);
58
59     public static final Instruction.Set.FlagFunction B_FLAG 
60         = Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagB);
61     
62     // COLUMN_LATENCY is a delay that is larger than the latency through an Infinity column
63     private static final int COLUMN_LATENCY = 10; // nanoseconds
64
65
66     // Officially, this should be the number of requeueing no-ops that
67     // can be inserted into an idle dock whose OLC is nonzero.
68     //
69     // Less formally, this is roughly the number of stages of
70     // buffering between the instruction insertion point and the
71     // instruction ring, plus the capacity of the instruction ring.
72     private static final int INSTRUCTION_IN_SATURATION_AMOUNT = 19;
73
74     // This is some number which is significantly greater than
75     // INSTRUCTION_IN_SATURATION_AMOUNT.  Increasing it may slow the tests down, but
76     // will never cause them to operate incorrectly.
77     private static final int MORE_THAN_INSTRUCTION_IN_SATURATION_AMOUNT = 25;
78         
79     // This is the number of items which can be in the instruction
80     // fifo ring WITHOUT causing it to stop circulating.
81     private static final int INSTRUCTION_RING_CAPACITY = 13;
82         
83     // Officially, this should be the number of data items which can
84     // be sent from the dock while the "data" proper stopper is in
85     // the "stopped" state
86     //
87     // Less formally, this is roughly the number of stages of
88     // buffering between the dock's data successor and the "data"
89     // proper stopper
90     /*
91       FIXME: what is the correct value here?
92       private static final int DATA_OUT_SATURATION_AMOUNT = XXX;
93     */
94
95     // This is some number which is greater than
96     // DATA_OUT_SATURATION_AMOUNT, but less than the capacity of the
97     // instruction fifo.
98     private static final int MORE_THAN_DATA_OUT_SATURATION_AMOUNT = 10;
99         
100     // Nominal cycle time assuming 4 GHz throughput
101     public static double CYCLE_TIME_NS;
102
103     //--------------------------------  types ---------------------------------
104
105     //--------------------------  private data --------------------------------
106     private static long startTime;
107
108     public static Indenter indenter = new Indenter();
109     private Marina marina;
110     private ChipModel model;
111     //private ChainControl cc;
112     //private JtagTester tester;
113     private CmdArgs cmdArgs;
114     private PowerChannel corePowerSupply, padsPowerSupply;
115     private VoltageReadable coreVoltmeter, voltmeterForCurrent;
116
117     private ChainTest ctD, ctR, ctC, ct;
118     private ChainControl ccD, ccR, ccC, cc;
119         
120     //--------------------------  private methods -----------------------------
121     /** @return true if simulation. Return false if we're testing silicon. */
122     private boolean sim() {return model instanceof SimulationModel;}
123         
124     private void prln(String msg) {indenter.prln(msg);}
125     private void pr(String msg) {indenter.pr(msg);}
126     private void adjustIndent(int n) {indenter.adjustIndent(n);}
127         
128     public static void fatal(boolean pred, String msg) { MarinaUtils.fatal(pred, msg); }
129
130     public static void fatalIfBitVectorsDoNotMatch(BitVector bv1, BitVector bv2) {
131         // FIXME: better error reporting needed here
132
133         fatal(bv1.getNumBits()!=bv2.getNumBits(), "lengths do not match");
134
135         boolean mismatch = false;
136         String err = "";
137         for(int i=0; i<bv1.getNumBits(); i++) {
138             if (bv1.get(i) != bv2.get(i)) {
139                 mismatch = true;
140                 err += ""+i+", ";
141             }
142         }
143         fatal(mismatch, "bit vectors do not match on bits " + err + "\n  "+bv1+"\n  "+bv2);
144     }
145
146     private static void printTestTime() {
147         long endTime = System.currentTimeMillis();
148         System.out.println("Test took: "+(endTime-startTime)/1000.0+"  sec");
149     }
150     
151     // Tell user what we're about to do
152     private static void reportTask(CmdArgs args) {
153         System.out.println("Begin testing Marina");
154         switch (args.mode) {
155             case WHOLE_CHIP_SCHEMATIC_PARASITICS:
156                 System.out.println("  Simulate whole chip, schematic parasitics");
157                 break;
158             case WHOLE_CHIP_LAYOUT_PARASITICS:
159                 System.out.println("  Simulate whole chip, layout parasitics");
160                 break;
161             case TEST_SILICON:
162                 System.out.println("  Test silicon");
163                 break;
164             default:
165                 fatal(true, "unrecognized CmdArgs.Mode");
166                 return;
167         }
168     }
169     private void setUpSuppliesAndMeters(Station station) {
170         // set up power supplies and meters
171         if (!sim()) {
172             prln("Testing station: "+station);
173             Infrastructure.gpibControllers = new int[] {0};
174             switch (cmdArgs.station) {
175                 case ONE:
176                     corePowerSupply = new Pst3202Channel("ch1", "HPST3202", 1);
177                     padsPowerSupply = new Pst3202Channel("ch2", "HPST3202", 2);
178                     break;
179                 case TWO:
180                     corePowerSupply = new Pst3202Channel("ch1", "HPST3202B", 1);
181                     padsPowerSupply = new Pst3202Channel("ch2", "HPST3202B", 2);
182                     break;
183                 default:
184                     fatal(true, "Unrecognized station: "+cmdArgs.station);
185             }
186             corePowerSupply.setCurrent((float)1.7);
187             corePowerSupply.setVoltageWait((float)1.0);
188                   
189             padsPowerSupply.setCurrent((float)0.100);
190             padsPowerSupply.setVoltageWait((float)1.8);
191                   
192             coreVoltmeter = new HP34401A(station.coreVoltmeter);
193             voltmeterForCurrent = new HP34401A(station.currentVoltmenter);
194         }
195     }
196         
197     private MarinaTest(String[] args) {
198         cmdArgs = new CmdArgs(args);
199         reportTask(cmdArgs);
200         if (cmdArgs.mode==Mode.TEST_SILICON) doSilicon(); else doSim();
201     }
202         
203     private void doSim() {
204         String netListName;
205         switch (cmdArgs.mode) {
206             case WHOLE_CHIP_SCHEMATIC_PARASITICS:
207                 netListName = NET_LIST; 
208                 break;
209             case WHOLE_CHIP_LAYOUT_PARASITICS:
210                 netListName = "marina_pads_guts.spi"; 
211                 break;
212             default:
213                 fatal(true, "unrecognized CmdArgs.Mode");
214                 return;
215         }
216         model = cmdArgs.useVerilog
217             ? new VerilogModel()
218             : cmdArgs.useHsim
219             ? new HsimModel()
220             : new NanosimModel();
221             
222         ((SimulationModel)model).setOptimizedDirectReadsWrites(true);
223
224         CYCLE_TIME_NS = cmdArgs.useVerilog ? (100*20) : 0.250;
225         int khz   = model instanceof VerilogModel ? 100000 : cmdArgs.jtagShift ? 20000 : 1000000;
226
227         prln("constructing jtag controller");
228         JtagTester tester = ((SimulationModel)model).createJtagTester("TCK", "TMS", "TRSTb", "TDI", "TDO");
229         tester.printInfo = false;
230
231         ChainControls ccs = new ChainControls();
232         PowerChannel pc = new ManualPowerChannel("pc", false);
233         /*
234         JtagTester testerD, testerR, testerC;
235         testerD = ((SimulationModel)model).createJtagSubchainTester("sid[1:9]", null); 
236         testerR = ((SimulationModel)model).createJtagSubchainTester("sir[1:9]", null); 
237         testerC = ((SimulationModel)model).createJtagSubchainTester("sic[1:9]", null); 
238         testerD.printInfo = testerR.printInfo = testerC.printInfo = false;
239
240         ccD = new ChainControl(SCAN_CHAIN_XML, testerD, 1.8f, khz);
241         ccR = new ChainControl(SCAN_CHAIN_XML, testerR, 1.8f, khz);
242         ccC = new ChainControl(SCAN_CHAIN_XML, testerC, 1.8f, khz);
243         ccD.noTestSeverity = ccR.noTestSeverity = ccC.noTestSeverity = Infrastructure.SEVERITY_NOMESSAGE;
244
245         
246         ctD = new ChainTest(ccD, pc);
247         ctR = new ChainTest(ccR, pc);
248         ctC = new ChainTest(ccC, pc);
249         */        
250         /*
251         ccs.addChain(Marina.DATA_CHAIN, ccD);
252         ccs.addChain(Marina.REPORT_CHAIN, ccR);
253         ccs.addChain(Marina.CONTROL_CHAIN, ccC);
254         */
255
256         cc = new ChainControl(SCAN_CHAIN_XML, tester, 1.8f, khz);
257         cc.noTestSeverity = Infrastructure.SEVERITY_NOMESSAGE;
258         ct = new ChainTest(cc, pc);
259         ccs.addChain(Marina.DATA_CHAIN, cc);
260         ccs.addChain(Marina.REPORT_CHAIN, cc);
261         ccs.addChain(Marina.CONTROL_CHAIN, cc);
262
263         marina = new Marina(ccs, model, !cmdArgs.jtagShift, indenter);
264
265         if (model instanceof VerilogModel)
266             ((SimulationModel)model).start("verilog", "marina.v", VerilogModel.DUMPVARS, !cmdArgs.jtagShift);
267         else if (model instanceof HsimModel)
268             ((SimulationModel)model).start("hsim64", netListName, 0, !cmdArgs.jtagShift);
269         else
270             ((SimulationModel)model).start("nanosim -c cfg", netListName, 0, !cmdArgs.jtagShift);
271
272         /*
273         ccC.resetInBits();
274         ccC.shift(Marina.CONTROL_CHAIN, false, true);
275         */
276
277         cc.resetInBits();
278         cc.shift(Marina.CONTROL_CHAIN, false, true);
279         
280         doOneTest(cmdArgs.testNum);
281         
282         ((SimulationModel)model).finish();
283     }
284     private void doSilicon() {
285         model = new SiliconChip();
286         String ip = cmdArgs.station.ipAddr;
287         JtagTester tester = new Netscan4(ip, cmdArgs.station.jtagChannel);
288         tester.printInfo = false;
289         int khz = 1000;
290         ChainControl cc = new ChainControl("???", tester, 1.8f, khz);
291         cc.noTestSeverity = Infrastructure.SEVERITY_NOMESSAGE;
292         ChainControls ccs = new ChainControls();
293         ccs.addChain(Marina.DATA_CHAIN, cc);
294         ccs.addChain(Marina.REPORT_CHAIN, cc);
295         ccs.addChain(Marina.CONTROL_CHAIN, cc);
296         marina = new Marina(ccs, model, false, indenter);
297         PowerChannel pc = new ManualPowerChannel("pc", false);
298         ChainTest ct = new ChainTest(cc, pc);
299         ct.testAllChains("marina", Infrastructure.SEVERITY_WARNING);
300         doOneTest(cmdArgs.testNum);
301         setUpSuppliesAndMeters(cmdArgs.station);
302     }
303
304     /** In the absence of looping, the longest path through Infinity is 4 column delays */
305     private void waitUntilQuiescent() {
306         model.waitNS(4*COLUMN_LATENCY);
307     }
308     
309     private double readCurrent() {
310         return voltmeterForCurrent.readVoltage() / cmdArgs.station.ammeterShuntResistance;
311     }
312     
313     /** Generate List of BitVectors where Token=true, high 25 data bits  
314      * are alternating ones and zeros, low 12 data bits increment from 
315      * zero, and address is given by addr. */
316     private List<BitVector> makeIncrDataConstAdr(int num, int addr) {
317         List<BitVector> ans = new ArrayList<BitVector>();
318         BitVector dHi = new BitVector(25, "dataHi");
319         BitVector dLo = new BitVector(12, "dataLo");
320         BitVector t = new BitVector("1", "token");
321         BitVector a = new BitVector(14, "addr");
322         dHi.setFromLong(0x00aaaaa);
323         a.setFromLong(addr);
324         for (int i=0; i<num; i++) {
325             dLo.setFromLong(i);
326             ans.add(dHi.cat(dLo).cat(t).cat(a));
327             dHi = dHi.not();
328         }
329         return ans;
330     }
331     private void stopToStop(ProperStopper s1, ProperStopper s2, 
332                             Counter ctr,
333                             List<BitVector> din) {
334         prln("Begin stopToStop");
335         adjustIndent(2);
336         
337         s1.stop();
338         
339         long ctrStart = ctr==null ? 0 : ctr.getCount();
340         
341         s1.fillMany(din);
342         waitUntilQuiescent();
343         
344         List<BitVector> dout = s2.drainMany();
345         
346         MarinaUtils.compareItemsOrdered(din, dout);
347         
348         if (ctr!=null) {
349             long ctrEnd = ctr.getCount();
350             long delta = ctrEnd - ctrStart;
351             long expect = din.size();
352             fatal(delta!=expect, 
353                   "counter delta wrong: expected delta: "+expect+
354                   " counter before:"+ctrStart+" counter after:"+ctrEnd);
355         }
356         
357         adjustIndent(-2);
358         prln("End stopToStop");
359     }
360     /** Burst data from src to dst. gate is stopped while loading src. gate
361      * is then run to allow the burst to flow. */
362     private void stopToStopBurst(ProperStopper src, ProperStopper gate, 
363                                  ProperStopper dst,
364                                  Counter ctr,
365                                  List<BitVector> din) {
366         prln("Begin stopToStopBurst test");
367         adjustIndent(2);
368                 
369         src.stop();
370         gate.stop();
371                 
372         long ctrStart = ctr==null ? 0 : ctr.getCount();
373                 
374         src.fillMany(din);
375         waitUntilQuiescent();
376
377         // open the gate to start the burst
378         gate.run();
379         waitUntilQuiescent();
380                 
381         List<BitVector> dout = dst.drainMany();
382                 
383         MarinaUtils.compareItemsOrdered(din, dout);
384                 
385         if (ctr!=null) {
386             long ctrEnd = ctr.getCount();
387             long delta = ctrEnd - ctrStart;
388                 
389             long expectA = din.size();
390             fatal(delta!=expectA, 
391                   "counter delta wrong: expected delta: "+expectA+
392                   " counter before:"+ctrStart+" counter after:"+ctrEnd);
393         }
394                 
395         adjustIndent(-2);
396         prln("End stopToStopBurst test");
397     }
398
399     private void stopToStopOne(ProperStopper s1, ProperStopper s2, 
400                                Counter ctr, int adr) {
401         prln("Begin stopToStopOne");
402         adjustIndent(2);
403         
404         List<BitVector> din = makeIncrDataConstAdr(1, adr);
405         stopToStop(s1, s2, ctr, din);
406
407         adjustIndent(-2);
408         prln("End stopToStopOne");
409     }
410     
411     private void stopToStopThree(ProperStopper s1, ProperStopper s2, 
412                                  Counter ctr, int adr) {
413         prln("Begin stopToStopOne");
414         adjustIndent(2);
415         
416         List<BitVector> din = makeIncrDataConstAdr(3, adr);
417         stopToStop(s1, s2, ctr, din);
418
419         adjustIndent(-2);
420         prln("End stopToStopOne");
421     }
422
423     private int indexOf(BitVector o, List<BitVector> dIn) {
424         for (int i=0; i<dIn.size(); i++) {
425             if (o.equals(dIn.get(i)))  return i;
426         }
427         return -1;
428     }
429     private String ringDump(List<BitVector> dIn, List<BitVector> dOut) {
430         StringBuffer sb = new StringBuffer();
431         sb.append("  ring dump: ");
432         for (BitVector o : dOut) {
433             sb.append(indexOf(o, dIn)+" ");
434         }
435         return sb.toString();
436     }
437
438     private int[][] makeIntArray2D(int a, int b) {
439         int[][] ans = new int[a][];
440         for (int i=0; i<a; i++) ans[i] = new int[b];
441         return ans;
442     }
443
444     //=========================================================================
445     // Put top level tests here
446
447     private void testChains(Marina marina) {
448         if (ctC!=null) {
449             prln("Testing control chain...");
450             ctC.testOneChain(Marina.CONTROL_CHAIN, Infrastructure.SEVERITY_WARNING);
451             ccC.resetInBits();
452             ccC.shift(Marina.CONTROL_CHAIN, false, true);
453         }
454         
455         if (ctD!=null) {
456             prln("Testing data chain...");
457             ctD.testOneChain(Marina.DATA_CHAIN, Infrastructure.SEVERITY_WARNING);
458             //ccD.resetInBits();
459             //ccD.shift(Marina.DATA_CHAIN, false, true);
460         }
461         
462         if (ctR!=null) {
463             prln("Testing report chain...");            
464             ctR.testOneChain(Marina.REPORT_CHAIN, Infrastructure.SEVERITY_WARNING);
465             //ccR.resetInBits();
466             //ccR.shift(Marina.REPORT_CHAIN, false, true);
467         }
468
469         if (ct!=null) {
470             prln("Testing control chain...");
471             ct.testOneChain(Marina.CONTROL_CHAIN, Infrastructure.SEVERITY_WARNING);
472             cc.resetInBits();
473             cc.shift(Marina.CONTROL_CHAIN, false, true);
474             prln("Testing data chain...");
475             ct.testOneChain(Marina.DATA_CHAIN, Infrastructure.SEVERITY_WARNING);
476             prln("Testing report chain...");            
477             ct.testOneChain(Marina.REPORT_CHAIN, Infrastructure.SEVERITY_WARNING);
478         }
479     }
480
481     private void testProperStoppers(Marina marina) {
482         prln("Begin testProperStoppers");
483         adjustIndent(2);
484
485         for(ProperStopper ps : new ProperStopper[] { marina.data, marina.instrIn }) {
486
487             prln("testing " + (ps == marina.data ? "data" : "instruction") + " stopper");
488             adjustIndent(2);
489
490             prln("un-stopping stopper");
491             ps.run();
492             fatal( ps.getStopped(), "stopper should not have been stopped, but was");
493
494             prln("stopping stopper");
495             ps.stop();
496             fatal( !ps.getStopped(), "stopper should have been stopped, but was not");
497
498             adjustIndent(-2);
499         }
500
501         adjustIndent(-2);
502     }
503
504     private void sendInstructions(Marina marina) {
505         prln("Begin sendInstructions");
506         adjustIndent(2);
507         
508         List<BitVector> din = new ArrayList<BitVector>();
509
510         BitVector count = new BitVector(MarinaPacket.WORD_WIDTH,"count");
511         BitVector one = new BitVector(MarinaPacket.WORD_WIDTH, "one");
512         count.setFromLong(0);
513         one.setFromLong(1);
514         for (int i=0; i<3; i++) {
515             din.add(count);
516             count = count.add(one);
517         }
518
519         for(BitVector d : din)
520             marina.instrIn.fill(new MarinaPacket(d, false, MarinaPacket.null_path));
521
522         adjustIndent(-2);
523         prln("End sendInstructions");
524     }
525
526     private void sendToken(Marina marina) {
527         prln("Begin sendToken");
528         adjustIndent(2);
529         
530         //getCtrsFlags(marina);
531         
532         int nbToks = marina.getNumTokens();
533         fatal(nbToks!=0, "Expected no tokens on initialization but got: "+nbToks+" tokens");
534
535         marina.instrIn.fill(setIlc(1));
536         marina.instrIn.fill(SEND_TOKEN);
537         nbToks = marina.getNumTokens();
538         fatal(nbToks!=1, "Expected one token to emerge but got: "+nbToks+" tokens");
539         
540         adjustIndent(-2);
541         prln("End sendToken");
542     }
543
544     private void sendData(Marina marina) {
545         prln("Begin sendData");
546         adjustIndent(2);
547         
548         edu.berkeley.fleet.api.BitVector bv = new edu.berkeley.fleet.api.BitVector(13);
549         for(int i=0; i<bv.length(); i+=2) bv.set(i, false);
550         MarinaPath path = new MarinaPath((MarinaFleet)dock.getShip().getFleet(), bv);
551
552         marina.instrIn.fill(setIlc(1));
553         marina.instrIn.fill(SEND_DATA);
554         
555         List<BitVector> dataItems = marina.data.drainMany();
556         fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
557
558         MarinaPacket mp = new MarinaPacket(dataItems.get(0));
559         fatal(mp.tokenhood, "Expected tokenhood=data, but got tokenhood=token");
560
561         adjustIndent(-2);
562         prln("End sendData");
563     }
564
565     private void sendDataIlcInfinite(Marina marina) {
566         prln("Begin sendDataIlcInfinite");
567         adjustIndent(2);
568         
569         marina.fillSouthProperStopper(new Instruction[] {
570                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,SetSource.Infinity),
571                 SEND_DATA,
572             });
573         
574         // more than MAX_ILC
575         int howmany = 70;
576         List<BitVector> dataItems = marina.data.drainMany(howmany);
577         fatal(dataItems.size()!=howmany,
578               "Expected an unending supply of data items to emerge but only got got: "+dataItems.size());
579
580         adjustIndent(-2);
581         prln("End sendDataIlcInfinite");
582     }
583
584     private Instruction setOlc(int olc) {
585         return new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, olc);
586     }
587     private Instruction setOlcIfZero(int olc) {
588         return new Instruction.Set(dock,Predicate.Default,SetDest.OuterLoopCounter, olc);
589     }
590     private Instruction setIlc(int ilc) {
591         return new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, ilc);
592     }
593
594     private void testFlagD(Marina marina) {
595         prln("Begin testFlagD");
596         adjustIndent(2);
597         
598         List<BitVector> toks;
599
600         Predicate only_if_olc_zero    = Predicate.FlagD;
601         Predicate only_if_olc_nonzero = Predicate.Default;
602
603         marina.instrIn.fill(setIlc(1));
604
605         for(int olc : new int[] { 1, 0 }) {
606             for(boolean predicate_olc_nonzero : new boolean[] { true, false }) {
607                 prln("Attempting send data item with "+
608                      "olc=="+olc+" and "+
609                      "predicate olc"+(predicate_olc_nonzero?"!=0":"==0"));
610                 adjustIndent(2);
611
612                 marina.fillSouthProperStopper(new Instruction[] {
613                         setOlc(olc),
614                         new Instruction.Move(dock,
615                                              predicate_olc_nonzero  // predicate   
616                                              ? only_if_olc_nonzero
617                                              : only_if_olc_zero
618                                              ,
619                                              false,                 // torpedoable 
620                                              null,                  // path        
621                                              false,                 // tokenIn     
622                                              false,                 // dataIn      
623                                              false,                 // latchData   
624                                              false,                 // latchPath   
625                                              true,                  // dataOut     
626                                              false                  // tokenOut    
627                                              ),
628                     });
629                 expectNorthFifoExactly((predicate_olc_nonzero == (olc!=0)) ? 1 : 0);
630
631                 for(int i=0; i<olc; i++)
632                     marina.instrIn.fill(DEC);
633
634                 adjustIndent(-2);
635             }
636         }
637         adjustIndent(-2);
638         prln("End testFlagD");
639     }
640
641     private void testPredicationOnAB(Marina marina) {
642         prln("Begin testPredicationOnAB");
643         adjustIndent(2);
644         
645         List<BitVector> dItems;
646
647         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 1));
648         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, 1));
649
650         for(boolean flag_a : new boolean[] { false, true }) {
651             for(boolean flag_b : new boolean[] { false, true }) {
652                 prln("Setting flags, a="+flag_a+" b="+flag_b);
653                 marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,
654                                                         flag_a
655                                                         ? Instruction.Set.FlagFunction.ONE
656                                                         : Instruction.Set.FlagFunction.ZERO,
657                                                         flag_b
658                                                         ? Instruction.Set.FlagFunction.ONE
659                                                         : Instruction.Set.FlagFunction.ZERO
660                                                         ));
661                 getCtrsFlags(marina);
662
663                 adjustIndent(2);
664                 for(Predicate predicate : new Predicate[] {
665                         Predicate.Default,
666                         Predicate.FlagA,
667                         Predicate.FlagB,
668                         Predicate.NotFlagA,
669                         Predicate.NotFlagB,
670                     }) {
671
672                     prln("Attempting send data with a="+flag_a+", b="+flag_b+", predicate="+predicate);
673                     adjustIndent(2);
674                     marina.instrIn.fill(new Instruction.Move(dock,
675                                                              predicate,  // predicate   
676                                                              false,      // torpedoable 
677                                                              null,       // path        
678                                                              false,      // tokenIn     
679                                                              false,      // dataIn      
680                                                              false,      // latchData   
681                                                              false,      // latchPath   
682                                                              true,       // dataOut     
683                                                              false       // tokenOut    
684                                                              ));
685                     adjustIndent(-2);
686                     dItems = marina.data.drainMany();
687                     int expected = predicate.evaluate(flag_a, flag_b, false, false) ? 1 : 0;
688                     fatal(dItems.size()!=expected, "Expected "+expected+" data items to emerge but got: "+
689                           dItems.size()+" items(s)");
690                 }
691                 adjustIndent(-2);
692             }
693         }
694         adjustIndent(-2);
695         prln("End testPredicationOnAB");
696     }
697
698
699     private void showOlc() {
700         prln("OLC=="+marina.getOLC());
701     }
702     private void expectOlc(int x) {
703         int olc = marina.getOLC();
704         fatal(x!=olc, "expected OLC=="+x+", but scanned out OLC=="+olc);
705     }
706
707     private void getCtrsFlags(Marina marina) {
708         prln("begin getCtrsFlags");
709         adjustIndent(2);
710         
711         showOlc();
712         Ilc ilc = marina.getILC();
713         prln("ILC.done=="+ilc.getDone()+
714              " ILC.infinity=="+ilc.getInfinity()+
715              " ILC.count=="+ilc.getCount());
716         prln("flagA=="+marina.getFlagA());
717         prln("flagB=="+marina.getFlagB());
718         adjustIndent(-2);
719         prln("end getCtrsFlags");
720     }
721
722     private void walkOneOLC(Marina marina) {
723         prln("Begin walkOneOLC");
724         adjustIndent(2);
725         for (int i=0; i<6; i++) {
726
727             if (marina.kesselsCounter) {
728                 System.out.println("master-clearing...");
729                 // master clear on each iteration; otherwise we'd need to "run down" the olc
730                 marina.masterClear();
731                 marina.enableInstructionSend(true);
732             }
733
734             int inOlc = i==-1 ? 0 : (1<<i);
735             marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, inOlc));
736
737             model.waitNS(128 * CYCLE_TIME_NS);
738
739             expectOlc(inOlc);
740             prln("walkOneOLC: "+inOlc+" checks out");
741         }
742         adjustIndent(-2);
743         prln("End walkOneOLC");
744     }
745     private void walkOneILC(Marina marina) {
746         prln("Begin walkOneILC");
747         adjustIndent(2);
748         for (int i=0; i<6; i++) {
749             // Mask off the "zero" bit position
750             int inIlc = 1 << i;
751             prln("inIlc="+inIlc);
752             marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, inIlc));
753             Ilc ilc = marina.getILC();
754             int outIlc = ilc.getCount();
755             fatal(outIlc!=inIlc, "bad ILC count: "+outIlc+" expected: "+inIlc);
756             fatal(ilc.getInfinity(), "bad Infinity bit: true");
757         }
758         prln("Now test the infinity bit");
759         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, SetSource.Infinity));
760         Ilc ilc = marina.getILC();
761         fatal(!ilc.getInfinity(), "bad Infinity bit: false");
762         adjustIndent(-2);
763         prln("End walkOneILC");
764     }
765     private void countIlc(Marina marina) {
766         final int maxIlc = 63;
767         prln("Begin countIlc");
768         adjustIndent(2);
769         
770         marina.instrIn.fill(new 
771                             Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, maxIlc));
772
773         int ilc = marina.getILC().getCount();
774         fatal(ilc!=maxIlc, "bad ILC count: "+ilc+" expected: "+maxIlc);
775                 
776         prln("execute a move instruction that does nothing except decrement the ILC to zero");
777         marina.instrIn.fill(
778                             new Instruction.Move(dock,
779                                                  Predicate.IgnoreFlagD, // predicate   
780                                                  false,                 // torpedoable 
781                                                  null,                  // path        
782                                                  false,                 // tokenIn     
783                                                  false,                 // dataIn      
784                                                  false,                 // latchData   
785                                                  false,                 // latchPath   
786                                                  false,                 // dataOut     
787                                                  false                  // tokenOut    
788                                                  ));
789         
790         // wait for ILC to count from 63 to 0
791         model.waitNS(128 * CYCLE_TIME_NS);
792         //model.waitNS(10000);
793
794         prln("Check that ILC==0");
795         ilc = marina.getILC().getCount();
796         fatal(ilc!=0, "bad ILC count: "+ilc+" expected: "+0);
797         
798         adjustIndent(-2);
799         prln("End countIlc");
800     }
801     // Note: countOlc takes 44 minutes to run on nanosim
802     private void countOlc(Marina marina) {
803         int maxOlc = 63;
804         prln("Begin countOlc");
805         adjustIndent(2);
806
807         marina.instrIn.fill(setOlc(maxOlc));
808
809         for (int i=maxOlc; i>=0; i--) {
810             model.waitNS(128 * CYCLE_TIME_NS);
811             prln("OLC should be: "+i);
812             expectOlc(i);
813             marina.instrIn.fill(new 
814                                 Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, SetSource.Decrement));
815         }
816
817         adjustIndent(-2);
818         prln("End countOlc");
819     }
820
821     private void saturateInstructionFifo(Marina marina, Instruction instruction, int quantity, boolean expect_it_to_jam_up) {
822         prln("Inserting "+quantity+" copies of \"" + instruction + "\"");
823         adjustIndent(2);
824         int i=0;
825         for(i=0; i<quantity; i++) {
826             prln("Inserting instruction " + (i+1) +"/"+ quantity);
827             marina.instrIn.fill(instruction);
828             boolean jammed = (marina.instrIn.getFillStateWire()==MarinaUtils.StateWireState.FULL);
829             if (jammed && expect_it_to_jam_up) {
830                 prln("Stopper remained full after inserting instruction; this was expected; we are happy.");
831                 adjustIndent(-2);
832                 return;
833             }
834             fatal(jammed, "Instruction stopper did not drain after inserting " + (i+1) + " instructions; not good!");
835         }
836         fatal(expect_it_to_jam_up, "Expected instruction stopper to jam up, but it did not");
837         adjustIndent(-2);
838         prln("Successfully inserted " + i + " instructions");
839     }
840
841     private static MarinaPath null_path = new MarinaPath((MarinaFleet)dock.getShip().getFleet(),
842                                                          MarinaUtils.sunToBerk(MarinaPacket.null_path));
843
844     private static final Instruction DEC = 
845         new Instruction.Set(dock,Predicate.Default,SetDest.OuterLoopCounter, SetSource.Decrement);
846
847     private static final Instruction FLAG_NOP =
848         new Instruction.Set(dock, Predicate.IgnoreFlagD,
849                             CLEAR_FLAG.add(Predicate.FlagA),
850                             CLEAR_FLAG.add(Predicate.FlagB));
851
852     private static final Instruction NOP =
853         new Instruction.Move(dock,
854                              Predicate.IgnoreFlagD,   /* predicate   */
855                              false,                 /* torpedoable */
856                              null,                  /* path        */
857                              false,                 /* tokenIn     */
858                              false,                 /* dataIn      */
859                              false,                 /* latchData   */
860                              false,                 /* latchPath   */
861                              false,                 /* dataOut     */
862                              false                  /* tokenOut    */
863                              );
864
865     private static final Instruction SEND_DATA =
866         new Instruction.Move(dock,
867                              Predicate.IgnoreFlagD,   /* predicate   */
868                              false,                 /* torpedoable */
869                              null_path,                  /* path        */
870                              false,                 /* tokenIn     */
871                              false,                 /* dataIn      */
872                              false,                 /* latchData   */
873                              false,                 /* latchPath   */
874                              true,                  /* dataOut     */
875                              false                  /* tokenOut    */
876                              );
877
878     private static final Instruction SEND_DATA_IF_D_NOT_SET =
879         new Instruction.Move(dock,
880                              Predicate.Default,     /* predicate   */
881                              false,                 /* torpedoable */
882                              null_path,             /* path        */
883                              false,                 /* tokenIn     */
884                              false,                 /* dataIn      */
885                              false,                 /* latchData   */
886                              false,                 /* latchPath   */
887                              true,                  /* dataOut     */
888                              false                  /* tokenOut    */
889                              );
890
891     private static final Instruction SEND_DATA_IF_D_SET =
892         new Instruction.Move(dock,
893                              Predicate.FlagD,       /* predicate   */
894                              false,                 /* torpedoable */
895                              null_path,             /* path        */
896                              false,                 /* tokenIn     */
897                              false,                 /* dataIn      */
898                              false,                 /* latchData   */
899                              false,                 /* latchPath   */
900                              true,                  /* dataOut     */
901                              false                  /* tokenOut    */
902                              );
903
904     private static final Instruction TORPEDOABLE_RECV_DATA =
905         new Instruction.Move(dock,
906                              Predicate.IgnoreFlagD, /* predicate   */
907                              true,                  /* torpedoable */
908                              null,                  /* path        */
909                              false,                 /* tokenIn     */
910                              true,                  /* dataIn      */
911                              true,                  /* latchData   */
912                              false,                 /* latchPath   */
913                              false,                 /* dataOut     */
914                              false                  /* tokenOut    */
915                              );
916
917     private static final Instruction RECV_DATA =
918         new Instruction.Move(dock,
919                              Predicate.IgnoreFlagD,   /* predicate   */
920                              false,                 /* torpedoable */
921                              null,                  /* path        */
922                              false,                 /* tokenIn     */
923                              true,                  /* dataIn      */
924                              true,                  /* latchData   */
925                              false,                 /* latchPath   */
926                              false,                 /* dataOut     */
927                              false                  /* tokenOut    */
928                              );
929
930     private static final Instruction SEND_TOKEN =
931         new Instruction.Move(dock,
932                              Predicate.IgnoreFlagD,   /* predicate   */
933                              false,                 /* torpedoable */
934                              null_path,                  /* path        */
935                              false,                 /* tokenIn     */
936                              false,                 /* dataIn      */
937                              false,                 /* latchData   */
938                              false,                 /* latchPath   */
939                              false,                 /* dataOut     */
940                              true                   /* tokenOut    */
941                              );
942
943     private static final Instruction RECV_TOKEN =
944         new Instruction.Move(dock,
945                              Predicate.IgnoreFlagD,   /* predicate   */
946                              false,                 /* torpedoable */
947                              null,                  /* path        */
948                              true,                  /* tokenIn     */
949                              false,                 /* dataIn      */
950                              false,                 /* latchData   */
951                              false,                 /* latchPath   */
952                              false,                 /* dataOut     */
953                              false                  /* tokenOut    */
954                              );
955
956
957     private void expectNorthFifoNoMoreThan(int num) {
958         model.waitNS(128 * CYCLE_TIME_NS);
959         List<BitVector> dataItems = marina.data.drainMany(num+1);
960         fatal(dataItems.size()>num,
961               "Expected no more than "+num+
962               " data items to emerge but got at least: "+dataItems.size());
963     }
964     private void expectNorthFifoExactly(int num) {
965         model.waitNS(128 * CYCLE_TIME_NS);
966         List<BitVector> dataItems = marina.data.drainMany(num+1);
967         fatal(dataItems.size()!=num,
968               "Expected exactly "+num+
969               " data items to emerge but got at least: "+dataItems.size());
970     }
971     private void expectTokensNoMoreThan(int num) {
972         int x = marina.getNumTokens();
973         List<BitVector> dataItems = marina.data.drainMany(num+1);
974         fatal(x>num,
975               "Expected no more than "+num+
976               " data items to emerge but got at least: "+x);
977     }
978     private void expectTokensExactly(int num) {
979         int x = marina.getNumTokens();
980         fatal(x!=num,
981               "Expected exactly "+num+
982               " data items to emerge but got at least: "+x);
983     }
984
985     private void testFlagDRecomputationTime(Marina marina) {
986         marina.instrIn.fill(setIlc(1));
987         marina.fillSouthProperStopper(new Instruction[] {
988                 RECV_DATA,
989                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,0),
990                 SEND_DATA_IF_D_NOT_SET
991             });
992         marina.fillNorthProperStopper();
993         expectNorthFifoNoMoreThan(0);
994
995         marina.fillSouthProperStopper(new Instruction[] {
996                 RECV_DATA,
997                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,1),
998                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.Decrement),
999                 SEND_DATA_IF_D_NOT_SET
1000             });
1001         marina.fillNorthProperStopper();
1002         expectNorthFifoNoMoreThan(0);
1003
1004         marina.fillSouthProperStopper(new Instruction[] {
1005                 RECV_DATA,
1006                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,2),
1007                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.Decrement),
1008                 SEND_DATA_IF_D_NOT_SET
1009             });
1010         marina.fillNorthProperStopper();
1011         expectNorthFifoExactly(1);
1012         marina.instrIn.fill(DEC);
1013
1014         marina.fillSouthProperStopper(new Instruction[] {
1015                 RECV_DATA,
1016                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,0),
1017                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,1),
1018                 SEND_DATA_IF_D_NOT_SET
1019             });
1020         marina.fillNorthProperStopper();
1021         expectNorthFifoExactly(1);
1022     }
1023
1024     private void testTailWaitsForHead(Marina marina) {
1025         marina.instrIn.fill(setIlc(1));
1026         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63));
1027         
1028         marina.enableInstructionSend(false);
1029         marina.enableInstructionRecirculate(true);
1030         
1031         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1032         marina.instrIn.fill(new Instruction.Head(dock));
1033         marina.instrIn.fill(SEND_DATA);
1034         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1035         marina.instrIn.fill(SEND_TOKEN);
1036         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1037         marina.instrIn.fill(new Instruction.Tail(dock));
1038         marina.instrIn.fillTorpedo();
1039         
1040         marina.enableInstructionRecirculate(false);
1041         marina.enableInstructionSend(true);
1042         marina.instrIn.run();
1043         
1044         expectNorthFifoNoMoreThan(0);
1045         prln("inserting into north proper stopper");
1046         marina.fillNorthProperStopper();
1047         expectNorthFifoExactly(1);
1048         int nbToks = marina.getNumTokens();
1049         fatal(nbToks!=1, "Expected one token to emerge but got: "+nbToks+" tokens");
1050     }
1051
1052         /*
1053         marina.instrIn.fill(setIlc(1));
1054         marina.instrIn.fill(setOlc(1));
1055
1056         // this makes the head wait for the torpedo
1057         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1058
1059         // the head should wait for the tail
1060         marina.instrIn.fill(new Instruction.Head(dock));
1061         marina.instrIn.fill(NOP);
1062         marina.instrIn.fill(SEND_DATA);
1063         marina.instrIn.fill(RECV_DATA);
1064
1065         expectNorthFifoNoMoreThan(0);
1066
1067         marina.instrIn.fillTorpedo();
1068         expectNorthFifoNoMoreThan(0);
1069
1070         marina.instrIn.fill(new Instruction.Tail(dock));
1071         expectNorthFifoExactly(1);
1072         */
1073
1074     private void testTailWithoutHead(Marina marina) {
1075         marina.instrIn.fill(setIlc(1));
1076         marina.fillSouthProperStopper(new Instruction[] {
1077                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63),
1078                 new Instruction.Tail(dock),
1079                 SEND_DATA,
1080             });
1081         List<BitVector> dataItems = marina.data.drainMany(1);
1082         fatal(dataItems.size()!=0, "Expected exactly no data items to emerge but got at least: "+dataItems.size());
1083     }
1084
1085     private void testHeadWaitsForTail(Marina marina) {
1086         List<BitVector> dataItems;
1087
1088         prln("Begin testHeadWaitsForTail");
1089         adjustIndent(2);
1090
1091         marina.instrIn.fill(setIlc(1));
1092         marina.fillSouthProperStopper(new Instruction[] {
1093                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63),
1094                 new Instruction.Head(dock),
1095                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1096                 SEND_DATA,
1097             });
1098         dataItems = marina.data.drainMany(1);
1099         fatal(dataItems.size()!=0, "Expected exactly no data items to emerge but got at least: "+dataItems.size());
1100         marina.instrIn.fill(new Instruction.Tail(dock));
1101
1102         BitVector bv = marina.data.drain();
1103         fatal(bv==null, "Expected at least one data item to emerge but got none");
1104
1105         adjustIndent(-2);
1106         prln("End testHeadWaitsForTail");
1107     }
1108
1109     private void testNonTorpedoableMoveDoesNotResetDFlag(Marina marina) {
1110         marina.instrIn.fill(setIlc(1));
1111         marina.fillSouthProperStopper(new Instruction[] {
1112                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,63),
1113                 new Instruction.Move(dock,
1114                                      Predicate.IgnoreFlagD, // predicate   
1115                                      true,                  // torpedoable 
1116                                      null,                  // path        
1117                                      true,                  // tokenIn     
1118                                      false,                 // dataIn      
1119                                      false,                 // latchData   
1120                                      false,                 // latchPath   
1121                                      false,                 // dataOut     
1122                                      false                  // tokenOut    
1123                                      ),
1124                 new Instruction.Move(dock,
1125                                      Predicate.FlagD,       // predicate   
1126                                      false,                 // torpedoable 
1127                                      null,                  // path        
1128                                      false,                 // tokenIn     
1129                                      false,                 // dataIn      
1130                                      false,                 // latchData   
1131                                      false,                 // latchPath   
1132                                      true,                  // dataOut     
1133                                      false                  // tokenOut    
1134                                      ),
1135             });
1136         marina.instrIn.fillTorpedo();
1137         expectNorthFifoExactly(1);
1138         marina.fillSouthProperStopper(new Instruction[] {
1139                 new Instruction.Move(dock,
1140                                      Predicate.Default,     // predicate   
1141                                      false,                 // torpedoable 
1142                                      null,                  // path        
1143                                      false,                 // tokenIn     
1144                                      false,                 // dataIn      
1145                                      false,                 // latchData   
1146                                      false,                 // latchPath   
1147                                      true,                  // dataOut     
1148                                      false                  // tokenOut    
1149                                      ),
1150             });
1151         expectNorthFifoNoMoreThan(0);
1152     }
1153
1154     private void testAbort(Marina marina) {
1155         
1156         marina.instrIn.fill(setIlc(1));
1157         marina.fillSouthProperStopper(new Instruction[] {
1158                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.DataLatch,1),
1159                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,2),
1160                 SEND_DATA_IF_D_NOT_SET,
1161                 new Instruction.Head(dock),
1162                 SEND_DATA_IF_D_NOT_SET,
1163                 new Instruction.Set(dock,Predicate.Default,SetDest.DataLatch,2),
1164                 new Instruction.Abort(dock, Predicate.FlagD),
1165                 new Instruction.Set(dock,Predicate.Default,SetDest.OuterLoopCounter,SetSource.Decrement),
1166                 new Instruction.Tail(dock),
1167             }, true);
1168         
1169         for(int i=0; i<4; i++) {
1170             BitVector bv;
1171             
1172             model.waitNS(128 * CYCLE_TIME_NS);
1173             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1174             fatal(bv==null, "no data item found");
1175             prln("got " + bv.toLong());
1176             fatal(bv.toLong()!=1, "expected 1, got " + bv.toLong());
1177             
1178             model.waitNS(128 * CYCLE_TIME_NS);
1179             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1180             fatal(bv==null, "no data item found");
1181             prln("got " + bv.toLong());
1182             fatal(bv.toLong()!=1, "expected 1, got " + bv.toLong());
1183             
1184             model.waitNS(128 * CYCLE_TIME_NS);
1185             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1186             fatal(bv==null, "no data item found");
1187             prln("got " + bv.toLong());
1188             fatal(bv.toLong()!=2, "expected 2, got " + bv.toLong());
1189             
1190         }
1191     }
1192
1193     private void testAbortOutsideOfLoop(Marina marina) {
1194         marina.instrIn.fill(setIlc(1));
1195         marina.fillSouthProperStopper(new Instruction[] {
1196                 // ensure that an abort doesn't cause problems if no loop is in progress
1197                 new Instruction.Abort(dock, Predicate.IgnoreFlagD),
1198                 SEND_DATA,
1199             });
1200         expectNorthFifoExactly(1);
1201     }
1202
1203     private void testFlagAB(Marina marina) {
1204         prln("Begin testFlagAB");
1205         adjustIndent(2);
1206
1207         Instruction.Set.FlagFunction zero = Instruction.Set.FlagFunction.ZERO;
1208         Instruction.Set.FlagFunction one  = zero;
1209
1210         
1211         // we should be able to use any pair of FlagX+NotFlagX,
1212         // but we toss them all in to maximize the chances of the
1213         // test passing (later we will try the individual
1214         // combinations to maximize the chances of failure).
1215         one = one.add(Predicate.FlagA);
1216         one = one.add(Predicate.NotFlagA);
1217         one = one.add(Predicate.FlagB);
1218         one = one.add(Predicate.NotFlagB);
1219         one = one.add(Predicate.FlagC);
1220         one = one.add(Predicate.NotFlagC);
1221
1222         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1));
1223         for(boolean fast : new boolean[] { true, false }) {
1224             // clear the flags to a known state, then check both 0->1 and 1->0 transitions
1225             for(boolean b : new boolean[] { false, true, false }) {
1226                 prln("state: a="+marina.getFlagA()+", b="+marina.getFlagB());
1227                 prln((b?"Setting":"Clearing")+" flags");
1228                 
1229                 Instruction inst = new Instruction.Set(dock,Predicate.IgnoreFlagD,
1230                                                        b ? one : zero,
1231                                                        b ? one : zero
1232                                                        );
1233                 if (fast) {
1234                     marina.fillSouthProperStopper(new Instruction[] {
1235                             RECV_DATA,
1236                             inst,
1237                             NOP,
1238                         });
1239                     model.waitNS(64 * CYCLE_TIME_NS);
1240                     marina.fillNorthProperStopper();
1241                 } else {
1242                     marina.instrIn.fill(inst);
1243                 }
1244
1245                 fatal(marina.getFlagA()!=b,
1246                       "after "+(b?"setting":"clearing")+" FlagA, it was still "+(b?"clear":"set"));
1247                 fatal(marina.getFlagB()!=b,
1248                       "after "+(b?"setting":"clearing")+" FlagB, it was still "+(b?"clear":"set"));
1249             }
1250         }
1251
1252         adjustIndent(-2);
1253         prln("End testFlagAB");         
1254     }
1255
1256     /**
1257      *  WARNING: this is a very, very, very long test case -- it goes
1258      *  through 216 iterations.
1259      */
1260     private void testFlagTruthTable(Marina marina) {
1261         prln("Begin testFlagTruthTable");
1262         adjustIndent(2);
1263
1264         marina.instrIn.fill(setIlc(1));
1265         Instruction.Set.FlagFunction zero = Instruction.Set.FlagFunction.ZERO;
1266         Instruction.Set.FlagFunction one  = zero.add(Predicate.FlagA).add(Predicate.NotFlagA);
1267
1268         for(Predicate a_input : new Predicate[] { null, Predicate.FlagA, Predicate.NotFlagA })
1269             for(Predicate b_input : new Predicate[] { null, Predicate.FlagB, Predicate.NotFlagB })
1270                 for(Predicate c_input : new Predicate[] { null, Predicate.FlagC, Predicate.NotFlagC })
1271                     for(boolean a_state : new boolean[] { false, true })
1272                         for(boolean b_state : new boolean[] { false, true })
1273                             for(boolean c_state : new boolean[] { false, true }) {
1274                                 for(boolean which : new boolean[] { false, true }) {
1275
1276                                     prln("before instruction: a="+a_state+", b="+b_state+", c="+c_state);
1277                                     // set A,B flags to a_state and b_state
1278                                     marina.instrIn.fill(new 
1279                                                         Instruction.Set(dock,Predicate.IgnoreFlagD,
1280                                                                         a_state ? one : zero,
1281                                                                         b_state ? one : zero
1282                                                                         ));
1283                                     
1284                                     // set C flag to c_state
1285                                     BitVector data = new BitVector(37, "empty");
1286                                     BitVector addr = new BitVector(14, "empty");
1287                                     for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1288                                     for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1289                                     addr.set(Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ONE, c_state);
1290                                     marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1291                                     marina.instrIn.fill(RECV_DATA);
1292                                     
1293                                     Instruction.Set.FlagFunction func = zero;
1294                                     if (a_input!=null) func = func.add(a_input);
1295                                     if (b_input!=null) func = func.add(b_input);
1296                                     if (c_input!=null) func = func.add(c_input);
1297
1298                                     Instruction inst = new 
1299                                         Instruction.Set(dock,Predicate.IgnoreFlagD,
1300                                                         !which ? func : zero.add(Predicate.FlagA),
1301                                                         which  ? func : zero.add(Predicate.FlagB)
1302                                                         );
1303
1304                                     marina.instrIn.fill(inst);
1305
1306                                     boolean expected_a = !which ? func.evaluate(a_state, b_state, c_state, false) : a_state;
1307                                     boolean expected_b =  which ? func.evaluate(a_state, b_state, c_state, false) : b_state;
1308                                     fatal(expected_a != marina.getFlagA(),
1309                                           "expected A="+expected_a+", but got "+marina.getFlagA());
1310                                     fatal(expected_b != marina.getFlagB(),
1311                                           "expected B="+expected_b+", but got "+marina.getFlagB());
1312                                 }
1313                             }
1314         adjustIndent(-2);
1315         prln("End testFlagTruthTable");         
1316     }
1317
1318     private void recvData(Marina marina) {
1319         prln("Begin recvData");
1320         adjustIndent(2);
1321
1322         marina.instrIn.fill(setIlc(1));
1323         marina.fillSouthProperStopper(new Instruction[] {
1324                 new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG),
1325                 new Instruction.Move(dock,
1326                                      Predicate.IgnoreFlagD, // predicate   
1327                                      false,                 // torpedoable 
1328                                      null,                  // path        
1329                                      false,                 // tokenIn     
1330                                      true,                  // dataIn      
1331                                      false,                 // latchData   
1332                                      false,                 // latchPath   
1333                                      false,                 // dataOut     
1334                                      false                  // tokenOut    
1335                                      ),
1336                 new Instruction.Set(dock,Predicate.IgnoreFlagD, SET_FLAG, SET_FLAG),
1337             });
1338         model.waitNS(64 * CYCLE_TIME_NS);
1339
1340         prln("checking to confirm that A flag is cleared");
1341         fatal(marina.getFlagA(), "bad A flag: "+marina.getFlagA());
1342         
1343         prln("inserting data item in north fifo ring");
1344         BitVector data = new BitVector(37, "empty");
1345         BitVector addr = new BitVector(14, "empty");
1346         for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1347         for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1348         marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1349         model.waitNS(64 * CYCLE_TIME_NS);
1350
1351         prln("checking to see if A flag got set");
1352         fatal(!marina.getFlagA(), "bad A flag: "+marina.getFlagA());
1353
1354         adjustIndent(-2);
1355         prln("End recvData");           
1356     }
1357
1358
1359     private void testRecvAndSendWalkingOne(Marina marina) {
1360         prln("Begin testRecvAndSendWalkingOne");
1361         adjustIndent(2);
1362
1363         marina.instrIn.fill(setIlc(1));
1364
1365         List<BitVector> dataItems;
1366         for(int bit=0; bit<37; bit++) {
1367
1368             BitVector data = new BitVector(37, "empty");
1369             BitVector addr = new BitVector(14, "empty");
1370             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1371             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1372             data.set(bit, true);
1373             prln("testing with bit pattern " + data);
1374
1375             prln("inserting data item into north fifo ring");
1376             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1377
1378             prln("stopping the north proper stopper");
1379             marina.data.stop();
1380
1381             dataItems = marina.data.drainMany(1);
1382             fatal(dataItems.size()!=0,
1383                   "found a data item waiting in the north proper stopper, but should not have");
1384
1385             marina.instrIn.fill(new Instruction.Move(dock,
1386                                                      Predicate.IgnoreFlagD,  // predicate   
1387                                                      false,                  // torpedoable 
1388                                                      null_path,              // path        
1389                                                      false,                  // tokenIn     
1390                                                      true,                   // dataIn      
1391                                                      true,                   // latchData   
1392                                                      false,                  // latchPath   
1393                                                      true,                   // dataOut     
1394                                                      false                   // tokenOut    
1395                                                      ));
1396
1397             dataItems = marina.data.drainMany(2);
1398             fatal(dataItems.size()!=1,
1399                   "found "+dataItems.size()+" data items in north fifo; expected one");
1400             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1401             fatalIfBitVectorsDoNotMatch(mp.data, data);
1402         }
1403
1404         adjustIndent(-2);
1405         prln("End testRecvAndSendWalkingOne");          
1406     }
1407
1408
1409
1410     private void setOlcFromDataLatch(Marina marina) {
1411         prln("Begin setOlcFromDataLatch");
1412         adjustIndent(2);
1413
1414         marina.instrIn.fill(setIlc(1));
1415
1416         // walk a bit from 0 to 5
1417         for(int bit=0; bit<6; bit++) {
1418             prln("inserting data item in north fifo ring");
1419             BitVector data = new BitVector(37, "empty");
1420             BitVector addr = new BitVector(14, "empty");
1421             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1422             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1423             data.set(bit, true);
1424             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1425
1426             marina.fillSouthProperStopper(new Instruction[] {
1427                     RECV_DATA,
1428                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.DataLatch),
1429                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.DataLatch,-1),
1430                 });
1431
1432             model.waitNS(CYCLE_TIME_NS * 64);
1433
1434             expectOlc(1<<bit);
1435
1436             if (marina.kesselsCounter) {
1437                 // master clear on each iteration; otherwise we'd need to "run down" the olc
1438                 marina.masterClear();
1439                 marina.enableInstructionSend(true);
1440             }
1441         }
1442
1443         adjustIndent(-2);
1444         prln("End setOlcFromDataLatch");        
1445     }
1446
1447     private void setIlcFromDataLatch(Marina marina) {
1448         prln("Begin setIlcFromDataLatch");
1449         adjustIndent(2);
1450
1451         marina.instrIn.fill(setIlc(1));
1452
1453         // walk a bit from 0 to 5
1454         for(int bit=5; bit>=0; bit--) {
1455             prln("inserting data item in north fifo ring");
1456             BitVector data = new BitVector(37, "empty");
1457             BitVector addr = new BitVector(14, "empty");
1458             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1459             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1460             data.set(bit, true);
1461             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1462
1463             marina.fillSouthProperStopper(new Instruction[] {
1464                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1465                     RECV_DATA,
1466                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,SetSource.DataLatch),
1467                 });
1468             model.waitNS(CYCLE_TIME_NS * 64);
1469
1470             int ilc = marina.getILC().getCount();
1471             fatal(ilc != (1<<bit), "expected ilc to be " + (1<<bit) + ", but got " + ilc); 
1472         }
1473
1474         adjustIndent(-2);
1475         prln("End setIlcFromDataLatch");        
1476     }
1477
1478     private void testSendAndRecvToken(Marina marina) {
1479         prln("Begin testSendAndRecvToken");
1480         adjustIndent(2);
1481
1482         marina.instrIn.fill(setIlc(1));
1483         marina.fillSouthProperStopper(new Instruction[] {
1484                 SEND_TOKEN,
1485                 RECV_TOKEN,
1486                 SEND_DATA,
1487             });
1488         expectNorthFifoExactly(1);
1489
1490         adjustIndent(-2);
1491         prln("End testSendAndRecvToken");       
1492     }
1493
1494     private void testSignExtendedLiteral(Marina marina) {
1495         prln("Begin testSignExtendedLiteral");
1496         adjustIndent(2);
1497
1498         marina.instrIn.fill(setIlc(1));
1499         for(long val : new long[] { (-1L << 14), -1, 0, 1 }) {
1500
1501             marina.fillSouthProperStopper(new Instruction[] {
1502                     new Instruction.Set(dock,Predicate.IgnoreFlagD,
1503                                         Instruction.Set.SetDest.DataLatch,
1504                                         val),
1505                     SEND_DATA,
1506                 });
1507             model.waitNS(CYCLE_TIME_NS * 64);
1508
1509             List<BitVector> dataItems = marina.data.drainMany(3);
1510             fatal(dataItems.size()!=1, "expected exactly one data item, got " + dataItems.size());
1511
1512             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1513             BitVector bv = mp.data;
1514             prln("got back " + mp);
1515
1516             boolean mismatch = false;
1517             String err = "";
1518             for(int i=0; i<37; i++) {
1519                 if (bv.get(i) != ( (val & (1L << i)) != 0 )) {
1520                     mismatch = true;
1521                     err += ""+i+", ";
1522                 }
1523             }
1524             fatal(mismatch, "data read back did not match inserted literal; mismatch on bits " + err);
1525         }
1526                 
1527         adjustIndent(-2);
1528         prln("End testSignExtendedLiteral");            
1529     }
1530
1531     private void testShiftedLiteral(Marina marina) {
1532         prln("Begin testShiftedLiteral");
1533         adjustIndent(2);
1534
1535         marina.instrIn.fill(setIlc(1));
1536         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,
1537                                                 Instruction.Set.SetDest.DataLatch,
1538                                                 0));
1539
1540         BitVector dreg = new BitVector(37, "what we think is in the d-register");
1541         for(int i=0; i<37; i++) dreg.set(i, false);
1542
1543         for(long val : new long[] { -1, 0, 1, (-1L << 18) }) {
1544
1545             edu.berkeley.fleet.api.BitVector immediate =
1546                 new edu.berkeley.fleet.api.BitVector(19);
1547             for(int i=0; i<immediate.length(); i++)
1548                 immediate.set(i, (val & (1L << i)) != 0);
1549
1550             // shift over 19 LSB's towards MSB
1551             for(int i=0; i<19; i++)
1552                 if (i+19 <= 36)  dreg.set(i+19, dreg.get(i));
1553             for(int i=0; i<19; i++)
1554                 dreg.set(i, immediate.get(i));
1555
1556             marina.fillSouthProperStopper(new Instruction[] {
1557                     new Instruction.Shift(dock,Predicate.IgnoreFlagD,immediate),
1558                     SEND_DATA,
1559                 });
1560
1561             model.waitNS(CYCLE_TIME_NS * 64);
1562             List<BitVector> dataItems = marina.data.drainMany(3);
1563             fatal(dataItems.size()!=1, "expected exactly one data item, got " + dataItems.size());
1564
1565             BitVector bv = new MarinaPacket(dataItems.get(0)).data;
1566             fatal(!bv.equals(dreg), "data read back did not match inserted literal.\n" +
1567                   "got:     "+bv.bitReverse().getState()+"\n"+
1568                   "expected:"+dreg.bitReverse().getState());
1569         }
1570                 
1571         adjustIndent(-2);
1572         prln("End testShiftedLiteral");         
1573     }
1574
1575     private void testFlagC(Marina marina) {
1576         prln("Begin testFlagC");
1577         adjustIndent(2);
1578
1579         // Russell says:
1580         // addr[14] == sigS
1581         // addr[1]  == sigA
1582         //
1583         // Adam says:
1584         // Dc=1 => sigS is copied into C-flag
1585         // Dc=0 => sigA is copied into C-flag
1586        
1587         marina.instrIn.fill(setIlc(1));
1588         for(boolean dc : new boolean[] { false, true }) {
1589             for(boolean c_flag : new boolean[] { true, false, true }) {
1590
1591                 prln("");
1592                 prln("****** checking case where dc="+dc+", cflag="+c_flag);
1593                 BitVector data = new BitVector(37, "empty");
1594                 BitVector addr = new BitVector(14, "empty");
1595                 for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1596                 for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1597
1598                 int whichbit = dc
1599                     ? Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ONE
1600                     : Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ZERO;
1601                 prln("setting addr["+whichbit+"] to "+(c_flag?"1":"0"));
1602                 addr.set(whichbit, c_flag);
1603
1604                 prln("... and filling north fifo proper stopper");
1605                 marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1606                 
1607                 prln("clearing flags");
1608                 prln("executing recv data with Dc="+dc);
1609                 prln("copying c-flag to a-flag");
1610                 marina.fillSouthProperStopper(new Instruction[] {
1611                         new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG),
1612                         new Instruction.Move(dock,
1613                                              Predicate.IgnoreFlagD,   /* predicate   */
1614                                              true,                  /* torpedoable */
1615                                              null,                  /* path        */
1616                                              false,                 /* tokenIn     */
1617                                              true,                  /* dataIn      */
1618                                              dc,                    /* latchData   */
1619                                              false,                 /* latchPath   */
1620                                              false,                 /* dataOut     */
1621                                              false                  /* tokenOut    */
1622                                              ),
1623                         FLAG_NOP,
1624                         new Instruction.Set(dock,Predicate.IgnoreFlagD,
1625                                             Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagC),
1626                                             CLEAR_FLAG
1627                                             ),
1628                     });
1629
1630                 model.waitNS(CYCLE_TIME_NS * 64);
1631                 
1632                 prln("checking to confirm that A flag is " + c_flag);
1633                 fatal(marina.getFlagA()!=c_flag, "bad A flag: "+marina.getFlagA());
1634             }
1635         }
1636         adjustIndent(-2);
1637         prln("End testFlagC");          
1638     }
1639
1640     private void sendDataWithPath(Marina marina) {
1641         prln("Begin sendDataWithPath");
1642         adjustIndent(2);
1643
1644         edu.berkeley.fleet.api.BitVector bv = new edu.berkeley.fleet.api.BitVector(13);
1645         marina.instrIn.fill(setIlc(1));
1646
1647         // alternating ones and zeroes
1648         for(int i=0; i<bv.length(); i+=2)
1649             bv.set(i, true);
1650         // and then ones in the lower four bits so it's not symmetric
1651         for(int i=0; i<4; i++)
1652             bv.set(i, true);
1653
1654         MarinaPath path = new MarinaPath((MarinaFleet)dock.getShip().getFleet(), bv);
1655
1656         marina.fillSouthProperStopper(new Instruction[] {
1657                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1658                 new Instruction.Move(dock,
1659                                      Predicate.IgnoreFlagD, /* predicate   */
1660                                      false,                 /* torpedoable */
1661                                      path,                  /* path        */
1662                                      false,                 /* tokenIn     */
1663                                      false,                 /* dataIn      */
1664                                      false,                 /* latchData   */
1665                                      false,                 /* latchPath   */
1666                                      true,                  /* dataOut     */
1667                                      false                  /* tokenOut    */
1668                                      ),
1669             });
1670
1671         List<BitVector> dataItems;
1672         MarinaPacket mp;
1673
1674         dataItems = marina.data.drainMany();
1675         fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1676         mp = new MarinaPacket(dataItems.get(0));
1677
1678         // the 14th bit of the outbound address cannot be set by the
1679         // ship, so we don't care about it
1680         fatalIfBitVectorsDoNotMatch(MarinaUtils.berkToSun(bv), mp.path.get(0,13));
1681
1682         prln("send data with no change to path");
1683         marina.instrIn.fill(new Instruction.Move(dock,
1684                                                  Predicate.IgnoreFlagD, /* predicate   */
1685                                                  false,                 /* torpedoable */
1686                                                  null,                  /* path        */
1687                                                  false,                 /* tokenIn     */
1688                                                  false,                 /* dataIn      */
1689                                                  false,                 /* latchData   */
1690                                                  false,                 /* latchPath   */
1691                                                  true,                  /* dataOut     */
1692                                                  false                  /* tokenOut    */
1693                                                  ));
1694
1695         dataItems = marina.data.drainMany();
1696         fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1697         mp = new MarinaPacket(dataItems.get(0));
1698
1699         // the 14th bit of the outbound address cannot be set by the
1700         // ship, so we don't care about it
1701         fatalIfBitVectorsDoNotMatch(MarinaUtils.berkToSun(bv), mp.path.get(0,13));
1702
1703         adjustIndent(-2);
1704         prln("End sendDataWithPath");
1705     }
1706
1707     private void recvPath(Marina marina) {
1708         prln("Begin recvPath");
1709         adjustIndent(2);
1710
1711         marina.instrIn.fill(setIlc(1));
1712         for(int bit=0; bit<11; bit++) {
1713             BitVector packet_data = new BitVector(37, "inbound data item");
1714             for(int i=0; i<37; i++) packet_data.set(i, false);
1715             packet_data.set(27+bit, true);
1716             BitVector packet_path = new BitVector(14, "inbound data item");
1717             for(int i=0; i<14; i++) packet_path.set(i, false);
1718
1719             marina.fillNorthProperStopper(new MarinaPacket(packet_data, false, packet_path));
1720                                            
1721             prln("recv path, send data (using recv'd path)");
1722             marina.instrIn.fill(new Instruction.Move(dock,
1723                                                      Predicate.IgnoreFlagD,   /* predicate   */
1724                                                      false,                 /* torpedoable */
1725                                                      null,                  /* path        */
1726                                                      false,                 /* tokenIn     */
1727                                                      true,                  /* dataIn      */
1728                                                      true,                  /* latchData   */
1729                                                      true,                  /* latchPath   */
1730                                                      true,                  /* dataOut     */
1731                                                      false                  /* tokenOut    */
1732                                                      ));
1733
1734             List<BitVector> dataItems = marina.data.drainMany();
1735             fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1736             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1737             
1738             fatalIfBitVectorsDoNotMatch(packet_data.get(25,11), mp.path.get(0,11));
1739             fatalIfBitVectorsDoNotMatch(packet_data, mp.data);
1740         }
1741
1742         adjustIndent(-2);
1743         prln("End recvPath");
1744     }
1745
1746     private void testILC(Marina marina) {
1747         prln("Begin testILC");
1748         adjustIndent(2);
1749
1750         for(int bit=0; bit<6; bit++) {
1751             int ilc = bit<0 ? 0 : (1<<bit);
1752             marina.fillSouthProperStopper(new Instruction[] {
1753                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,ilc),
1754                     SEND_DATA,
1755                 });
1756             List<BitVector> dataItems = marina.data.drainMany();
1757             fatal(dataItems.size()!=ilc, "Expected "+ilc+" data item(s) to emerge but got: "+dataItems.size()+" data items");
1758         }
1759
1760         adjustIndent(-2);
1761         prln("End testILC");
1762     }
1763
1764     private void testILCZero(Marina marina) {
1765         adjustIndent(2);
1766         marina.fillSouthProperStopper(new Instruction[] {
1767                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,0),
1768                 SEND_DATA,
1769                 SEND_TOKEN,
1770             });
1771         expectNorthFifoNoMoreThan(0);
1772         expectTokensExactly(1);
1773         adjustIndent(-2);
1774     }
1775
1776     private void sendTorpedo(Marina marina) {
1777         prln("Begin sendTorpedo");
1778         adjustIndent(2);
1779         marina.instrIn.fill(setIlc(1));
1780         marina.instrIn.fill(setOlc(63));
1781
1782         model.waitNS(128 * CYCLE_TIME_NS);
1783         expectOlc(63);
1784
1785         marina.instrIn.fill(new 
1786                             Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG));
1787         fatal(marina.getFlagA(), "bad A flag: true");
1788         fatal(marina.getFlagB(), "bad B flag: true");
1789
1790         prln("execute a move instruction that does nothing but loops until torpedo arrives"); 
1791         prln("A=1, B=B This instruction should not execute because D-flag is set");
1792         prln("Set A=A, B=1 This instruction should execute because D-flag is set");
1793
1794         model.waitNS(128 * CYCLE_TIME_NS);
1795
1796         marina.fillSouthProperStopper(new Instruction[] {
1797                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, SetSource.Infinity),
1798                 new Instruction.Move(dock,
1799                                      Predicate.IgnoreFlagD, // predicate   
1800                                      true,                  // torpedoable 
1801                                      null,                  // path        
1802                                      false,                 // tokenIn     
1803                                      true,                  // dataIn      
1804                                      false,                 // latchData   
1805                                      false,                 // latchPath   
1806                                      false,                 // dataOut     
1807                                      false                  // tokenOut    
1808                                      ),
1809                 new Instruction.Set(dock,Predicate.Default,
1810                                     SET_FLAG,
1811                                     Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagB)
1812                                     ),
1813                 new Instruction.Set(dock, Predicate.FlagD,
1814                                     Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagA),
1815                                     SET_FLAG
1816                                     ),
1817             });
1818
1819         model.waitNS(128 * CYCLE_TIME_NS);
1820
1821         prln("send torpedo. This should clear the OLC");
1822         marina.instrIn.fillTorpedo();
1823         model.waitNS(128 * CYCLE_TIME_NS);
1824
1825         model.waitNS(128 * CYCLE_TIME_NS);
1826                 
1827         prln("A should remain false, B should be true");
1828         fatal(marina.getFlagA(), "bad A flag: true");
1829         fatal(!marina.getFlagB(), "bad B flag: false");
1830         
1831         model.waitNS(128 * CYCLE_TIME_NS);
1832
1833         prln("Reload OLC after torpedo, clears D-flag");
1834         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63));
1835
1836         // FIXME: find another way to test this
1837         model.waitNS(128 * CYCLE_TIME_NS);
1838         expectOlc(63);
1839                 
1840         prln("Set A=1, B=1 This instruction should execute because OLC!=0");
1841         marina.instrIn.fill(new 
1842                             Instruction.Set(dock,Predicate.Default, SET_FLAG, SET_FLAG));
1843
1844         prln("A and B should be true");
1845         fatal(!marina.getFlagA(), "bad A flag: false");
1846         fatal(!marina.getFlagB(), "bad B flag: false");
1847                 
1848         adjustIndent(-2);
1849         prln("End sendTorpedo");        
1850     }    
1851
1852     private void testTorpedoOnAnInfinite(Marina marina) {
1853         prln("Begin testTorpedoOnAnInfinite");
1854         adjustIndent(2);
1855
1856         List<BitVector> dataItems;
1857
1858         marina.instrIn.fill(setIlc(1));
1859         for(boolean torpedoable : new boolean[] { true, false }) {
1860             
1861             marina.fillSouthProperStopper(new Instruction[] {
1862                     new Instruction.Move(dock,
1863                                          Predicate.IgnoreFlagD, // predicate   
1864                                          false,                 // torpedoable 
1865                                          null,                  // path        
1866                                          false,                 // tokenIn     
1867                                          false,                 // dataIn      
1868                                          false,                 // latchData   
1869                                          false,                 // latchPath   
1870                                          false,                 // dataOut     
1871                                          true                   // tokenOut    
1872                                          ),
1873                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,SetSource.Infinity),
1874                     new Instruction.Move(dock,
1875                                          Predicate.IgnoreFlagD, // predicate   
1876                                          torpedoable,           // torpedoable 
1877                                          null,                  // path        
1878                                          true,                  // tokenIn     
1879                                          false,                 // dataIn      
1880                                          false,                 // latchData   
1881                                          false,                 // latchPath   
1882                                          false,                 // dataOut     
1883                                          true                   // tokenOut    
1884                                          ),
1885                     // FIXME: this probably should be removed, unless Ivan doesn't want to change the behavior
1886                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1887
1888                     SEND_DATA,
1889                 });
1890             
1891             // expect nothing to come out, because the NOP is executing
1892             dataItems = marina.data.drainMany(2);
1893             fatal(dataItems.size()!=0, "Expected no data item(s) to emerge but got at least: "+dataItems.size()+" data items");
1894             
1895             marina.instrIn.fillTorpedo();
1896             
1897             int expected = torpedoable?1:0;
1898             dataItems = marina.data.drainMany(2);
1899             fatal(dataItems.size()!=expected, "Expected "+expected+" item to emerge but got: "+dataItems.size()+" data items");
1900
1901             fatal(!marina.getILC().getDone(), "Expected ilc=done, but got "+marina.getILC());
1902         }
1903
1904         adjustIndent(-2);
1905         prln("End testTorpedoOnAnInfinite");
1906     }
1907
1908     private void testOlcDecrementAtHighSpeed(Marina marina) {
1909         prln("Begin testOlcDecrementAtHighSpeed");
1910         adjustIndent(2);
1911
1912         List<BitVector> dataItems;
1913         
1914         // Each element of the following pair of arrays is one "test".
1915         // The OLC will be loaded with olcs[i] and then decremented
1916         // decr_amounts[i] times; after that has happened the zeroness
1917         // of the OLC will be checked by executing a MOVE with
1918         // [olc!=0] as the predicate.
1919
1920         int[] olcs         = new int[] { 3, 3, 3, 10, 41 };
1921         int[] decr_amounts = new int[] { 2, 3, 4, 9,  9  };
1922
1923         for(int which=0; which<olcs.length; which++) {
1924             int olc = olcs[which];
1925             int decr_amount = decr_amounts[which];
1926
1927             prln("inserting set olc="+olc);
1928             prln("inserting set ilc=1");
1929             marina.fillSouthProperStopper(new Instruction[] {
1930                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1931                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,olc),
1932                 });
1933
1934             // commenting the following four lines causes this test to pass
1935
1936             prln("inserting: "+decr_amount+" olc-- instructions");
1937             prln("inserting: [!d] send data");
1938             Instruction[] instructions = new Instruction[decr_amount+1];
1939             for(int i=0; i<decr_amount; i++)
1940                 instructions[i] =
1941                     new Instruction.Set(dock,
1942                                         Predicate.Default,
1943                                         SetDest.OuterLoopCounter,
1944                                         SetSource.Decrement);
1945             instructions[instructions.length-1] =
1946                 new Instruction.Move(dock,
1947                                      Predicate.Default,     // predicate   
1948                                      false,                 // torpedoable 
1949                                      null,                  // path        
1950                                      false,                 // tokenIn     
1951                                      false,                 // dataIn      
1952                                      false,                 // latchData   
1953                                      false,                 // latchPath   
1954                                      true,                  // dataOut     
1955                                      false                  // tokenOut    
1956                                      );
1957
1958             marina.fillSouthProperStopper(instructions);
1959             model.waitNS(64 * CYCLE_TIME_NS);
1960
1961             int expected = decr_amount>=olc ? 0 : 1;
1962             dataItems = marina.data.drainMany(2);
1963             fatal(dataItems.size()!=expected, "Expected "+expected+" item to emerge but got: "+dataItems.size()+" data items");
1964
1965             if (marina.kesselsCounter) {
1966                 // master clear on each iteration; otherwise we'd need to "run down" the olc
1967                 marina.masterClear();
1968                 marina.enableInstructionSend(true);
1969             }
1970         }
1971
1972         adjustIndent(-2);
1973         prln("End testOlcDecrementAtHighSpeed");
1974     }
1975
1976     private void flipIlcBit(Marina marina) {
1977         prln("Begin flipIlcBit");
1978         adjustIndent(2);
1979         prln("Using the set ILC instruction, toggle a single bit between zero and one. \n" +
1980              "Check correct setting of the ILC zero bit");
1981
1982         for (int i=0; i<6; i++) {
1983             int notZero = 1<<i;
1984
1985             prln("Then immediately set ILC="+notZero);
1986             marina.fillSouthProperStopper(new Instruction[] {
1987                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, 0),
1988                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, notZero),
1989                 });
1990                 
1991             model.waitNS(64 * CYCLE_TIME_NS);
1992
1993             prln("Verify ILC using scan chain");
1994             Ilc ilc = marina.getILC();
1995             int ilcCount = ilc.getCount();
1996             fatal(ilcCount!=notZero, "bad ILC count: "+ilcCount+" expected: "+notZero);
1997             fatal(ilc.getInfinity(), "bad ILC Infinity bit: true");
1998                    
1999             marina.fillSouthProperStopper(new Instruction[] {     
2000                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, notZero),
2001                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, 0),
2002                 });
2003
2004             model.waitNS(64 * CYCLE_TIME_NS);
2005                         
2006             prln("Verify ILC using scan chain");
2007             ilc = marina.getILC();
2008             ilcCount = ilc.getCount();
2009             fatal(ilcCount!=0, "bad ILC count: "+ilcCount+" expected: 0");
2010             fatal(ilc.getInfinity(), "bad ILC Infinity bit: true");
2011         }
2012
2013         adjustIndent(-2);
2014         prln("End flipIlcBit");
2015     }
2016     private void flipOlcBit(Marina marina) {
2017         prln("Begin flipOlcBit");
2018         adjustIndent(2);
2019         prln("Using the set OLC instruction, toggle a single bit between zero and one. \n" +
2020              "Check correct setting of the OLC zero bit");
2021
2022         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG));
2023
2024         for (int i=0; i<6; i++) {
2025             int notZero = 32 >> i;
2026
2027             if (marina.kesselsCounter) {
2028                 // master clear on each iteration; otherwise we'd need to "run down" the olc
2029                 marina.masterClear();
2030                 marina.enableInstructionSend(true);
2031             }
2032
2033             int outOlc;
2034             prln("Set OLC=0");
2035             prln("Then immediately set OLC="+notZero);
2036             marina.fillSouthProperStopper(new Instruction[] {
2037                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 0),
2038                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, notZero),
2039                 });
2040
2041             model.waitNS(64 * CYCLE_TIME_NS);
2042             prln("Verify OLC count using scan chain");
2043             expectOlc(notZero);
2044
2045             if (!marina.kesselsCounter) {
2046                 prln("Set OLC="+notZero);
2047                 prln("Then immediately set OLC=0");
2048                 marina.fillSouthProperStopper(new Instruction[] {
2049                         new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, notZero),
2050                         new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 0),
2051                     });
2052                 
2053                 model.waitNS(64 * CYCLE_TIME_NS);
2054                 prln("Verify OLC count using scan chain");
2055                 expectOlc(0);
2056             }
2057         }
2058         
2059         adjustIndent(-2);
2060         prln("End flipOlcBit");
2061     }
2062     private void testSouthRecirculate(Marina marina, int AMOUNT) {
2063         prln("Begin testSouthRecirculate("+AMOUNT+")");
2064         adjustIndent(2);
2065
2066         marina.enableInstructionSend(false);
2067         marina.enableInstructionRecirculate(true);
2068         
2069         prln("Completely fill south ring");
2070         adjustIndent(2);
2071         for (int i=0; i<AMOUNT; i++) {
2072             prln("inserting item " + (i+1) + " / " + AMOUNT);
2073             BitVector path = new BitVector(MarinaPacket.PATH_WIDTH, "path");
2074             BitVector data = new BitVector(MarinaPacket.WORD_WIDTH, "path");
2075             path.set(0, MarinaPacket.PATH_WIDTH, false);
2076             data.setFromLong(i+9);
2077             marina.instrIn.fill(new MarinaPacket(data, false, path));
2078         }
2079         adjustIndent(-2);
2080
2081         prln("Drain south ring and check contents");
2082         adjustIndent(2);
2083         List<BitVector> out = marina.instrIn.drainMany();
2084         boolean bad = false;
2085         for (int i=0; i<AMOUNT; i++) {
2086             prln("extracting item " + (i+1) + " / " + AMOUNT);
2087             //int expect = (i+Marina.SOUTH_RING_CAPACITY-1) % Marina.SOUTH_RING_CAPACITY;
2088             int expect = i+9;
2089             long got = new MarinaPacket(out.get(i)).data.toLong();
2090             if (got!=expect) {
2091                 bad = true;
2092                 prln("  bad instruction: "+got+" expected: "+expect);
2093             } else {
2094                 prln("  good instruction.");
2095             }
2096         }
2097         fatal(bad, "data inserted does not match data retrieved");
2098         adjustIndent(-2);
2099         
2100         for (int i=0; i<5; i++) {}
2101         
2102         adjustIndent(-2);
2103         prln("End testSouthRecirculate("+AMOUNT+")");
2104     }
2105     private void doOneTest(int testNum) {
2106         prln("");
2107         prln("============================================================");
2108         prln("MarinaTest: performing test: "+testNum);
2109
2110         if (testNum!=0) {
2111             marina.masterClear();
2112             marina.enableInstructionSend(true);
2113         }
2114         
2115         try {
2116             switch (testNum) {
2117                 case 0: {
2118
2119                     // these tests run fairly quickly
2120
2121
2122                     doOneTest(1);       // passes extracted parasitics
2123                     doOneTest(2);       // passes extracted parasitics
2124                     doOneTest(3);       // passes extracted parasitics
2125                     doOneTest(4);       // passes extracted parasitics
2126                     doOneTest(5);       // passes extracted parasitics
2127                     doOneTest(6);
2128                     doOneTest(1002);
2129                     doOneTest(1005);
2130                     doOneTest(3019);
2131                     doOneTest(3025);
2132
2133                     doOneTest(1000);    // passes extracted parasitics
2134                     doOneTest(1001);    // passes extracted parasitics
2135                     doOneTest(1003);    // passes extracted parasitics
2136                     doOneTest(3000);    // passes extracted parasitics
2137                     doOneTest(3001);    // passes extracted parasitics
2138                     doOneTest(3003);    // passes extracted parasitics
2139                     doOneTest(3004);    // passes extracted parasitics
2140                     doOneTest(3005);    // passes extracted parasitics
2141                     doOneTest(3006);    // passes extracted parasitics
2142                     doOneTest(3007);    // passes extracted parasitics
2143                     doOneTest(3008);    // passes extracted parasitics
2144                     doOneTest(3009);    // passes extracted parasitics
2145                     doOneTest(3010);    // passes extracted parasitics
2146                     doOneTest(3011);    // passes extracted parasitics
2147                     doOneTest(3012);    // passes extracted parasitics
2148                     doOneTest(3013);    // passes extracted parasitics
2149                     doOneTest(3014);    // passes extracted parasitics
2150                     doOneTest(3015);    // passes extracted parasitics
2151                     doOneTest(3019);    // passes extracted parasitics
2152                     doOneTest(3020);    // passes extracted parasitics
2153                     doOneTest(3022);    // passes extracted parasitics
2154                     doOneTest(3023);    // passes extracted parasitics
2155                     doOneTest(3026);    // passes extracted parasitics
2156                     doOneTest(3027);    // passes extracted parasitics
2157                     doOneTest(3028);    // passes extracted parasitics
2158                     
2159                     // these tests take a while and usually pass
2160                     doOneTest(1002);
2161                     doOneTest(1004);
2162                     doOneTest(1005);
2163                     doOneTest(1006);
2164                     doOneTest(3002);
2165                     doOneTest(3016);
2166                     doOneTest(3021);
2167                     doOneTest(3024);
2168                     doOneTest(3025);
2169                     
2170                     // this takes an insanely long time
2171                     doOneTest(3017);
2172                     break;
2173                 }
2174                 case 1:    testChains(marina);                     break; // passes, 24-Mar (+verilog)
2175                 case 2:    testProperStoppers(marina);             break; // passes, 24-Mar (+verilog)
2176                 case 3:    testSouthRecirculate(marina, 1);        break; // passes, 24-Mar (+verilog)
2177                 case 4:    getCtrsFlags(marina);                   break; //         20-Apr (+verilog)
2178                 case 5:    sendInstructions(marina);               break; // passes, 24-Mar (+verilog)
2179                 case 6:    walkOneOLC(marina);                     break; //         21-Apr (+verilog)
2180                 
2181                     // Russell's tests begin with 1000
2182                 case 1000: walkOneILC(marina);                     break; //         20-Apr (+verilog)
2183                 case 1001: countIlc(marina);                       break; //         20-Apr (+verilog)
2184                 case 1002: countOlc(marina);                       break; //         23-Apr (+verilog)
2185
2186                 case 1003: sendTorpedo(marina);                    break; //         23-Apr (+verilog)  [with wor-hack]
2187
2188                 case 1004: flipIlcBit(marina);                     break; //         20-Apr (+verilog)
2189                 case 1005: flipOlcBit(marina);                     break; //         21-Apr (+verilog)
2190
2191                 case 1006: testSouthRecirculate(marina, Marina.SOUTH_RING_CAPACITY-1);        break; // passes, 24-Mar (+verilog)
2192
2193                     // Adam's tests begin with 3000
2194                 case 3000: sendToken(marina);                      break; // passes, 24-Mar (+verilog)
2195                 case 3001: testFlagAB(marina);                     break; // passes, 08-Apr (+verilog)
2196                 case 3002: testPredicationOnAB(marina);            break; //         22-Apr (+verilog)
2197                 case 3003: testFlagC(marina);                      break; //         23-Apr (+verilog)
2198                 case 3004: testFlagD(marina);                      break; //         23-Apr (+verilog)
2199                 case 3005: testFlagDRecomputationTime(marina);     break;
2200
2201                 case 3006: testTailWaitsForHead(marina);           break;
2202                 case 3007: testTailWithoutHead(marina);            break;
2203                 case 3008: testHeadWaitsForTail(marina);           break; //         22-Apr (+verilog)
2204                 case 3009: testAbort(marina);                      break; //         22-Apr (+verilog)
2205
2206                 case 3010: sendData(marina);                       break; // passes, 24-Mar (+verilog)
2207                 case 3011: recvData(marina);                       break; //         21-Apr (+verilog)
2208                 case 3012: sendDataWithPath(marina);               break; // passes, 13-Apr (+verilog)
2209
2210                 case 3013: testSignExtendedLiteral(marina);        break; //         20-Apr (+verilog)
2211                 case 3014: testShiftedLiteral(marina);             break; //         20-Apr (+verilog)
2212                 case 3015: testSendAndRecvToken(marina);           break; //         21-Apr (+verilog)
2213
2214                 case 3016: sendDataIlcInfinite(marina);            break; //         22-Apr (+verilog)
2215                 case 3017: testFlagTruthTable(marina);             break; //         23-Apr (+verilog)
2216
2217                 case 3019: setOlcFromDataLatch(marina);            break; //         23-Apr (+verilog)
2218                 case 3020: setIlcFromDataLatch(marina);            break; //         23-Apr (+verilog)
2219                 case 3021: recvPath(marina);                       break; //         22-Apr (+verilog)
2220                 case 3022: testILC(marina);                        break; //         23-Apr (+verilog)
2221                 case 3023: testTorpedoOnAnInfinite(marina);        break; //         23-Apr (+verilog)
2222                 case 3024: testRecvAndSendWalkingOne(marina);      break; //         21-Apr (+verilog)
2223                 case 3025: testOlcDecrementAtHighSpeed(marina);    break; //         23-Apr (+verilog)
2224
2225                 case 3026: testNonTorpedoableMoveDoesNotResetDFlag(marina);        break; //         23-Apr (+verilog)
2226                 case 3027: testILCZero(marina);                    break;
2227                 case 3028: testAbortOutsideOfLoop(marina); break;
2228
2229                 default:
2230                     fatal(true, "Test number: "+testNum+" doesn't exist.");
2231                     break;
2232             }
2233             // If we get here then test passed
2234             prln("Test Result: Passed");
2235             printTestTime();
2236             //Infrastructure.exit(0);
2237         } catch (MarinaUtils.FailureException fe) {
2238             System.out.println("******************************************************************************");
2239             System.out.println("******************************************************************************");
2240             System.out.println("******************************************************************************");
2241             System.out.println("******************************************************************************");
2242             fe.printStackTrace();
2243         }
2244     }
2245
2246
2247     //============================ for public use =============================
2248
2249     /** Exit codes:
2250      * 0: test detected success
2251      * 2: test detected failure
2252      * 1: test crashed
2253      */ 
2254     public static void main(String[] args) {
2255         startTime = System.currentTimeMillis();
2256         new MarinaTest(args);
2257     }
2258
2259 }