add FpgaDestination.getPathLength() for measuring hop counts
[fleet.git] / src / edu / berkeley / fleet / fpga / Fpga.java
index bc97213..372b9fb 100644 (file)
@@ -1,8 +1,7 @@
 package edu.berkeley.fleet.fpga;
 import edu.berkeley.fleet.fpga.*;
-import edu.berkeley.fleet.doc.*;
 import edu.berkeley.fleet.api.*;
-import edu.berkeley.fleet.ies44.*;
+import edu.berkeley.fleet.two.*;
 import edu.berkeley.fleet.*;
 import java.lang.reflect.*;
 import edu.berkeley.sbp.chr.*;
@@ -11,471 +10,341 @@ import edu.berkeley.sbp.meta.*;
 import edu.berkeley.sbp.util.*;
 import java.util.*;
 import java.io.*;
+import edu.berkeley.fleet.two.*;
+import static edu.berkeley.fleet.two.FleetTwoFleet.*;
+import static edu.berkeley.fleet.fpga.verilog.Verilog.*;
+import edu.berkeley.fleet.two.PercolatedPort;
 
-public class Fpga extends Fleet {
 
-    public ArrayList<FpgaShip> shiplist   = new ArrayList<FpgaShip>();
-    public HashMap<String,FpgaShip> ships = new HashMap<String,FpgaShip>();
-    public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)shiplist.iterator(); }
+public class Fpga extends FleetTwoFleet {
 
-    private String bitfile;
+    public  Module top;
+    Ship debugShip;
 
-    public static void main(String[] s) throws Exception {
-        new Fpga().dumpFabric(false);
-    }
+    public LinkedHashMap<String,FpgaShip> ships = new LinkedHashMap<String,FpgaShip>();
+    public Iterator<Ship> iterator() { return (Iterator<Ship>)(Object)ships.values().iterator(); }
 
-    public Fpga() { this("gaspified.bit"); }
-    public Fpga(String bitfile) {
-        this.bitfile = bitfile;
-        createShip("Debug",   "debug");
-        createShip("Memory",    "memory");
-        createShip("Memory",    "memory2");  // need this to avoid a bug
-        createShip("Fifo",    "fifo1");
-        createShip("Fifo",    "fifo2");
-        createShip("Alu2",    "alu2a");
-        createShip("BitFifo",   "bitfifo");
-        // above is the minimal ship set needed to run the regression suite, excluding "ships" tests
-        createShip("Alu1",    "alu1");
-        createShip("Lut3",      "lut3");
-        createShip("Alu3",      "alu3");
-
-        /*
-        createShip("Stack",     "Stack");
-        createShip("Fifo",    "fifo3");
-        createShip("Choice",    "Choice");
-        */
-        // above is the minimal ship set needed to run the regression suite, including "ships" tests
-
-        // below are extra bonus ships
-        /*
-        createShip("Alu2",    "alu2b");
-        createShip("Alu2",    "alu2c");
-        createShip("Alu2",    "alu2d");
-        createShip("Fifo",    "fifo4");
-        createShip("Memory",    "Memory");
-        createShip("Choice",    "Choice");
-        createShip("Choice",    "Choice");
-        createShip("Choice",    "Choice");
-        */
-        dumpFabric(true);
+    public Ship getShip(String type, int ordinal) {
+        for(Ship s : this)
+            if (s.getType().equals(type))
+                if (--ordinal < 0)
+                    return s;
+        return null;
     }
 
-    public Ship createShip(String type, String name) {
-        try {
-            ShipDescription sd = new ShipDescription(name, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
-            FpgaShip ship = new FpgaShip(this, name, type, sd);
-            ships.put(name, ship);
-            shiplist.add(ship);
-            return ship;
-        } catch (IOException e) { throw new RuntimeException(e); }
+    public static void main(String[] s) throws Exception { 
+        new Fpga(new Module("main")).top.dump(s[0]);
+        PrintWriter pw;
+
+        pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(s[0]+"/timescale.v")));
+        pw.println("`timescale 1ns / 10ps");
+        pw.close();
+
+        pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(s[0]+"/vram.v")));
+        pw.println("`define BRAM_ADDR_WIDTH 19");
+        pw.println("`define BRAM_DATA_WIDTH 3");
+        pw.println("`define BRAM_SIZE (640*480)");
+        pw.println("`define BRAM_NAME vram");
+        pw.println("`include \"bram.inc\"");
+        pw.close();
     }
 
-    public FleetProcess run(final byte[] instructions) {
+    public Module getVerilogModule() { return top; }
+
+    public FleetProcess run(Instruction[] instructions) {
         try {
-            return new Client(bitfile, instructions);
-        } catch (IOException e) { throw new RuntimeException(e); }
+            return new Client(this, "none", instructions);
+        } catch (Exception e) { throw new RuntimeException(e); }
     }
 
-    public void dumpFabric(boolean quiet) {
-        // FIXME: this is really ugly: the order of port declarations in
-        //        the XXXShip.java file must match the order in the .balsa file!
-
-        ArrayList instructionports = new ArrayList<FpgaPump>();
-        for(FpgaShip ship : shiplist)
-            for(Pump port : ship.getPumps())
-                if (!((FpgaPump)port).special())
-                    instructionports.add(port);
-        FabricTree instructions =
-            new FabricTree((FpgaPump[])instructionports.toArray(new FpgaPump[0]),
-                           "ihorn",
-                           "instruction");
-
-        ArrayList inputports = new ArrayList<FpgaPump>();
-        for(FpgaShip ship : shiplist)
-            for(Pump port : ship.getPumps())
-                if (!((FpgaPump)port).special())
-                    inputports.add(port);
-        FabricTree inputs =
-            new FabricTree((FpgaPump[])inputports.toArray(new FpgaPump[0]),
-                           "horn",
-                           "dest");
-
-        ArrayList outputports = new ArrayList<FpgaPump>();
-        for(FpgaShip ship : shiplist)
-            for(Pump port : ship.getPumps())
-                if (!((FpgaPump)port).special() || ((FpgaPump)port).dhorn())
-                    outputports.add(port);
-        FabricTree outputs =
-            new FabricTree((FpgaPump[])outputports.toArray(new FpgaPump[0]),
-                           "funnel",
-                           "source");
-
-        ArrayList ihornports = new ArrayList<FpgaPump>();
-        for(FpgaShip ship : shiplist)
-            for(Pump port : ship.getPumps())
-                if (((FpgaPump)port).ihorn())
-                    ihornports.add(port);
-        FabricTree ihorns =
-            new FabricTree((FpgaPump[])ihornports.toArray(new FpgaPump[0]),
-                           "funnel",
-                           "ihorn");
-
-        if (quiet) return;
-        System.out.println("`include \"macros.v\"");
-        System.out.println("module fabric(clk, rst, data_Memory0_command_r, data_Memory0_command_a, data_Memory0_command,");
-        System.out.println("                   data_Debug0_out_r, data_Debug0_out_a, data_Debug0_out);");
-        System.out.println("  input  clk;");
-        System.out.println("  input  rst;");
-        System.out.println("  input  data_Memory0_command_r;");
-        System.out.println("  output data_Memory0_command_a;");
-        System.out.println("  output data_Debug0_out_r;");
-        System.out.println("  input  data_Debug0_out_a;");
-        System.out.println("  output [(`PACKET_WIDTH-1):0]      data_Debug0_out;");
-        System.out.println("  input  [(`PACKET_WIDTH-1):0]      data_Memory0_command;");
-        //System.out.println("  wire   [(`INSTRUCTION_WIDTH-1):0] data_Memory0_ihorn;");
-        //System.out.println("  wire   [(`PACKET_WIDTH-1):0]      data_Memory0_dhorn;");
-        System.out.println();
-        
-        System.out.println();
-
-        instructions.dumpChannels(true);
-        outputs.dumpChannels(true);
-        inputs.dumpChannels(true);
-        ihorns.dumpChannels(true);
-        for(FpgaShip ship : shiplist)
-            for(Pump port : ship.getPumps())
-                if (!((FpgaPump)port).special() || ((FpgaPump)port).dhorn())
-                    System.out.println("  wire [(`PACKET_WIDTH-1):0] data_"
-                                       +getUniqueName(ship)+"_"+port.getName()+";");
-
-        System.out.println("wire [(`PACKET_WIDTH-1):0] ihornleft;");
-
-        System.out.println("");
-        instructions.dumpChannels(false);
-        System.out.println("");
-        outputs.dumpChannels(false);
-        System.out.println("");
-        inputs.dumpChannels(false);
-        System.out.println("");
-        ihorns.dumpChannels(false);
-        System.out.println("");
-        for(FpgaShip ship : shiplist) {
-            System.out.print(ship.getType().toLowerCase());
-            System.out.print(" ");
-            System.out.print("krunk"+(krunk++));
-            System.out.print("(clk, rst, ");
-            boolean first = true;
-            for(Pump port : ship.getPumps()) {
-                if (!first) System.out.print(", ");
-                first = false;
-                String prefix = "data_";
-                if (((FpgaPump)port).ihorn()) prefix = "ihorn_";
-                if (((FpgaPump)port).dhorn()) prefix = "source_";
-                System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
-                System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
-                System.out.print(prefix+getUniqueName(port.getShip())+"_"+port.getName());
-                System.out.print(" ");
-            }
-            System.out.println(");");
-
-            for(Pump port : ship.getPumps()) {
-                if (((FpgaPump)port).special()) continue;
-                if (((FpgaPump)port).inbox) {
-                    System.out.print("inbox");
-                } else {
-                    System.out.print("outbox");
-                }
-                System.out.print(" krunk"+(krunk++)+"(clk, rst, ");
-                System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
-                System.out.print("instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
-                System.out.print("`packet_data(instruction_"+getUniqueName(port.getShip())+"_"+port.getName()+"), ");
-                System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
-                System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
-                System.out.print("dest_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
-                System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
-                System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
-                System.out.print("source_"+getUniqueName(port.getShip())+"_"+port.getName()+", ");
-                System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_r, ");
-                System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName()+"_a, ");
-                System.out.print("data_"+getUniqueName(port.getShip())+"_"+port.getName());
-                System.out.print(");");
-                System.out.println();
-            }
+    protected BitVector getDestAddr(Path path) {
+        return ((FpgaPath)path).toBitVector();
+    }
 
-        }
+    // Setup //////////////////////////////////////////////////////////////////////////////
 
-        System.out.println("funnel ihornfun(clk, rst, "+
-                           "             ihornleft_r, ihornleft_a, ihornleft,"+
-                           "             ihorn_r, ihorn_a, ihorn,"+
-                           "             source_r, source_a, source);");
-        System.out.println("horn tophorn(clk, rst, "+
-                           "             ihornleft_r, ihornleft_a, ihornleft,"+
-                           "             instruction_r, instruction_a, instruction,"+
-                           "             dest_r, dest_a, dest);");
-        /*
-        System.out.println("assign instruction_r = ihorn_r;");
-        System.out.println("assign ihorn_a = instruction_a;");
-        System.out.println("assign instruction = ihorn;");
-        System.out.println("assign dest_r = source_r;");
-        System.out.println("assign source_a = dest_a;");
-        System.out.println("assign dest = source;");
-        */
-        System.out.println("endmodule");
+    Ship createShip(String type) throws IOException {
+        ShipDescription sd = new ShipDescription(this, type, new BufferedReader(new InputStreamReader(new FileInputStream("ships/"+type+".ship"))));
+        int count = 0;
+        for(Ship ship : ships.values()) if (ship.getType().equals(type)) count++;
+        String name = type+count;
+        FpgaShip ship = new FpgaShip(this, sd);
+        ships.put(name, ship);
+        return ship;
     }
 
-    private static class FabricTree {
-        int master_idx = 1;
-        String prefix;
-        Node root;
-        public void dumpChannels(boolean decl) { root.dumpChannels(0, decl); }
-        public FabricTree(FpgaPump[] ports, String component, String prefix) {
-            this.prefix = prefix;
-            root = (Node)mkNode("", component, ports, 0, ports.length, 0, 0);
-        }
-        private Object mkNode(String name, String component, FpgaPump[] ports,
-                              int start, int end, int addr, int bits) {
-            if (end-start == 0) return null;
-            if (end-start == 1) {
-                FpgaPump p = ports[start];
-                if (prefix.equals("instruction")) {
-                    p.instr_addr = (addr<<1);
-                    p.instr_bits = bits+1;
-                } else if (prefix.equals("dest")) {
-                    p.addr = (addr << 1) | 1;
-                    p.bits = bits+1;
-                    if (bits >= 11)
-                        throw new RuntimeException("too many pumps!");
-                    int count = 0;
-                    for(Destination d : p.getDestinations()) {
-                        if (!(d instanceof FpgaPump.VirtualPort)) continue;
-                        FpgaPump.VirtualPort vp = (FpgaPump.VirtualPort)d;
-                        vp.addr = p.addr | (count << bits);
-                        count++;
-                    }
-                }
-                return p;
-            }
-            int len = end-start;
-            int count   = 0;
-            int count2  = 0;
-            int breakpt = 0;
-            if (end-start <= 2) {
-                breakpt = (start+end)/2;
-            } else {
-                for(int i=start; i<end; i++)
-                    count += count(ports[i].getDestinations());
-                for(int i=start; i<end-1; i++) {
-                    count2 += count(ports[i].getDestinations());
-                    breakpt = i;
-                    if (i>start && count2 >= count/2) break;
-                }
-            }
-            return new Node(name,
-                            component,
-                            mkNode(name+"_0", component, ports, start, breakpt, addr,               bits+1),
-                            mkNode(name+"_1", component, ports, breakpt, end,   addr | (1 << bits), bits+1),
-                            addr,
-                            bits);
-        }
-        private String describe(String prefix, Object o) {
-            if (o==null) return null;
-            if (o instanceof FpgaPump) {
-                FpgaPump p = (FpgaPump)o;
-                return prefix+"_"+getUniqueName(p.getShip())+"_"+p.getName();
-            }
-            if (o instanceof Node) {
-                return ((Node)o).describe(prefix);
-            }
-            return null;
+    public Fpga() throws Exception { this(new Module("main")); }
+    public Fpga(Module top) throws Exception {
+        this.top = top;
+        debugShip = createShip("Debug");
+
+        boolean small = true;
+        //boolean small = false;
+
+        if (small) {
+            for(int i=0; i<2; i++) createShip("Alu");
+            for(int i=0; i<1; i++) createShip("Memory");
+            for(int i=0; i<2; i++) createShip("Fifo");
+            createShip("Counter");
+            createShip("CarrySaveAdder");
+            createShip("Rotator");
+            createShip("Lut3");
+            createShip("Timer");
+            createShip("DDR2");
+            createShip("Dvi");
+
+        } else {
+
+            for(int i=0; i<3; i++)  createShip("Memory");
+            for(int i=0; i<3; i++)  createShip("Alu");
+            for(int i=0; i<2; i++)  createShip("Fifo");
+            for(int i=0; i<14; i++) createShip("Counter");
+
+            /*
+            // "really big" configuration: 138 docks
+            for(int i=0; i<4; i++)  createShip("Alu");
+            */
+
+            //createShip("CarrySaveAdder");
+            //createShip("Rotator");
+            //createShip("Lut3");
+
+            createShip("Timer");
+            createShip("DDR2");
+            createShip("Dvi");
         }
-        private class Node {
-            Object left;
-            Object right;
-            String name;
-            String component;
-            int addr;
-            int bits;
-            public Node(String name, String component, Object left, Object right, int addr, int bits) {
-                this.left = left;
-                this.right = right;
-                this.name = name;
-                this.component = component;
-                this.addr = addr;
-                this.bits = bits;
-            }
-            public void dumpChannels(int indentamount, boolean decl) {
-                String indent = "";
-                for(int i=0; i<indentamount; i++) indent += "  ";
-                if (decl) {
-                    String n = describe(prefix).startsWith("instruction")
-                        ? "[(`PACKET_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
-                    System.out.println("  wire "+n+" "+indent+describe(prefix)+";");
-                } else {
-                    System.out.println("     "+indent+
-                                       component+" "+
-                                       "krunk"+(krunk++)+"(clk, rst, "+
-                                       describe(prefix)+"_r, "+
-                                       describe(prefix)+"_a, "+
-                                       describe(prefix)+", "+
-                                       FabricTree.this.describe(prefix, left)+"_r, "+
-                                       FabricTree.this.describe(prefix, left)+"_a, "+
-                                       FabricTree.this.describe(prefix, left)+", "+
-                                       FabricTree.this.describe(prefix, right)+"_r, "+
-                                       FabricTree.this.describe(prefix, right)+"_a, "+
-                                       FabricTree.this.describe(prefix, right)+
-                                       ");");
-                }
-                dumpChannels(left, indentamount+1, decl);
-                dumpChannels(right, indentamount+1, decl);
-            }
-            public void dumpChannels(Object o, int indentamount, boolean decl) {
-                if (o==null) return;
-                if (o instanceof Node) {
-                    ((Node)o).dumpChannels(indentamount, decl);
+
+        // for FifoShip
+        new Module.InstantiatedModule(top, new FifoModule(8, WIDTH_WORD));
+
+        ArrayList dests   = new ArrayList<FabricElement>();
+        ArrayList sources = new ArrayList<FabricElement>();
+        for(FpgaShip ship : (Iterable<FpgaShip>)(Object)this) {
+            for(Dock port : ship) {
+                if (port.isInputDock()) {
+                    sources.add(((FpgaDock)port));
+                    dests.add(port.getInstructionDestination());
+                    dests.add(port.getDataDestination());
                 } else {
-                    String indent = "";
-                    for(int i=0; i<indentamount; i++) indent += "  ";
-                    if (decl) {
-                        String n = FabricTree.this.describe(prefix,o).startsWith("instruction")
-                            ? "[(`PACKET_WIDTH-1):0]" : "[(`PACKET_WIDTH-1):0]";
-                        System.out.println("  wire "+n+" "+indent+FabricTree.this.describe(prefix,o)+";");
-                    }
+                    sources.add(((FpgaDock)port));
+                    dests.add(port.getInstructionDestination());
+                    dests.add(port.getDataDestination());
                 }
             }
-            public String describe(String prefix) {
-                return prefix+name;
+            for(Module.SourcePort sp0 : ship.docklessPorts.values()) {
+                final Module.SourcePort sp = sp0;
+                sources.add(new FabricElement.AbstractFabricElement() {
+                        private FabricElement upstream;
+                        public int      getPathLength(FpgaDestination dest) { return upstream.getPathLength(dest); }
+                        public FpgaPath getPath(FpgaDestination dest, BitVector signal) { return upstream.getPath(dest, signal); }
+                        public void addOutput(FabricElement out, Module.Port outPort) {
+                            this.upstream = out;
+                            sp.connect((Module.SinkPort)outPort);
+                        }
+                    });
             }
         }
+        FabricElement top_horn = mkNode((FabricElement[])dests.toArray(new FabricElement[0]), true);
+        mkNode((FabricElement[])sources.toArray(new FabricElement[0]), false)
+            .addOutput(top_horn, top_horn.getInputPort());
     }
-    public static int krunk=0;
 
-    private static String getUniqueName(Ship ship) {
-        return ship.getType() + ship.getOrdinal();
+    public FabricElement mkNode(FabricElement[] ports, boolean is_horn) { return mkNode(ports, is_horn, 0, ports.length); }
+    public FabricElement mkNode(FabricElement[] ports, boolean is_horn, int start, int end) {
+        switch(end-start) {
+            case 0: throw new RuntimeException("this should never happen");
+            case 1: return ports[start];
+            default: {
+                FabricElement leftPort  = mkNode(ports, is_horn,  start,         (end+start)/2);
+                FabricElement rightPort = mkNode(ports, is_horn,  (end+start)/2, end);
+                return is_horn
+                    ? new HornModule.HornInstance(this, top,     leftPort, rightPort)
+                    : new FunnelModule.FunnelInstance(this, top, leftPort, rightPort);
+            }
+        }
     }
 
-    private static int count(Iterable<Destination> it) {
-        int ret = 0;
-        for(Destination d : it)
-            ret++;
-        return ret;
-    }
+
+    // Expand //////////////////////////////////////////////////////////////////////////////
 
     public void expand(ShipDescription sd) {
         try {
             if (sd.getSection("fpga")==null) return;
             String filename = sd.getName().toLowerCase();
+
+            if (sd.getSection("ucf") != null) {
+                File outf = new File("build/fpga/"+filename+".ucf");
+                FileOutputStream out = new FileOutputStream(outf);
+                PrintWriter pw = new PrintWriter(out);
+                pw.println(sd.getSection("ucf"));
+                pw.flush();
+                pw.close();
+            }
+
             File outf = new File("build/fpga/"+filename+".v");
             new File(outf.getParent()).mkdirs();
             System.err.println("writing to " + outf);
             FileOutputStream out = new FileOutputStream(outf);
             PrintWriter pw = new PrintWriter(out);
 
-            boolean auto =
-                !"debug".equals(filename) &&
-                !"execute".equals(filename) &&
-                !"memory".equals(filename) &&
-                !"fifo".equals(filename);
+            pw.println("`define WORDWIDTH                "+WIDTH_WORD);
+            pw.println("`define CODEBAG_SIZE_BITS        "+CBD_SIZE.valmaskwidth);
+            pw.println();
 
-            if (auto) {
-                pw.println("`include \"macros.v\"");
-                pw.println();
+            for(DockDescription dd : sd.ports()) {
+                String name = dd.getName();
+                pw.println("`define "+name+"_full    ("+name+"_r && !"+name+"_a)");
+                pw.println("`define "+name+"_empty  (!"+name+"_r && !"+name+"_a)");
+                if (dd.isInputDock()) {
+                    // gets stuck on colliding-tokens
+                    //pw.println("`define drain_"+name+"  if ("+name+"_r && !"+name+"_a) "+name+"_a <= 1;");
+
+                    // gets stuck on colliding-tokens
+                    //pw.println("`define drain_"+name+"  if ("+name+"_r) "+name+"_a <= 1;");
+
+                    // also gets stuck
+                    //pw.println("`define drain_"+name+"  if (!"+name+"_a) "+name+"_a <= 1;");
+                    pw.println("`define drain_"+name+"  "+name+"_a <= 1;");
+                } else {
+                    pw.println("`define fill_"+name+"  "+name+"_r <= 1;");
+                }
+            }
 
             pw.print("`define reset ");
-            for(PumpDescription bb : sd) {
+            for(DockDescription bb : sd.ports()) {
+                String bb_name = bb.getName();
+                if (bb.isInputDock()) pw.print(bb_name+"_a <= 1; ");
+                else                  pw.print(bb_name+"_r <= 0; ");
+            }
+            pw.println();
+
+            pw.print("`define cleanup ");
+
+            // output docks
+            for(DockDescription dd : sd.ports())
+                if (!dd.isInputDock())
+                    pw.print("if ( "+dd.getName()+"_r && "+dd.getName()+"_a) "+dd.getName()+"_r <= 0; ");
+
+            // input docks: if all inputs are flushing, drain them all
+            pw.print("if (1");
+            for(DockDescription bb : sd.ports())
+                if (bb.isInputDock())
+                    pw.print(" && "+bb.getName()+"_f");
+            pw.print(") begin ");
+            for(DockDescription bb : sd.ports())
+                if (bb.isInputDock())
+                    pw.print(bb.getName()+"_a <= 1; ");
+
+            // input docks: if no inputs are flushing, do normal stuff
+            pw.print("end else if (1");
+            for(DockDescription bb : sd.ports())
+                if (bb.isInputDock())
+                    pw.print(" && !"+bb.getName()+"_f");
+            pw.print(") begin ");
+
+            for(DockDescription bb : sd.ports())
+                if (bb.isInputDock())
+                    pw.print("if (!"+bb.getName()+"_r_ && "+bb.getName()+"_a) "+bb.getName()+"_a <= 0; ");
+
+            // input docks: if some-but-not-all inputs are flushing, drain all non-flushing docks
+            pw.print("end else begin ");
+
+            for(DockDescription bb : sd.ports())
+                if (bb.isInputDock()) {
+                    pw.print("if (!"+bb.getName()+"_r && "+bb.getName()+"_a) "+bb.getName()+"_a <= 0; ");
+                    pw.print("if ("+bb.getName()+"_r && !"+bb.getName()+"_a) "+bb.getName()+"_a <= 1; ");
+                }
+
+            pw.print(" end");
+
+            pw.println();
+            
+            pw.println("module " + filename + "( clk, rst ");
+            for(DockDescription bb : sd.ports()) {
                 String bb_name = bb.getName();
-                if (bb.isInbox()) {
-                    pw.print(bb_name+"_a <= 1; ");
+                pw.print("        ");
+                if (bb.isInputDock()) {
+                    pw.print(", " + bb_name+"_r_");
+                    pw.print(", " + bb_name+"_a_");
+                    pw.print(", " + bb_name+"_d");
                 } else {
-                    pw.print(bb_name+"_r <= 0; ");
+                    pw.print(", " + bb_name+"_r_");
+                    pw.print(", " + bb_name+"_a");
+                    pw.print(", " + bb_name+"_d_");
                 }
+                pw.println();
+            }
+            for(PercolatedPort pp : sd.percolatedPorts) {
+                pw.print("    , ");
+                pw.println(pp.name);
             }
+            pw.println("        );");
             pw.println();
+            pw.println("    input clk;");
+            pw.println("    input rst;");
+            for(PercolatedPort pp : sd.percolatedPorts) {
+                switch(pp.type) {
+                    case UP:    pw.print("output"); break;
+                    case DOWN:  pw.print("input");  break;
+                    case INOUT: pw.print("inout");  break;
+                }
+                pw.print("  ");
+                if (pp.width > 1)
+                    pw.print("["+(pp.width-1)+":0]");
+                pw.print(" ");
+                pw.print(pp.name);
+                pw.println(";");
+            }
 
-                pw.println("module " + filename + "( clk, rst ");
-                for(PumpDescription bb : sd) {
-                    String bb_name = bb.getName();
-                    pw.print("        ");
-                    if (bb.isInbox()) {
-                        pw.print(", " + bb_name+"_r");
-                        pw.print(", " + bb_name+"_a_");
-                        pw.print(", " + bb_name+"_d");
-                    } else {
-                        pw.print(", " + bb_name+"_r_");
-                        pw.print(", " + bb_name+"_a");
-                        pw.print(", " + bb_name+"_d_");
-                    }
-                    pw.println();
+            for(DockDescription bb : sd.ports()) {
+                String bb_name = bb.getName();
+                int width = bb.isDockless() ? WIDTH_PACKET : WIDTH_WORD;
+                if (bb.isInputDock()) {
+                    pw.println("        input   ["+width+":0] "+bb_name+"_d;");
+                    pw.println("        input   "+bb_name+"_r_;");
+                    pw.println("        wire    "+bb_name+"_r;");
+                    pw.println("        assign  "+bb_name+"_r = "+bb_name+"_r_ & ~"+bb_name+"_d["+width+"];");
+                    pw.println("        output  "+bb_name+"_a_;");
+                    pw.println("        reg     "+bb_name+"_a;");
+                    pw.println("        initial "+bb_name+"_a  = 0;");
+                    pw.println("        wire    "+bb_name+"_f;");
+                    pw.println("        assign  "+bb_name+"_f  = "+bb_name+"_r_ & "+bb_name+"_d["+width+"] && ~"+bb_name+"_a;");
+                    pw.println("        assign  "+bb_name+"_a_ = "+bb_name+"_a;");
+                } else {
+                    pw.println("        output  ["+width+":0] "+bb_name+"_d_;");
+                    pw.println("        input   "+bb_name+"_a;");
+                    pw.println("        output  "+bb_name+"_r_;");
+                    pw.println("        reg     "+bb_name+"_r;");
+                    pw.println("        initial "+bb_name+"_r  = 0;");
+                    pw.println("        assign  "+bb_name+"_r_ = "+bb_name+"_r;");
                 }
-                pw.println("        );");
                 pw.println();
-                pw.println("    input clk;");
-                pw.println("    input rst;");
-                for(PumpDescription bb : sd) {
-                    String bb_name = bb.getName();
-                    pw.print("        ");
-                    if (bb.isInbox()) {
-                        pw.println("`input(" +
-                                   bb_name+"_r,  "+
-                                   bb_name+"_a,  "+
-                                   bb_name+"_a_, "+
-                                   "[(`PACKET_WIDTH-1):0],"+
-                                   bb_name+"_d)"
-                                   );
-                    } else {
-                        pw.println("`output(" +
-                                   bb_name+"_r,  "+
-                                   bb_name+"_r_, "+
-                                   bb_name+"_a,  "+
-                                   "[(`PACKET_WIDTH-1):0],"+
-                                   bb_name+"_d_)"
-                                   );
-                        pw.println("`defreg(" +
-                                   bb_name+"_d_,  "+
-                                   "[(`PACKET_WIDTH-1):0],"+
-                                   bb_name+"_d)"
-                                   );
-                    }
-                    pw.println();
-                }
             }
 
-            pw.println(sd.getSection("fpga"));
+            if (filename.equals("fifo")) {
+                pw.println("  wire in_a__;");
+                pw.println("  wire out_r__;");
+                pw.println("  fifo8x37 fifo8x37(clk, rst,");
+                pw.println("                    in_r,    in_a__, in_d,");
+                pw.println("                    out_r__, out_a,  out_d_);");
+                pw.println("  always @(posedge clk) begin");
+                pw.println("    if (rst) begin");
+                pw.println("      `reset");
+                pw.println("    end else begin");
+                pw.println("      `cleanup");
+                pw.println("      out_r <= out_r__;");
+                pw.println("      if (in_a__) in_a  <= 1;");
+                pw.println("    end");
+                pw.println("  end");
+            } else {
+                pw.println(sd.getSection("fpga"));
+            }
 
-            if (auto)
-                pw.println("endmodule");
+            pw.println("endmodule");
 
             pw.flush();
             pw.close();
         } catch (Exception e) { throw new RuntimeException(e); }
     }
 
-    public int computeOffset(int origin, int target) { return (target - origin)/6; }
-    public int computeTarget(int origin, int offset) { return origin + (offset*6); }
-
-    private FpgaInstructionEncoder iie = new FpgaInstructionEncoder();
-    public Instruction readInstruction(DataInputStream is) throws IOException { return iie.readInstruction(is); }
-    public Instruction readInstruction(long instr) { return iie.readInstruction(instr); }
-    public long writeInstruction(Instruction d) { return writeInstruction(d); }
-    public void writeInstruction(DataOutputStream os, Instruction d) throws IOException { iie.writeInstruction(os, d); }
-
-    private class FpgaInstructionEncoder extends InstructionEncoder {
-        public long getDestAddr(Destination box) { return ((FpgaPump.VirtualPort)box).addr; }
-        public long getBoxInstAddr(Pump box) { return ((FpgaPump)box).instr_addr; }
-        public Destination getDestByAddr(long dest) {
-            for(Ship ship : Fpga.this)
-                for(Pump bb : ship.getPumps())
-                    for(Destination d : bb.getDestinations())
-                        if (getDestAddr(d)==dest)
-                            return d;
-            return null;
-        }
-        public Pump getBoxByInstAddr(long dest) {
-            for(Ship ship : Fpga.this)
-                for(Pump bb : ship.getPumps())
-                    if (((FpgaPump)bb).instr_addr == dest)
-                        return bb;
-            return null;
-        }
-    }
-
-}
\ No newline at end of file
+}