MarinaTest: reduce messages
[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 TORPEDOABLE_RECV_DATA =
892         new Instruction.Move(dock,
893                              Predicate.IgnoreFlagD, /* predicate   */
894                              true,                  /* torpedoable */
895                              null,                  /* path        */
896                              false,                 /* tokenIn     */
897                              true,                  /* dataIn      */
898                              true,                  /* latchData   */
899                              false,                 /* latchPath   */
900                              false,                 /* dataOut     */
901                              false                  /* tokenOut    */
902                              );
903
904     private static final Instruction RECV_DATA =
905         new Instruction.Move(dock,
906                              Predicate.IgnoreFlagD,   /* predicate   */
907                              false,                 /* 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 SEND_TOKEN =
918         new Instruction.Move(dock,
919                              Predicate.IgnoreFlagD,   /* predicate   */
920                              false,                 /* torpedoable */
921                              null_path,                  /* path        */
922                              false,                 /* tokenIn     */
923                              false,                 /* dataIn      */
924                              false,                 /* latchData   */
925                              false,                 /* latchPath   */
926                              false,                 /* dataOut     */
927                              true                   /* tokenOut    */
928                              );
929
930     private static final Instruction RECV_TOKEN =
931         new Instruction.Move(dock,
932                              Predicate.IgnoreFlagD,   /* predicate   */
933                              false,                 /* torpedoable */
934                              null,                  /* path        */
935                              true,                  /* tokenIn     */
936                              false,                 /* dataIn      */
937                              false,                 /* latchData   */
938                              false,                 /* latchPath   */
939                              false,                 /* dataOut     */
940                              false                  /* tokenOut    */
941                              );
942
943
944     private void expectNorthFifoNoMoreThan(int num) {
945         model.waitNS(128 * CYCLE_TIME_NS);
946         List<BitVector> dataItems = marina.data.drainMany(num+1);
947         fatal(dataItems.size()>num,
948               "Expected no more than "+num+
949               " data items to emerge but got at least: "+dataItems.size());
950     }
951     private void expectNorthFifoExactly(int num) {
952         model.waitNS(128 * CYCLE_TIME_NS);
953         List<BitVector> dataItems = marina.data.drainMany(num+1);
954         fatal(dataItems.size()!=num,
955               "Expected exactly "+num+
956               " data items to emerge but got at least: "+dataItems.size());
957     }
958     private void expectTokensNoMoreThan(int num) {
959         int x = marina.getNumTokens();
960         List<BitVector> dataItems = marina.data.drainMany(num+1);
961         fatal(x>num,
962               "Expected no more than "+num+
963               " data items to emerge but got at least: "+x);
964     }
965     private void expectTokensExactly(int num) {
966         int x = marina.getNumTokens();
967         fatal(x!=num,
968               "Expected exactly "+num+
969               " data items to emerge but got at least: "+x);
970     }
971
972     private void testFlagDRecomputationTime(Marina marina) {
973         marina.instrIn.fill(setIlc(1));
974         marina.fillSouthProperStopper(new Instruction[] {
975                 RECV_DATA,
976                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,0),
977                 SEND_DATA_IF_D_NOT_SET
978             });
979         marina.fillNorthProperStopper();
980         expectNorthFifoNoMoreThan(0);
981
982         marina.fillSouthProperStopper(new Instruction[] {
983                 RECV_DATA,
984                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,1),
985                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.Decrement),
986                 SEND_DATA_IF_D_NOT_SET
987             });
988         marina.fillNorthProperStopper();
989         expectNorthFifoNoMoreThan(0);
990
991         marina.fillSouthProperStopper(new Instruction[] {
992                 RECV_DATA,
993                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,2),
994                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.Decrement),
995                 SEND_DATA_IF_D_NOT_SET
996             });
997         marina.fillNorthProperStopper();
998         expectNorthFifoExactly(1);
999         marina.instrIn.fill(DEC);
1000
1001         marina.fillSouthProperStopper(new Instruction[] {
1002                 RECV_DATA,
1003                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,0),
1004                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,1),
1005                 SEND_DATA_IF_D_NOT_SET
1006             });
1007         marina.fillNorthProperStopper();
1008         expectNorthFifoExactly(1);
1009     }
1010
1011     private void testTailWaitsForHead(Marina marina) {
1012         marina.instrIn.fill(setIlc(1));
1013         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63));
1014         
1015         marina.enableInstructionSend(false);
1016         marina.enableInstructionRecirculate(true);
1017         
1018         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1019         marina.instrIn.fill(new Instruction.Head(dock));
1020         marina.instrIn.fill(SEND_DATA);
1021         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1022         marina.instrIn.fill(SEND_TOKEN);
1023         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1024         marina.instrIn.fill(new Instruction.Tail(dock));
1025         marina.instrIn.fillTorpedo();
1026         
1027         marina.enableInstructionRecirculate(false);
1028         marina.enableInstructionSend(true);
1029         marina.instrIn.run();
1030         
1031         expectNorthFifoNoMoreThan(0);
1032         prln("inserting into north proper stopper");
1033         marina.fillNorthProperStopper();
1034         expectNorthFifoExactly(1);
1035         int nbToks = marina.getNumTokens();
1036         fatal(nbToks!=1, "Expected one token to emerge but got: "+nbToks+" tokens");
1037     }
1038
1039         /*
1040         marina.instrIn.fill(setIlc(1));
1041         marina.instrIn.fill(setOlc(1));
1042
1043         // this makes the head wait for the torpedo
1044         marina.instrIn.fill(TORPEDOABLE_RECV_DATA);
1045
1046         // the head should wait for the tail
1047         marina.instrIn.fill(new Instruction.Head(dock));
1048         marina.instrIn.fill(NOP);
1049         marina.instrIn.fill(SEND_DATA);
1050         marina.instrIn.fill(RECV_DATA);
1051
1052         expectNorthFifoNoMoreThan(0);
1053
1054         marina.instrIn.fillTorpedo();
1055         expectNorthFifoNoMoreThan(0);
1056
1057         marina.instrIn.fill(new Instruction.Tail(dock));
1058         expectNorthFifoExactly(1);
1059         */
1060
1061     private void testTailWithoutHead(Marina marina) {
1062         marina.instrIn.fill(setIlc(1));
1063         marina.fillSouthProperStopper(new Instruction[] {
1064                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63),
1065                 new Instruction.Tail(dock),
1066                 SEND_DATA,
1067             });
1068         List<BitVector> dataItems = marina.data.drainMany(1);
1069         fatal(dataItems.size()!=0, "Expected exactly no data items to emerge but got at least: "+dataItems.size());
1070     }
1071
1072     private void testHeadWaitsForTail(Marina marina) {
1073         List<BitVector> dataItems;
1074
1075         prln("Begin testHeadWaitsForTail");
1076         adjustIndent(2);
1077
1078         marina.instrIn.fill(setIlc(1));
1079         marina.fillSouthProperStopper(new Instruction[] {
1080                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63),
1081                 new Instruction.Head(dock),
1082                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1083                 SEND_DATA,
1084             });
1085         dataItems = marina.data.drainMany(1);
1086         fatal(dataItems.size()!=0, "Expected exactly no data items to emerge but got at least: "+dataItems.size());
1087         marina.instrIn.fill(new Instruction.Tail(dock));
1088
1089         BitVector bv = marina.data.drain();
1090         fatal(bv==null, "Expected at least one data item to emerge but got none");
1091
1092         adjustIndent(-2);
1093         prln("End testHeadWaitsForTail");
1094     }
1095
1096     private void testNonTorpedoableMoveDoesNotResetDFlag(Marina marina) {
1097         marina.instrIn.fill(setIlc(1));
1098         marina.fillSouthProperStopper(new Instruction[] {
1099                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,63),
1100                 new Instruction.Move(dock,
1101                                      Predicate.IgnoreFlagD, // predicate   
1102                                      true,                  // torpedoable 
1103                                      null,                  // path        
1104                                      true,                  // tokenIn     
1105                                      false,                 // dataIn      
1106                                      false,                 // latchData   
1107                                      false,                 // latchPath   
1108                                      false,                 // dataOut     
1109                                      false                  // tokenOut    
1110                                      ),
1111                 new Instruction.Move(dock,
1112                                      Predicate.FlagD,       // predicate   
1113                                      false,                 // torpedoable 
1114                                      null,                  // path        
1115                                      false,                 // tokenIn     
1116                                      false,                 // dataIn      
1117                                      false,                 // latchData   
1118                                      false,                 // latchPath   
1119                                      true,                  // dataOut     
1120                                      false                  // tokenOut    
1121                                      ),
1122             });
1123         marina.instrIn.fillTorpedo();
1124         expectNorthFifoExactly(1);
1125         marina.fillSouthProperStopper(new Instruction[] {
1126                 new Instruction.Move(dock,
1127                                      Predicate.Default,     // predicate   
1128                                      false,                 // torpedoable 
1129                                      null,                  // path        
1130                                      false,                 // tokenIn     
1131                                      false,                 // dataIn      
1132                                      false,                 // latchData   
1133                                      false,                 // latchPath   
1134                                      true,                  // dataOut     
1135                                      false                  // tokenOut    
1136                                      ),
1137             });
1138         expectNorthFifoNoMoreThan(0);
1139     }
1140
1141     private void testAbort(Marina marina) {
1142         
1143         marina.instrIn.fill(setIlc(1));
1144         marina.fillSouthProperStopper(new Instruction[] {
1145                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.DataLatch,1),
1146                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,2),
1147                 SEND_DATA_IF_D_NOT_SET,
1148                 new Instruction.Head(dock),
1149                 SEND_DATA_IF_D_NOT_SET,
1150                 new Instruction.Set(dock,Predicate.Default,SetDest.DataLatch,2),
1151                 new Instruction.Abort(dock, Predicate.FlagD),
1152                 new Instruction.Set(dock,Predicate.Default,SetDest.OuterLoopCounter,SetSource.Decrement),
1153                 new Instruction.Tail(dock),
1154             }, true);
1155         
1156         for(int i=0; i<4; i++) {
1157             BitVector bv;
1158             
1159             model.waitNS(128 * CYCLE_TIME_NS);
1160             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1161             fatal(bv==null, "no data item found");
1162             prln("got " + bv.toLong());
1163             fatal(bv.toLong()!=1, "expected 1, got " + bv.toLong());
1164             
1165             model.waitNS(128 * CYCLE_TIME_NS);
1166             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1167             fatal(bv==null, "no data item found");
1168             prln("got " + bv.toLong());
1169             fatal(bv.toLong()!=1, "expected 1, got " + bv.toLong());
1170             
1171             model.waitNS(128 * CYCLE_TIME_NS);
1172             bv = new MarinaPacket(marina.data.drain()).data.bitReverse();
1173             fatal(bv==null, "no data item found");
1174             prln("got " + bv.toLong());
1175             fatal(bv.toLong()!=2, "expected 2, got " + bv.toLong());
1176             
1177         }
1178     }
1179
1180     private void testAbortOutsideOfLoop(Marina marina) {
1181         marina.instrIn.fill(setIlc(1));
1182         marina.fillSouthProperStopper(new Instruction[] {
1183                 // ensure that an abort doesn't cause problems if no loop is in progress
1184                 new Instruction.Abort(dock, Predicate.IgnoreFlagD),
1185                 SEND_DATA,
1186             });
1187         expectNorthFifoExactly(1);
1188     }
1189
1190     private void testFlagAB(Marina marina) {
1191         prln("Begin testFlagAB");
1192         adjustIndent(2);
1193
1194         Instruction.Set.FlagFunction zero = Instruction.Set.FlagFunction.ZERO;
1195         Instruction.Set.FlagFunction one  = zero;
1196
1197         
1198         // we should be able to use any pair of FlagX+NotFlagX,
1199         // but we toss them all in to maximize the chances of the
1200         // test passing (later we will try the individual
1201         // combinations to maximize the chances of failure).
1202         one = one.add(Predicate.FlagA);
1203         one = one.add(Predicate.NotFlagA);
1204         one = one.add(Predicate.FlagB);
1205         one = one.add(Predicate.NotFlagB);
1206         one = one.add(Predicate.FlagC);
1207         one = one.add(Predicate.NotFlagC);
1208
1209         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1));
1210         for(boolean fast : new boolean[] { true, false }) {
1211             // clear the flags to a known state, then check both 0->1 and 1->0 transitions
1212             for(boolean b : new boolean[] { false, true, false }) {
1213                 prln("state: a="+marina.getFlagA()+", b="+marina.getFlagB());
1214                 prln((b?"Setting":"Clearing")+" flags");
1215                 
1216                 Instruction inst = new Instruction.Set(dock,Predicate.IgnoreFlagD,
1217                                                        b ? one : zero,
1218                                                        b ? one : zero
1219                                                        );
1220                 if (fast) {
1221                     marina.fillSouthProperStopper(new Instruction[] {
1222                             RECV_DATA,
1223                             inst,
1224                             NOP,
1225                         });
1226                     model.waitNS(64 * CYCLE_TIME_NS);
1227                     marina.fillNorthProperStopper();
1228                 } else {
1229                     marina.instrIn.fill(inst);
1230                 }
1231
1232                 fatal(marina.getFlagA()!=b,
1233                       "after "+(b?"setting":"clearing")+" FlagA, it was still "+(b?"clear":"set"));
1234                 fatal(marina.getFlagB()!=b,
1235                       "after "+(b?"setting":"clearing")+" FlagB, it was still "+(b?"clear":"set"));
1236             }
1237         }
1238
1239         adjustIndent(-2);
1240         prln("End testFlagAB");         
1241     }
1242
1243     /**
1244      *  WARNING: this is a very, very, very long test case -- it goes
1245      *  through 216 iterations.
1246      */
1247     private void testFlagTruthTable(Marina marina) {
1248         prln("Begin testFlagTruthTable");
1249         adjustIndent(2);
1250
1251         marina.instrIn.fill(setIlc(1));
1252         Instruction.Set.FlagFunction zero = Instruction.Set.FlagFunction.ZERO;
1253         Instruction.Set.FlagFunction one  = zero.add(Predicate.FlagA).add(Predicate.NotFlagA);
1254
1255         for(Predicate a_input : new Predicate[] { null, Predicate.FlagA, Predicate.NotFlagA })
1256             for(Predicate b_input : new Predicate[] { null, Predicate.FlagB, Predicate.NotFlagB })
1257                 for(Predicate c_input : new Predicate[] { null, Predicate.FlagC, Predicate.NotFlagC })
1258                     for(boolean a_state : new boolean[] { false, true })
1259                         for(boolean b_state : new boolean[] { false, true })
1260                             for(boolean c_state : new boolean[] { false, true }) {
1261                                 for(boolean which : new boolean[] { false, true }) {
1262
1263                                     prln("before instruction: a="+a_state+", b="+b_state+", c="+c_state);
1264                                     // set A,B flags to a_state and b_state
1265                                     marina.instrIn.fill(new 
1266                                                         Instruction.Set(dock,Predicate.IgnoreFlagD,
1267                                                                         a_state ? one : zero,
1268                                                                         b_state ? one : zero
1269                                                                         ));
1270                                     
1271                                     // set C flag to c_state
1272                                     BitVector data = new BitVector(37, "empty");
1273                                     BitVector addr = new BitVector(14, "empty");
1274                                     for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1275                                     for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1276                                     addr.set(Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ONE, c_state);
1277                                     marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1278                                     marina.instrIn.fill(RECV_DATA);
1279                                     
1280                                     Instruction.Set.FlagFunction func = zero;
1281                                     if (a_input!=null) func = func.add(a_input);
1282                                     if (b_input!=null) func = func.add(b_input);
1283                                     if (c_input!=null) func = func.add(c_input);
1284
1285                                     Instruction inst = new 
1286                                         Instruction.Set(dock,Predicate.IgnoreFlagD,
1287                                                         !which ? func : zero.add(Predicate.FlagA),
1288                                                         which  ? func : zero.add(Predicate.FlagB)
1289                                                         );
1290
1291                                     marina.instrIn.fill(inst);
1292
1293                                     boolean expected_a = !which ? func.evaluate(a_state, b_state, c_state, false) : a_state;
1294                                     boolean expected_b =  which ? func.evaluate(a_state, b_state, c_state, false) : b_state;
1295                                     fatal(expected_a != marina.getFlagA(),
1296                                           "expected A="+expected_a+", but got "+marina.getFlagA());
1297                                     fatal(expected_b != marina.getFlagB(),
1298                                           "expected B="+expected_b+", but got "+marina.getFlagB());
1299                                 }
1300                             }
1301         adjustIndent(-2);
1302         prln("End testFlagTruthTable");         
1303     }
1304
1305     private void recvData(Marina marina) {
1306         prln("Begin recvData");
1307         adjustIndent(2);
1308
1309         marina.instrIn.fill(setIlc(1));
1310         marina.fillSouthProperStopper(new Instruction[] {
1311                 new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG),
1312                 new Instruction.Move(dock,
1313                                      Predicate.IgnoreFlagD, // predicate   
1314                                      false,                 // torpedoable 
1315                                      null,                  // path        
1316                                      false,                 // tokenIn     
1317                                      true,                  // dataIn      
1318                                      false,                 // latchData   
1319                                      false,                 // latchPath   
1320                                      false,                 // dataOut     
1321                                      false                  // tokenOut    
1322                                      ),
1323                 new Instruction.Set(dock,Predicate.IgnoreFlagD, SET_FLAG, SET_FLAG),
1324             });
1325         model.waitNS(64 * CYCLE_TIME_NS);
1326
1327         prln("checking to confirm that A flag is cleared");
1328         fatal(marina.getFlagA(), "bad A flag: "+marina.getFlagA());
1329         
1330         prln("inserting data item in north fifo ring");
1331         BitVector data = new BitVector(37, "empty");
1332         BitVector addr = new BitVector(14, "empty");
1333         for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1334         for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1335         marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1336         model.waitNS(64 * CYCLE_TIME_NS);
1337
1338         prln("checking to see if A flag got set");
1339         fatal(!marina.getFlagA(), "bad A flag: "+marina.getFlagA());
1340
1341         adjustIndent(-2);
1342         prln("End recvData");           
1343     }
1344
1345
1346     private void testRecvAndSendWalkingOne(Marina marina) {
1347         prln("Begin testRecvAndSendWalkingOne");
1348         adjustIndent(2);
1349
1350         marina.instrIn.fill(setIlc(1));
1351
1352         List<BitVector> dataItems;
1353         for(int bit=0; bit<37; bit++) {
1354
1355             BitVector data = new BitVector(37, "empty");
1356             BitVector addr = new BitVector(14, "empty");
1357             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1358             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1359             data.set(bit, true);
1360             prln("testing with bit pattern " + data);
1361
1362             prln("inserting data item into north fifo ring");
1363             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1364
1365             prln("stopping the north proper stopper");
1366             marina.data.stop();
1367
1368             dataItems = marina.data.drainMany(1);
1369             fatal(dataItems.size()!=0,
1370                   "found a data item waiting in the north proper stopper, but should not have");
1371
1372             marina.instrIn.fill(new Instruction.Move(dock,
1373                                                      Predicate.IgnoreFlagD,  // predicate   
1374                                                      false,                  // torpedoable 
1375                                                      null_path,              // path        
1376                                                      false,                  // tokenIn     
1377                                                      true,                   // dataIn      
1378                                                      true,                   // latchData   
1379                                                      false,                  // latchPath   
1380                                                      true,                   // dataOut     
1381                                                      false                   // tokenOut    
1382                                                      ));
1383
1384             dataItems = marina.data.drainMany(2);
1385             fatal(dataItems.size()!=1,
1386                   "found "+dataItems.size()+" data items in north fifo; expected one");
1387             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1388             fatalIfBitVectorsDoNotMatch(mp.data, data);
1389         }
1390
1391         adjustIndent(-2);
1392         prln("End testRecvAndSendWalkingOne");          
1393     }
1394
1395
1396
1397     private void setOlcFromDataLatch(Marina marina) {
1398         prln("Begin setOlcFromDataLatch");
1399         adjustIndent(2);
1400
1401         marina.instrIn.fill(setIlc(1));
1402
1403         // walk a bit from 0 to 5
1404         for(int bit=0; bit<6; bit++) {
1405             prln("inserting data item in north fifo ring");
1406             BitVector data = new BitVector(37, "empty");
1407             BitVector addr = new BitVector(14, "empty");
1408             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1409             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1410             data.set(bit, true);
1411             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1412
1413             marina.fillSouthProperStopper(new Instruction[] {
1414                     RECV_DATA,
1415                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,SetSource.DataLatch),
1416                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.DataLatch,-1),
1417                 });
1418
1419             model.waitNS(CYCLE_TIME_NS * 64);
1420
1421             expectOlc(1<<bit);
1422
1423             if (marina.kesselsCounter) {
1424                 // master clear on each iteration; otherwise we'd need to "run down" the olc
1425                 marina.masterClear();
1426                 marina.enableInstructionSend(true);
1427             }
1428         }
1429
1430         adjustIndent(-2);
1431         prln("End setOlcFromDataLatch");        
1432     }
1433
1434     private void setIlcFromDataLatch(Marina marina) {
1435         prln("Begin setIlcFromDataLatch");
1436         adjustIndent(2);
1437
1438         marina.instrIn.fill(setIlc(1));
1439
1440         // walk a bit from 0 to 5
1441         for(int bit=5; bit>=0; bit--) {
1442             prln("inserting data item in north fifo ring");
1443             BitVector data = new BitVector(37, "empty");
1444             BitVector addr = new BitVector(14, "empty");
1445             for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1446             for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1447             data.set(bit, true);
1448             marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1449
1450             marina.fillSouthProperStopper(new Instruction[] {
1451                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1452                     RECV_DATA,
1453                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,SetSource.DataLatch),
1454                 });
1455             model.waitNS(CYCLE_TIME_NS * 64);
1456
1457             int ilc = marina.getILC().getCount();
1458             fatal(ilc != (1<<bit), "expected ilc to be " + (1<<bit) + ", but got " + ilc); 
1459         }
1460
1461         adjustIndent(-2);
1462         prln("End setIlcFromDataLatch");        
1463     }
1464
1465     private void testSendAndRecvToken(Marina marina) {
1466         prln("Begin testSendAndRecvToken");
1467         adjustIndent(2);
1468
1469         marina.instrIn.fill(setIlc(1));
1470         marina.fillSouthProperStopper(new Instruction[] {
1471                 SEND_TOKEN,
1472                 RECV_TOKEN,
1473                 SEND_DATA,
1474             });
1475         expectNorthFifoExactly(1);
1476
1477         adjustIndent(-2);
1478         prln("End testSendAndRecvToken");       
1479     }
1480
1481     private void testSignExtendedLiteral(Marina marina) {
1482         prln("Begin testSignExtendedLiteral");
1483         adjustIndent(2);
1484
1485         marina.instrIn.fill(setIlc(1));
1486         for(long val : new long[] { (-1L << 14), -1, 0, 1 }) {
1487
1488             marina.fillSouthProperStopper(new Instruction[] {
1489                     new Instruction.Set(dock,Predicate.IgnoreFlagD,
1490                                         Instruction.Set.SetDest.DataLatch,
1491                                         val),
1492                     SEND_DATA,
1493                 });
1494             model.waitNS(CYCLE_TIME_NS * 64);
1495
1496             List<BitVector> dataItems = marina.data.drainMany(3);
1497             fatal(dataItems.size()!=1, "expected exactly one data item, got " + dataItems.size());
1498
1499             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1500             BitVector bv = mp.data;
1501             prln("got back " + mp);
1502
1503             boolean mismatch = false;
1504             String err = "";
1505             for(int i=0; i<37; i++) {
1506                 if (bv.get(i) != ( (val & (1L << i)) != 0 )) {
1507                     mismatch = true;
1508                     err += ""+i+", ";
1509                 }
1510             }
1511             fatal(mismatch, "data read back did not match inserted literal; mismatch on bits " + err);
1512         }
1513                 
1514         adjustIndent(-2);
1515         prln("End testSignExtendedLiteral");            
1516     }
1517
1518     private void testShiftedLiteral(Marina marina) {
1519         prln("Begin testShiftedLiteral");
1520         adjustIndent(2);
1521
1522         marina.instrIn.fill(setIlc(1));
1523         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,
1524                                                 Instruction.Set.SetDest.DataLatch,
1525                                                 0));
1526
1527         BitVector dreg = new BitVector(37, "what we think is in the d-register");
1528         for(int i=0; i<37; i++) dreg.set(i, false);
1529
1530         for(long val : new long[] { -1, 0, 1, (-1L << 18) }) {
1531
1532             edu.berkeley.fleet.api.BitVector immediate =
1533                 new edu.berkeley.fleet.api.BitVector(19);
1534             for(int i=0; i<immediate.length(); i++)
1535                 immediate.set(i, (val & (1L << i)) != 0);
1536
1537             // shift over 19 LSB's towards MSB
1538             for(int i=0; i<19; i++)
1539                 if (i+19 <= 36)  dreg.set(i+19, dreg.get(i));
1540             for(int i=0; i<19; i++)
1541                 dreg.set(i, immediate.get(i));
1542
1543             marina.fillSouthProperStopper(new Instruction[] {
1544                     new Instruction.Shift(dock,Predicate.IgnoreFlagD,immediate),
1545                     SEND_DATA,
1546                 });
1547
1548             model.waitNS(CYCLE_TIME_NS * 64);
1549             List<BitVector> dataItems = marina.data.drainMany(3);
1550             fatal(dataItems.size()!=1, "expected exactly one data item, got " + dataItems.size());
1551
1552             BitVector bv = new MarinaPacket(dataItems.get(0)).data;
1553             fatal(!bv.equals(dreg), "data read back did not match inserted literal.\n" +
1554                   "got:     "+bv.bitReverse().getState()+"\n"+
1555                   "expected:"+dreg.bitReverse().getState());
1556         }
1557                 
1558         adjustIndent(-2);
1559         prln("End testShiftedLiteral");         
1560     }
1561
1562     private void testFlagC(Marina marina) {
1563         prln("Begin testFlagC");
1564         adjustIndent(2);
1565
1566         // Russell says:
1567         // addr[14] == sigS
1568         // addr[1]  == sigA
1569         //
1570         // Adam says:
1571         // Dc=1 => sigS is copied into C-flag
1572         // Dc=0 => sigA is copied into C-flag
1573        
1574         marina.instrIn.fill(setIlc(1));
1575         for(boolean dc : new boolean[] { false, true }) {
1576             for(boolean c_flag : new boolean[] { true, false, true }) {
1577
1578                 prln("");
1579                 prln("****** checking case where dc="+dc+", cflag="+c_flag);
1580                 BitVector data = new BitVector(37, "empty");
1581                 BitVector addr = new BitVector(14, "empty");
1582                 for(int i=0; i<data.getNumBits(); i++) data.set(i, false);
1583                 for(int i=0; i<addr.getNumBits(); i++) addr.set(i, false);
1584
1585                 int whichbit = dc
1586                     ? Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ONE
1587                     : Marina.INDEX_OF_ADDRESS_BIT_COPIED_TO_C_FLAG_WHEN_DC_EQUALS_ZERO;
1588                 prln("setting addr["+whichbit+"] to "+(c_flag?"1":"0"));
1589                 addr.set(whichbit, c_flag);
1590
1591                 prln("... and filling north fifo proper stopper");
1592                 marina.fillNorthProperStopper(new MarinaPacket(data, false, addr));
1593                 
1594                 prln("clearing flags");
1595                 prln("executing recv data with Dc="+dc);
1596                 prln("copying c-flag to a-flag");
1597                 marina.fillSouthProperStopper(new Instruction[] {
1598                         new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG),
1599                         new Instruction.Move(dock,
1600                                              Predicate.IgnoreFlagD,   /* predicate   */
1601                                              true,                  /* torpedoable */
1602                                              null,                  /* path        */
1603                                              false,                 /* tokenIn     */
1604                                              true,                  /* dataIn      */
1605                                              dc,                    /* latchData   */
1606                                              false,                 /* latchPath   */
1607                                              false,                 /* dataOut     */
1608                                              false                  /* tokenOut    */
1609                                              ),
1610                         FLAG_NOP,
1611                         new Instruction.Set(dock,Predicate.IgnoreFlagD,
1612                                             Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagC),
1613                                             CLEAR_FLAG
1614                                             ),
1615                     });
1616
1617                 model.waitNS(CYCLE_TIME_NS * 64);
1618                 
1619                 prln("checking to confirm that A flag is " + c_flag);
1620                 fatal(marina.getFlagA()!=c_flag, "bad A flag: "+marina.getFlagA());
1621             }
1622         }
1623         adjustIndent(-2);
1624         prln("End testFlagC");          
1625     }
1626
1627     private void sendDataWithPath(Marina marina) {
1628         prln("Begin sendDataWithPath");
1629         adjustIndent(2);
1630
1631         edu.berkeley.fleet.api.BitVector bv = new edu.berkeley.fleet.api.BitVector(13);
1632         marina.instrIn.fill(setIlc(1));
1633
1634         // alternating ones and zeroes
1635         for(int i=0; i<bv.length(); i+=2)
1636             bv.set(i, true);
1637         // and then ones in the lower four bits so it's not symmetric
1638         for(int i=0; i<4; i++)
1639             bv.set(i, true);
1640
1641         MarinaPath path = new MarinaPath((MarinaFleet)dock.getShip().getFleet(), bv);
1642
1643         marina.fillSouthProperStopper(new Instruction[] {
1644                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1645                 new Instruction.Move(dock,
1646                                      Predicate.IgnoreFlagD, /* predicate   */
1647                                      false,                 /* torpedoable */
1648                                      path,                  /* path        */
1649                                      false,                 /* tokenIn     */
1650                                      false,                 /* dataIn      */
1651                                      false,                 /* latchData   */
1652                                      false,                 /* latchPath   */
1653                                      true,                  /* dataOut     */
1654                                      false                  /* tokenOut    */
1655                                      ),
1656             });
1657
1658         List<BitVector> dataItems;
1659         MarinaPacket mp;
1660
1661         dataItems = marina.data.drainMany();
1662         fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1663         mp = new MarinaPacket(dataItems.get(0));
1664
1665         // the 14th bit of the outbound address cannot be set by the
1666         // ship, so we don't care about it
1667         fatalIfBitVectorsDoNotMatch(MarinaUtils.berkToSun(bv), mp.path.get(0,13));
1668
1669         prln("send data with no change to path");
1670         marina.instrIn.fill(new Instruction.Move(dock,
1671                                                  Predicate.IgnoreFlagD, /* predicate   */
1672                                                  false,                 /* torpedoable */
1673                                                  null,                  /* path        */
1674                                                  false,                 /* tokenIn     */
1675                                                  false,                 /* dataIn      */
1676                                                  false,                 /* latchData   */
1677                                                  false,                 /* latchPath   */
1678                                                  true,                  /* dataOut     */
1679                                                  false                  /* tokenOut    */
1680                                                  ));
1681
1682         dataItems = marina.data.drainMany();
1683         fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1684         mp = new MarinaPacket(dataItems.get(0));
1685
1686         // the 14th bit of the outbound address cannot be set by the
1687         // ship, so we don't care about it
1688         fatalIfBitVectorsDoNotMatch(MarinaUtils.berkToSun(bv), mp.path.get(0,13));
1689
1690         adjustIndent(-2);
1691         prln("End sendDataWithPath");
1692     }
1693
1694     private void recvPath(Marina marina) {
1695         prln("Begin recvPath");
1696         adjustIndent(2);
1697
1698         marina.instrIn.fill(setIlc(1));
1699         for(int bit=0; bit<11; bit++) {
1700             BitVector packet_data = new BitVector(37, "inbound data item");
1701             for(int i=0; i<37; i++) packet_data.set(i, false);
1702             packet_data.set(27+bit, true);
1703             BitVector packet_path = new BitVector(14, "inbound data item");
1704             for(int i=0; i<14; i++) packet_path.set(i, false);
1705
1706             marina.fillNorthProperStopper(new MarinaPacket(packet_data, false, packet_path));
1707                                            
1708             prln("recv path, send data (using recv'd path)");
1709             marina.instrIn.fill(new Instruction.Move(dock,
1710                                                      Predicate.IgnoreFlagD,   /* predicate   */
1711                                                      false,                 /* torpedoable */
1712                                                      null,                  /* path        */
1713                                                      false,                 /* tokenIn     */
1714                                                      true,                  /* dataIn      */
1715                                                      true,                  /* latchData   */
1716                                                      true,                  /* latchPath   */
1717                                                      true,                  /* dataOut     */
1718                                                      false                  /* tokenOut    */
1719                                                      ));
1720
1721             List<BitVector> dataItems = marina.data.drainMany();
1722             fatal(dataItems.size()!=1, "Expected one data item to emerge but got: "+dataItems.size()+" data items");
1723             MarinaPacket mp = new MarinaPacket(dataItems.get(0));
1724             
1725             fatalIfBitVectorsDoNotMatch(packet_data.get(25,11), mp.path.get(0,11));
1726             fatalIfBitVectorsDoNotMatch(packet_data, mp.data);
1727         }
1728
1729         adjustIndent(-2);
1730         prln("End recvPath");
1731     }
1732
1733     private void testILC(Marina marina) {
1734         prln("Begin testILC");
1735         adjustIndent(2);
1736
1737         for(int bit=0; bit<6; bit++) {
1738             int ilc = bit<0 ? 0 : (1<<bit);
1739             marina.fillSouthProperStopper(new Instruction[] {
1740                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,ilc),
1741                     SEND_DATA,
1742                 });
1743             List<BitVector> dataItems = marina.data.drainMany();
1744             fatal(dataItems.size()!=ilc, "Expected "+ilc+" data item(s) to emerge but got: "+dataItems.size()+" data items");
1745         }
1746
1747         adjustIndent(-2);
1748         prln("End testILC");
1749     }
1750
1751     private void testILCZero(Marina marina) {
1752         adjustIndent(2);
1753         marina.fillSouthProperStopper(new Instruction[] {
1754                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,0),
1755                 SEND_DATA,
1756                 SEND_TOKEN,
1757             });
1758         expectNorthFifoNoMoreThan(0);
1759         expectTokensExactly(1);
1760         adjustIndent(-2);
1761     }
1762
1763     private void sendTorpedo(Marina marina) {
1764         prln("Begin sendTorpedo");
1765         adjustIndent(2);
1766         marina.instrIn.fill(setIlc(1));
1767         marina.instrIn.fill(setOlc(63));
1768
1769         model.waitNS(128 * CYCLE_TIME_NS);
1770         expectOlc(63);
1771
1772         marina.instrIn.fill(new 
1773                             Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG));
1774         fatal(marina.getFlagA(), "bad A flag: true");
1775         fatal(marina.getFlagB(), "bad B flag: true");
1776
1777         prln("execute a move instruction that does nothing but loops until torpedo arrives"); 
1778         prln("A=1, B=B This instruction should not execute because D-flag is set");
1779         prln("Set A=A, B=1 This instruction should execute because D-flag is set");
1780
1781         model.waitNS(128 * CYCLE_TIME_NS);
1782
1783         marina.fillSouthProperStopper(new Instruction[] {
1784                 new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, SetSource.Infinity),
1785                 new Instruction.Move(dock,
1786                                      Predicate.IgnoreFlagD, // predicate   
1787                                      true,                  // torpedoable 
1788                                      null,                  // path        
1789                                      false,                 // tokenIn     
1790                                      true,                  // dataIn      
1791                                      false,                 // latchData   
1792                                      false,                 // latchPath   
1793                                      false,                 // dataOut     
1794                                      false                  // tokenOut    
1795                                      ),
1796                 new Instruction.Set(dock,Predicate.Default,
1797                                     SET_FLAG,
1798                                     Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagB)
1799                                     ),
1800                 new Instruction.Set(dock, Predicate.FlagD,
1801                                     Instruction.Set.FlagFunction.ZERO.add(Predicate.FlagA),
1802                                     SET_FLAG
1803                                     ),
1804             });
1805
1806         model.waitNS(128 * CYCLE_TIME_NS);
1807
1808         prln("send torpedo. This should clear the OLC");
1809         marina.instrIn.fillTorpedo();
1810         model.waitNS(128 * CYCLE_TIME_NS);
1811
1812         model.waitNS(128 * CYCLE_TIME_NS);
1813                 
1814         prln("A should remain false, B should be true");
1815         fatal(marina.getFlagA(), "bad A flag: true");
1816         fatal(!marina.getFlagB(), "bad B flag: false");
1817         
1818         model.waitNS(128 * CYCLE_TIME_NS);
1819
1820         prln("Reload OLC after torpedo, clears D-flag");
1821         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 63));
1822
1823         // FIXME: find another way to test this
1824         model.waitNS(128 * CYCLE_TIME_NS);
1825         expectOlc(63);
1826                 
1827         prln("Set A=1, B=1 This instruction should execute because OLC!=0");
1828         marina.instrIn.fill(new 
1829                             Instruction.Set(dock,Predicate.Default, SET_FLAG, SET_FLAG));
1830
1831         prln("A and B should be true");
1832         fatal(!marina.getFlagA(), "bad A flag: false");
1833         fatal(!marina.getFlagB(), "bad B flag: false");
1834                 
1835         adjustIndent(-2);
1836         prln("End sendTorpedo");        
1837     }    
1838
1839     private void testTorpedoOnAnInfinite(Marina marina) {
1840         prln("Begin testTorpedoOnAnInfinite");
1841         adjustIndent(2);
1842
1843         List<BitVector> dataItems;
1844
1845         marina.instrIn.fill(setIlc(1));
1846         for(boolean torpedoable : new boolean[] { true, false }) {
1847             
1848             marina.fillSouthProperStopper(new Instruction[] {
1849                     new Instruction.Move(dock,
1850                                          Predicate.IgnoreFlagD, // predicate   
1851                                          false,                 // torpedoable 
1852                                          null,                  // path        
1853                                          false,                 // tokenIn     
1854                                          false,                 // dataIn      
1855                                          false,                 // latchData   
1856                                          false,                 // latchPath   
1857                                          false,                 // dataOut     
1858                                          true                   // tokenOut    
1859                                          ),
1860                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,SetSource.Infinity),
1861                     new Instruction.Move(dock,
1862                                          Predicate.IgnoreFlagD, // predicate   
1863                                          torpedoable,           // torpedoable 
1864                                          null,                  // path        
1865                                          true,                  // tokenIn     
1866                                          false,                 // dataIn      
1867                                          false,                 // latchData   
1868                                          false,                 // latchPath   
1869                                          false,                 // dataOut     
1870                                          true                   // tokenOut    
1871                                          ),
1872                     // FIXME: this probably should be removed, unless Ivan doesn't want to change the behavior
1873                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1874
1875                     SEND_DATA,
1876                 });
1877             
1878             // expect nothing to come out, because the NOP is executing
1879             dataItems = marina.data.drainMany(2);
1880             fatal(dataItems.size()!=0, "Expected no data item(s) to emerge but got at least: "+dataItems.size()+" data items");
1881             
1882             marina.instrIn.fillTorpedo();
1883             
1884             int expected = torpedoable?1:0;
1885             dataItems = marina.data.drainMany(2);
1886             fatal(dataItems.size()!=expected, "Expected "+expected+" item to emerge but got: "+dataItems.size()+" data items");
1887
1888             fatal(!marina.getILC().getDone(), "Expected ilc=done, but got "+marina.getILC());
1889         }
1890
1891         adjustIndent(-2);
1892         prln("End testTorpedoOnAnInfinite");
1893     }
1894
1895     private void testOlcDecrementAtHighSpeed(Marina marina) {
1896         prln("Begin testOlcDecrementAtHighSpeed");
1897         adjustIndent(2);
1898
1899         List<BitVector> dataItems;
1900         
1901         // Each element of the following pair of arrays is one "test".
1902         // The OLC will be loaded with olcs[i] and then decremented
1903         // decr_amounts[i] times; after that has happened the zeroness
1904         // of the OLC will be checked by executing a MOVE with
1905         // [olc!=0] as the predicate.
1906
1907         int[] olcs         = new int[] { 3, 3, 3, 10, 41 };
1908         int[] decr_amounts = new int[] { 2, 3, 4, 9,  9  };
1909
1910         for(int which=0; which<olcs.length; which++) {
1911             int olc = olcs[which];
1912             int decr_amount = decr_amounts[which];
1913
1914             prln("inserting set olc="+olc);
1915             prln("inserting set ilc=1");
1916             marina.fillSouthProperStopper(new Instruction[] {
1917                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter,1),
1918                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter,olc),
1919                 });
1920
1921             // commenting the following four lines causes this test to pass
1922
1923             prln("inserting: "+decr_amount+" olc-- instructions");
1924             prln("inserting: [!d] send data");
1925             Instruction[] instructions = new Instruction[decr_amount+1];
1926             for(int i=0; i<decr_amount; i++)
1927                 instructions[i] =
1928                     new Instruction.Set(dock,
1929                                         Predicate.Default,
1930                                         SetDest.OuterLoopCounter,
1931                                         SetSource.Decrement);
1932             instructions[instructions.length-1] =
1933                 new Instruction.Move(dock,
1934                                      Predicate.Default,     // predicate   
1935                                      false,                 // torpedoable 
1936                                      null,                  // path        
1937                                      false,                 // tokenIn     
1938                                      false,                 // dataIn      
1939                                      false,                 // latchData   
1940                                      false,                 // latchPath   
1941                                      true,                  // dataOut     
1942                                      false                  // tokenOut    
1943                                      );
1944
1945             marina.fillSouthProperStopper(instructions);
1946             model.waitNS(64 * CYCLE_TIME_NS);
1947
1948             int expected = decr_amount>=olc ? 0 : 1;
1949             dataItems = marina.data.drainMany(2);
1950             fatal(dataItems.size()!=expected, "Expected "+expected+" item to emerge but got: "+dataItems.size()+" data items");
1951
1952             if (marina.kesselsCounter) {
1953                 // master clear on each iteration; otherwise we'd need to "run down" the olc
1954                 marina.masterClear();
1955                 marina.enableInstructionSend(true);
1956             }
1957         }
1958
1959         adjustIndent(-2);
1960         prln("End testOlcDecrementAtHighSpeed");
1961     }
1962
1963     private void flipIlcBit(Marina marina) {
1964         prln("Begin flipIlcBit");
1965         adjustIndent(2);
1966         prln("Using the set ILC instruction, toggle a single bit between zero and one. \n" +
1967              "Check correct setting of the ILC zero bit");
1968
1969         for (int i=0; i<6; i++) {
1970             int notZero = 1<<i;
1971
1972             prln("Then immediately set ILC="+notZero);
1973             marina.fillSouthProperStopper(new Instruction[] {
1974                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, 0),
1975                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, notZero),
1976                 });
1977                 
1978             model.waitNS(64 * CYCLE_TIME_NS);
1979
1980             prln("Verify ILC using scan chain");
1981             Ilc ilc = marina.getILC();
1982             int ilcCount = ilc.getCount();
1983             fatal(ilcCount!=notZero, "bad ILC count: "+ilcCount+" expected: "+notZero);
1984             fatal(ilc.getInfinity(), "bad ILC Infinity bit: true");
1985                    
1986             marina.fillSouthProperStopper(new Instruction[] {     
1987                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, notZero),
1988                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.InnerLoopCounter, 0),
1989                 });
1990
1991             model.waitNS(64 * CYCLE_TIME_NS);
1992                         
1993             prln("Verify ILC using scan chain");
1994             ilc = marina.getILC();
1995             ilcCount = ilc.getCount();
1996             fatal(ilcCount!=0, "bad ILC count: "+ilcCount+" expected: 0");
1997             fatal(ilc.getInfinity(), "bad ILC Infinity bit: true");
1998         }
1999
2000         adjustIndent(-2);
2001         prln("End flipIlcBit");
2002     }
2003     private void flipOlcBit(Marina marina) {
2004         prln("Begin flipOlcBit");
2005         adjustIndent(2);
2006         prln("Using the set OLC instruction, toggle a single bit between zero and one. \n" +
2007              "Check correct setting of the OLC zero bit");
2008
2009         marina.instrIn.fill(new Instruction.Set(dock,Predicate.IgnoreFlagD, CLEAR_FLAG, CLEAR_FLAG));
2010
2011         for (int i=0; i<6; i++) {
2012             int notZero = 32 >> i;
2013
2014             if (marina.kesselsCounter) {
2015                 // master clear on each iteration; otherwise we'd need to "run down" the olc
2016                 marina.masterClear();
2017                 marina.enableInstructionSend(true);
2018             }
2019
2020             int outOlc;
2021             prln("Set OLC=0");
2022             prln("Then immediately set OLC="+notZero);
2023             marina.fillSouthProperStopper(new Instruction[] {
2024                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 0),
2025                     new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, notZero),
2026                 });
2027
2028             model.waitNS(64 * CYCLE_TIME_NS);
2029             prln("Verify OLC count using scan chain");
2030             expectOlc(notZero);
2031
2032             if (!marina.kesselsCounter) {
2033                 prln("Set OLC="+notZero);
2034                 prln("Then immediately set OLC=0");
2035                 marina.fillSouthProperStopper(new Instruction[] {
2036                         new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, notZero),
2037                         new Instruction.Set(dock,Predicate.IgnoreFlagD,SetDest.OuterLoopCounter, 0),
2038                     });
2039                 
2040                 model.waitNS(64 * CYCLE_TIME_NS);
2041                 prln("Verify OLC count using scan chain");
2042                 expectOlc(0);
2043             }
2044         }
2045         
2046         adjustIndent(-2);
2047         prln("End flipOlcBit");
2048     }
2049     private void testSouthRecirculate(Marina marina, int AMOUNT) {
2050         prln("Begin testSouthRecirculate("+AMOUNT+")");
2051         adjustIndent(2);
2052
2053         marina.enableInstructionSend(false);
2054         marina.enableInstructionRecirculate(true);
2055         
2056         prln("Completely fill south ring");
2057         adjustIndent(2);
2058         for (int i=0; i<AMOUNT; i++) {
2059             prln("inserting item " + (i+1) + " / " + AMOUNT);
2060             BitVector path = new BitVector(MarinaPacket.PATH_WIDTH, "path");
2061             BitVector data = new BitVector(MarinaPacket.WORD_WIDTH, "path");
2062             path.set(0, MarinaPacket.PATH_WIDTH, false);
2063             data.setFromLong(i+9);
2064             marina.instrIn.fill(new MarinaPacket(data, false, path));
2065         }
2066         adjustIndent(-2);
2067
2068         prln("Drain south ring and check contents");
2069         adjustIndent(2);
2070         List<BitVector> out = marina.instrIn.drainMany();
2071         boolean bad = false;
2072         for (int i=0; i<AMOUNT; i++) {
2073             prln("extracting item " + (i+1) + " / " + AMOUNT);
2074             //int expect = (i+Marina.SOUTH_RING_CAPACITY-1) % Marina.SOUTH_RING_CAPACITY;
2075             int expect = i+9;
2076             long got = new MarinaPacket(out.get(i)).data.toLong();
2077             if (got!=expect) {
2078                 bad = true;
2079                 prln("  bad instruction: "+got+" expected: "+expect);
2080             } else {
2081                 prln("  good instruction.");
2082             }
2083         }
2084         fatal(bad, "data inserted does not match data retrieved");
2085         adjustIndent(-2);
2086         
2087         for (int i=0; i<5; i++) {}
2088         
2089         adjustIndent(-2);
2090         prln("End testSouthRecirculate("+AMOUNT+")");
2091     }
2092     private void doOneTest(int testNum) {
2093         prln("");
2094         prln("============================================================");
2095         prln("MarinaTest: performing test: "+testNum);
2096
2097         if (testNum!=0) {
2098             marina.masterClear();
2099             marina.enableInstructionSend(true);
2100         }
2101         
2102         try {
2103             switch (testNum) {
2104                 case 0: {
2105
2106                     // these tests run fairly quickly
2107
2108
2109                     doOneTest(1);       // passes extracted parasitics
2110                     doOneTest(2);       // passes extracted parasitics
2111                     doOneTest(3);       // passes extracted parasitics
2112                     doOneTest(4);       // passes extracted parasitics
2113                     doOneTest(5);       // passes extracted parasitics
2114                     doOneTest(6);
2115                     doOneTest(1002);
2116                     doOneTest(1005);
2117                     doOneTest(3019);
2118                     doOneTest(3025);
2119
2120                     doOneTest(1000);    // passes extracted parasitics
2121                     doOneTest(1001);    // passes extracted parasitics
2122                     doOneTest(1003);    // passes extracted parasitics
2123                     doOneTest(3000);    // passes extracted parasitics
2124                     doOneTest(3001);    // passes extracted parasitics
2125                     doOneTest(3003);    // passes extracted parasitics
2126                     doOneTest(3004);    // passes extracted parasitics
2127                     doOneTest(3005);    // passes extracted parasitics
2128                     doOneTest(3006);    // passes extracted parasitics
2129                     doOneTest(3007);    // passes extracted parasitics
2130                     doOneTest(3008);    // passes extracted parasitics
2131                     doOneTest(3009);    // passes extracted parasitics
2132                     doOneTest(3010);    // passes extracted parasitics
2133                     doOneTest(3011);    // passes extracted parasitics
2134                     doOneTest(3012);    // passes extracted parasitics
2135                     doOneTest(3013);    // passes extracted parasitics
2136                     doOneTest(3014);    // passes extracted parasitics
2137                     doOneTest(3015);    // passes extracted parasitics
2138                     doOneTest(3019);    // passes extracted parasitics
2139                     doOneTest(3020);    // passes extracted parasitics
2140                     doOneTest(3022);    // passes extracted parasitics
2141                     doOneTest(3023);    // passes extracted parasitics
2142                     doOneTest(3026);    // passes extracted parasitics
2143                     doOneTest(3027);    // passes extracted parasitics
2144                     doOneTest(3028);    // passes extracted parasitics
2145                     
2146                     // these tests take a while and usually pass
2147                     doOneTest(1002);
2148                     doOneTest(1004);
2149                     doOneTest(1005);
2150                     doOneTest(1006);
2151                     doOneTest(3002);
2152                     doOneTest(3016);
2153                     doOneTest(3021);
2154                     doOneTest(3024);
2155                     doOneTest(3025);
2156                     
2157                     // this takes an insanely long time
2158                     doOneTest(3017);
2159                     break;
2160                 }
2161                 case 1:    testChains(marina);                     break; // passes, 24-Mar (+verilog)
2162                 case 2:    testProperStoppers(marina);             break; // passes, 24-Mar (+verilog)
2163                 case 3:    testSouthRecirculate(marina, 1);        break; // passes, 24-Mar (+verilog)
2164                 case 4:    getCtrsFlags(marina);                   break; //         20-Apr (+verilog)
2165                 case 5:    sendInstructions(marina);               break; // passes, 24-Mar (+verilog)
2166                 case 6:    walkOneOLC(marina);                     break; //         21-Apr (+verilog)
2167                 
2168                     // Russell's tests begin with 1000
2169                 case 1000: walkOneILC(marina);                     break; //         20-Apr (+verilog)
2170                 case 1001: countIlc(marina);                       break; //         20-Apr (+verilog)
2171                 case 1002: countOlc(marina);                       break; //         23-Apr (+verilog)
2172
2173                 case 1003: sendTorpedo(marina);                    break; //         23-Apr (+verilog)  [with wor-hack]
2174
2175                 case 1004: flipIlcBit(marina);                     break; //         20-Apr (+verilog)
2176                 case 1005: flipOlcBit(marina);                     break; //         21-Apr (+verilog)
2177
2178                 case 1006: testSouthRecirculate(marina, Marina.SOUTH_RING_CAPACITY-1);        break; // passes, 24-Mar (+verilog)
2179
2180                     // Adam's tests begin with 3000
2181                 case 3000: sendToken(marina);                      break; // passes, 24-Mar (+verilog)
2182                 case 3001: testFlagAB(marina);                     break; // passes, 08-Apr (+verilog)
2183                 case 3002: testPredicationOnAB(marina);            break; //         22-Apr (+verilog)
2184                 case 3003: testFlagC(marina);                      break; //         23-Apr (+verilog)
2185                 case 3004: testFlagD(marina);                      break; //         23-Apr (+verilog)
2186                 case 3005: testFlagDRecomputationTime(marina);     break;
2187
2188                 case 3006: testTailWaitsForHead(marina);           break;
2189                 case 3007: testTailWithoutHead(marina);            break;
2190                 case 3008: testHeadWaitsForTail(marina);           break; //         22-Apr (+verilog)
2191                 case 3009: testAbort(marina);                      break; //         22-Apr (+verilog)
2192
2193                 case 3010: sendData(marina);                       break; // passes, 24-Mar (+verilog)
2194                 case 3011: recvData(marina);                       break; //         21-Apr (+verilog)
2195                 case 3012: sendDataWithPath(marina);               break; // passes, 13-Apr (+verilog)
2196
2197                 case 3013: testSignExtendedLiteral(marina);        break; //         20-Apr (+verilog)
2198                 case 3014: testShiftedLiteral(marina);             break; //         20-Apr (+verilog)
2199                 case 3015: testSendAndRecvToken(marina);           break; //         21-Apr (+verilog)
2200
2201                 case 3016: sendDataIlcInfinite(marina);            break; //         22-Apr (+verilog)
2202                 case 3017: testFlagTruthTable(marina);             break; //         23-Apr (+verilog)
2203
2204                 case 3019: setOlcFromDataLatch(marina);            break; //         23-Apr (+verilog)
2205                 case 3020: setIlcFromDataLatch(marina);            break; //         23-Apr (+verilog)
2206                 case 3021: recvPath(marina);                       break; //         22-Apr (+verilog)
2207                 case 3022: testILC(marina);                        break; //         23-Apr (+verilog)
2208                 case 3023: testTorpedoOnAnInfinite(marina);        break; //         23-Apr (+verilog)
2209                 case 3024: testRecvAndSendWalkingOne(marina);      break; //         21-Apr (+verilog)
2210                 case 3025: testOlcDecrementAtHighSpeed(marina);    break; //         23-Apr (+verilog)
2211
2212                 case 3026: testNonTorpedoableMoveDoesNotResetDFlag(marina);        break; //         23-Apr (+verilog)
2213                 case 3027: testILCZero(marina);                    break;
2214                 case 3028: testAbortOutsideOfLoop(marina); break;
2215
2216                 default:
2217                     fatal(true, "Test number: "+testNum+" doesn't exist.");
2218                     break;
2219             }
2220             // If we get here then test passed
2221             prln("Test Result: Passed");
2222             printTestTime();
2223             //Infrastructure.exit(0);
2224         } catch (MarinaUtils.FailureException fe) {
2225             System.out.println("******************************************************************************");
2226             System.out.println("******************************************************************************");
2227             System.out.println("******************************************************************************");
2228             System.out.println("******************************************************************************");
2229             fe.printStackTrace();
2230         }
2231     }
2232
2233
2234     //============================ for public use =============================
2235
2236     /** Exit codes:
2237      * 0: test detected success
2238      * 2: test detected failure
2239      * 1: test crashed
2240      */ 
2241     public static void main(String[] args) {
2242         startTime = System.currentTimeMillis();
2243         new MarinaTest(args);
2244     }
2245
2246 }