Merge branch "partner", to simplify partner integration.
authorBen Pfaff <blp@nicira.com>
Mon, 15 Sep 2008 22:31:36 +0000 (15:31 -0700)
committerBen Pfaff <blp@nicira.com>
Mon, 15 Sep 2008 22:31:36 +0000 (15:31 -0700)
65 files changed:
INSTALL
configure.ac
controller/controller.c
datapath/datapath.c
datapath/datapath.h
datapath/dp_dev.c
datapath/flow.c
datapath/forward.c
datapath/forward.h
datapath/hwtable_dummy/hwtable_dummy.c
datapath/linux-2.6/compat-2.6/include/linux/skbuff.h
datapath/linux-2.6/compat-2.6/include/linux/tcp.h
datapath/linux-2.6/compat-2.6/include/linux/workqueue.h [new file with mode: 0644]
datapath/table-hash.c
datapath/table-linear.c
datapath/table.h
ext
include/Makefile.am
include/nicira-ext.h [new file with mode: 0644]
include/openflow.h
include/rconn.h
include/stp.h [new file with mode: 0644]
include/vconn-provider.h
include/vconn-stream.h
include/vconn.h
include/vlog-modules.def
lib/Makefile.am
lib/dpif.c
lib/learning-switch.c
lib/ofp-print.c
lib/rconn.c
lib/stp.c [new file with mode: 0644]
lib/vconn-netlink.c
lib/vconn-ssl.c
lib/vconn-stream.c
lib/vconn-tcp.c
lib/vconn-unix.c
lib/vconn.c
secchan/secchan.8.in
secchan/secchan.c
switch/datapath.c
switch/datapath.h
switch/switch-flow.c
switch/switch.c
switch/table-hash.c
switch/table-linear.c
switch/table.h
tests/Makefile.am
tests/test-stp-ieee802.1d-1998 [new file with mode: 0644]
tests/test-stp-ieee802.1d-2004-fig17.4 [new file with mode: 0644]
tests/test-stp-ieee802.1d-2004-fig17.6 [new file with mode: 0644]
tests/test-stp-ieee802.1d-2004-fig17.7 [new file with mode: 0644]
tests/test-stp-iol-io-1.1 [new file with mode: 0644]
tests/test-stp-iol-io-1.2 [new file with mode: 0644]
tests/test-stp-iol-io-1.4 [new file with mode: 0644]
tests/test-stp-iol-io-1.5 [new file with mode: 0644]
tests/test-stp-iol-op-1.1 [new file with mode: 0644]
tests/test-stp-iol-op-1.4 [new file with mode: 0644]
tests/test-stp-iol-op-3.1 [new file with mode: 0644]
tests/test-stp-iol-op-3.3 [new file with mode: 0644]
tests/test-stp-iol-op-3.4 [new file with mode: 0644]
tests/test-stp.c [new file with mode: 0644]
tests/test-stp.sh [new file with mode: 0755]
utilities/dpctl.8
utilities/dpctl.c

diff --git a/INSTALL b/INSTALL
index 3ade549..9163526 100644 (file)
--- a/INSTALL
+++ b/INSTALL
@@ -562,9 +562,11 @@ Establishing a Public Key Infrastructure
 
 If you do not have a PKI, the ofp-pki script included with OpenFlow
 can help.  To create an initial PKI structure, invoke it as:
-      % ofp-pki new-pki
-which will create and populate a new directory named "pki" under the
-current directory.
+      % ofp-pki init
+which will create and populate a new PKI directory.  The default
+location for the PKi directory depends on how the OpenFlow tree was
+configured (to see the configured default, look for the --dir option
+description in the output of "ofp-pki --help").
 
 The pki directory contains two important subdirectories.  The
 controllerca subdirectory contains controller certificate authority
index 570c7de..1505c6b 100644 (file)
@@ -57,7 +57,7 @@ AC_SUBST(KARCH)
 OFP_CHECK_LINUX(l26, 2.6, 2.6, KSRC26, L26_ENABLED)
 OFP_CHECK_LINUX(l24, 2.4, 2.4, KSRC24, L24_ENABLED)
 
-CFLAGS="$CFLAGS -Wall -Wno-sign-compare -Wpointer-arith"
+CFLAGS="$CFLAGS -Wall -Wno-sign-compare"
 
 OFP_ENABLE_EXT
 
index a3ce2bd..1bed5c6 100644 (file)
@@ -84,7 +84,7 @@ int
 main(int argc, char *argv[])
 {
     struct switch_ switches[MAX_SWITCHES];
-    struct vconn *listeners[MAX_LISTENERS];
+    struct pvconn *listeners[MAX_LISTENERS];
     int n_switches, n_listeners;
     int retval;
     int i;
@@ -112,22 +112,25 @@ main(int argc, char *argv[])
         struct vconn *vconn;
         int retval;
 
-        retval = vconn_open(name, &vconn);
-        if (retval) {
-            VLOG_ERR("%s: connect: %s", name, strerror(retval));
-            continue;
-        }
-
-        if (vconn_is_passive(vconn)) {
-            if (n_listeners >= MAX_LISTENERS) {
-                ofp_fatal(0, "max %d passive connections", n_listeners);
-            }
-            listeners[n_listeners++] = vconn;
-        } else {
+        retval = vconn_open(name, OFP_VERSION, &vconn);
+        if (!retval) {
             if (n_switches >= MAX_SWITCHES) {
                 ofp_fatal(0, "max %d switch connections", n_switches);
             }
             new_switch(&switches[n_switches++], vconn, name);
+            continue;
+        } else if (retval == EAFNOSUPPORT) {
+            struct pvconn *pvconn;
+            retval = pvconn_open(name, &pvconn);
+            if (!retval) {
+                if (n_listeners >= MAX_LISTENERS) {
+                    ofp_fatal(0, "max %d passive connections", n_listeners);
+                }
+                listeners[n_listeners++] = pvconn;
+            }
+        }
+        if (retval) {
+            VLOG_ERR("%s: connect: %s", name, strerror(retval));
         }
     }
     if (n_switches == 0 && n_listeners == 0) {
@@ -146,14 +149,14 @@ main(int argc, char *argv[])
             struct vconn *new_vconn;
             int retval;
 
-            retval = vconn_accept(listeners[i], &new_vconn);
+            retval = pvconn_accept(listeners[i], OFP_VERSION, &new_vconn);
             if (!retval || retval == EAGAIN) {
                 if (!retval) {
                     new_switch(&switches[n_switches++], new_vconn, "tcp");
                 }
                 i++;
             } else {
-                vconn_close(listeners[i]);
+                pvconn_close(listeners[i]);
                 listeners[i] = listeners[--n_listeners];
             }
         }
@@ -184,7 +187,7 @@ main(int argc, char *argv[])
         /* Wait for something to happen. */
         if (n_switches < MAX_SWITCHES) {
             for (i = 0; i < n_listeners; i++) {
-                vconn_accept_wait(listeners[i]);
+                pvconn_wait(listeners[i]);
             }
         }
         for (i = 0; i < n_switches; i++) {
index d405fc1..8eb0660 100644 (file)
@@ -65,30 +65,10 @@ MODULE_PARM(serial_num, "s");
 /* Number of milliseconds between runs of the maintenance thread. */
 #define MAINT_SLEEP_MSECS 1000
 
-enum br_port_flags {
-       BRPF_NO_FLOOD = 1 << 0,
-};
-
-enum br_port_status {
-       BRPS_PORT_DOWN = 1 << 0,
-       BRPS_LINK_DOWN = 1 << 1,
-};
-
 #define UINT32_MAX                       4294967295U
 #define UINT16_MAX                       65535
 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
 
-struct net_bridge_port {
-       u16     port_no;
-       u32 flags;             /* BRPF_* flags */
-       u32 status;            /* BRPS_* flags */
-       spinlock_t lock;
-       struct work_struct port_task;
-       struct datapath *dp;
-       struct net_device *dev;
-       struct list_head node; /* Element in datapath.ports. */
-};
-
 static struct genl_family dp_genl_family;
 static struct genl_multicast_group mc_group;
 
@@ -485,7 +465,7 @@ do_port_input(struct net_bridge_port *p, struct sk_buff *skb)
 {
        /* Push the Ethernet header back on. */
        skb_push(skb, ETH_HLEN);
-       fwd_port_input(p->dp->chain, skb, p->port_no);
+       fwd_port_input(p->dp->chain, skb, p);
 }
 
 /*
@@ -537,7 +517,7 @@ static inline unsigned packet_length(const struct sk_buff *skb)
 static int
 output_all(struct datapath *dp, struct sk_buff *skb, int flood)
 {
-       u32 disable = flood ? BRPF_NO_FLOOD : 0;
+       u32 disable = flood ? OFPPFL_NO_FLOOD : 0;
        struct net_bridge_port *p;
        int prev_port = -1;
 
@@ -550,12 +530,12 @@ output_all(struct datapath *dp, struct sk_buff *skb, int flood)
                                kfree_skb(skb);
                                return -ENOMEM;
                        }
-                       dp_output_port(dp, clone, prev_port); 
+                       dp_output_port(dp, clone, prev_port, 0); 
                }
                prev_port = p->port_no;
        }
        if (prev_port != -1)
-               dp_output_port(dp, skb, prev_port);
+               dp_output_port(dp, skb, prev_port, 0);
        else
                kfree_skb(skb);
 
@@ -594,7 +574,8 @@ static int xmit_skb(struct sk_buff *skb)
 
 /* Takes ownership of 'skb' and transmits it to 'out_port' on 'dp'.
  */
-int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
+int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port,
+                  int ignore_no_fwd)
 {
        BUG_ON(!skb);
        switch (out_port){
@@ -610,10 +591,8 @@ int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
                return xmit_skb(skb);
                
        case OFPP_TABLE: {
-               struct net_bridge_port *p = skb->dev->br_port;
-               int retval;
-               retval = run_flow_through_tables(dp->chain, skb,
-                                                p ? p->port_no : OFPP_LOCAL);
+               int retval = run_flow_through_tables(dp->chain, skb,
+                                                    skb->dev->br_port);
                if (retval)
                        kfree_skb(skb);
                return retval;
@@ -645,6 +624,10 @@ int dp_output_port(struct datapath *dp, struct sk_buff *skb, int out_port)
                                printk("can't directly forward to input port\n");
                        return -EINVAL;
                }
+               if (p->flags & OFPPFL_NO_FWD && !ignore_no_fwd) {
+                       kfree_skb(skb);
+                       return 0;
+               }
                skb->dev = p->dev; 
                return xmit_skb(skb);
        }
@@ -713,13 +696,15 @@ static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
        desc->features = 0;
        desc->speed = 0;
 
+       if (p->port_no < 255) {
+               /* FIXME: this is a layering violation and should really be
+                * done in the secchan, as with OFPC_STP in
+                * OFP_SUPPORTED_CAPABILITIES. */
+               desc->features |= OFPPF_STP;
+       }
+
        spin_lock_irqsave(&p->lock, flags);
-       if (p->flags & BRPF_NO_FLOOD) 
-               desc->flags |= htonl(OFPPFL_NO_FLOOD);
-       else if (p->status & BRPS_PORT_DOWN)
-               desc->flags |= htonl(OFPPFL_PORT_DOWN);
-       else if (p->status & BRPS_LINK_DOWN)
-               desc->flags |= htonl(OFPPFL_LINK_DOWN);
+       desc->flags = htonl(p->flags | p->status);
        spin_unlock_irqrestore(&p->lock, flags);
 
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,24)
@@ -743,11 +728,11 @@ static void fill_port_desc(struct net_bridge_port *p, struct ofp_phy_port *desc)
                        if (ecmd.supported & SUPPORTED_10000baseT_Full)
                                desc->features |= OFPPF_10GB_FD;
 
-                       desc->features = htonl(desc->features);
                        desc->speed = htonl(ecmd.speed);
                }
        }
 #endif
+       desc->features = htonl(desc->features);
 }
 
 static int 
@@ -756,15 +741,13 @@ fill_features_reply(struct datapath *dp, struct ofp_switch_features *ofr)
        struct net_bridge_port *p;
        int port_count = 0;
 
-       ofr->datapath_id    = cpu_to_be64(dp->id); 
+       ofr->datapath_id  = cpu_to_be64(dp->id); 
 
-       ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
-       ofr->n_compression  = 0;                                           /* Not supported */
-       ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
-       ofr->buffer_mb      = htonl(UINT32_MAX);
-       ofr->n_buffers      = htonl(N_PKT_BUFFERS);
-       ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
-       ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
+       ofr->n_buffers    = htonl(N_PKT_BUFFERS);
+       ofr->n_tables     = dp->chain->n_tables;
+       ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
+       ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
+       memset(ofr->pad, 0, sizeof ofr->pad);
 
        list_for_each_entry_rcu (p, &dp->port_list, node) {
                fill_port_desc(p, &ofr->ports[port_count]);
@@ -815,6 +798,29 @@ dp_send_config_reply(struct datapath *dp, const struct sender *sender)
        return send_openflow_skb(skb, sender);
 }
 
+int
+dp_send_hello(struct datapath *dp, const struct sender *sender,
+             const struct ofp_header *request)
+{
+       if (request->version < OFP_VERSION) {
+               char err[64];
+               sprintf(err, "Only version 0x%02x supported", OFP_VERSION);
+               dp_send_error_msg(dp, sender, OFPET_HELLO_FAILED,
+                                 OFPHFC_INCOMPATIBLE, err, strlen(err));
+               return -EINVAL;
+       } else {
+               struct sk_buff *skb;
+               struct ofp_header *reply;
+
+               reply = alloc_openflow_skb(dp, sizeof *reply,
+                                          OFPT_HELLO, sender, &skb);
+               if (!reply)
+                       return -ENOMEM;
+
+               return send_openflow_skb(skb, sender);
+       }
+}
+
 /* Callback function for a workqueue to disable an interface */
 static void
 down_port_cb(struct work_struct *work)
@@ -827,7 +833,7 @@ down_port_cb(struct work_struct *work)
                if (net_ratelimit())
                        printk("problem bringing up port %s\n", p->dev->name);
        rtnl_unlock();
-       p->status |= BRPS_PORT_DOWN;
+       p->status |= OFPPFL_PORT_DOWN;
 }
 
 /* Callback function for a workqueue to enable an interface */
@@ -842,7 +848,7 @@ up_port_cb(struct work_struct *work)
                if (net_ratelimit())
                        printk("problem bringing down port %s\n", p->dev->name);
        rtnl_unlock();
-       p->status &= ~BRPS_PORT_DOWN;
+       p->status &= ~OFPPFL_PORT_DOWN;
 }
 
 int
@@ -854,16 +860,17 @@ dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
        struct net_bridge_port *p = (port_no < OFPP_MAX ? dp->ports[port_no]
                                     : port_no == OFPP_LOCAL ? dp->local_port
                                     : NULL);
+       uint32_t flag_mask;
+
        /* Make sure the port id hasn't changed since this was sent */
        if (!p || memcmp(opp->hw_addr, p->dev->dev_addr, ETH_ALEN))
                return -1;
 
        spin_lock_irqsave(&p->lock, flags);
-       if (opm->mask & htonl(OFPPFL_NO_FLOOD)) {
-               if (opp->flags & htonl(OFPPFL_NO_FLOOD))
-                       p->flags |= BRPF_NO_FLOOD;
-               else 
-                       p->flags &= ~BRPF_NO_FLOOD;
+       flag_mask = ntohl(opm->mask) & PORT_FLAG_BITS;
+       if (flag_mask) {
+               p->flags &= ~flag_mask;
+               p->flags |= ntohl(opp->flags) & flag_mask;
        }
 
        /* Modifying the status of an interface requires taking a lock
@@ -872,11 +879,11 @@ dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
         * context. */
        if (opm->mask & htonl(OFPPFL_PORT_DOWN)) {
                if ((opp->flags & htonl(OFPPFL_PORT_DOWN))
-                                       && (p->status & BRPS_PORT_DOWN) == 0) {
+                   && (p->status & OFPPFL_PORT_DOWN) == 0) {
                        PREPARE_WORK(&p->port_task, down_port_cb);
                        schedule_work(&p->port_task);
                } else if ((opp->flags & htonl(OFPPFL_PORT_DOWN)) == 0
-                                       && (p->status & BRPS_PORT_DOWN)) {
+                          && (p->status & OFPPFL_PORT_DOWN)) {
                        PREPARE_WORK(&p->port_task, up_port_cb);
                        schedule_work(&p->port_task);
                }
@@ -902,14 +909,14 @@ update_port_status(struct net_bridge_port *p)
        orig_status = p->status;
 
        if (p->dev->flags & IFF_UP) 
-               p->status &= ~BRPS_PORT_DOWN;
+               p->status &= ~OFPPFL_PORT_DOWN;
        else
-               p->status |= BRPS_PORT_DOWN;
+               p->status |= OFPPFL_PORT_DOWN;
 
        if (netif_carrier_ok(p->dev))
-               p->status &= ~BRPS_LINK_DOWN;
+               p->status &= ~OFPPFL_LINK_DOWN;
        else
-               p->status |= BRPS_LINK_DOWN;
+               p->status |= OFPPFL_LINK_DOWN;
 
        spin_unlock_irqrestore(&p->lock, flags);
        return (orig_status != p->status);
@@ -963,13 +970,13 @@ EXPORT_SYMBOL(dp_send_flow_expired);
 
 int
 dp_send_error_msg(struct datapath *dp, const struct sender *sender, 
-               uint16_t type, uint16_t code, const uint8_t *data, size_t len)
+               uint16_t type, uint16_t code, const void *data, size_t len)
 {
        struct sk_buff *skb;
        struct ofp_error_msg *oem;
 
 
-       oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR_MSG
+       oem = alloc_openflow_skb(dp, sizeof(*oem)+len, OFPT_ERROR, 
                        sender, &skb);
        if (!oem)
                return -ENOMEM;
@@ -1415,6 +1422,7 @@ static int table_stats_dump(struct datapath *dp, void *state,
                dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
                strncpy(ots->name, stats.name, sizeof ots->name);
                ots->table_id = i;
+               ots->wildcards = htonl(stats.wildcards);
                memset(ots->pad, 0, sizeof ots->pad);
                ots->max_entries = htonl(stats.max_flows);
                ots->active_count = htonl(stats.n_flows);
@@ -1565,6 +1573,8 @@ dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
         * struct genl_ops.  This kluge supports earlier versions also. */
        cb->done = dp_genl_openflow_done;
 
+       sender.pid = NETLINK_CB(cb->skb).pid;
+       sender.seq = cb->nlh->nlmsg_seq;
        if (!cb->args[0]) {
                struct nlattr *attrs[DP_GENL_A_MAX + 1];
                struct ofp_stats_request *rq;
@@ -1590,13 +1600,22 @@ dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
                        return -EINVAL;
 
                rq = nla_data(va);
+               sender.xid = rq->header.xid;
                type = ntohs(rq->type);
-               if (rq->header.version != OFP_VERSION
-                   || rq->header.type != OFPT_STATS_REQUEST
-                   || ntohs(rq->header.length) != len
-                   || type >= ARRAY_SIZE(stats)
-                   || !stats[type].dump)
+               if (rq->header.version != OFP_VERSION) {
+                       dp_send_error_msg(dp, &sender, OFPET_BAD_REQUEST,
+                                         OFPBRC_BAD_VERSION, rq, len);
                        return -EINVAL;
+               }
+               if (rq->header.type != OFPT_STATS_REQUEST
+                   || ntohs(rq->header.length) != len)
+                       return -EINVAL;
+
+               if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
+                       dp_send_error_msg(dp, &sender, OFPET_BAD_REQUEST,
+                                         OFPBRC_BAD_STAT, rq, len);
+                       return -EINVAL;
+               }
 
                s = &stats[type];
                body_len = len - offsetof(struct ofp_stats_request, body);
@@ -1615,6 +1634,7 @@ dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
                        cb->args[4] = (long) state;
                }
        } else if (cb->args[0] == 1) {
+               sender.xid = cb->args[3];
                dp_idx = cb->args[1];
                s = &stats[cb->args[2]];
 
@@ -1625,10 +1645,6 @@ dp_genl_openflow_dumpit(struct sk_buff *skb, struct netlink_callback *cb)
                return 0;
        }
 
-       sender.xid = cb->args[3];
-       sender.pid = NETLINK_CB(cb->skb).pid;
-       sender.seq = cb->nlh->nlmsg_seq;
-
        osr = put_openflow_headers(dp, skb, OFPT_STATS_REPLY, &sender,
                                   &max_openflow_len);
        if (IS_ERR(osr))
index 44a3b69..0b26b4a 100644 (file)
@@ -6,6 +6,7 @@
 #include <linux/mutex.h>
 #include <linux/netlink.h>
 #include <linux/netdevice.h>
+#include <linux/workqueue.h>
 #include <linux/skbuff.h>
 #include "openflow.h"
 #include "flow.h"
@@ -23,6 +24,7 @@
 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
                | OFPC_TABLE_STATS \
                | OFPC_PORT_STATS \
+               | OFPC_STP \
                | OFPC_MULTI_PHY_TX )
 
 /* Actions supported by this implementation. */
@@ -68,9 +70,24 @@ struct sender {
        uint32_t seq;           /* Netlink sequence ID of request. */
 };
 
+#define PORT_STATUS_BITS (OFPPFL_PORT_DOWN | OFPPFL_LINK_DOWN)
+#define PORT_FLAG_BITS (~PORT_STATUS_BITS)
+
+struct net_bridge_port {
+       u16     port_no;
+       u32 flags;              /* Some subset of PORT_FLAG_BITS. */
+       u32 status;             /* Some subset of PORT_STATUS_BITS. */
+       spinlock_t lock;
+       struct work_struct port_task;
+       struct datapath *dp;
+       struct net_device *dev;
+       struct list_head node; /* Element in datapath.ports. */
+};
+
 extern struct mutex dp_mutex;
 
-int dp_output_port(struct datapath *, struct sk_buff *, int out_port);
+int dp_output_port(struct datapath *, struct sk_buff *, int out_port,
+                  int ignore_no_fwd);
 int dp_output_control(struct datapath *, struct sk_buff *, uint32_t, 
                        size_t, int);
 int dp_set_origin(struct datapath *, uint16_t, struct sk_buff *);
@@ -79,10 +96,12 @@ int dp_send_config_reply(struct datapath *, const struct sender *);
 int dp_send_flow_expired(struct datapath *, struct sw_flow *,
                         enum ofp_flow_expired_reason);
 int dp_send_error_msg(struct datapath *, const struct sender *, 
-                       uint16_t, uint16_t, const uint8_t *, size_t);
+                       uint16_t, uint16_t, const void *, size_t);
 int dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
 int dp_send_echo_reply(struct datapath *, const struct sender *,
                       const struct ofp_header *);
+int dp_send_hello(struct datapath *, const struct sender *,
+                 const struct ofp_header *);
 
 /* Should hold at least RCU read lock when calling */
 struct datapath *dp_get(int dp_idx);
index 4601852..195accb 100644 (file)
@@ -3,6 +3,7 @@
 #include <linux/etherdevice.h>
 #include <linux/rcupdate.h>
 #include <linux/skbuff.h>
+#include <linux/workqueue.h>
 
 #include "datapath.h"
 #include "forward.h"
 struct dp_dev {
        struct net_device_stats stats;
        struct datapath *dp;
+       struct sk_buff_head xmit_queue;
+       struct work_struct xmit_work;
 };
 
+
 static struct dp_dev *dp_dev_priv(struct net_device *netdev) 
 {
        return netdev_priv(netdev);
@@ -60,14 +64,37 @@ static int dp_dev_xmit(struct sk_buff *skb, struct net_device *netdev)
        dp_dev->stats.tx_packets++;
        dp_dev->stats.tx_bytes += skb->len;
 
-       skb_reset_mac_header(skb);
-       rcu_read_lock();
-       fwd_port_input(dp->chain, skb, OFPP_LOCAL);
-       rcu_read_unlock();
+       if (skb_queue_len(&dp_dev->xmit_queue) >= dp->netdev->tx_queue_len) {
+               /* Queue overflow.  Stop transmitter. */
+               netif_stop_queue(dp->netdev);
+
+               /* We won't see all dropped packets individually, so overrun
+                * error is appropriate. */
+               dp_dev->stats.tx_fifo_errors++;
+       }
+       skb_queue_tail(&dp_dev->xmit_queue, skb);
+       dp->netdev->trans_start = jiffies;
+
+       schedule_work(&dp_dev->xmit_work);
 
        return 0;
 }
 
+static void dp_dev_do_xmit(struct work_struct *work)
+{
+       struct dp_dev *dp_dev = container_of(work, struct dp_dev, xmit_work);
+       struct datapath *dp = dp_dev->dp;
+       struct sk_buff *skb;
+
+       while ((skb = skb_dequeue(&dp_dev->xmit_queue)) != NULL) {
+               skb_reset_mac_header(skb);
+               rcu_read_lock();
+               fwd_port_input(dp->chain, skb, dp->local_port);
+               rcu_read_unlock();
+       }
+       netif_wake_queue(dp->netdev);
+}
+
 static int dp_dev_open(struct net_device *netdev)
 {
        netif_start_queue(netdev);
@@ -89,7 +116,7 @@ do_setup(struct net_device *netdev)
        netdev->hard_start_xmit = dp_dev_xmit;
        netdev->open = dp_dev_open;
        netdev->stop = dp_dev_stop;
-       netdev->tx_queue_len = 0;
+       netdev->tx_queue_len = 100;
        netdev->set_mac_address = dp_dev_mac_addr;
 
        netdev->flags = IFF_BROADCAST | IFF_MULTICAST;
@@ -121,14 +148,19 @@ int dp_dev_setup(struct datapath *dp)
 
        dp_dev = dp_dev_priv(netdev);
        dp_dev->dp = dp;
+       skb_queue_head_init(&dp_dev->xmit_queue);
+       INIT_WORK(&dp_dev->xmit_work, dp_dev_do_xmit);
        dp->netdev = netdev;
        return 0;
 }
 
 void dp_dev_destroy(struct datapath *dp)
 {
+       struct dp_dev *dp_dev = dp_dev_priv(dp->netdev);
+
        netif_tx_disable(dp->netdev);
        synchronize_net();
+       skb_queue_purge(&dp_dev->xmit_queue);
        unregister_netdev(dp->netdev);
        free_netdev(dp->netdev);
 }
index a2c96ab..71dd823 100644 (file)
@@ -187,7 +187,8 @@ void flow_free(struct sw_flow *flow)
 {
        if (unlikely(!flow))
                return;
-       kfree(flow->actions);
+       if (flow->actions)
+               kfree(flow->actions);
        kmem_cache_free(flow_cache, flow);
 }
 EXPORT_SYMBOL(flow_free);
index 239e801..4334655 100644 (file)
@@ -4,6 +4,8 @@
  * Stanford Junior University
  */
 
+#include <linux/netdevice.h>
+#include <linux/etherdevice.h>
 #include <linux/if_ether.h>
 #include <linux/if_vlan.h>
 #include <linux/in.h>
@@ -26,59 +28,70 @@ static int make_writable(struct sk_buff **);
 static struct sk_buff *retrieve_skb(uint32_t id);
 static void discard_skb(uint32_t id);
 
-/* 'skb' was received on 'in_port', a physical switch port between 0 and
- * OFPP_MAX.  Process it according to 'chain'.  Returns 0 if successful, in
- * which case 'skb' is destroyed, or -ESRCH if there is no matching flow, in
- * which case 'skb' still belongs to the caller. */
+/* 'skb' was received on port 'p', which may be a physical switch port, the
+ * local port, or a null pointer.  Process it according to 'chain'.  Returns 0
+ * if successful, in which case 'skb' is destroyed, or -ESRCH if there is no
+ * matching flow, in which case 'skb' still belongs to the caller. */
 int run_flow_through_tables(struct sw_chain *chain, struct sk_buff *skb,
-                           int in_port)
+                           struct net_bridge_port *p)
 {
+       /* Ethernet address used as the destination for STP frames. */
+       static const uint8_t stp_eth_addr[ETH_ALEN]
+               = { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x01 };
        struct sw_flow_key key;
        struct sw_flow *flow;
 
-       if (flow_extract(skb, in_port, &key)
+       if (flow_extract(skb, p ? p->port_no : OFPP_NONE, &key)
            && (chain->dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
                /* Drop fragment. */
                kfree_skb(skb);
                return 0;
        }
+       if (p && p->flags & (OFPPFL_NO_RECV | OFPPFL_NO_RECV_STP) &&
+           p->flags & (compare_ether_addr(key.dl_dst, stp_eth_addr)
+                       ? OFPPFL_NO_RECV : OFPPFL_NO_RECV_STP)) {
+               kfree_skb(skb);
+               return 0;
+       }
 
        flow = chain_lookup(chain, &key);
        if (likely(flow != NULL)) {
                flow_used(flow, skb);
                execute_actions(chain->dp, skb, &key,
-                               flow->actions, flow->n_actions);
+                               flow->actions, flow->n_actions, 0);
                return 0;
        } else {
                return -ESRCH;
        }
 }
 
-/* 'skb' was received on 'in_port', a physical switch port between 0 and
- * OFPP_MAX.  Process it according to 'chain', sending it up to the controller
- * if no flow matches.  Takes ownership of 'skb'. */
-void fwd_port_input(struct sw_chain *chain, struct sk_buff *skb, int in_port)
+/* 'skb' was received on port 'p', which may be a physical switch port, the
+ * local port, or a null pointer.  Process it according to 'chain', sending it
+ * up to the controller if no flow matches.  Takes ownership of 'skb'. */
+void fwd_port_input(struct sw_chain *chain, struct sk_buff *skb,
+                   struct net_bridge_port *p)
 {
-       if (run_flow_through_tables(chain, skb, in_port))
+       if (run_flow_through_tables(chain, skb, p))
                dp_output_control(chain->dp, skb, fwd_save_skb(skb), 
                                  chain->dp->miss_send_len,
                                  OFPR_NO_MATCH);
 }
 
 static int do_output(struct datapath *dp, struct sk_buff *skb, size_t max_len,
-                       int out_port)
+                    int out_port, int ignore_no_fwd)
 {
        if (!skb)
                return -ENOMEM;
        return (likely(out_port != OFPP_CONTROLLER)
-               ? dp_output_port(dp, skb, out_port)
+               ? dp_output_port(dp, skb, out_port, ignore_no_fwd)
                : dp_output_control(dp, skb, fwd_save_skb(skb),
                                         max_len, OFPR_ACTION));
 }
 
 void execute_actions(struct datapath *dp, struct sk_buff *skb,
-                               const struct sw_flow_key *key,
-                               const struct ofp_action *actions, int n_actions)
+                    const struct sw_flow_key *key,
+                    const struct ofp_action *actions, int n_actions,
+                    int ignore_no_fwd)
 {
        /* Every output action needs a separate clone of 'skb', but the common
         * case is just a single output action, so that doing a clone and
@@ -97,7 +110,7 @@ void execute_actions(struct datapath *dp, struct sk_buff *skb,
 
                if (prev_port != -1) {
                        do_output(dp, skb_clone(skb, GFP_ATOMIC),
-                                 max_len, prev_port);
+                                 max_len, prev_port, ignore_no_fwd);
                        prev_port = -1;
                }
 
@@ -119,7 +132,7 @@ void execute_actions(struct datapath *dp, struct sk_buff *skb,
                }
        }
        if (prev_port != -1)
-               do_output(dp, skb, max_len, prev_port);
+               do_output(dp, skb, max_len, prev_port, ignore_no_fwd);
        else
                kfree_skb(skb);
 }
@@ -287,6 +300,13 @@ struct sk_buff *execute_setter(struct sk_buff *skb, uint16_t eth_proto,
        return skb;
 }
 
+static int
+recv_hello(struct sw_chain *chain, const struct sender *sender,
+          const void *msg)
+{
+       return dp_send_hello(chain->dp, sender, msg);
+}
+
 static int
 recv_features_request(struct sw_chain *chain, const struct sender *sender,
                      const void *msg) 
@@ -367,7 +387,7 @@ recv_packet_out(struct sw_chain *chain, const struct sender *sender,
        dp_set_origin(chain->dp, ntohs(opo->in_port), skb);
 
        flow_extract(skb, ntohs(opo->in_port), &key);
-       execute_actions(chain->dp, skb, &key, opo->actions, n_actions);
+       execute_actions(chain->dp, skb, &key, opo->actions, n_actions, 1);
 
        return 0;
 }
@@ -452,7 +472,7 @@ add_flow(struct sw_chain *chain, const struct ofp_flow_mod *ofm)
                        struct sw_flow_key key;
                        flow_used(flow, skb);
                        flow_extract(skb, ntohs(ofm->match.in_port), &key);
-                       execute_actions(chain->dp, skb, &key, ofm->actions, n_actions);
+                       execute_actions(chain->dp, skb, &key, ofm->actions, n_actions, 0);
                }
                else
                        error = -ESRCH;
@@ -504,6 +524,10 @@ fwd_control_input(struct sw_chain *chain, const struct sender *sender,
        };
 
        static const struct openflow_packet packets[] = {
+               [OFPT_HELLO] = {
+                       sizeof (struct ofp_header),
+                       recv_hello,
+               },
                [OFPT_FEATURES_REQUEST] = {
                        sizeof (struct ofp_header),
                        recv_features_request,
@@ -538,21 +562,34 @@ fwd_control_input(struct sw_chain *chain, const struct sender *sender,
                },
        };
 
-       const struct openflow_packet *pkt;
        struct ofp_header *oh;
 
        oh = (struct ofp_header *) msg;
-       if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
-               || ntohs(oh->length) > length)
+       if (oh->version != OFP_VERSION
+           && oh->type != OFPT_HELLO
+           && oh->type != OFPT_ERROR
+           && oh->type != OFPT_ECHO_REQUEST
+           && oh->type != OFPT_ECHO_REPLY
+           && oh->type != OFPT_VENDOR)
+       {
+               dp_send_error_msg(chain->dp, sender, OFPET_BAD_REQUEST,
+                                 OFPBRC_BAD_VERSION, msg, length);
+               return -EINVAL;
+       }
+       if (ntohs(oh->length) > length)
                return -EINVAL;
 
-       pkt = &packets[oh->type];
-       if (!pkt->handler)
-               return -ENOSYS;
-       if (length < pkt->min_size)
-               return -EFAULT;
-
-       return pkt->handler(chain, sender, msg);
+       if (oh->type < ARRAY_SIZE(packets)) {
+               const struct openflow_packet *pkt = &packets[oh->type];
+               if (pkt->handler) {
+                       if (length < pkt->min_size)
+                               return -EFAULT;
+                       return pkt->handler(chain, sender, msg);
+               }
+       }
+       dp_send_error_msg(chain->dp, sender, OFPET_BAD_REQUEST,
+                         OFPBRC_BAD_TYPE, msg, length);
+       return -EINVAL;
 }
 
 /* Packet buffering. */
index 90288d0..73152f9 100644 (file)
@@ -22,8 +22,10 @@ struct sender;
 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
 
 
-void fwd_port_input(struct sw_chain *, struct sk_buff *, int in_port);
-int run_flow_through_tables(struct sw_chain *, struct sk_buff *, int in_port);
+void fwd_port_input(struct sw_chain *, struct sk_buff *,
+                   struct net_bridge_port *);
+int run_flow_through_tables(struct sw_chain *, struct sk_buff *,
+                           struct net_bridge_port *);
 int fwd_control_input(struct sw_chain *, const struct sender *,
                      const void *, size_t);
 
@@ -33,8 +35,9 @@ void fwd_discard_all(void);
 void fwd_exit(void);
 
 void execute_actions(struct datapath *, struct sk_buff *,
-                       const struct sw_flow_key *, 
-                       const struct ofp_action *, int n_actions);
+                    const struct sw_flow_key *, 
+                    const struct ofp_action *, int n_actions,
+                    int ignore_no_fwd);
 struct sk_buff *execute_setter(struct sk_buff *, uint16_t,
                        const struct sw_flow_key *, const struct ofp_action *);
 
index 6f21e1d..e3e0eb4 100644 (file)
@@ -105,6 +105,7 @@ static int do_delete(struct sw_table *swt, struct sw_flow *flow)
         */
        list_del_rcu(&flow->node);
        list_del_rcu(&flow->iter_node);
+       flow_deferred_free(flow);
        return 1;
 }
 
@@ -190,12 +191,12 @@ static int table_dummy_iterate(struct sw_table *swt,
                               int (*callback)(struct sw_flow *, void *),
                               void *private)
 {
-       struct sw_table_dummy *tl = (struct sw_table_dummy *) swt;
+       struct sw_table_dummy *td = (struct sw_table_dummy *) swt;
        struct sw_flow *flow;
        unsigned long start;
 
        start = ~position->private[0];
-       list_for_each_entry (flow, &tl->iter_flows, iter_node) {
+       list_for_each_entry (flow, &td->iter_flows, iter_node) {
                if (flow->serial <= start && flow_matches_2wild(key,
                                                                &flow->key)) {
                        int error = callback(flow, private);
@@ -213,8 +214,10 @@ static void table_dummy_stats(struct sw_table *swt,
 {
        struct sw_table_dummy *td = (struct sw_table_dummy *) swt;
        stats->name = "dummy";
-       stats->n_flows = td->n_flows;
+       stats->wildcards = OFPFW_ALL;      /* xxx Set this appropriately */
+       stats->n_flows   = td->n_flows;
        stats->max_flows = td->max_flows;
+       stats->n_matched = swt->n_matched;
 }
 
 
index 878e58d..9430f52 100644 (file)
@@ -66,6 +66,10 @@ static inline void skb_set_mac_header(struct sk_buff *skb, const int offset)
        skb->mac.raw = skb->data + offset;
 }
 
+static inline int skb_transport_offset(const struct sk_buff *skb)
+{
+    return skb_transport_header(skb) - skb->data;
+}
 #endif /* linux kernel < 2.6.22 */
 
 #endif
index 528f16a..e8b5197 100644 (file)
@@ -11,6 +11,11 @@ static inline struct tcphdr *tcp_hdr(const struct sk_buff *skb)
 {
        return (struct tcphdr *)skb_transport_header(skb);
 }
+
+static inline unsigned int tcp_hdrlen(const struct sk_buff *skb)
+{
+        return tcp_hdr(skb)->doff * 4;
+}
 #endif /* __KERNEL__ */
 
 #endif /* linux kernel < 2.6.22 */
diff --git a/datapath/linux-2.6/compat-2.6/include/linux/workqueue.h b/datapath/linux-2.6/compat-2.6/include/linux/workqueue.h
new file mode 100644 (file)
index 0000000..1ac3b6e
--- /dev/null
@@ -0,0 +1,42 @@
+#ifndef __LINUX_WORKQUEUE_WRAPPER_H
+#define __LINUX_WORKQUEUE_WRAPPER_H 1
+
+#include_next <linux/workqueue.h>
+
+#include <linux/version.h>
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,20)
+
+#ifdef __KERNEL__
+/*
+ * initialize a work-struct's func and data pointers:
+ */
+#undef PREPARE_WORK
+#define PREPARE_WORK(_work, _func)                              \
+        do {                                                    \
+               (_work)->func = (void(*)(void*)) _func;         \
+                (_work)->data = _work;                         \
+        } while (0)
+
+/*
+ * initialize all of a work-struct:
+ */
+#undef INIT_WORK
+#define INIT_WORK(_work, _func)                                 \
+        do {                                                    \
+                INIT_LIST_HEAD(&(_work)->entry);                \
+                (_work)->pending = 0;                           \
+                PREPARE_WORK((_work), (_func));                 \
+                init_timer(&(_work)->timer);                    \
+        } while (0)
+
+#endif /* __KERNEL__ */
+
+#endif /* linux kernel < 2.6.20 */
+
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,22)
+/* There is no equivalent to cancel_work_sync() so just flush all
+ * pending work. */
+#define cancel_work_sync(_work) flush_scheduled_work()
+#endif
+
+#endif
index d87b510..b31e8f0 100644 (file)
@@ -60,6 +60,11 @@ static int table_hash_insert(struct sw_table *swt, struct sw_flow *flow)
        } else {
                struct sw_flow *old_flow = *bucket;
                if (flow_keys_equal(&old_flow->key, &flow->key)) {
+                       /* Keep stats from the original flow */
+                       flow->init_time = old_flow->init_time;
+                       flow->packet_count = old_flow->packet_count;
+                       flow->byte_count = old_flow->byte_count;
+
                        rcu_assign_pointer(*bucket, flow);
                        flow_deferred_free(old_flow);
                        retval = 1;
@@ -186,7 +191,8 @@ static void table_hash_stats(struct sw_table *swt,
 {
        struct sw_table_hash *th = (struct sw_table_hash *) swt;
        stats->name = "hash";
-       stats->n_flows = th->n_flows;
+       stats->wildcards = 0;          /* No wildcards are supported. */
+       stats->n_flows   = th->n_flows;
        stats->max_flows = th->bucket_mask + 1;
        stats->n_matched = swt->n_matched;
 }
@@ -310,7 +316,8 @@ static void table_hash2_stats(struct sw_table *swt,
        for (i = 0; i < 2; i++)
                table_hash_stats(t2->subtable[i], &substats[i]);
        stats->name = "hash2";
-       stats->n_flows = substats[0].n_flows + substats[1].n_flows;
+       stats->wildcards = 0;          /* No wildcards are supported. */
+       stats->n_flows   = substats[0].n_flows + substats[1].n_flows;
        stats->max_flows = substats[0].max_flows + substats[1].max_flows;
        stats->n_matched = swt->n_matched;
 }
index e7c6e67..a9c7dcc 100644 (file)
@@ -48,6 +48,11 @@ static int table_linear_insert(struct sw_table *swt, struct sw_flow *flow)
                if (f->priority == flow->priority
                                && f->key.wildcards == flow->key.wildcards
                                && flow_matches_2wild(&f->key, &flow->key)) {
+                       /* Keep stats from the original flow */
+                       flow->init_time = f->init_time;
+                       flow->packet_count = f->packet_count;
+                       flow->byte_count = f->byte_count;
+
                        flow->serial = f->serial;
                        list_replace_rcu(&f->node, &flow->node);
                        list_replace_rcu(&f->iter_node, &flow->iter_node);
@@ -157,7 +162,8 @@ static void table_linear_stats(struct sw_table *swt,
 {
        struct sw_table_linear *tl = (struct sw_table_linear *) swt;
        stats->name = "linear";
-       stats->n_flows = tl->n_flows;
+       stats->wildcards = OFPFW_ALL;
+       stats->n_flows   = tl->n_flows;
        stats->max_flows = tl->max_flows;
        stats->n_matched = swt->n_matched;
 }
index 26fd466..c47e1e6 100644 (file)
@@ -12,7 +12,9 @@ struct datapath;
 
 /* Table statistics. */
 struct sw_table_stats {
-       const char *name;                /* Human-readable name. */
+       const char *name;            /* Human-readable name. */
+       uint32_t wildcards;          /* Bitmap of OFPFW_* wildcards that are
+                                       supported by the table. */
        unsigned int n_flows;        /* Number of active flows. */
        unsigned int max_flows;      /* Flow capacity. */
        unsigned long int n_matched; /* Number of packets that have hit. */
diff --git a/ext b/ext
index 5e70c38..15707fb 160000 (submodule)
--- a/ext
+++ b/ext
@@ -1 +1 @@
-Subproject commit 5e70c38c78be569f075ec4d8f6e224f0d2e3df53
+Subproject commit 15707fb578371cdd0b7ee8c84758d78633e0177b
index a575a37..148a7e3 100644 (file)
@@ -30,6 +30,7 @@ noinst_HEADERS = \
        socket-util.h \
        type-props.h \
        timeval.h \
+       stp.h \
        util.h \
        vconn.h \
        vconn-ssl.h \
diff --git a/include/nicira-ext.h b/include/nicira-ext.h
new file mode 100644 (file)
index 0000000..6e16faf
--- /dev/null
@@ -0,0 +1,63 @@
+/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
+ * Junior University
+ *
+ * We are making the OpenFlow specification and associated documentation
+ * (Software) available for public use and benefit with the expectation
+ * that others will use, modify and enhance the Software and contribute
+ * those enhancements back to the community. However, since we would
+ * like to make the Software available for broadest use, with as few
+ * restrictions as possible permission is hereby granted, free of
+ * charge, to any person obtaining a copy of this Software to deal in
+ * the Software under the copyrights without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * The name and trademarks of copyright holder(s) may NOT be used in
+ * advertising or publicity pertaining to the Software or any
+ * derivatives without specific, written prior permission.
+ */
+
+#ifndef NICIRA_EXT_H
+#define NICIRA_EXT_H 1
+
+#include "openflow.h"
+
+/* The following vendor extensions, proposed by Nicira Networks, are not yet
+ * ready for standardization (and may never be), so they are not included in
+ * openflow.h. */
+
+#define NX_VENDOR_ID 0x00002320
+
+enum nicira_type {
+    /* Switch status request.  The request body is an ASCII string that
+     * specifies a prefix of the key names to include in the output; if it is
+     * the null string, then all key-value pairs are included. */
+    NXT_STATUS_REQUEST,
+
+    /* Switch status reply.  The reply body is an ASCII string of key-value
+     * pairs in the form "key=value\n". */
+    NXT_STATUS_REPLY
+};
+
+struct nicira_header {
+    struct ofp_header header;
+    uint32_t vendor_id;         /* NX_VENDOR_ID. */
+    uint32_t subtype;           /* One of NXT_* above. */
+};
+OFP_ASSERT(sizeof(struct nicira_header) == sizeof(struct ofp_vendor) + 4);
+
+#endif /* nicira-ext.h */
index 1ad8227..77dbc52 100644 (file)
 #define OFP_PACKED              /* SWIG doesn't understand __attribute. */
 #endif
 
-/* Maximum length of a OpenFlow packet. */
-#define OFP_MAXLEN (sizeof(struct ofp_switch_features) \
-        + (sizeof(struct ofp_phy_port) * OFPP_MAX) + 200)
-
-
 /* The most significant bit being set in the version field indicates an
  * experimental OpenFlow version.  
  */
-#define OFP_VERSION   0x89
+#define OFP_VERSION   0x91
 
 #define OFP_MAX_TABLE_NAME_LEN 32
 #define OFP_MAX_PORT_NAME_LEN  16
@@ -101,23 +96,34 @@ enum ofp_port {
 };
 
 enum ofp_type {
-    OFPT_FEATURES_REQUEST,    /*  0 Controller/switch message */
-    OFPT_FEATURES_REPLY,      /*  1 Controller/switch message */
-    OFPT_GET_CONFIG_REQUEST,  /*  2 Controller/switch message */
-    OFPT_GET_CONFIG_REPLY,    /*  3 Controller/switch message */
-    OFPT_SET_CONFIG,          /*  4 Controller/switch message */
-    OFPT_PACKET_IN,           /*  5 Async message */
-    OFPT_PACKET_OUT,          /*  6 Controller/switch message */
-    OFPT_FLOW_MOD,            /*  7 Controller/switch message */
-    OFPT_FLOW_EXPIRED,        /*  8 Async message */
-    OFPT_TABLE,               /*  9 Controller/switch message */
-    OFPT_PORT_MOD,            /* 10 Controller/switch message */
-    OFPT_PORT_STATUS,         /* 11 Async message */
-    OFPT_ERROR_MSG,           /* 12 Async message */
-    OFPT_STATS_REQUEST,       /* 13 Controller/switch message */
-    OFPT_STATS_REPLY,         /* 14 Controller/switch message */
-    OFPT_ECHO_REQUEST,        /* 15 Symmetric message */
-    OFPT_ECHO_REPLY           /* 16 Symmetric message */
+    /* Immutable messages. */
+    OFPT_HELLO,               /* Symmetric message */
+    OFPT_ERROR,               /* Symmetric message */
+    OFPT_ECHO_REQUEST,        /* Symmetric message */
+    OFPT_ECHO_REPLY,          /* Symmetric message */
+    OFPT_VENDOR,              /* Symmetric message */
+
+    /* Switch configuration messages. */
+    OFPT_FEATURES_REQUEST,    /* Controller/switch message */
+    OFPT_FEATURES_REPLY,      /* Controller/switch message */
+    OFPT_GET_CONFIG_REQUEST,  /* Controller/switch message */
+    OFPT_GET_CONFIG_REPLY,    /* Controller/switch message */
+    OFPT_SET_CONFIG,          /* Controller/switch message */
+
+    /* Asynchronous messages. */
+    OFPT_PACKET_IN,           /* Async message */
+    OFPT_FLOW_EXPIRED,        /* Async message */
+    OFPT_PORT_STATUS,         /* Async message */
+
+    /* Controller command messages. */
+    OFPT_PACKET_OUT,          /* Controller/switch message */
+    OFPT_FLOW_MOD,            /* Controller/switch message */
+    OFPT_PORT_MOD,            /* Controller/switch message */
+    OFPT_TABLE,               /* Controller/switch message */
+
+    /* Statistics messages. */
+    OFPT_STATS_REQUEST,       /* Controller/switch message */
+    OFPT_STATS_REPLY          /* Controller/switch message */
 };
 
 /* Header on all OpenFlow packets. */
@@ -131,6 +137,12 @@ struct ofp_header {
 };
 OFP_ASSERT(sizeof(struct ofp_header) == 8);
 
+/* OFPT_HELLO.  This message has an empty body, but implementations must
+ * ignore any data included in the body, to allow for future extensions. */
+struct ofp_hello {
+    struct ofp_header header;
+};
+
 #define OFP_DEFAULT_MISS_SEND_LEN   128
 
 enum ofp_config_flags {
@@ -164,12 +176,32 @@ enum ofp_capabilities {
     OFPC_IP_REASM     = 1 << 5  /* Can reassemble IP fragments. */
 };
 
-/* Flags to indicate behavior of the physical port */
+/* Flags to indicate behavior of the physical port. */
 enum ofp_port_flags {
-    OFPPFL_NO_FLOOD  = 1 << 0, /* Do not include this port when flooding. */
-    OFPPFL_PORT_DOWN = 1 << 1, /* Port is configured down. */
-    OFPPFL_LINK_DOWN = 1 << 2, /* No physical link on interface.  
-                                  NOTE: Non-settable field */
+    /* Read/write bits. */
+    OFPPFL_PORT_DOWN    = 1 << 1, /* Port is configured down. */
+    OFPPFL_NO_STP       = 1 << 3, /* Disable 802.1D spanning tree on port. */
+    OFPPFL_NO_RECV      = 1 << 4, /* Drop most packets received on port. */
+    OFPPFL_NO_RECV_STP  = 1 << 5, /* Drop received 802.1D STP packets. */
+    OFPPFL_NO_FWD       = 1 << 6, /* Drop packets forwarded to port. */
+    OFPPFL_NO_PACKET_IN = 1 << 7, /* Do not send packet-in msgs for port. */
+
+    /* Read-only bits. */
+    OFPPFL_LINK_DOWN    = 1 << 2, /* No physical link present. */
+
+    /* Read-only when STP is enabled (when OFPPFL_NO_STP is not set).
+     * Read/write when STP is disabled (when OFPPFL_NO_STP is set).
+     *
+     * The OFPPFL_STP_* bits have no effect on switch operation.  The
+     * controller must adjust OFPPFL_NO_RECV, OFPPFL_NO_FWD, and
+     * OFPPFL_NO_PACKET_IN appropriately to fully implement an 802.1D spanning
+     * tree. */
+    OFPPFL_NO_FLOOD     = 1 << 0, /* Do not include this port when flooding. */
+    OFPPFL_STP_LISTEN   = 0 << 8, /* Not learning or relaying frames. */
+    OFPPFL_STP_LEARN    = 1 << 8, /* Learning but not relaying frames. */
+    OFPPFL_STP_FORWARD  = 2 << 8, /* Learning and relaying frames. */
+    OFPPFL_STP_BLOCK    = 3 << 8, /* Not part of spanning tree. */
+    OFPPFL_STP_MASK     = 3 << 8, /* Bit mask for OFPPFL_STP_* values. */
 };
 
 /* Features of physical ports available in a datapath. */
@@ -181,6 +213,7 @@ enum ofp_port_features {
     OFPPF_1GB_HD     = 1 << 4, /* 1 Gb half-duplex rate support. */
     OFPPF_1GB_FD     = 1 << 5, /* 1 Gb full-duplex rate support. */
     OFPPF_10GB_FD    = 1 << 6, /* 10 Gb full-duplex rate support. */
+    OFPPF_STP        = 1 << 7, /* 802.1D spanning tree supported on port. */
 };
 
 
@@ -201,26 +234,21 @@ struct ofp_switch_features {
     uint64_t datapath_id;   /* Datapath unique ID.  Only the lower 48-bits
                                are meaningful. */
 
-    /* Table info. */
-    uint32_t n_exact;       /* Max exact-match table entries. */
-    uint32_t n_compression; /* Max entries compressed on service port. */
-    uint32_t n_general;     /* Max entries of arbitrary form. */
-
-    /* Buffer limits.  A datapath that cannot buffer reports 0.*/
-    uint32_t buffer_mb;     /* Space for buffering packets, in MB. */
     uint32_t n_buffers;     /* Max packets buffered at once. */
 
+    uint8_t n_tables;       /* Number of tables supported by datapath. */
+    uint8_t pad[3];         /* Align to 64-bits. */
+
     /* Features. */
     uint32_t capabilities;  /* Bitmap of support "ofp_capabilities". */
     uint32_t actions;       /* Bitmap of supported "ofp_action_type"s. */
-    uint8_t pad[4];         /* Align to 64-bits. */
 
     /* Port info.*/
     struct ofp_phy_port ports[0];  /* Port definitions.  The number of ports
                                       is inferred from the length field in
                                       the header. */
 };
-OFP_ASSERT(sizeof(struct ofp_switch_features) == 48);
+OFP_ASSERT(sizeof(struct ofp_switch_features) == 32);
 
 /* What changed about the physical port */
 enum ofp_port_reason {
@@ -324,6 +352,8 @@ OFP_ASSERT(sizeof(struct ofp_packet_out) == 16);
 
 enum ofp_flow_mod_command {
     OFPFC_ADD,              /* New flow. */
+    OFPFC_MODIFY,           /* Modify all matching flows. */
+    OFPFC_MODIFY_STRICT,    /* Strictly match wildcards and priority. */
     OFPFC_DELETE,           /* Delete all matching flows. */
     OFPFC_DELETE_STRICT     /* Strictly match wildcards and priority. */
 };
@@ -432,7 +462,31 @@ struct ofp_flow_expired {
 };
 OFP_ASSERT(sizeof(struct ofp_flow_expired) == 72);
 
-/* Error message (datapath -> controller). */
+/* Values for 'type' in ofp_error_message.  These values are immutable: they
+ * will not change in future versions of the protocol (although new values may
+ * be added). */
+enum ofp_error_type {
+    OFPET_HELLO_FAILED,         /* Hello protocol failed. */
+    OFPET_BAD_REQUEST           /* Request was not understood. */
+};
+
+/* ofp_error_msg 'code' values for OFPET_HELLO_FAILED.  'data' contains an
+ * ASCII text string that may give failure details. */
+enum ofp_hello_failed_code {
+    OFPHFC_INCOMPATIBLE         /* No compatible version. */
+};
+
+/* ofp_error_msg 'code' values for OFPET_BAD_REQUEST.  'data' contains at least
+ * the first 64 bytes of the failed request. */
+enum ofp_bad_request_code {
+    OFPBRC_BAD_VERSION,         /* ofp_header.version not supported. */
+    OFPBRC_BAD_TYPE,            /* ofp_header.type not supported. */
+    OFPBRC_BAD_STAT,            /* ofp_stats_request.type not supported. */
+    OFPBRC_BAD_VENDOR           /* Vendor not supported (in ofp_vendor or
+                                 * ofp_stats_request or ofp_stats_reply). */
+};
+
+/* OFPT_ERROR: Error message (datapath -> controller). */
 struct ofp_error_msg {
     struct ofp_header header;
 
@@ -469,13 +523,11 @@ enum ofp_stats_types {
      * The reply body is an array of struct ofp_port_stats. */
     OFPST_PORT,
 
-    /* Switch status.
-     * The request body is an ASCII string that specifies a prefix of the key
-     * names to include in the output; if it is the null string, then all
-     * key-value pairs are included.
-     * The reply body is an ASCII string of key-value pairs in the form
-     * "key=value\n". */
-    OFPST_SWITCH
+    /* Vendor extension.
+     * The request and reply bodies begin with a 32-bit vendor ID, which takes
+     * the same form as in "struct ofp_vendor".  The request and reply bodies
+     * are otherwise vendor-defined. */
+    OFPST_VENDOR = 0xffff
 };
 
 struct ofp_stats_request {
@@ -557,12 +609,14 @@ OFP_ASSERT(sizeof(struct ofp_aggregate_stats_reply) == 24);
 
 /* Body of reply to OFPST_TABLE request. */
 struct ofp_table_stats {
-    uint8_t table_id;
+    uint8_t table_id;        /* Identifier of table.  Lower numbered tables 
+                                are consulted first. */
     uint8_t pad[3];          /* Align to 32-bits */
     char name[OFP_MAX_TABLE_NAME_LEN];
+    uint32_t wildcards;      /* Bitmap of OFPFW_* wildcards that are 
+                                supported by the table. */
     uint32_t max_entries;    /* Max number of entries supported */
     uint32_t active_count;   /* Number of active entries */
-    uint8_t pad2[4];         /* Align to 64 bits. */
     uint64_t matched_count;  /* Number of packets that hit table */
 };
 OFP_ASSERT(sizeof(struct ofp_table_stats) == 56);
@@ -590,4 +644,15 @@ struct ofp_port_stats {
 };
 OFP_ASSERT(sizeof(struct ofp_port_stats) == 104);
 
+/* Vendor extension. */
+struct ofp_vendor {
+    struct ofp_header header;   /* Type OFPT_VENDOR. */
+    uint32_t vendor;            /* Vendor ID:
+                                 * - MSB 0: low-order bytes are Ethernet OUI.
+                                 * - MSB != 0: defined by OpenFlow
+                                 *   consortium. */
+    /* Vendor-defined arbitrary additional data. */
+};
+OFP_ASSERT(sizeof(struct ofp_vendor) == 12);
+
 #endif /* openflow.h */
index 69f9b8d..53054c1 100644 (file)
@@ -73,6 +73,8 @@ int rconn_send_with_limit(struct rconn *, struct ofpbuf *,
 unsigned int rconn_packets_sent(const struct rconn *);
 unsigned int rconn_packets_received(const struct rconn *);
 
+void rconn_add_monitor(struct rconn *, struct vconn *);
+
 const char *rconn_get_name(const struct rconn *);
 bool rconn_is_alive(const struct rconn *);
 bool rconn_is_connected(const struct rconn *);
diff --git a/include/stp.h b/include/stp.h
new file mode 100644 (file)
index 0000000..3305e60
--- /dev/null
@@ -0,0 +1,107 @@
+/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
+ * Junior University
+ *
+ * We are making the OpenFlow specification and associated documentation
+ * (Software) available for public use and benefit with the expectation
+ * that others will use, modify and enhance the Software and contribute
+ * those enhancements back to the community. However, since we would
+ * like to make the Software available for broadest use, with as few
+ * restrictions as possible permission is hereby granted, free of
+ * charge, to any person obtaining a copy of this Software to deal in
+ * the Software under the copyrights without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * The name and trademarks of copyright holder(s) may NOT be used in
+ * advertising or publicity pertaining to the Software or any
+ * derivatives without specific, written prior permission.
+ */
+
+#ifndef STP_H
+#define STP_H 1
+
+/* This is an implementation of Spanning Tree Protocol as described in IEEE
+ * 802.1D-1998, clauses 8 and 9.  Section numbers refer to this standard.  */
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "compiler.h"
+#include "util.h"
+
+/* Ethernet address used as the destination for STP frames. */
+extern const uint8_t stp_eth_addr[6];
+
+/* LLC field values used for STP frames. */
+#define STP_LLC_SSAP 0x42
+#define STP_LLC_DSAP 0x42
+#define STP_LLC_CNTL 0x03
+
+/* Bridge identifier.  Top 16 bits are a priority value (numerically lower
+ * values are higher priorities).  Bottom 48 bits are MAC address of bridge. */
+typedef uint64_t stp_identifier;
+
+/* Basic STP functionality. */
+#define STP_MAX_PORTS 255
+struct stp *stp_create(const char *name, stp_identifier bridge_id,
+                       void (*send_bpdu)(const void *bpdu, size_t bpdu_size,
+                                         int port_no, void *aux),
+                       void *aux);
+void stp_destroy(struct stp *);
+void stp_tick(struct stp *, int elapsed);
+void stp_set_bridge_priority(struct stp *, uint16_t new_priority);
+
+/* STP properties. */
+const char *stp_get_name(const struct stp *);
+stp_identifier stp_get_bridge_id(const struct stp *);
+stp_identifier stp_get_designated_root(const struct stp *);
+bool stp_is_root_bridge(const struct stp *);
+int stp_get_root_path_cost(const struct stp *);
+
+/* Obtaining STP ports. */
+struct stp_port *stp_get_port(struct stp *, int port_no);
+struct stp_port *stp_get_root_port(struct stp *);
+bool stp_get_changed_port(struct stp *, struct stp_port **portp);
+
+/* State of an STP port.
+ *
+ * A port is in exactly one state at any given time, but distinct bits are used
+ * for states to allow testing for more than one state with a bit mask. */
+enum stp_state {
+    STP_DISABLED = 1 << 0,       /* 8.4.5: Disabled by management. */
+    STP_LISTENING = 1 << 1,      /* 8.4.2: Not learning or relaying frames. */
+    STP_LEARNING = 1 << 2,       /* 8.4.3: Learning but not relaying frames. */
+    STP_FORWARDING = 1 << 3,     /* 8.4.4: Learning and relaying frames. */
+    STP_BLOCKING = 1 << 4        /* 8.4.1: Initial boot state. */
+};
+const char *stp_state_name(enum stp_state);
+bool stp_forward_in_state(enum stp_state);
+bool stp_learn_in_state(enum stp_state);
+
+void stp_received_bpdu(struct stp_port *, const void *bpdu, size_t bpdu_size);
+
+struct stp *stp_port_get_stp(struct stp_port *);
+int stp_port_no(const struct stp_port *);
+enum stp_state stp_port_get_state(const struct stp_port *);
+void stp_port_enable(struct stp_port *);
+void stp_port_disable(struct stp_port *);
+void stp_port_set_priority(struct stp_port *, uint8_t new_priority);
+void stp_port_set_path_cost(struct stp_port *, unsigned int path_cost);
+void stp_port_set_speed(struct stp_port *, unsigned int speed);
+void stp_port_enable_change_detection(struct stp_port *);
+void stp_port_disable_change_detection(struct stp_port *);
+
+#endif /* stp.h */
index 3a40e23..cf033af 100644 (file)
 #ifndef VCONN_PROVIDER_H
 #define VCONN_PROVIDER_H 1
 
-/* Provider interface, which provide a virtual connection to an OpenFlow
- * device. */
+/* Provider interface to vconns, which provide a virtual connection to an
+ * OpenFlow device. */
 
+#include <assert.h>
 #include "vconn.h"
+\f
+/* Active virtual connection to an OpenFlow device. */
 
-/* Virtual connection to an OpenFlow device. */
+/* Active virtual connection to an OpenFlow device.
+ *
+ * This structure should be treated as opaque by vconn implementations. */
 struct vconn {
     struct vconn_class *class;
-    int connect_status;
+    int state;
+    int error;
+    int min_version;
+    int version;
     uint32_t ip;
     char *name;
 };
 
 void vconn_init(struct vconn *, struct vconn_class *, int connect_status,
                 uint32_t ip, const char *name);
+static inline void vconn_assert_class(const struct vconn *vconn,
+                                      const struct vconn_class *class)
+{
+    assert(vconn->class == class);
+}
 
 struct vconn_class {
     /* Prefix for connection names, e.g. "nl", "tcp". */
@@ -72,58 +85,105 @@ struct vconn_class {
     /* Closes 'vconn' and frees associated memory. */
     void (*close)(struct vconn *vconn);
 
-    /* Tries to complete the connection on 'vconn', which must be an active
-     * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
-     * was successful or a positive errno value if it failed.  If the
-     * connection is still in progress, returns EAGAIN.
+    /* Tries to complete the connection on 'vconn'.  If 'vconn''s connection is
+     * complete, returns 0 if the connection was successful or a positive errno
+     * value if it failed.  If the connection is still in progress, returns
+     * EAGAIN.
      *
      * The connect function must not block waiting for the connection to
      * complete; instead, it should return EAGAIN immediately. */
     int (*connect)(struct vconn *vconn);
 
-    /* Tries to accept a new connection on 'vconn', which must be a passive
-     * vconn.  If successful, stores the new connection in '*new_vconnp' and
-     * returns 0.  Otherwise, returns a positive errno value.
-     *
-     * The accept function must not block waiting for a connection.  If no
-     * connection is ready to be accepted, it should return EAGAIN.
-     *
-     * Nonnull iff this is a passive vconn (one that accepts connections and
-     * does not transfer data). */
-    int (*accept)(struct vconn *vconn, struct vconn **new_vconnp);
-
-    /* Tries to receive an OpenFlow message from 'vconn', which must be an
-     * active vconn.  If successful, stores the received message into '*msgp'
-     * and returns 0.  The caller is responsible for destroying the message
-     * with ofpbuf_delete().  On failure, returns a positive errno value and
-     * stores a null pointer into '*msgp'.
+    /* Tries to receive an OpenFlow message from 'vconn'.  If successful,
+     * stores the received message into '*msgp' and returns 0.  The caller is
+     * responsible for destroying the message with ofpbuf_delete().  On
+     * failure, returns a positive errno value and stores a null pointer into
+     * '*msgp'.
      *
      * If the connection has been closed in the normal fashion, returns EOF.
      *
      * The recv function must not block waiting for a packet to arrive.  If no
-     * packets have been received, it should return EAGAIN.
-     *
-     * Nonnull iff this is an active vconn (one that transfers data and does
-     * not accept connections). */
+     * packets have been received, it should return EAGAIN. */
     int (*recv)(struct vconn *vconn, struct ofpbuf **msgp);
 
-    /* Tries to queue 'msg' for transmission on 'vconn', which must be an
-     * active vconn.  If successful, returns 0, in which case ownership of
-     * 'msg' is transferred to the vconn.  Success does not guarantee that
-     * 'msg' has been or ever will be delivered to the peer, only that it has
-     * been queued for transmission.
+    /* Tries to queue 'msg' for transmission on 'vconn'.  If successful,
+     * returns 0, in which case ownership of 'msg' is transferred to the vconn.
+     * Success does not guarantee that 'msg' has been or ever will be delivered
+     * to the peer, only that it has been queued for transmission.
      *
      * Returns a positive errno value on failure, in which case the caller
      * retains ownership of 'msg'.
      *
      * The send function must not block.  If 'msg' cannot be immediately
-     * accepted for transmission, it should return EAGAIN.
-     *
-     * Nonnull iff this is an active vconn (one that transfers data and does
-     * not accept connections). */
+     * accepted for transmission, it should return EAGAIN. */
     int (*send)(struct vconn *vconn, struct ofpbuf *msg);
 
-    void (*wait)(struct vconn *vconn, enum vconn_wait_type);
+    /* Arranges for the poll loop to wake up when 'vconn' is ready to take an
+     * action of the given 'type'. */
+    void (*wait)(struct vconn *vconn, enum vconn_wait_type type);
+};
+\f
+/* Passive virtual connection to an OpenFlow device.
+ *
+ * This structure should be treated as opaque by vconn implementations. */
+struct pvconn {
+    struct pvconn_class *class;
+    char *name;
 };
 
+void pvconn_init(struct pvconn *, struct pvconn_class *, const char *name);
+static inline void pvconn_assert_class(const struct pvconn *pvconn,
+                                       const struct pvconn_class *class)
+{
+    assert(pvconn->class == class);
+}
+
+struct pvconn_class {
+    /* Prefix for connection names, e.g. "ptcp", "pssl". */
+    const char *name;
+
+    /* Attempts to start listening for OpenFlow connections.  'name' is the
+     * full connection name provided by the user, e.g. "nl:0", "tcp:1.2.3.4".
+     * This name is useful for error messages but must not be modified.
+     *
+     * 'suffix' is a copy of 'name' following the colon and may be modified.
+     *
+     * Returns 0 if successful, otherwise a positive errno value.  If
+     * successful, stores a pointer to the new connection in '*pvconnp'.
+     *
+     * The listen function must not block.  If the connection cannot be
+     * completed immediately, it should return EAGAIN (not EINPROGRESS, as
+     * returned by the connect system call) and continue the connection in the
+     * background. */
+    int (*listen)(const char *name, char *suffix, struct pvconn **pvconnp);
+
+    /* Closes 'pvconn' and frees associated memory. */
+    void (*close)(struct pvconn *pvconn);
+
+    /* Tries to accept a new connection on 'pvconn'.  If successful, stores the
+     * new connection in '*new_vconnp' and returns 0.  Otherwise, returns a
+     * positive errno value.
+     *
+     * The accept function must not block waiting for a connection.  If no
+     * connection is ready to be accepted, it should return EAGAIN. */
+    int (*accept)(struct pvconn *pvconn, struct vconn **new_vconnp);
+
+    /* Arranges for the poll loop to wake up when a connection is ready to be
+     * accepted on 'pvconn'. */
+    void (*wait)(struct pvconn *pvconn);
+};
+
+/* Active and passive vconn classes. */
+extern struct vconn_class tcp_vconn_class;
+extern struct pvconn_class ptcp_pvconn_class;
+extern struct vconn_class unix_vconn_class;
+extern struct pvconn_class punix_pvconn_class;
+#ifdef HAVE_OPENSSL
+extern struct vconn_class ssl_vconn_class;
+extern struct pvconn_class pssl_pvconn_class;
+#endif
+#ifdef HAVE_NETLINK
+extern struct vconn_class netlink_vconn_class;
+#endif
+
 #endif /* vconn-provider.h */
index d7eb59f..a9b1e7b 100644 (file)
 #include <stdint.h>
 
 struct vconn;
+struct pvconn;
 struct sockaddr;
 
 int new_stream_vconn(const char *name, int fd, int connect_status,
                      uint32_t ip, struct vconn **vconnp);
-int new_pstream_vconn(const char *name, int fd,
+int new_pstream_pvconn(const char *name, int fd,
                       int (*accept_cb)(int fd, const struct sockaddr *,
                                        size_t sa_len, struct vconn **),
-                      struct vconn **vconnp);
+                      struct pvconn **pvconnp);
 
 #endif /* vconn-stream.h */
index 224fd56..91bb687 100644 (file)
 
 struct ofpbuf;
 struct flow;
-struct pollfd;
 struct ofp_header;
+struct pvconn;
 struct vconn;
 
-/* Client interface to vconns, which provide a virtual connection to an
- * OpenFlow device. */
-
 void vconn_usage(bool active, bool passive);
-int vconn_open(const char *name, struct vconn **);
+
+/* Active vconns: virtual connections to OpenFlow devices. */
+int vconn_open(const char *name, int min_version, struct vconn **);
 void vconn_close(struct vconn *);
-bool vconn_is_passive(const struct vconn *);
+const char *vconn_get_name(const struct vconn *);
 uint32_t vconn_get_ip(const struct vconn *);
 int vconn_connect(struct vconn *);
-int vconn_accept(struct vconn *, struct vconn **);
 int vconn_recv(struct vconn *, struct ofpbuf **);
 int vconn_send(struct vconn *, struct ofpbuf *);
 int vconn_transact(struct vconn *, struct ofpbuf *, struct ofpbuf **);
 
-int vconn_open_block(const char *name, struct vconn **);
+int vconn_open_block(const char *name, int min_version, struct vconn **);
 int vconn_send_block(struct vconn *, struct ofpbuf *);
 int vconn_recv_block(struct vconn *, struct ofpbuf **);
 
 enum vconn_wait_type {
     WAIT_CONNECT,
-    WAIT_ACCEPT,
     WAIT_RECV,
     WAIT_SEND
 };
 void vconn_wait(struct vconn *, enum vconn_wait_type);
 void vconn_connect_wait(struct vconn *);
-void vconn_accept_wait(struct vconn *);
 void vconn_recv_wait(struct vconn *);
 void vconn_send_wait(struct vconn *);
 
+/* Passive vconns: virtual listeners for incoming OpenFlow connections. */
+int pvconn_open(const char *name, struct pvconn **);
+void pvconn_close(struct pvconn *);
+int pvconn_accept(struct pvconn *, int min_version, struct vconn **);
+void pvconn_wait(struct pvconn *);
+
+/* OpenFlow protocol utility functions. */
 void *make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **);
 void *make_openflow_xid(size_t openflow_len, uint8_t type,
                         uint32_t xid, struct ofpbuf **);
@@ -90,16 +93,4 @@ struct ofpbuf *make_unbuffered_packet_out(const struct ofpbuf *packet,
 struct ofpbuf *make_echo_request(void);
 struct ofpbuf *make_echo_reply(const struct ofp_header *rq);
 
-extern struct vconn_class tcp_vconn_class;
-extern struct vconn_class ptcp_vconn_class;
-extern struct vconn_class unix_vconn_class;
-extern struct vconn_class punix_vconn_class;
-#ifdef HAVE_OPENSSL
-extern struct vconn_class ssl_vconn_class;
-extern struct vconn_class pssl_vconn_class;
-#endif
-#ifdef HAVE_NETLINK
-extern struct vconn_class netlink_vconn_class;
-#endif
-
 #endif /* vconn.h */
index 22553de..9edb8a8 100644 (file)
@@ -18,6 +18,7 @@ VLOG_MODULE(ofp_discover)
 VLOG_MODULE(poll_loop)
 VLOG_MODULE(secchan)
 VLOG_MODULE(rconn)
+VLOG_MODULE(stp)
 VLOG_MODULE(switch)
 VLOG_MODULE(terminal)
 VLOG_MODULE(socket_util)
index a78597f..be29812 100644 (file)
@@ -25,6 +25,7 @@ libopenflow_a_SOURCES = \
        rconn.c \
        socket-util.c \
        timeval.c \
+       stp.c \
        util.c \
        vconn-tcp.c \
        vconn-unix.c \
index b04439f..da06f16 100644 (file)
@@ -110,7 +110,7 @@ static const struct nl_policy openflow_policy[] = {
     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
     [DP_GENL_A_OPENFLOW] = { .type = NL_A_UNSPEC,
                               .min_len = sizeof(struct ofp_header),
-                              .max_len = OFP_MAXLEN },
+                              .max_len = 65535 },
 };
 
 /* Tries to receive an openflow message from the kernel on 'sock'.  If
index e118405..fedf73e 100644 (file)
@@ -61,6 +61,7 @@ struct lswitch {
     int max_idle;
 
     uint64_t datapath_id;
+    uint32_t capabilities;
     time_t last_features_request;
     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
 
@@ -74,10 +75,16 @@ static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
 
 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
 static void send_features_request(struct lswitch *, struct rconn *);
+static void process_switch_features(struct lswitch *, struct rconn *,
+                                    struct ofp_switch_features *);
 static void process_packet_in(struct lswitch *, struct rconn *,
                               struct ofp_packet_in *);
 static void process_echo_request(struct lswitch *, struct rconn *,
                                  struct ofp_header *);
+static void process_port_status(struct lswitch *, struct rconn *,
+                                struct ofp_port_status *);
+static void process_phy_port(struct lswitch *, struct rconn *,
+                             const struct ofp_phy_port *);
 
 /* Creates and returns a new learning switch.
  *
@@ -116,6 +123,7 @@ min_size(uint8_t type)
 {
     return (type == OFPT_FEATURES_REPLY ? sizeof(struct ofp_switch_features)
             : type == OFPT_PACKET_IN ? offsetof (struct ofp_packet_in, data)
+            : type == OFPT_PORT_STATUS ? sizeof(struct ofp_port_status)
             : sizeof(struct ofp_header));
 }
 
@@ -141,12 +149,13 @@ lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
     if (oh->type == OFPT_ECHO_REQUEST) {
         process_echo_request(sw, rconn, msg->data);
     } else if (oh->type == OFPT_FEATURES_REPLY) {
-        struct ofp_switch_features *osf = msg->data;
-        sw->datapath_id = osf->datapath_id;
+        process_switch_features(sw, rconn, msg->data);
     } else if (sw->datapath_id == 0) {
         send_features_request(sw, rconn);
     } else if (oh->type == OFPT_PACKET_IN) {
         process_packet_in(sw, rconn, msg->data);
+    } else if (oh->type == OFPT_PORT_STATUS) {
+        process_port_status(sw, rconn, msg->data);
     } else {
         if (VLOG_IS_DBG_ENABLED()) {
             char *p = ofp_to_string(msg->data, msg->size, 2);
@@ -162,25 +171,14 @@ send_features_request(struct lswitch *sw, struct rconn *rconn)
     time_t now = time_now();
     if (now >= sw->last_features_request + 1) {
         struct ofpbuf *b;
-        struct ofp_header *ofr;
         struct ofp_switch_config *osc;
 
         /* Send OFPT_FEATURES_REQUEST. */
-        b = ofpbuf_new(0);
-        ofr = ofpbuf_put_uninit(b, sizeof *ofr);
-        memset(ofr, 0, sizeof *ofr);
-        ofr->type = OFPT_FEATURES_REQUEST;
-        ofr->version = OFP_VERSION;
-        ofr->length = htons(sizeof *ofr);
+        make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
         queue_tx(sw, rconn, b);
 
         /* Send OFPT_SET_CONFIG. */
-        b = ofpbuf_new(0);
-        osc = ofpbuf_put_uninit(b, sizeof *osc);
-        memset(osc, 0, sizeof *osc);
-        osc->header.type = OFPT_SET_CONFIG;
-        osc->header.version = OFP_VERSION;
-        osc->header.length = htons(sizeof *osc);
+        osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
         osc->flags = htons(OFPC_SEND_FLOW_EXP);
         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
         queue_tx(sw, rconn, b);
@@ -203,6 +201,22 @@ queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
     }
 }
 
+static void
+process_switch_features(struct lswitch *sw, struct rconn *rconn,
+                        struct ofp_switch_features *osf)
+{
+    size_t n_ports = ((ntohs(osf->header.length)
+                       - offsetof(struct ofp_switch_features, ports))
+                      / sizeof *osf->ports);
+    size_t i;
+
+    sw->datapath_id = osf->datapath_id;
+    sw->capabilities = ntohl(osf->capabilities);
+    for (i = 0; i < n_ports; i++) {
+        process_phy_port(sw, rconn, &osf->ports[i]);
+    }
+}
+
 static void
 process_packet_in(struct lswitch *sw, struct rconn *rconn,
                   struct ofp_packet_in *opi)
@@ -265,3 +279,62 @@ process_echo_request(struct lswitch *sw, struct rconn *rconn,
 {
     queue_tx(sw, rconn, make_echo_reply(rq));
 }
+
+static void
+process_port_status(struct lswitch *sw, struct rconn *rconn,
+                    struct ofp_port_status *ops)
+{
+    process_phy_port(sw, rconn, &ops->desc);
+}
+
+static void
+process_phy_port(struct lswitch *sw, struct rconn *rconn,
+                 const struct ofp_phy_port *opp)
+{
+    if (sw->capabilities & OFPC_STP && opp->features & ntohl(OFPPF_STP)) {
+        uint32_t flags = ntohl(opp->flags);
+        uint32_t new_flags = flags & ~(OFPPFL_NO_RECV | OFPPFL_NO_RECV_STP
+                                       | OFPPFL_NO_FWD | OFPPFL_NO_PACKET_IN);
+        if (!(flags & (OFPPFL_NO_STP | OFPPFL_PORT_DOWN | OFPPFL_LINK_DOWN))) {
+            bool forward = false;
+            bool learn = false;
+            switch (flags & OFPPFL_STP_MASK) {
+            case OFPPFL_STP_LISTEN:
+            case OFPPFL_STP_BLOCK:
+                break;
+            case OFPPFL_STP_LEARN:
+                learn = true;
+                break;
+            case OFPPFL_STP_FORWARD:
+                forward = learn = true;
+                break;
+            }
+            if (!forward) {
+                new_flags |= OFPPFL_NO_RECV | OFPPFL_NO_FWD;
+            }
+            if (!learn) {
+                new_flags |= OFPPFL_NO_PACKET_IN;
+            }
+        }
+        if (flags != new_flags) {
+            struct ofp_port_mod *opm;
+            struct ofpbuf *b;
+            int retval;
+
+            VLOG_WARN("port %d: flags=%x new_flags=%x",
+                      ntohs(opp->port_no), flags, new_flags);
+            opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
+            opm->mask = htonl(flags ^ new_flags);
+            opm->desc = *opp;
+            opm->desc.flags = htonl(new_flags);
+            retval = rconn_send(rconn, b, NULL);
+            if (retval) {
+                if (retval != ENOTCONN) {
+                    VLOG_WARN_RL(&rl, "%s: send: %s",
+                                 rconn_get_name(rconn), strerror(retval));
+                }
+                ofpbuf_delete(b);
+            }
+        }
+    }
+}
index 6f0957a..e78a24a 100644 (file)
@@ -411,11 +411,8 @@ ofp_print_switch_features(struct ds *string, const void *oh, size_t len,
     int i;
 
     ds_put_format(string, "dp id:%"PRIx64"\n", ntohll(osf->datapath_id));
-    ds_put_format(string, "tables: exact:%d, compressed:%d, general:%d\n",
-           ntohl(osf->n_exact), 
-           ntohl(osf->n_compression), ntohl(osf->n_general));
-    ds_put_format(string, "buffers: size:%d, number:%d\n",
-           ntohl(osf->buffer_mb), ntohl(osf->n_buffers));
+    ds_put_format(string, "n_tables:%d, n_buffers:%d\n", osf->n_tables,
+            ntohl(osf->n_buffers));
     ds_put_format(string, "features: capabilities:%#x, actions:%#x\n",
            ntohl(osf->capabilities), ntohl(osf->actions));
 
@@ -599,16 +596,82 @@ ofp_print_flow_expired(struct ds *string, const void *oh, size_t len,
          ntohll(ofe->byte_count));
 }
 
-/* Pretty-print the OFPT_ERROR_MSG packet of 'len' bytes at 'oh' to 'string'
+struct error_type {
+    int type;
+    int code;
+    const char *name;
+};
+
+static const struct error_type error_types[] = {
+#define ERROR_TYPE(TYPE) {TYPE, -1, #TYPE}
+#define ERROR_CODE(TYPE, CODE) {TYPE, CODE, #CODE}
+    ERROR_TYPE(OFPET_HELLO_FAILED),
+    ERROR_CODE(OFPET_HELLO_FAILED, OFPHFC_INCOMPATIBLE),
+
+    ERROR_TYPE(OFPET_BAD_REQUEST),
+    ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VERSION),
+    ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE),
+    ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT),
+    ERROR_CODE(OFPET_BAD_REQUEST, OFPBRC_BAD_VERSION),
+};
+#define N_ERROR_TYPES ARRAY_SIZE(error_types)
+
+static const char *
+lookup_error_type(int type)
+{
+    const struct error_type *t;
+
+    for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
+        if (t->type == type && t->code == -1) {
+            return t->name;
+        }
+    }
+    return "?";
+}
+
+static const char *
+lookup_error_code(int type, int code)
+{
+    const struct error_type *t;
+
+    for (t = error_types; t < &error_types[N_ERROR_TYPES]; t++) {
+        if (t->type == type && t->code == code) {
+            return t->name;
+        }
+    }
+    return "?";
+}
+
+/* Pretty-print the OFPT_ERROR packet of 'len' bytes at 'oh' to 'string'
  * at the given 'verbosity' level. */
 static void
 ofp_print_error_msg(struct ds *string, const void *oh, size_t len, 
                        int verbosity)
 {
     const struct ofp_error_msg *oem = oh;
+    int type = ntohs(oem->type);
+    int code = ntohs(oem->code);
+    char *s;
 
-    ds_put_format(string, 
-         " type%d code%d\n", ntohs(oem->type), ntohs(oem->code));
+    ds_put_format(string, " type%d(%s) code%d(%s) payload:\n",
+                  type, lookup_error_type(type),
+                  code, lookup_error_code(type, code));
+
+    switch (type) {
+    case OFPET_HELLO_FAILED:
+        ds_put_printable(string, (char *) oem->data, len - sizeof *oem);
+        break;
+
+    case OFPET_BAD_REQUEST:
+        s = ofp_to_string(oem->data, len - sizeof *oem, 1);
+        ds_put_cstr(string, s);
+        free(s);
+        break;
+
+    default:
+        ds_put_hex_dump(string, oem->data, len - sizeof *oem, 0, true);
+        break;
+    }
 }
 
 /* Pretty-print the OFPT_PORT_STATUS packet of 'len' bytes at 'oh' to 'string'
@@ -807,29 +870,22 @@ ofp_table_stats_reply(struct ds *string, const void *body, size_t len,
         strncpy(name, ts->name, sizeof name);
         name[OFP_MAX_TABLE_NAME_LEN] = '\0';
 
-        ds_put_format(string, "  table %"PRIu8": ", ts->table_id);
-        ds_put_format(string, "name %-8s, ", name);
-        ds_put_format(string, "max %6"PRIu32", ", ntohl(ts->max_entries));
-        ds_put_format(string, "active %6"PRIu32", ", ntohl(ts->active_count));
-        ds_put_format(string, "matched %6"PRIu64"\n",
+        ds_put_format(string, "  %d: %-8s: ", ts->table_id, name);
+        ds_put_format(string, "wild=0x%05"PRIx32", ", ntohl(ts->wildcards));
+        ds_put_format(string, "max=%6"PRIu32", ", ntohl(ts->max_entries));
+        ds_put_format(string, "active=%6"PRIu32", ", ntohl(ts->active_count));
+        ds_put_format(string, "matched=%6"PRIu64"\n",
                       ntohll(ts->matched_count));
      }
 }
 
 static void
-switch_status_reply(struct ds *string, const void *body, size_t len,
-                    int verbosity UNUSED)
+vendor_stat(struct ds *string, const void *body, size_t len,
+            int verbosity UNUSED)
 {
-    char *save_ptr = NULL;
-    char *s, *line;
-
-    s = xmemdup0(body, len);
-    for (line = strtok_r(s, "\n\n", &save_ptr); line != NULL;
-         line = strtok_r(NULL, "\n\n", &save_ptr)) {
-        ds_put_printable(string, line, strlen(line));
-        ds_put_char(string, '\n');
-    }
-    free(s);
+    ds_put_format(string, " vendor=%08"PRIx32, ntohl(*(uint32_t *) body));
+    ds_put_format(string, " %zu bytes additional data",
+                  len - sizeof(uint32_t));
 }
 
 enum stats_direction {
@@ -891,10 +947,10 @@ print_stats(struct ds *string, int type, const void *body, size_t body_len,
             { 0, SIZE_MAX, ofp_port_stats_reply },
         },
         {
-            OFPST_SWITCH,
-            "switch status",
-            { 0, 0, NULL, },
-            { 0, SIZE_MAX, switch_status_reply },
+            OFPST_VENDOR,
+            "vendor-specific",
+            { sizeof(uint32_t), SIZE_MAX, vendor_stat },
+            { sizeof(uint32_t), SIZE_MAX, vendor_stat },
         },
         {
             -1,
@@ -987,6 +1043,12 @@ struct openflow_packet {
 };
 
 static const struct openflow_packet packets[] = {
+    {
+        OFPT_HELLO,
+        "hello",
+        sizeof (struct ofp_header),
+        NULL,
+    },
     {
         OFPT_FEATURES_REQUEST,
         "features_request",
@@ -1054,7 +1116,7 @@ static const struct openflow_packet packets[] = {
         ofp_print_port_status
     },
     {
-        OFPT_ERROR_MSG,
+        OFPT_ERROR,
         "error_msg",
         sizeof (struct ofp_error_msg),
         ofp_print_error_msg,
index 7eb93ba..fabd61e 100644 (file)
@@ -39,6 +39,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include "ofpbuf.h"
+#include "openflow.h"
 #include "poll-loop.h"
 #include "sat-math.h"
 #include "timeval.h"
@@ -113,6 +114,11 @@ struct rconn {
      * an echo request as an inactivity probe packet.  We should receive back
      * a response. */
     int probe_interval;         /* Secs of inactivity before sending probe. */
+
+    /* Messages sent or received are copied to the monitor connections. */
+#define MAX_MONITORS 8
+    struct vconn *monitors[8];
+    size_t n_monitors;
 };
 
 static unsigned int elapsed_in_this_state(const struct rconn *);
@@ -124,6 +130,7 @@ static int reconnect(struct rconn *);
 static void disconnect(struct rconn *, int error);
 static void flush_queue(struct rconn *);
 static void question_connectivity(struct rconn *);
+static void copy_to_monitor(struct rconn *, const struct ofpbuf *);
 
 /* Creates a new rconn, connects it (reliably) to 'name', and returns it. */
 struct rconn *
@@ -188,6 +195,8 @@ rconn_create(int probe_interval, int max_backoff)
 
     rc->probe_interval = probe_interval ? MAX(5, probe_interval) : 0;
 
+    rc->n_monitors = 0;
+
     return rc;
 }
 
@@ -264,7 +273,7 @@ reconnect(struct rconn *rc)
 
     VLOG_WARN("%s: connecting...", rc->name);
     rc->n_attempted_connections++;
-    retval = vconn_open(rc->name, &rc->vconn);
+    retval = vconn_open(rc->name, OFP_VERSION, &rc->vconn);
     if (!retval) {
         rc->backoff_deadline = time_now() + rc->backoff;
         state_transition(rc, S_CONNECTING);
@@ -302,13 +311,8 @@ run_CONNECTING(struct rconn *rc)
     if (!retval) {
         VLOG_WARN("%s: connected", rc->name);
         rc->n_successful_connections++;
-        if (vconn_is_passive(rc->vconn)) {
-            ofp_error(0, "%s: passive vconn not supported", rc->name);
-            state_transition(rc, S_VOID);
-        } else {
-            state_transition(rc, S_ACTIVE);
-            rc->last_connected = rc->state_entered;
-        }
+        state_transition(rc, S_ACTIVE);
+        rc->last_connected = rc->state_entered;
     } else if (retval != EAGAIN) {
         VLOG_WARN("%s: connection failed (%s)", rc->name, strerror(retval));
         disconnect(rc, retval);
@@ -428,6 +432,7 @@ rconn_recv(struct rconn *rc)
         struct ofpbuf *buffer;
         int error = vconn_recv(rc->vconn, &buffer);
         if (!error) {
+            copy_to_monitor(rc, buffer);
             rc->last_received = time_now();
             rc->packets_received++;
             if (rc->state == S_IDLE) {
@@ -468,6 +473,7 @@ int
 rconn_send(struct rconn *rc, struct ofpbuf *b, int *n_queued)
 {
     if (rconn_is_connected(rc)) {
+        copy_to_monitor(rc, b);
         b->private = n_queued;
         if (n_queued) {
             ++*n_queued;
@@ -485,7 +491,7 @@ rconn_send(struct rconn *rc, struct ofpbuf *b, int *n_queued)
 /* Sends 'b' on 'rc'.  Increments '*n_queued' while the packet is in flight; it
  * will be decremented when it has been sent (or discarded due to
  * disconnection).  Returns 0 if successful, EAGAIN if '*n_queued' is already
- * at least as large of 'queue_limit', or ENOTCONN if 'rc' is not currently
+ * at least as large as 'queue_limit', or ENOTCONN if 'rc' is not currently
  * connected.  Regardless of return value, 'b' is destroyed.
  *
  * Because 'b' may be sent (or discarded) before this function returns, the
@@ -515,6 +521,21 @@ rconn_packets_sent(const struct rconn *rc)
     return rc->packets_sent;
 }
 
+/* Adds 'vconn' to 'rc' as a monitoring connection, to which all messages sent
+ * and received on 'rconn' will be copied.  'rc' takes ownership of 'vconn'. */
+void
+rconn_add_monitor(struct rconn *rc, struct vconn *vconn)
+{
+    if (rc->n_monitors < ARRAY_SIZE(rc->monitors)) {
+        VLOG_WARN("new monitor connection from %s", vconn_get_name(vconn));
+        rc->monitors[rc->n_monitors++] = vconn;
+    } else {
+        VLOG_DBG("too many monitor connections, discarding %s",
+                 vconn_get_name(vconn));
+        vconn_close(vconn);
+    }
+}
+
 /* Returns 'rc''s name (the 'name' argument passed to rconn_new()). */
 const char *
 rconn_get_name(const struct rconn *rc)
@@ -766,3 +787,31 @@ question_connectivity(struct rconn *rc)
         rc->last_questioned = now;
     }
 }
+
+static void
+copy_to_monitor(struct rconn *rc, const struct ofpbuf *b)
+{
+    struct ofpbuf *clone = NULL;
+    int retval;
+    size_t i;
+
+    for (i = 0; i < rc->n_monitors; ) {
+        struct vconn *vconn = rc->monitors[i];
+
+        if (!clone) {
+            clone = ofpbuf_clone(b);
+        }
+        retval = vconn_send(vconn, clone);
+        if (!retval) {
+            clone = NULL;
+        } else if (retval != EAGAIN) {
+            VLOG_DBG("%s: closing monitor connection to %s: %s",
+                     rconn_get_name(rc), vconn_get_name(vconn),
+                     strerror(retval));
+            rc->monitors[i] = rc->monitors[--rc->n_monitors];
+            continue;
+        }
+        i++;
+    }
+    ofpbuf_delete(clone);
+}
diff --git a/lib/stp.c b/lib/stp.c
new file mode 100644 (file)
index 0000000..6f7f09a
--- /dev/null
+++ b/lib/stp.c
@@ -0,0 +1,1064 @@
+/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
+ * Junior University
+ *
+ * We are making the OpenFlow specification and associated documentation
+ * (Software) available for public use and benefit with the expectation
+ * that others will use, modify and enhance the Software and contribute
+ * those enhancements back to the community. However, since we would
+ * like to make the Software available for broadest use, with as few
+ * restrictions as possible permission is hereby granted, free of
+ * charge, to any person obtaining a copy of this Software to deal in
+ * the Software under the copyrights without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * The name and trademarks of copyright holder(s) may NOT be used in
+ * advertising or publicity pertaining to the Software or any
+ * derivatives without specific, written prior permission.
+ */
+
+/* Based on sample implementation in 802.1D-1998.  Above copyright and license
+ * applies to all modifications. */
+
+#include "stp.h"
+#include <arpa/inet.h>
+#include <assert.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include "packets.h"
+#include "util.h"
+#include "xtoxll.h"
+
+#include "vlog.h"
+#define THIS_MODULE VLM_stp
+
+/* Ethernet address used as the destination for STP frames. */
+const uint8_t stp_eth_addr[ETH_ADDR_LEN]
+= { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x01 };
+
+#define STP_PROTOCOL_ID 0x0000
+#define STP_PROTOCOL_VERSION 0x00
+#define STP_TYPE_CONFIG 0x00
+#define STP_TYPE_TCN 0x80
+
+struct stp_bpdu_header {
+    uint16_t protocol_id;       /* STP_PROTOCOL_ID. */
+    uint8_t protocol_version;   /* STP_PROTOCOL_VERSION. */
+    uint8_t bpdu_type;          /* One of STP_TYPE_*. */
+} __attribute__((packed));
+BUILD_ASSERT_DECL(sizeof(struct stp_bpdu_header) == 4);
+
+enum stp_config_bpdu_flags {
+    STP_CONFIG_TOPOLOGY_CHANGE_ACK = 0x80,
+    STP_CONFIG_TOPOLOGY_CHANGE = 0x01
+};
+
+struct stp_config_bpdu {
+    struct stp_bpdu_header header; /* Type STP_TYPE_CONFIG. */
+    uint8_t flags;                 /* STP_CONFIG_* flags. */
+    uint64_t root_id;              /* 8.5.1.1: Bridge believed to be root. */
+    uint32_t root_path_cost;       /* 8.5.1.2: Cost of path to root. */
+    uint64_t bridge_id;            /* 8.5.1.3: ID of transmitting bridge. */
+    uint16_t port_id;              /* 8.5.1.4: Port transmitting the BPDU. */
+    uint16_t message_age;          /* 8.5.1.5: Age of BPDU at tx time. */
+    uint16_t max_age;              /* 8.5.1.6: Timeout for received data. */
+    uint16_t hello_time;           /* 8.5.1.7: Time between BPDU generation. */
+    uint16_t forward_delay;        /* 8.5.1.8: State progression delay. */
+} __attribute__((packed));
+BUILD_ASSERT_DECL(sizeof(struct stp_config_bpdu) == 35);
+
+struct stp_tcn_bpdu {
+    struct stp_bpdu_header header; /* Type STP_TYPE_TCN. */
+} __attribute__((packed));
+BUILD_ASSERT_DECL(sizeof(struct stp_tcn_bpdu) == 4);
+
+struct stp_timer {
+    bool active;                 /* Timer in use? */
+    int value;                   /* Current value of timer, counting up. */
+};
+
+struct stp_port {
+    struct stp *stp;
+    int port_id;                    /* 8.5.5.1: Unique port identifier. */
+    enum stp_state state;           /* 8.5.5.2: Current state. */
+    int path_cost;                  /* 8.5.5.3: Cost of tx/rx on this port. */
+    stp_identifier designated_root; /* 8.5.5.4. */
+    int designated_cost;            /* 8.5.5.5: Path cost to root on port. */
+    stp_identifier designated_bridge; /* 8.5.5.6. */
+    int designated_port;            /* 8.5.5.7: Port to send config msgs on. */
+    bool topology_change_ack;       /* 8.5.5.8: Flag for next config BPDU. */
+    bool config_pending;            /* 8.5.5.9: Send BPDU when hold expires? */
+    bool change_detection_enabled;  /* 8.5.5.10: Detect topology changes? */
+
+    struct stp_timer message_age_timer; /* 8.5.6.1: Age of received info. */
+    struct stp_timer forward_delay_timer; /* 8.5.6.2: State change timer. */
+    struct stp_timer hold_timer;        /* 8.5.6.3: BPDU rate limit timer. */
+
+    bool state_changed;
+};
+
+struct stp {
+    /* Static bridge data. */
+    char *name;                     /* Human-readable name for log messages. */
+    stp_identifier bridge_id;       /* 8.5.3.7: This bridge. */
+    int max_age;                    /* 8.5.3.4: Time to drop received data. */
+    int hello_time;                 /* 8.5.3.5: Time between sending BPDUs. */
+    int forward_delay;              /* 8.5.3.6: Delay between state changes. */
+    int bridge_max_age;             /* 8.5.3.8: max_age when we're root. */
+    int bridge_hello_time;          /* 8.5.3.9: hello_time as root. */
+    int bridge_forward_delay;       /* 8.5.3.10: forward_delay as root. */
+
+    /* Dynamic bridge data. */
+    stp_identifier designated_root; /* 8.5.3.1: Bridge believed to be root. */
+    unsigned int root_path_cost;    /* 8.5.3.2: Cost of path to root. */
+    struct stp_port *root_port;     /* 8.5.3.3: Lowest cost port to root. */
+    bool topology_change_detected;  /* 8.5.3.11: Detected a topology change? */
+    bool topology_change;           /* 8.5.3.12: Received topology change? */
+
+    /* Bridge timers. */
+    struct stp_timer hello_timer;   /* 8.5.4.1: Hello timer. */
+    struct stp_timer tcn_timer;     /* 8.5.4.2: Topology change timer. */
+    struct stp_timer topology_change_timer; /* 8.5.4.3. */
+
+    /* Ports. */
+    struct stp_port ports[STP_MAX_PORTS];
+
+    /* Interface to client. */
+    struct stp_port *first_changed_port;
+    void (*send_bpdu)(const void *bpdu, size_t bpdu_size,
+                      int port_no, void *aux);
+    void *aux;
+};
+
+#define FOR_EACH_ENABLED_PORT(PORT, STP)                        \
+    for ((PORT) = stp_next_enabled_port((STP), (STP)->ports);   \
+         (PORT);                                                \
+         (PORT) = stp_next_enabled_port((STP), (PORT) + 1))
+static struct stp_port *
+stp_next_enabled_port(const struct stp *stp, const struct stp_port *port)
+{
+    for (; port < &stp->ports[ARRAY_SIZE(stp->ports)]; port++) {
+        if (port->state != STP_DISABLED) {
+            return (struct stp_port *) port;
+        }
+    }
+    return NULL;
+}
+
+#define SECONDS_TO_TIMER(SECS) ((SECS) * 0x100)
+
+#define MESSAGE_AGE_INCREMENT 1
+
+static void stp_transmit_config(struct stp_port *);
+static bool stp_supersedes_port_info(const struct stp_port *,
+                                     const struct stp_config_bpdu *);
+static void stp_record_config_information(struct stp_port *,
+                                          const struct stp_config_bpdu *);
+static void stp_record_config_timeout_values(struct stp *,
+                                             const struct stp_config_bpdu  *);
+static bool stp_is_designated_port(const struct stp_port *);
+static void stp_config_bpdu_generation(struct stp *);
+static void stp_transmit_tcn(struct stp *);
+static void stp_configuration_update(struct stp *);
+static bool stp_supersedes_root(const struct stp_port *root,
+                                const struct stp_port *);
+static void stp_root_selection(struct stp *);
+static void stp_designated_port_selection(struct stp *);
+static void stp_become_designated_port(struct stp_port *);
+static void stp_port_state_selection(struct stp *);
+static void stp_make_forwarding(struct stp_port *);
+static void stp_make_blocking(struct stp_port *);
+static void stp_set_port_state(struct stp_port *, enum stp_state);
+static void stp_topology_change_detection(struct stp *);
+static void stp_topology_change_acknowledged(struct stp *);
+static void stp_acknowledge_topology_change(struct stp_port *);
+static void stp_received_config_bpdu(struct stp *, struct stp_port *,
+                                     const struct stp_config_bpdu *);
+static void stp_received_tcn_bpdu(struct stp *, struct stp_port *,
+                                  const struct stp_tcn_bpdu *);
+static void stp_hello_timer_expiry(struct stp *);
+static void stp_message_age_timer_expiry(struct stp_port *);
+static bool stp_is_designated_for_some_port(const struct stp *);
+static void stp_forward_delay_timer_expiry(struct stp_port *);
+static void stp_tcn_timer_expiry(struct stp *);
+static void stp_topology_change_timer_expiry(struct stp *);
+static void stp_hold_timer_expiry(struct stp_port *);
+static void stp_initialize_port(struct stp_port *, enum stp_state);
+static void stp_become_root_bridge(struct stp *stp);
+
+static void stp_start_timer(struct stp_timer *, int value);
+static void stp_stop_timer(struct stp_timer *);
+static bool stp_timer_expired(struct stp_timer *, int elapsed, int timeout);
+
+/* Creates and returns a new STP instance that initially has no port enabled.
+ *
+ * 'bridge_id' should be a 48-bit MAC address as returned by
+ * eth_addr_to_uint64().  'bridge_id' may also have a priority value in its top
+ * 16 bits; if those bits are set to 0, the default bridge priority of 32768 is
+ * used.  (This priority may be changed with stp_set_bridge_priority().)
+ *
+ * When the bridge needs to send out a BPDU, it calls 'send_bpdu', passing
+ * 'aux' as auxiliary data.  This callback may be called from stp_tick() or
+ * stp_received_bpdu().
+ */
+struct stp *
+stp_create(const char *name, stp_identifier bridge_id,
+           void (*send_bpdu)(const void *bpdu, size_t bpdu_size,
+                             int port_no, void *aux),
+           void *aux)
+{
+    struct stp *stp;
+    struct stp_port *p;
+
+    stp = xcalloc(1, sizeof *stp);
+    stp->name = xstrdup(name);
+    stp->bridge_id = bridge_id;
+    if (!(stp->bridge_id >> 48)) {
+        stp->bridge_id |= UINT64_C(32768) << 48;
+    }
+    stp->max_age = SECONDS_TO_TIMER(20);
+    stp->hello_time = SECONDS_TO_TIMER(2);
+    stp->forward_delay = SECONDS_TO_TIMER(15);
+    stp->bridge_max_age = stp->max_age;
+    stp->bridge_hello_time = stp->hello_time;
+    stp->bridge_forward_delay = stp->forward_delay;
+
+    stp->designated_root = stp->bridge_id;
+    stp->root_path_cost = 0;
+    stp->root_port = NULL;
+    stp->topology_change_detected = false;
+    stp->topology_change = false;
+
+    stp_stop_timer(&stp->tcn_timer);
+    stp_stop_timer(&stp->topology_change_timer);
+    stp_start_timer(&stp->hello_timer, 0);
+
+    stp->send_bpdu = send_bpdu;
+    stp->aux = aux;
+
+    stp->first_changed_port = &stp->ports[ARRAY_SIZE(stp->ports)];
+    for (p = stp->ports; p < &stp->ports[ARRAY_SIZE(stp->ports)]; p++) {
+        p->stp = stp;
+        p->port_id = (stp_port_no(p) + 1) | (128 << 8);
+        p->path_cost = 19;      /* Recommended default for 100 Mb/s link. */
+        stp_initialize_port(p, STP_DISABLED);
+    }
+    return stp;
+}
+
+/* Destroys 'stp'. */
+void
+stp_destroy(struct stp *stp)
+{
+    free(stp);
+}
+
+void
+stp_tick(struct stp *stp, int elapsed)
+{
+    struct stp_port *p;
+
+    if (stp_timer_expired(&stp->hello_timer, elapsed, stp->hello_time)) {
+        stp_hello_timer_expiry(stp);
+    }
+    if (stp_timer_expired(&stp->tcn_timer, elapsed, stp->bridge_hello_time)) {
+        stp_tcn_timer_expiry(stp);
+    }
+    if (stp_timer_expired(&stp->topology_change_timer, elapsed,
+                          stp->max_age + stp->forward_delay)) {
+        stp_topology_change_timer_expiry(stp);
+    }
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_timer_expired(&p->message_age_timer, elapsed, stp->max_age)) {
+            stp_message_age_timer_expiry(p);
+        }
+    }
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_timer_expired(&p->forward_delay_timer, elapsed,
+                              stp->forward_delay)) {
+            stp_forward_delay_timer_expiry(p);
+        }
+        if (stp_timer_expired(&p->hold_timer, elapsed, SECONDS_TO_TIMER(1))) {
+            stp_hold_timer_expiry(p);
+        }
+    }
+}
+
+void
+stp_set_bridge_priority(struct stp *stp, uint16_t new_priority)
+{
+    stp_identifier new_bridge_id;
+    bool root;
+    struct stp_port *p;
+
+    new_bridge_id = ((stp->bridge_id & UINT64_C(0xffffffffffff))
+                     | ((uint64_t) new_priority << 48));
+    root = stp_is_root_bridge(stp);
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_is_designated_port(p)) {
+            p->designated_bridge = new_bridge_id;
+        }
+    }
+    stp->bridge_id = new_bridge_id;
+    stp_configuration_update(stp);
+    stp_port_state_selection(stp);
+    if (stp_is_root_bridge(stp) && !root) {
+        stp_become_root_bridge(stp);
+    }
+}
+
+/* Returns the name given to 'stp' in the call to stp_create(). */
+const char *
+stp_get_name(const struct stp *stp)
+{
+    return stp->name;
+}
+
+/* Returns the bridge ID for 'stp'. */
+stp_identifier
+stp_get_bridge_id(const struct stp *stp)
+{
+    return stp->bridge_id;
+}
+
+/* Returns the bridge ID of the bridge currently believed to be the root. */
+stp_identifier
+stp_get_designated_root(const struct stp *stp)
+{
+    return stp->designated_root;
+}
+
+/* Returns true if 'stp' believes itself to the be root of the spanning tree,
+ * false otherwise. */
+bool
+stp_is_root_bridge(const struct stp *stp)
+{
+    return stp->bridge_id == stp->designated_root;
+}
+
+/* Returns the cost of the path from 'stp' to the root of the spanning tree. */
+int
+stp_get_root_path_cost(const struct stp *stp)
+{
+    return stp->root_path_cost;
+}
+
+/* Returns the port in 'stp' with index 'port_no', which must be between 0 and
+ * STP_MAX_PORTS. */
+struct stp_port *
+stp_get_port(struct stp *stp, int port_no)
+{
+    assert(port_no >= 0 && port_no < ARRAY_SIZE(stp->ports));
+    return &stp->ports[port_no];
+}
+
+/* Returns the port connecting 'stp' to the root bridge, or a null pointer if
+ * there is no such port. */
+struct stp_port *
+stp_get_root_port(struct stp *stp)
+{
+    return stp->root_port;
+}
+
+/* Finds a port whose state has changed.  If successful, stores the port whose
+ * state changed in '*portp' and returns true.  If no port has changed, stores
+ * NULL in '*portp' and returns false. */
+bool
+stp_get_changed_port(struct stp *stp, struct stp_port **portp)
+{
+    struct stp_port *end = &stp->ports[ARRAY_SIZE(stp->ports)];
+    struct stp_port *p;
+
+    for (p = stp->first_changed_port; p < end; p++) {
+        if (p->state_changed) {
+            p->state_changed = false;
+            stp->first_changed_port = p + 1;
+            *portp = p;
+            return true;
+        }
+    }
+    stp->first_changed_port = end;
+    *portp = NULL;
+    return false;
+}
+
+/* Returns the name for the given 'state' (for use in debugging and log
+ * messages). */
+const char *
+stp_state_name(enum stp_state state)
+{
+    switch (state) {
+    case STP_DISABLED:
+        return "disabled";
+    case STP_LISTENING:
+        return "listening";
+    case STP_LEARNING:
+        return "learning";
+    case STP_FORWARDING:
+        return "forwarding";
+    case STP_BLOCKING:
+        return "blocking";
+    default:
+        NOT_REACHED();
+    }
+}
+
+/* Returns true if 'state' is one in which packets received on a port should
+ * be forwarded, false otherwise. */
+bool
+stp_forward_in_state(enum stp_state state)
+{
+    return state == STP_FORWARDING;
+}
+
+/* Returns true if 'state' is one in which MAC learning should be done on
+ * packets received on a port, false otherwise. */
+bool
+stp_learn_in_state(enum stp_state state)
+{
+    return state & (STP_LEARNING | STP_FORWARDING);
+}
+
+/* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
+ * 'bpdu_size' bytes in length, was received on port 'p'.
+ *
+ * This function may call the 'send_bpdu' function provided to stp_create(). */
+void
+stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
+{
+    struct stp *stp = p->stp;
+    const struct stp_bpdu_header *header;
+
+    if (p->state == STP_DISABLED) {
+        return;
+    }
+
+    if (bpdu_size < sizeof(struct stp_bpdu_header)) {
+        VLOG_WARN("%s: received runt %zu-byte BPDU", stp->name, bpdu_size);
+        return;
+    }
+
+    header = bpdu;
+    if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
+        VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
+                  stp->name, ntohs(header->protocol_id));
+        return;
+    }
+    if (header->protocol_version != STP_PROTOCOL_VERSION) {
+        VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
+                 stp->name, header->protocol_version);
+    }
+
+    switch (header->bpdu_type) {
+    case STP_TYPE_CONFIG:
+        if (bpdu_size < sizeof(struct stp_config_bpdu)) {
+            VLOG_WARN("%s: received config BPDU with invalid size %zu",
+                      stp->name, bpdu_size);
+            return;
+        }
+        stp_received_config_bpdu(stp, p, bpdu);
+        break;
+
+    case STP_TYPE_TCN:
+        if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
+            VLOG_WARN("%s: received TCN BPDU with invalid size %zu",
+                      stp->name, bpdu_size);
+            return;
+        }
+        stp_received_tcn_bpdu(stp, p, bpdu);
+        break;
+
+    default:
+        VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
+                  stp->name, header->bpdu_type);
+        return;
+    }
+}
+
+/* Returns the STP entity in which 'p' is nested. */
+struct stp *
+stp_port_get_stp(struct stp_port *p)
+{
+    return p->stp;
+}
+
+/* Returns the index of port 'p' within its bridge. */
+int
+stp_port_no(const struct stp_port *p)
+{
+    struct stp *stp = p->stp;
+    assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
+    return p - stp->ports;
+}
+
+/* Returns the state of port 'p'. */
+enum stp_state
+stp_port_get_state(const struct stp_port *p)
+{
+    return p->state;
+}
+
+/* Disables STP on port 'p'. */
+void
+stp_port_disable(struct stp_port *p)
+{
+    struct stp *stp = p->stp;
+    if (p->state != STP_DISABLED) {
+        bool root = stp_is_root_bridge(stp);
+        stp_become_designated_port(p);
+        stp_set_port_state(p, STP_DISABLED);
+        p->topology_change_ack = false;
+        p->config_pending = false;
+        stp_stop_timer(&p->message_age_timer);
+        stp_stop_timer(&p->forward_delay_timer);
+        stp_configuration_update(stp);
+        stp_port_state_selection(stp);
+        if (stp_is_root_bridge(stp) && !root) {
+            stp_become_root_bridge(stp);
+        }
+    }
+}
+
+/* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
+void
+stp_port_enable(struct stp_port *p)
+{
+    if (p->state == STP_DISABLED) {
+        stp_initialize_port(p, STP_BLOCKING);
+        stp_port_state_selection(p->stp);
+    }
+}
+
+/* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
+ * are interpreted as higher priorities. */
+void
+stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
+{
+    uint16_t new_port_id = (p->port_id & 0xff) | (new_priority << 8);
+    if (p->port_id != new_port_id) {
+        struct stp *stp = p->stp;
+        if (stp_is_designated_port(p)) {
+            p->designated_port = new_port_id;
+        }
+        p->port_id = new_port_id;
+        if (stp->bridge_id == p->designated_bridge
+            && p->port_id < p->designated_port) {
+            stp_become_designated_port(p);
+            stp_port_state_selection(stp);
+        }
+    }
+}
+
+/* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
+ * used to indicate faster links.  Use stp_port_set_speed() to automatically
+ * generate a default path cost from a link speed. */
+void
+stp_port_set_path_cost(struct stp_port *p, unsigned int path_cost)
+{
+    if (p->path_cost != path_cost) {
+        struct stp *stp = p->stp;
+        p->path_cost = path_cost;
+        stp_configuration_update(stp);
+        stp_port_state_selection(stp);
+    }
+}
+
+/* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
+void
+stp_port_set_speed(struct stp_port *p, unsigned int speed)
+{
+    stp_port_set_path_cost(p, (speed >= 10000 ? 2  /* 10 Gb/s. */
+                               : speed >= 1000 ? 4 /* 1 Gb/s. */
+                               : speed >= 100 ? 19 /* 100 Mb/s. */
+                               : speed >= 16 ? 62  /* 16 Mb/s. */
+                               : speed >= 10 ? 100 /* 10 Mb/s. */
+                               : speed >= 4 ? 250  /* 4 Mb/s. */
+                               : 19));             /* 100 Mb/s (guess). */
+}
+
+/* Enables topology change detection on port 'p'. */
+void
+stp_port_enable_change_detection(struct stp_port *p)
+{
+    p->change_detection_enabled = true;
+}
+
+/* Disables topology change detection on port 'p'. */
+void
+stp_port_disable_change_detection(struct stp_port *p)
+{
+    p->change_detection_enabled = false;
+}
+\f
+static void
+stp_transmit_config(struct stp_port *p)
+{
+    struct stp *stp = p->stp;
+    bool root = stp_is_root_bridge(stp);
+    if (!root && !stp->root_port) {
+        return;
+    }
+    if (p->hold_timer.active) {
+        p->config_pending = true;
+    } else {
+        struct stp_config_bpdu config;
+        memset(&config, 0, sizeof config);
+        config.header.protocol_id = htons(STP_PROTOCOL_ID);
+        config.header.protocol_version = STP_PROTOCOL_VERSION;
+        config.header.bpdu_type = STP_TYPE_CONFIG;
+        config.flags = 0;
+        if (p->topology_change_ack) {
+            config.flags |= htons(STP_CONFIG_TOPOLOGY_CHANGE_ACK);
+        }
+        if (stp->topology_change) {
+            config.flags |= htons(STP_CONFIG_TOPOLOGY_CHANGE);
+        }
+        config.root_id = htonll(stp->designated_root);
+        config.root_path_cost = htonl(stp->root_path_cost);
+        config.bridge_id = htonll(stp->bridge_id);
+        config.port_id = htons(p->port_id);
+        if (root) {
+            config.message_age = htons(0);
+        } else {
+            config.message_age = htons(stp->root_port->message_age_timer.value
+                                       + MESSAGE_AGE_INCREMENT);
+        }
+        config.max_age = htons(stp->max_age);
+        config.hello_time = htons(stp->hello_time);
+        config.forward_delay = htons(stp->forward_delay);
+        if (ntohs(config.message_age) < stp->max_age) {
+            p->topology_change_ack = false;
+            p->config_pending = false;
+            stp->send_bpdu(&config, sizeof config, stp_port_no(p), stp->aux);
+            stp_start_timer(&p->hold_timer, 0);
+        }
+    }
+}
+
+static bool
+stp_supersedes_port_info(const struct stp_port *p,
+                         const struct stp_config_bpdu *config)
+{
+    if (ntohll(config->root_id) != p->designated_root) {
+        return ntohll(config->root_id) < p->designated_root;
+    } else if (ntohl(config->root_path_cost) != p->designated_cost) {
+        return ntohl(config->root_path_cost) < p->designated_cost;
+    } else if (ntohll(config->bridge_id) != p->designated_bridge) {
+        return ntohll(config->bridge_id) < p->designated_bridge;
+    } else {
+        return (ntohll(config->bridge_id) != p->stp->bridge_id
+                || ntohs(config->port_id) <= p->designated_port);
+    }
+}
+
+static void
+stp_record_config_information(struct stp_port *p,
+                              const struct stp_config_bpdu *config)
+{
+    p->designated_root = ntohll(config->root_id);
+    p->designated_cost = ntohl(config->root_path_cost);
+    p->designated_bridge = ntohll(config->bridge_id);
+    p->designated_port = ntohs(config->port_id);
+    stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
+}
+
+static void
+stp_record_config_timeout_values(struct stp *stp,
+                                 const struct stp_config_bpdu  *config)
+{
+    stp->max_age = ntohs(config->max_age);
+    stp->hello_time = ntohs(config->hello_time);
+    stp->forward_delay = ntohs(config->forward_delay);
+    stp->topology_change = config->flags & htons(STP_CONFIG_TOPOLOGY_CHANGE);
+}
+
+static bool
+stp_is_designated_port(const struct stp_port *p)
+{
+    return (p->designated_bridge == p->stp->bridge_id
+            && p->designated_port == p->port_id);
+}
+
+static void
+stp_config_bpdu_generation(struct stp *stp)
+{
+    struct stp_port *p;
+
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_is_designated_port(p)) {
+            stp_transmit_config(p);
+        }
+    }
+}
+
+static void
+stp_transmit_tcn(struct stp *stp)
+{
+    struct stp_port *p = stp->root_port;
+    struct stp_tcn_bpdu tcn_bpdu;
+    if (!p) {
+        return;
+    }
+    tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
+    tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
+    tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
+    stp->send_bpdu(&tcn_bpdu, sizeof tcn_bpdu, stp_port_no(p), stp->aux);
+}
+
+static void
+stp_configuration_update(struct stp *stp)
+{
+    stp_root_selection(stp);
+    stp_designated_port_selection(stp);
+}
+
+static bool
+stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
+{
+    int p_cost = p->designated_cost + p->path_cost;
+    int root_cost = root->designated_cost + root->path_cost;
+
+    if (p->designated_root != root->designated_root) {
+        return p->designated_root < root->designated_root;
+    } else if (p_cost != root_cost) {
+        return p_cost < root_cost;
+    } else if (p->designated_bridge != root->designated_bridge) {
+        return p->designated_bridge < root->designated_bridge;
+    } else if (p->designated_port != root->designated_port) {
+        return p->designated_port < root->designated_port;
+    } else {
+        return p->port_id < root->port_id;
+    }
+}
+
+static void
+stp_root_selection(struct stp *stp)
+{
+    struct stp_port *p, *root;
+
+    root = NULL;
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_is_designated_port(p)
+            || p->designated_root >= stp->bridge_id) {
+            continue;
+        }
+        if (root && !stp_supersedes_root(root, p)) {
+            continue;
+        }
+        root = p;
+    }
+    stp->root_port = root;
+    if (!root) {
+        stp->designated_root = stp->bridge_id;
+        stp->root_path_cost = 0;
+    } else {
+        stp->designated_root = root->designated_root;
+        stp->root_path_cost = root->designated_cost + root->path_cost;
+    }
+}
+
+static void
+stp_designated_port_selection(struct stp *stp)
+{
+    struct stp_port *p;
+
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (stp_is_designated_port(p)
+            || p->designated_root != stp->designated_root
+            || stp->root_path_cost < p->designated_cost
+            || (stp->root_path_cost == p->designated_cost
+                && (stp->bridge_id < p->designated_bridge
+                    || (stp->bridge_id == p->designated_bridge
+                        && p->port_id <= p->designated_port))))
+        {
+            stp_become_designated_port(p);
+        }
+    }
+}
+
+static void
+stp_become_designated_port(struct stp_port *p)
+{
+    struct stp *stp = p->stp;
+    p->designated_root = stp->designated_root;
+    p->designated_cost = stp->root_path_cost;
+    p->designated_bridge = stp->bridge_id;
+    p->designated_port = p->port_id;
+}
+
+static void
+stp_port_state_selection(struct stp *stp)
+{
+    struct stp_port *p;
+
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (p == stp->root_port) {
+            p->config_pending = false;
+            p->topology_change_ack = false;
+            stp_make_forwarding(p);
+        } else if (stp_is_designated_port(p)) {
+            stp_stop_timer(&p->message_age_timer);
+            stp_make_forwarding(p);
+        } else {
+            p->config_pending = false;
+            p->topology_change_ack = false;
+            stp_make_blocking(p);
+        }
+    }
+}
+
+static void
+stp_make_forwarding(struct stp_port *p)
+{
+    if (p->state == STP_BLOCKING) {
+        stp_set_port_state(p, STP_LISTENING);
+        stp_start_timer(&p->forward_delay_timer, 0);
+    }
+}
+
+static void
+stp_make_blocking(struct stp_port *p)
+{
+    if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
+        if (p->state & (STP_FORWARDING | STP_LEARNING)) {
+            if (p->change_detection_enabled) {
+                stp_topology_change_detection(p->stp);
+            }
+        }
+        stp_set_port_state(p, STP_BLOCKING);
+        stp_stop_timer(&p->forward_delay_timer);
+    }
+}
+
+static void
+stp_set_port_state(struct stp_port *p, enum stp_state state)
+{
+    if (state != p->state && !p->state_changed) {
+        p->state_changed = true;
+        if (p < p->stp->first_changed_port) {
+            p->stp->first_changed_port = p;
+        }
+    }
+    p->state = state;
+}
+
+static void
+stp_topology_change_detection(struct stp *stp)
+{
+    if (stp_is_root_bridge(stp)) {
+        stp->topology_change = true;
+        stp_start_timer(&stp->topology_change_timer, 0);
+    } else if (!stp->topology_change_detected) {
+        stp_transmit_tcn(stp);
+        stp_start_timer(&stp->tcn_timer, 0);
+    }
+    stp->topology_change_detected = true;
+}
+
+static void
+stp_topology_change_acknowledged(struct stp *stp)
+{
+    stp->topology_change_detected = false;
+    stp_stop_timer(&stp->tcn_timer);
+}
+
+static void
+stp_acknowledge_topology_change(struct stp_port *p)
+{
+    p->topology_change_ack = true;
+    stp_transmit_config(p);
+}
+
+void
+stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
+                         const struct stp_config_bpdu *config)
+{
+    if (ntohs(config->message_age) >= ntohs(config->max_age)) {
+        VLOG_WARN("%s: received config BPDU with message age (%u) greater "
+                  "than max age (%u)",
+                  stp->name,
+                  ntohs(config->message_age), ntohs(config->max_age));
+        return;
+    }
+    if (p->state != STP_DISABLED) {
+        bool root = stp_is_root_bridge(stp);
+        if (stp_supersedes_port_info(p, config)) {
+            stp_record_config_information(p, config);
+            stp_configuration_update(stp);
+            stp_port_state_selection(stp);
+            if (!stp_is_root_bridge(stp) && root) {
+                stp_stop_timer(&stp->hello_timer);
+                if (stp->topology_change_detected) {
+                    stp_stop_timer(&stp->topology_change_timer);
+                    stp_transmit_tcn(stp);
+                    stp_start_timer(&stp->tcn_timer, 0);
+                }
+            }
+            if (p == stp->root_port) {
+                stp_record_config_timeout_values(stp, config);
+                stp_config_bpdu_generation(stp);
+                if (config->flags & htons(STP_CONFIG_TOPOLOGY_CHANGE_ACK)) {
+                    stp_topology_change_acknowledged(stp);
+                }
+            }
+        } else if (stp_is_designated_port(p)) {
+            stp_transmit_config(p);
+        }
+    }
+}
+
+void
+stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p,
+                      const struct stp_tcn_bpdu *tcn)
+{
+    if (p->state != STP_DISABLED) {
+        if (stp_is_designated_port(p)) {
+            stp_topology_change_detection(stp);
+            stp_acknowledge_topology_change(p);
+        }
+    }
+}
+
+static void
+stp_hello_timer_expiry(struct stp *stp)
+{
+    stp_config_bpdu_generation(stp);
+    stp_start_timer(&stp->hello_timer, 0);
+}
+
+static void
+stp_message_age_timer_expiry(struct stp_port *p)
+{
+    struct stp *stp = p->stp;
+    bool root = stp_is_root_bridge(stp);
+    stp_become_designated_port(p);
+    stp_configuration_update(stp);
+    stp_port_state_selection(stp);
+    if (stp_is_root_bridge(stp) && !root) {
+        stp->max_age = stp->bridge_max_age;
+        stp->hello_time = stp->bridge_hello_time;
+        stp->forward_delay = stp->bridge_forward_delay;
+        stp_topology_change_detection(stp);
+        stp_stop_timer(&stp->tcn_timer);
+        stp_config_bpdu_generation(stp);
+        stp_start_timer(&stp->hello_timer, 0);
+    }
+}
+
+static bool
+stp_is_designated_for_some_port(const struct stp *stp)
+{
+    const struct stp_port *p;
+
+    FOR_EACH_ENABLED_PORT (p, stp) {
+        if (p->designated_bridge == stp->bridge_id) {
+            return true;
+        }
+    }
+    return false;
+}
+
+static void
+stp_forward_delay_timer_expiry(struct stp_port *p)
+{
+    if (p->state == STP_LISTENING) {
+        stp_set_port_state(p, STP_LEARNING);
+        stp_start_timer(&p->forward_delay_timer, 0);
+    } else if (p->state == STP_LEARNING) {
+        stp_set_port_state(p, STP_FORWARDING);
+        if (stp_is_designated_for_some_port(p->stp)) {
+            if (p->change_detection_enabled) {
+                stp_topology_change_detection(p->stp);
+            }
+        }
+    }
+}
+
+static void
+stp_tcn_timer_expiry(struct stp *stp)
+{
+    stp_transmit_tcn(stp);
+    stp_start_timer(&stp->tcn_timer, 0);
+}
+
+static void
+stp_topology_change_timer_expiry(struct stp *stp)
+{
+    stp->topology_change_detected = false;
+    stp->topology_change = false;
+}
+
+static void
+stp_hold_timer_expiry(struct stp_port *p)
+{
+    if (p->config_pending) {
+        stp_transmit_config(p);
+    }
+}
+
+static void
+stp_initialize_port(struct stp_port *p, enum stp_state state)
+{
+    assert(state & (STP_DISABLED | STP_BLOCKING));
+    stp_become_designated_port(p);
+    stp_set_port_state(p, state);
+    p->topology_change_ack = false;
+    p->config_pending = false;
+    p->change_detection_enabled = true;
+    stp_stop_timer(&p->message_age_timer);
+    stp_stop_timer(&p->forward_delay_timer);
+    stp_stop_timer(&p->hold_timer);
+}
+
+static void
+stp_become_root_bridge(struct stp *stp)
+{
+    stp->max_age = stp->bridge_max_age;
+    stp->hello_time = stp->bridge_hello_time;
+    stp->forward_delay = stp->bridge_forward_delay;
+    stp_topology_change_detection(stp);
+    stp_stop_timer(&stp->tcn_timer);
+    stp_config_bpdu_generation(stp);
+    stp_start_timer(&stp->hello_timer, 0);
+}
+
+static void
+stp_start_timer(struct stp_timer *timer, int value)
+{
+    timer->value = value;
+    timer->active = true;
+}
+
+static void
+stp_stop_timer(struct stp_timer *timer)
+{
+    timer->active = false;
+}
+
+static bool
+stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
+{
+    if (timer->active) {
+        timer->value += elapsed;
+        if (timer->value >= timeout) {
+            timer->active = false;
+            return true;
+        }
+    }
+    return false;
+}
+
index aabd01b..0149a37 100644 (file)
@@ -65,7 +65,7 @@ struct netlink_vconn
 static struct netlink_vconn *
 netlink_vconn_cast(struct vconn *vconn) 
 {
-    assert(vconn->class == &netlink_vconn_class);
+    vconn_assert_class(vconn, &netlink_vconn_class);
     return CONTAINER_OF(vconn, struct netlink_vconn, vconn); 
 }
 
@@ -146,7 +146,6 @@ struct vconn_class netlink_vconn_class = {
     netlink_open,               /* open */
     netlink_close,              /* close */
     NULL,                       /* connect */
-    NULL,                       /* accept */
     netlink_recv,               /* recv */
     netlink_send,               /* send */
     netlink_wait,               /* wait */
index ef5885b..2801c0c 100644 (file)
@@ -250,7 +250,7 @@ error:
 static struct ssl_vconn *
 ssl_vconn_cast(struct vconn *vconn)
 {
-    assert(vconn->class == &ssl_vconn_class);
+    vconn_assert_class(vconn, &ssl_vconn_class);
     return CONTAINER_OF(vconn, struct ssl_vconn, vconn);
 }
 
@@ -655,7 +655,6 @@ struct vconn_class ssl_vconn_class = {
     ssl_open,                   /* open */
     ssl_close,                  /* close */
     ssl_connect,                /* connect */
-    NULL,                       /* accept */
     ssl_recv,                   /* recv */
     ssl_send,                   /* send */
     ssl_wait,                   /* wait */
@@ -663,24 +662,26 @@ struct vconn_class ssl_vconn_class = {
 \f
 /* Passive SSL. */
 
-struct pssl_vconn
+struct pssl_pvconn
 {
-    struct vconn vconn;
+    struct pvconn pvconn;
     int fd;
 };
 
-static struct pssl_vconn *
-pssl_vconn_cast(struct vconn *vconn)
+struct pvconn_class pssl_pvconn_class;
+
+static struct pssl_pvconn *
+pssl_pvconn_cast(struct pvconn *pvconn)
 {
-    assert(vconn->class == &pssl_vconn_class);
-    return CONTAINER_OF(vconn, struct pssl_vconn, vconn);
+    pvconn_assert_class(pvconn, &pssl_pvconn_class);
+    return CONTAINER_OF(pvconn, struct pssl_pvconn, pvconn);
 }
 
 static int
-pssl_open(const char *name, char *suffix, struct vconn **vconnp)
+pssl_open(const char *name, char *suffix, struct pvconn **pvconnp)
 {
     struct sockaddr_in sin;
-    struct pssl_vconn *pssl;
+    struct pssl_pvconn *pssl;
     int retval;
     int fd;
     unsigned int yes = 1;
@@ -731,24 +732,24 @@ pssl_open(const char *name, char *suffix, struct vconn **vconnp)
     }
 
     pssl = xmalloc(sizeof *pssl);
-    vconn_init(&pssl->vconn, &pssl_vconn_class, 0, 0, name);
+    pvconn_init(&pssl->pvconn, &pssl_pvconn_class, name);
     pssl->fd = fd;
-    *vconnp = &pssl->vconn;
+    *pvconnp = &pssl->pvconn;
     return 0;
 }
 
 static void
-pssl_close(struct vconn *vconn)
+pssl_close(struct pvconn *pvconn)
 {
-    struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
+    struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
     close(pssl->fd);
     free(pssl);
 }
 
 static int
-pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
+pssl_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
 {
-    struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
+    struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
     struct sockaddr_in sin;
     socklen_t sin_len = sizeof sin;
     char name[128];
@@ -779,22 +780,18 @@ pssl_accept(struct vconn *vconn, struct vconn **new_vconnp)
 }
 
 static void
-pssl_wait(struct vconn *vconn, enum vconn_wait_type wait)
+pssl_wait(struct pvconn *pvconn)
 {
-    struct pssl_vconn *pssl = pssl_vconn_cast(vconn);
-    assert(wait == WAIT_ACCEPT);
+    struct pssl_pvconn *pssl = pssl_pvconn_cast(pvconn);
     poll_fd_wait(pssl->fd, POLLIN);
 }
 
-struct vconn_class pssl_vconn_class = {
-    "pssl",                     /* name */
-    pssl_open,                  /* open */
-    pssl_close,                 /* close */
-    NULL,                       /* connect */
-    pssl_accept,                /* accept */
-    NULL,                       /* recv */
-    NULL,                       /* send */
-    pssl_wait,                  /* wait */
+struct pvconn_class pssl_pvconn_class = {
+    "pssl",
+    pssl_open,
+    pssl_close,
+    pssl_accept,
+    pssl_wait,
 };
 \f
 /*
index 8379509..f5fe947 100644 (file)
@@ -85,7 +85,7 @@ new_stream_vconn(const char *name, int fd, int connect_status,
 static struct stream_vconn *
 stream_vconn_cast(struct vconn *vconn)
 {
-    assert(vconn->class == &stream_vconn_class);
+    vconn_assert_class(vconn, &stream_vconn_class);
     return CONTAINER_OF(vconn, struct stream_vconn, vconn);
 }
 
@@ -250,7 +250,6 @@ static struct vconn_class stream_vconn_class = {
     NULL,                       /* open */
     stream_close,               /* close */
     stream_connect,             /* connect */
-    NULL,                       /* accept */
     stream_recv,                /* recv */
     stream_send,                /* send */
     stream_wait,                /* wait */
@@ -258,30 +257,30 @@ static struct vconn_class stream_vconn_class = {
 \f
 /* Passive stream socket vconn. */
 
-struct pstream_vconn
+struct pstream_pvconn
 {
-    struct vconn vconn;
+    struct pvconn pvconn;
     int fd;
     int (*accept_cb)(int fd, const struct sockaddr *, size_t sa_len,
                      struct vconn **);
 };
 
-static struct vconn_class pstream_vconn_class;
+static struct pvconn_class pstream_pvconn_class;
 
-static struct pstream_vconn *
-pstream_vconn_cast(struct vconn *vconn)
+static struct pstream_pvconn *
+pstream_pvconn_cast(struct pvconn *pvconn)
 {
-    assert(vconn->class == &pstream_vconn_class);
-    return CONTAINER_OF(vconn, struct pstream_vconn, vconn);
+    pvconn_assert_class(pvconn, &pstream_pvconn_class);
+    return CONTAINER_OF(pvconn, struct pstream_pvconn, pvconn);
 }
 
 int
-new_pstream_vconn(const char *name, int fd,
+new_pstream_pvconn(const char *name, int fd,
                   int (*accept_cb)(int fd, const struct sockaddr *,
                                    size_t sa_len, struct vconn **),
-                  struct vconn **vconnp)
+                  struct pvconn **pvconnp)
 {
-    struct pstream_vconn *ps;
+    struct pstream_pvconn *ps;
     int retval;
 
     retval = set_nonblocking(fd);
@@ -298,26 +297,25 @@ new_pstream_vconn(const char *name, int fd,
     }
 
     ps = xmalloc(sizeof *ps);
-    ps->vconn.class = &pstream_vconn_class;
-    ps->vconn.connect_status = 0;
+    pvconn_init(&ps->pvconn, &pstream_pvconn_class, name);
     ps->fd = fd;
     ps->accept_cb = accept_cb;
-    *vconnp = &ps->vconn;
+    *pvconnp = &ps->pvconn;
     return 0;
 }
 
 static void
-pstream_close(struct vconn *vconn)
+pstream_close(struct pvconn *pvconn)
 {
-    struct pstream_vconn *ps = pstream_vconn_cast(vconn);
+    struct pstream_pvconn *ps = pstream_pvconn_cast(pvconn);
     close(ps->fd);
     free(ps);
 }
 
 static int
-pstream_accept(struct vconn *vconn, struct vconn **new_vconnp)
+pstream_accept(struct pvconn *pvconn, struct vconn **new_vconnp)
 {
-    struct pstream_vconn *ps = pstream_vconn_cast(vconn);
+    struct pstream_pvconn *ps = pstream_pvconn_cast(pvconn);
     struct sockaddr_storage ss;
     socklen_t ss_len = sizeof ss;
     int new_fd;
@@ -343,20 +341,16 @@ pstream_accept(struct vconn *vconn, struct vconn **new_vconnp)
 }
 
 static void
-pstream_wait(struct vconn *vconn, enum vconn_wait_type wait)
+pstream_wait(struct pvconn *pvconn)
 {
-    struct pstream_vconn *ps = pstream_vconn_cast(vconn);
-    assert(wait == WAIT_ACCEPT);
+    struct pstream_pvconn *ps = pstream_pvconn_cast(pvconn);
     poll_fd_wait(ps->fd, POLLIN);
 }
 
-static struct vconn_class pstream_vconn_class = {
-    "pstream",                  /* name */
-    NULL,                       /* open */
-    pstream_close,              /* close */
-    NULL,                       /* connect */
-    pstream_accept,             /* accept */
-    NULL,                       /* recv */
-    NULL,                       /* send */
-    pstream_wait                /* wait */
+static struct pvconn_class pstream_pvconn_class = {
+    "pstream",
+    NULL,
+    pstream_close,
+    pstream_accept,
+    pstream_wait
 };
index 3d336c4..2c8522d 100644 (file)
@@ -131,7 +131,6 @@ struct vconn_class tcp_vconn_class = {
     tcp_open,                   /* open */
     NULL,                       /* close */
     NULL,                       /* connect */
-    NULL,                       /* accept */
     NULL,                       /* recv */
     NULL,                       /* send */
     NULL,                       /* wait */
@@ -143,7 +142,7 @@ static int ptcp_accept(int fd, const struct sockaddr *sa, size_t sa_len,
                        struct vconn **vconnp);
 
 static int
-ptcp_open(const char *name, char *suffix, struct vconn **vconnp)
+ptcp_open(const char *name, char *suffix, struct pvconn **pvconnp)
 {
     struct sockaddr_in sin;
     int retval;
@@ -173,7 +172,7 @@ ptcp_open(const char *name, char *suffix, struct vconn **vconnp)
         return error;
     }
 
-    return new_pstream_vconn("ptcp", fd, ptcp_accept, vconnp);
+    return new_pstream_pvconn("ptcp", fd, ptcp_accept, pvconnp);
 }
 
 static int
@@ -194,14 +193,8 @@ ptcp_accept(int fd, const struct sockaddr *sa, size_t sa_len,
     return new_tcp_vconn(name, fd, 0, sin, vconnp);
 }
 
-struct vconn_class ptcp_vconn_class = {
-    "ptcp",                     /* name */
-    ptcp_open,                  /* open */
-    NULL,                       /* close */
-    NULL,                       /* connect */
-    NULL,                       /* accept */
-    NULL,                       /* recv */
-    NULL,                       /* send */
-    NULL,                       /* wait */
+struct pvconn_class ptcp_pvconn_class = {
+    "ptcp",
+    ptcp_open,
 };
 
index e84674f..9b08b10 100644 (file)
@@ -85,7 +85,6 @@ struct vconn_class unix_vconn_class = {
     unix_open,                  /* open */
     NULL,                       /* close */
     NULL,                       /* connect */
-    NULL,                       /* accept */
     NULL,                       /* recv */
     NULL,                       /* send */
     NULL,                       /* wait */
@@ -97,7 +96,7 @@ static int punix_accept(int fd, const struct sockaddr *sa, size_t sa_len,
                         struct vconn **vconnp);
 
 static int
-punix_open(const char *name, char *suffix, struct vconn **vconnp)
+punix_open(const char *name, char *suffix, struct pvconn **pvconnp)
 {
     int fd;
 
@@ -107,7 +106,7 @@ punix_open(const char *name, char *suffix, struct vconn **vconnp)
         return errno;
     }
 
-    return new_pstream_vconn("punix", fd, punix_accept, vconnp);
+    return new_pstream_pvconn("punix", fd, punix_accept, pvconnp);
 }
 
 static int
@@ -127,14 +126,8 @@ punix_accept(int fd, const struct sockaddr *sa, size_t sa_len,
     return new_stream_vconn(name, fd, 0, 0, vconnp);
 }
 
-struct vconn_class punix_vconn_class = {
-    "punix",                    /* name */
-    punix_open,                 /* open */
-    NULL,                       /* close */
-    NULL,                       /* connect */
-    NULL,                       /* accept */
-    NULL,                       /* recv */
-    NULL,                       /* send */
-    NULL,                       /* wait */
+struct pvconn_class punix_pvconn_class = {
+    "punix",
+    punix_open,
 };
 
index 7162f6b..1c3b699 100644 (file)
@@ -40,6 +40,7 @@
 #include <poll.h>
 #include <stdlib.h>
 #include <string.h>
+#include "dynamic-string.h"
 #include "flow.h"
 #include "ofp-print.h"
 #include "ofpbuf.h"
 #define THIS_MODULE VLM_vconn
 #include "vlog.h"
 
+/* State of an active vconn.*/
+enum vconn_state {
+    /* This is the ordinary progression of states. */
+    VCS_CONNECTING,             /* Underlying vconn is not connected. */
+    VCS_SEND_HELLO,             /* Waiting to send OFPT_HELLO message. */
+    VCS_RECV_HELLO,             /* Waiting to receive OFPT_HELLO message. */
+    VCS_CONNECTED,              /* Connection established. */
+
+    /* These states are entered only when something goes wrong. */
+    VCS_SEND_ERROR,             /* Sending OFPT_ERROR message. */
+    VCS_DISCONNECTED            /* Connection failed or connection closed. */
+};
+
 static struct vconn_class *vconn_classes[] = {
     &tcp_vconn_class,
-    &ptcp_vconn_class,
+    &unix_vconn_class,
 #ifdef HAVE_NETLINK
     &netlink_vconn_class,
 #endif
 #ifdef HAVE_OPENSSL
     &ssl_vconn_class,
-    &pssl_vconn_class,
 #endif
-    &unix_vconn_class,
-    &punix_vconn_class,
+};
+
+static struct pvconn_class *pvconn_classes[] = {
+    &ptcp_pvconn_class,
+    &punix_pvconn_class,
+#ifdef HAVE_OPENSSL
+    &pssl_pvconn_class,
+#endif
 };
 
 /* High rate limit because most of the rate-limiting here is individual
@@ -70,6 +89,9 @@ static struct vconn_class *vconn_classes[] = {
  * really need to see them. */
 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(600, 600);
 
+static int do_recv(struct vconn *, struct ofpbuf **);
+static int do_send(struct vconn *, struct ofpbuf *);
+
 /* Check the validity of the vconn class structures. */
 static void
 check_vconn_classes(void)
@@ -81,12 +103,23 @@ check_vconn_classes(void)
         struct vconn_class *class = vconn_classes[i];
         assert(class->name != NULL);
         assert(class->open != NULL);
-        if (class->close || class->accept || class->recv || class->send
-            || class->wait) {
+        if (class->close || class->recv || class->send || class->wait) {
             assert(class->close != NULL);
-            assert(class->accept
-                   ? !class->recv && !class->send
-                   :  class->recv && class->send);
+            assert(class->recv != NULL);
+            assert(class->send != NULL);
+            assert(class->wait != NULL);
+        } else {
+            /* This class delegates to another one. */
+        }
+    }
+
+    for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
+        struct pvconn_class *class = pvconn_classes[i];
+        assert(class->name != NULL);
+        assert(class->listen != NULL);
+        if (class->close || class->accept || class->wait) {
+            assert(class->close != NULL);
+            assert(class->accept != NULL);
             assert(class->wait != NULL);
         } else {
             /* This class delegates to another one. */
@@ -143,14 +176,18 @@ vconn_usage(bool active, bool passive)
 }
 
 /* Attempts to connect to an OpenFlow device.  'name' is a connection name in
- * the form "TYPE:ARGS", where TYPE is the vconn class's name and ARGS are
- * vconn class-specific.
+ * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS
+ * are vconn class-specific.
+ *
+ * The vconn will automatically negotiate an OpenFlow protocol version
+ * acceptable to both peers on the connection.  The version negotiated will be
+ * no lower than 'min_version' and no higher than OFP_VERSION.
  *
  * Returns 0 if successful, otherwise a positive errno value.  If successful,
  * stores a pointer to the new connection in '*vconnp', otherwise a null
  * pointer.  */
 int
-vconn_open(const char *name, struct vconn **vconnp)
+vconn_open(const char *name, int min_version, struct vconn **vconnp)
 {
     size_t prefix_len;
     size_t i;
@@ -160,7 +197,6 @@ vconn_open(const char *name, struct vconn **vconnp)
     *vconnp = NULL;
     prefix_len = strcspn(name, ":");
     if (prefix_len == strlen(name)) {
-        ofp_error(0, "`%s' not correct format for peer name", name);
         return EAFNOSUPPORT;
     }
     for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) {
@@ -172,25 +208,24 @@ vconn_open(const char *name, struct vconn **vconnp)
             int retval = class->open(name, suffix_copy, &vconn);
             free(suffix_copy);
             if (!retval) {
-                assert(vconn->connect_status != EAGAIN
+                assert(vconn->state != VCS_CONNECTING
                        || vconn->class->connect);
-                vconn->name = xstrdup(name);
+                vconn->min_version = min_version;
                 *vconnp = vconn;
             }
             return retval;
         }
     }
-    ofp_error(0, "unknown peer type `%.*s'", (int) prefix_len, name);
     return EAFNOSUPPORT;
 }
 
 int
-vconn_open_block(const char *name, struct vconn **vconnp)
+vconn_open_block(const char *name, int min_version, struct vconn **vconnp)
 {
     struct vconn *vconn;
     int error;
 
-    error = vconn_open(name, &vconn);
+    error = vconn_open(name, min_version, &vconn);
     while (error == EAGAIN) {
         vconn_connect_wait(vconn);
         poll_block();
@@ -217,14 +252,11 @@ vconn_close(struct vconn *vconn)
     }
 }
 
-/* Returns true if 'vconn' is a passive vconn, that is, its purpose is to
- * wait for connections to arrive, not to transfer data.  Returns false if
- * 'vconn' is an active vconn, that is, its purpose is to transfer data, not
- * to wait for new connections to arrive. */
-bool
-vconn_is_passive(const struct vconn *vconn)
+/* Returns the name of 'vconn', that is, the string passed to vconn_open(). */
+const char *
+vconn_get_name(const struct vconn *vconn)
 {
-    return vconn->class->accept != NULL;
+    return vconn->name;
 }
 
 /* Returns the IP address of the peer, or 0 if the peer is not connected over
@@ -235,40 +267,157 @@ vconn_get_ip(const struct vconn *vconn)
     return vconn->ip;
 }
 
-/* Tries to complete the connection on 'vconn', which must be an active
- * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
- * was successful or a positive errno value if it failed.  If the
- * connection is still in progress, returns EAGAIN. */
-int
-vconn_connect(struct vconn *vconn)
+static void
+vcs_connecting(struct vconn *vconn) 
 {
-    if (vconn->connect_status == EAGAIN) {
-        vconn->connect_status = (vconn->class->connect)(vconn);
-        assert(vconn->connect_status != EINPROGRESS);
+    int retval = (vconn->class->connect)(vconn);
+    assert(retval != EINPROGRESS);
+    if (!retval) {
+        vconn->state = VCS_SEND_HELLO;
+    } else if (retval != EAGAIN) {
+        vconn->state = VCS_DISCONNECTED;
+        vconn->error = retval;
     }
-    return vconn->connect_status;
 }
 
-/* Tries to accept a new connection on 'vconn', which must be a passive vconn.
- * If successful, stores the new connection in '*new_vconn' and returns 0.
- * Otherwise, returns a positive errno value.
- *
- * vconn_accept will not block waiting for a connection.  If no connection is
- * ready to be accepted, it returns EAGAIN immediately. */
-int
-vconn_accept(struct vconn *vconn, struct vconn **new_vconn)
+static void
+vcs_send_hello(struct vconn *vconn)
 {
+    struct ofpbuf *b;
     int retval;
 
-    retval = (vconn->class->accept)(vconn, new_vconn);
+    make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b);
+    retval = do_send(vconn, b);
+    if (!retval) {
+        vconn->state = VCS_RECV_HELLO;
+    } else {
+        ofpbuf_delete(b);
+        if (retval != EAGAIN) {
+            vconn->state = VCS_DISCONNECTED;
+            vconn->error = retval;
+        }
+    }
+}
+
+static void
+vcs_recv_hello(struct vconn *vconn)
+{
+    struct ofpbuf *b;
+    int retval;
 
+    retval = do_recv(vconn, &b);
+    if (!retval) {
+        struct ofp_header *oh = b->data;
+
+        if (oh->type == OFPT_HELLO) {
+            if (b->size > sizeof *oh) {
+                struct ds msg = DS_EMPTY_INITIALIZER;
+                ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name);
+                ds_put_hex_dump(&msg, b->data, b->size, 0, true);
+                VLOG_WARN_RL(&rl, ds_cstr(&msg));
+                ds_destroy(&msg);
+            }
+
+            vconn->version = MIN(OFP_VERSION, oh->version);
+            if (vconn->version < vconn->min_version) {
+                VLOG_WARN_RL(&rl, "%s: version negotiation failed: we support "
+                             "versions 0x%02x to 0x%02x inclusive but peer "
+                             "supports no later than version 0x%02"PRIx8,
+                             vconn->name, vconn->min_version, OFP_VERSION,
+                             oh->version);
+                vconn->state = VCS_SEND_ERROR;
+            } else {
+                VLOG_DBG("%s: negotiated OpenFlow version 0x%02x "
+                         "(we support versions 0x%02x to 0x%02x inclusive, "
+                         "peer no later than version 0x%02"PRIx8")",
+                         vconn->name, vconn->version, vconn->min_version,
+                         OFP_VERSION, oh->version);
+                vconn->state = VCS_CONNECTED;
+            }
+            ofpbuf_delete(b);
+            return;
+        } else {
+            char *s = ofp_to_string(b->data, b->size, 1);
+            VLOG_WARN_RL(&rl, "%s: received message while expecting hello: %s",
+                         vconn->name, s);
+            free(s);
+            retval = EPROTO;
+            ofpbuf_delete(b);
+        }
+    }
+
+    if (retval != EAGAIN) {
+        vconn->state = VCS_DISCONNECTED;
+        vconn->error = retval;
+    }
+}
+
+static void
+vcs_send_error(struct vconn *vconn)
+{
+    struct ofp_error_msg *error;
+    struct ofpbuf *b;
+    char s[128];
+    int retval;
+
+    snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but "
+             "you support no later than version 0x%02"PRIx8".",
+             vconn->min_version, OFP_VERSION, vconn->version);
+    error = make_openflow(sizeof *error, OFPT_ERROR, &b);
+    error->type = htons(OFPET_HELLO_FAILED);
+    error->code = htons(OFPHFC_INCOMPATIBLE);
+    ofpbuf_put(b, s, strlen(s));
+    retval = do_send(vconn, b);
     if (retval) {
-        *new_vconn = NULL;
-    } else {
-        assert((*new_vconn)->connect_status != EAGAIN
-               || (*new_vconn)->class->connect);
+        ofpbuf_delete(b);
+    }
+    if (retval != EAGAIN) {
+        vconn->state = VCS_DISCONNECTED;
+        vconn->error = retval ? retval : EPROTO;
     }
-    return retval;
+}
+
+/* Tries to complete the connection on 'vconn', which must be an active
+ * vconn.  If 'vconn''s connection is complete, returns 0 if the connection
+ * was successful or a positive errno value if it failed.  If the
+ * connection is still in progress, returns EAGAIN. */
+int
+vconn_connect(struct vconn *vconn)
+{
+    enum vconn_state last_state;
+
+    assert(vconn->min_version >= 0);
+    do {
+        last_state = vconn->state;
+        switch (vconn->state) {
+        case VCS_CONNECTING:
+            vcs_connecting(vconn);
+            break;
+
+        case VCS_SEND_HELLO:
+            vcs_send_hello(vconn);
+            break;
+
+        case VCS_RECV_HELLO:
+            vcs_recv_hello(vconn);
+            break;
+
+        case VCS_CONNECTED:
+            return 0;
+
+        case VCS_SEND_ERROR:
+            vcs_send_error(vconn);
+            break;
+
+        case VCS_DISCONNECTED:
+            return vconn->error;
+
+        default:
+            NOT_REACHED();
+        }
+    } while (vconn->state != last_state);
+
+    return EAGAIN;
 }
 
 /* Tries to receive an OpenFlow message from 'vconn', which must be an active
@@ -284,25 +433,45 @@ vconn_recv(struct vconn *vconn, struct ofpbuf **msgp)
 {
     int retval = vconn_connect(vconn);
     if (!retval) {
-        retval = (vconn->class->recv)(vconn, msgp);
-        if (!retval) {
-            struct ofp_header *oh;
-
-            if (VLOG_IS_DBG_ENABLED()) {
-                char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
-                VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
-                free(s);
-            }
+        retval = do_recv(vconn, msgp);
+    }
+    return retval;
+}
 
-            oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
-            if (oh->version != OFP_VERSION) {
+static int
+do_recv(struct vconn *vconn, struct ofpbuf **msgp)
+{
+    int retval;
+
+    retval = (vconn->class->recv)(vconn, msgp);
+    if (!retval) {
+        struct ofp_header *oh;
+
+        if (VLOG_IS_DBG_ENABLED()) {
+            char *s = ofp_to_string((*msgp)->data, (*msgp)->size, 1);
+            VLOG_DBG_RL(&rl, "%s: received: %s", vconn->name, s);
+            free(s);
+        }
+
+        oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh);
+        if (oh->version != vconn->version
+            && oh->type != OFPT_HELLO
+            && oh->type != OFPT_ERROR
+            && oh->type != OFPT_ECHO_REQUEST
+            && oh->type != OFPT_ECHO_REPLY
+            && oh->type != OFPT_VENDOR)
+        {
+            if (vconn->version < 0) {
+                VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
+                            "before version negotiation complete",
+                            vconn->name, oh->version);
+            } else {
                 VLOG_ERR_RL(&rl, "%s: received OpenFlow version %02"PRIx8" "
                             "!= expected %02x",
-                            vconn->name, oh->version, OFP_VERSION);
-                ofpbuf_delete(*msgp);
-                *msgp = NULL;
-                return EPROTO;
+                            vconn->name, oh->version, vconn->version);
             }
+            ofpbuf_delete(*msgp);
+            retval = EPROTO;
         }
     }
     if (retval) {
@@ -327,18 +496,28 @@ vconn_send(struct vconn *vconn, struct ofpbuf *msg)
 {
     int retval = vconn_connect(vconn);
     if (!retval) {
-        assert(msg->size >= sizeof(struct ofp_header));
-        assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
-        if (!VLOG_IS_DBG_ENABLED()) { 
-            retval = (vconn->class->send)(vconn, msg);
-        } else {
-            char *s = ofp_to_string(msg->data, msg->size, 1);
-            retval = (vconn->class->send)(vconn, msg);
-            if (retval != EAGAIN) {
-                VLOG_DBG_RL(&rl, "%s: sent (%s): %s", vconn->name, strerror(retval), s);
-            }
-            free(s);
+        retval = do_send(vconn, msg);
+    }
+    return retval;
+}
+
+static int
+do_send(struct vconn *vconn, struct ofpbuf *msg)
+{
+    int retval;
+
+    assert(msg->size >= sizeof(struct ofp_header));
+    assert(((struct ofp_header *) msg->data)->length == htons(msg->size));
+    if (!VLOG_IS_DBG_ENABLED()) {
+        retval = (vconn->class->send)(vconn, msg);
+    } else {
+        char *s = ofp_to_string(msg->data, msg->size, 1);
+        retval = (vconn->class->send)(vconn, msg);
+        if (retval != EAGAIN) {
+            VLOG_DBG_RL(&rl, "%s: sent (%s): %s",
+                        vconn->name, strerror(retval), s);
         }
+        free(s);
     }
     return retval;
 }
@@ -409,22 +588,29 @@ vconn_transact(struct vconn *vconn, struct ofpbuf *request,
 void
 vconn_wait(struct vconn *vconn, enum vconn_wait_type wait)
 {
-    int connect_status;
+    assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
 
-    assert(vconn_is_passive(vconn)
-           ? wait == WAIT_ACCEPT || wait == WAIT_CONNECT
-           : wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND);
+    switch (vconn->state) {
+    case VCS_CONNECTING:
+        wait = WAIT_CONNECT;
+        break;
 
-    connect_status = vconn_connect(vconn);
-    if (connect_status) {
-        if (connect_status == EAGAIN) {
-            wait = WAIT_CONNECT;
-        } else {
-            poll_immediate_wake();
-            return;
-        }
-    }
+    case VCS_SEND_HELLO:
+    case VCS_SEND_ERROR:
+        wait = WAIT_SEND;
+        break;
+
+    case VCS_RECV_HELLO:
+        wait = WAIT_RECV;
+        break;
+
+    case VCS_CONNECTED:
+        break;
 
+    case VCS_DISCONNECTED:
+        poll_immediate_wake();
+        return;
+    }
     (vconn->class->wait)(vconn, wait);
 }
 
@@ -434,12 +620,6 @@ vconn_connect_wait(struct vconn *vconn)
     vconn_wait(vconn, WAIT_CONNECT);
 }
 
-void
-vconn_accept_wait(struct vconn *vconn)
-{
-    vconn_wait(vconn, WAIT_ACCEPT);
-}
-
 void
 vconn_recv_wait(struct vconn *vconn)
 {
@@ -452,6 +632,83 @@ vconn_send_wait(struct vconn *vconn)
     vconn_wait(vconn, WAIT_SEND);
 }
 
+/* Attempts to start listening for OpenFlow connections.  'name' is a
+ * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn
+ * class's name and ARGS are vconn class-specific.
+ *
+ * Returns 0 if successful, otherwise a positive errno value.  If successful,
+ * stores a pointer to the new connection in '*pvconnp', otherwise a null
+ * pointer.  */
+int
+pvconn_open(const char *name, struct pvconn **pvconnp)
+{
+    size_t prefix_len;
+    size_t i;
+
+    check_vconn_classes();
+
+    *pvconnp = NULL;
+    prefix_len = strcspn(name, ":");
+    if (prefix_len == strlen(name)) {
+        return EAFNOSUPPORT;
+    }
+    for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) {
+        struct pvconn_class *class = pvconn_classes[i];
+        if (strlen(class->name) == prefix_len
+            && !memcmp(class->name, name, prefix_len)) {
+            char *suffix_copy = xstrdup(name + prefix_len + 1);
+            int retval = class->listen(name, suffix_copy, pvconnp);
+            free(suffix_copy);
+            if (retval) {
+                *pvconnp = NULL;
+            }
+            return retval;
+        }
+    }
+    return EAFNOSUPPORT;
+}
+
+/* Closes 'pvconn'. */
+void
+pvconn_close(struct pvconn *pvconn)
+{
+    if (pvconn != NULL) {
+        char *name = pvconn->name;
+        (pvconn->class->close)(pvconn);
+        free(name);
+    }
+}
+
+/* Tries to accept a new connection on 'pvconn'.  If successful, stores the new
+ * connection in '*new_vconn' and returns 0.  Otherwise, returns a positive
+ * errno value.
+ *
+ * The new vconn will automatically negotiate an OpenFlow protocol version
+ * acceptable to both peers on the connection.  The version negotiated will be
+ * no lower than 'min_version' and no higher than OFP_VERSION.
+ *
+ * pvconn_accept() will not block waiting for a connection.  If no connection
+ * is ready to be accepted, it returns EAGAIN immediately. */
+int
+pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn)
+{
+    int retval = (pvconn->class->accept)(pvconn, new_vconn);
+    if (retval) {
+        *new_vconn = NULL;
+    } else {
+        assert((*new_vconn)->state != VCS_CONNECTING
+               || (*new_vconn)->class->connect);
+        (*new_vconn)->min_version = min_version;
+    }
+    return retval;
+}
+
+void
+pvconn_wait(struct pvconn *pvconn)
+{
+    (pvconn->class->wait)(pvconn);
+}
+
 /* Allocates and returns the first byte of a buffer 'openflow_len' bytes long,
  * containing an OpenFlow header with the given 'type' and a random transaction
  * id.  Stores the new buffer in '*bufferp'.  The caller must free the buffer
@@ -545,7 +802,7 @@ make_unbuffered_packet_out(const struct ofpbuf *packet,
     size_t size = sizeof *opo + sizeof opo->actions[0];
     struct ofpbuf *out = ofpbuf_new(size + packet->size);
     opo = ofpbuf_put_uninit(out, size);
-    memset(opo, 0, sizeof *opo);
+    memset(opo, 0, size);
     opo->header.version = OFP_VERSION;
     opo->header.type = OFPT_PACKET_OUT;
     opo->buffer_id = htonl(UINT32_MAX);
@@ -611,8 +868,20 @@ vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status,
            uint32_t ip, const char *name)
 {
     vconn->class = class;
-    vconn->connect_status = connect_status;
+    vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING
+                    : !connect_status ? VCS_SEND_HELLO
+                    : VCS_DISCONNECTED);
+    vconn->error = connect_status;
+    vconn->version = -1;
+    vconn->min_version = -1;
     vconn->ip = ip;
     vconn->name = xstrdup(name);
 }
 
+void
+pvconn_init(struct pvconn *pvconn, struct pvconn_class *class,
+            const char *name)
+{
+    pvconn->class = class;
+    pvconn->name = xstrdup(name);
+}
index e3d297e..c04e8d3 100644 (file)
@@ -295,11 +295,35 @@ are mandatory when this form is used.
 .TP
 \fBptcp:\fR[\fIport\fR]
 Listens for TCP connections on \fIport\fR (default: 975).
-.RE
 
 .TP
 \fBpunix:\fIfile\fR
 Listens for connections on Unix domain server socket named \fIfile\fR.
+.RE
+
+.TP
+\fB-m\fR, \fB--monitor=\fImethod\fR
+Configures the switch to additionally listen for incoming OpenFlow
+connections for switch monitoring with \fBdpctl\fR's \fBmonitor\fR
+command.  The \fImethod\fR must be given as one of the passive
+OpenFlow connection methods listed above as acceptable for
+\fB--listen\fR.
+
+When \fBdpctl monitor\fR makes a monitoring connection, \fBsecchan\fR
+sends it a copy of every OpenFlow message sent to or received from the
+kernel in the normal course of its operations.  It does not send a
+copy of any messages sent to or from the OpenFlow connection to the
+controller.  Most of these messages will be seen anyhow, however,
+because \fBsecchan\fR mainly acts as a relay between the controller
+and the kernel.  \fBsecchan\fR also does not send a copy of any
+messages sent to or from the OpenFlow connection to the controller.
+Such messages will typically \fBnot\fR be seen, because \fBsecchan\fR
+maintains a separate connection to the kernel for each management
+connection.
+
+Messages are copied to the monitoring connections on a best-effort
+basis.  In particular, if the socket buffer of the monitoring
+connection fills up, some messages will be lost.
 
 .TP
 \fB-p\fR, \fB--private-key=\fIprivkey.pem\fR
index 9508369..f00df4a 100644 (file)
 #include "list.h"
 #include "mac-learning.h"
 #include "netdev.h"
+#include "nicira-ext.h"
 #include "ofpbuf.h"
 #include "openflow.h"
 #include "packets.h"
 #include "poll-loop.h"
 #include "rconn.h"
+#include "stp.h"
 #include "timeval.h"
 #include "util.h"
 #include "vconn-ssl.h"
@@ -92,6 +94,7 @@ struct settings {
     const char *controller_name; /* Controller (if not discovery mode). */
     const char *listener_names[MAX_MGMT]; /* Listen for mgmt connections. */
     size_t n_listeners;          /* Number of mgmt connection listeners. */
+    const char *monitor_name;   /* Listen for traffic monitor connections. */
 
     /* Failure behavior. */
     enum fail_mode fail_mode; /* Act as learning switch if no controller? */
@@ -126,7 +129,7 @@ struct relay {
 };
 
 struct hook {
-    bool (*packet_cb)(struct relay *, int half, void *aux);
+    bool (*packet_cb[2])(struct relay *, void *aux);
     void (*periodic_cb)(void *aux);
     void (*wait_cb)(void *aux);
     void *aux;
@@ -137,17 +140,25 @@ static struct vlog_rate_limit vrl = VLOG_RATE_LIMIT_INIT(60, 60);
 static void parse_options(int argc, char *argv[], struct settings *);
 static void usage(void) NO_RETURN;
 
+static struct pvconn *open_passive_vconn(const char *name);
+static struct vconn *accept_vconn(struct pvconn *pvconn);
+
 static struct relay *relay_create(struct rconn *local, struct rconn *remote,
                                   bool is_mgmt_conn);
-static struct relay *relay_accept(const struct settings *, struct vconn *);
+static struct relay *relay_accept(const struct settings *, struct pvconn *);
 static void relay_run(struct relay *, const struct hook[], size_t n_hooks);
 static void relay_wait(struct relay *);
 static void relay_destroy(struct relay *);
 
-static struct hook make_hook(bool (*packet_cb)(struct relay *, int, void *),
+static struct hook make_hook(bool (*local_packet_cb)(struct relay *, void *),
+                             bool (*remote_packet_cb)(struct relay *, void *),
                              void (*periodic_cb)(void *),
                              void (*wait_cb)(void *),
                              void *aux);
+static struct ofp_packet_in *get_ofp_packet_in(struct relay *);
+static bool get_ofp_packet_eth_header(struct relay *, struct ofp_packet_in **,
+                                      struct eth_header **);
+static void get_ofp_packet_payload(struct ofp_packet_in *, struct ofpbuf *);
 
 struct switch_status;
 struct status_reply;
@@ -172,6 +183,20 @@ static void discovery_wait(struct discovery *);
 static struct hook in_band_hook_create(const struct settings *,
                                        struct switch_status *,
                                        struct rconn *remote);
+
+struct port_watcher;
+static struct hook port_watcher_create(struct rconn *local,
+                                       struct rconn *remote,
+                                       struct port_watcher **);
+static uint32_t port_watcher_get_flags(const struct port_watcher *,
+                                       int port_no);
+static void port_watcher_set_flags(struct port_watcher *,
+                                   int port_no, uint32_t flags, uint32_t mask);
+
+static struct hook stp_hook_create(const struct settings *,
+                                   struct port_watcher *,
+                                   struct rconn *local, struct rconn *remote);
+
 static struct hook fail_open_hook_create(const struct settings *,
                                          struct switch_status *,
                                          struct rconn *local,
@@ -195,13 +220,16 @@ main(int argc, char *argv[])
     struct hook hooks[8];
     size_t n_hooks = 0;
 
-    struct vconn *listeners[MAX_MGMT];
+    struct pvconn *monitor;
+
+    struct pvconn *listeners[MAX_MGMT];
     size_t n_listeners;
 
     struct rconn *local_rconn, *remote_rconn;
     struct relay *controller_relay;
     struct discovery *discovery;
     struct switch_status *switch_status;
+    struct port_watcher *pw;
     int i;
     int retval;
 
@@ -212,20 +240,12 @@ main(int argc, char *argv[])
     parse_options(argc, argv, &s);
     signal(SIGPIPE, SIG_IGN);
 
-    /* Start listening for management connections. */
+    /* Start listening for management and monitoring connections. */
     n_listeners = 0;
     for (i = 0; i < s.n_listeners; i++) {
-        const char *name = s.listener_names[i];
-        struct vconn *listener;
-        retval = vconn_open(name, &listener);
-        if (retval && retval != EAGAIN) {
-            ofp_fatal(retval, "opening %s", name);
-        }
-        if (!vconn_is_passive(listener)) {
-            ofp_fatal(0, "%s is not a passive vconn", name);
-        }
-        listeners[n_listeners++] = listener;
+        listeners[n_listeners++] = open_passive_vconn(s.listener_names[i]);
     }
+    monitor = s.monitor_name ? open_passive_vconn(s.monitor_name) : NULL;
 
     /* Initialize switch status hook. */
     hooks[n_hooks++] = switch_status_hook_create(&s, &switch_status);
@@ -267,6 +287,8 @@ main(int argc, char *argv[])
     list_push_back(&relays, &controller_relay->node);
 
     /* Set up hooks. */
+    hooks[n_hooks++] = port_watcher_create(local_rconn, remote_rconn, &pw);
+    hooks[n_hooks++] = stp_hook_create(&s, pw, local_rconn, remote_rconn);
     if (s.in_band) {
         hooks[n_hooks++] = in_band_hook_create(&s, switch_status,
                                                remote_rconn);
@@ -298,6 +320,12 @@ main(int argc, char *argv[])
                 list_push_back(&relays, &r->node);
             }
         }
+        if (monitor) {
+            struct vconn *new = accept_vconn(monitor);
+            if (new) {
+                rconn_add_monitor(local_rconn, new);
+            }
+        }
         for (i = 0; i < n_hooks; i++) {
             if (hooks[i].periodic_cb) {
                 hooks[i].periodic_cb(hooks[i].aux);
@@ -322,7 +350,10 @@ main(int argc, char *argv[])
             relay_wait(r);
         }
         for (i = 0; i < n_listeners; i++) {
-            vconn_accept_wait(listeners[i]);
+            pvconn_wait(listeners[i]);
+        }
+        if (monitor) {
+            pvconn_wait(monitor);
         }
         for (i = 0; i < n_hooks; i++) {
             if (hooks[i].wait_cb) {
@@ -338,35 +369,91 @@ main(int argc, char *argv[])
     return 0;
 }
 
+static struct pvconn *
+open_passive_vconn(const char *name)
+{
+    struct pvconn *pvconn;
+    int retval;
+
+    retval = pvconn_open(name, &pvconn);
+    if (retval && retval != EAGAIN) {
+        ofp_fatal(retval, "opening %s", name);
+    }
+    return pvconn;
+}
+
+static struct vconn *
+accept_vconn(struct pvconn *pvconn)
+{
+    struct vconn *new;
+    int retval;
+
+    retval = pvconn_accept(pvconn, OFP_VERSION, &new);
+    if (retval && retval != EAGAIN) {
+        VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
+    }
+    return new;
+}
+
 static struct hook
-make_hook(bool (*packet_cb)(struct relay *, int half, void *aux),
+make_hook(bool (*local_packet_cb)(struct relay *, void *aux),
+          bool (*remote_packet_cb)(struct relay *, void *aux),
           void (*periodic_cb)(void *aux),
           void (*wait_cb)(void *aux),
           void *aux)
 {
     struct hook h;
-    h.packet_cb = packet_cb;
+    h.packet_cb[HALF_LOCAL] = local_packet_cb;
+    h.packet_cb[HALF_REMOTE] = remote_packet_cb;
     h.periodic_cb = periodic_cb;
     h.wait_cb = wait_cb;
     h.aux = aux;
     return h;
 }
+
+static struct ofp_packet_in *
+get_ofp_packet_in(struct relay *r)
+{
+    struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
+    struct ofp_header *oh = msg->data;
+    if (oh->type == OFPT_PACKET_IN) {
+        if (msg->size >= offsetof (struct ofp_packet_in, data)) {
+            return msg->data;
+        } else {
+            VLOG_WARN("packet too short (%zu bytes) for packet_in",
+                      msg->size);
+        }
+    }
+    return NULL;
+}
+
+static bool
+get_ofp_packet_eth_header(struct relay *r, struct ofp_packet_in **opip,
+                          struct eth_header **ethp)
+{
+    const int min_len = offsetof(struct ofp_packet_in, data) + ETH_HEADER_LEN;
+    struct ofp_packet_in *opi = get_ofp_packet_in(r);
+    if (opi && ntohs(opi->header.length) >= min_len) {
+        *opip = opi;
+        *ethp = (void *) opi->data;
+        return true;
+    }
+    return false;
+}
+
 \f
 /* OpenFlow message relaying. */
 
 static struct relay *
-relay_accept(const struct settings *s, struct vconn *listen_vconn)
+relay_accept(const struct settings *s, struct pvconn *pvconn)
 {
     struct vconn *new_remote, *new_local;
     char *nl_name_without_subscription;
     struct rconn *r1, *r2;
     int retval;
 
-    retval = vconn_accept(listen_vconn, &new_remote);
-    if (retval) {
-        if (retval != EAGAIN) {
-            VLOG_WARN_RL(&vrl, "accept failed (%s)", strerror(retval));
-        }
+    new_remote = accept_vconn(pvconn);
+    if (!new_remote) {
         return NULL;
     }
 
@@ -377,7 +464,7 @@ relay_accept(const struct settings *s, struct vconn *listen_vconn)
      * obtaining a subscription for ofp_packet_in or ofp_flow_expired
      * messages.*/
     nl_name_without_subscription = xasprintf("%s:0", s->nl_name);
-    retval = vconn_open(nl_name_without_subscription, &new_local);
+    retval = vconn_open(nl_name_without_subscription, OFP_VERSION, &new_local);
     if (retval) {
         VLOG_ERR_RL(&vrl, "could not connect to %s (%s)",
                     nl_name_without_subscription, strerror(retval));
@@ -426,10 +513,10 @@ relay_run(struct relay *r, const struct hook hooks[], size_t n_hooks)
 
             if (!this->rxbuf) {
                 this->rxbuf = rconn_recv(this->rconn);
-                if (this->rxbuf) {
+                if (this->rxbuf && (i == HALF_REMOTE || !r->is_mgmt_conn)) {
                     const struct hook *h;
                     for (h = hooks; h < &hooks[n_hooks]; h++) {
-                        if (h->packet_cb(r, i, h->aux)) {
+                        if (h->packet_cb[i] && h->packet_cb[i](r, h->aux)) {
                             ofpbuf_delete(this->rxbuf);
                             this->rxbuf = NULL;
                             progress = true;
@@ -497,6 +584,558 @@ relay_destroy(struct relay *r)
     free(r);
 }
 \f
+/* Port status watcher. */
+
+typedef void port_watcher_cb_func(uint16_t port_no,
+                                  const struct ofp_phy_port *old,
+                                  const struct ofp_phy_port *new,
+                                  void *aux);
+
+struct port_watcher_cb {
+    port_watcher_cb_func *function;
+    void *aux;
+};
+
+struct port_watcher {
+    struct rconn *local_rconn;
+    struct rconn *remote_rconn;
+    struct ofp_phy_port ports[OFPP_MAX + 1];
+    time_t last_feature_request;
+    bool got_feature_reply;
+    int n_txq;
+    struct port_watcher_cb cbs[2];
+    int n_cbs;
+};
+
+/* Returns the number of fields that differ from 'a' to 'b'. */
+static int
+opp_differs(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
+{
+    BUILD_ASSERT_DECL(sizeof *a == 36); /* Trips when we add or remove fields. */
+    return ((a->port_no != b->port_no)
+            + (memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr) != 0)
+            + (memcmp(a->name, b->name, sizeof a->name) != 0)
+            + (a->flags != b->flags)
+            + (a->speed != b->speed)
+            + (a->features != b->features));
+}
+
+static void
+sanitize_opp(struct ofp_phy_port *opp)
+{
+    size_t i;
+
+    for (i = 0; i < sizeof opp->name; i++) {
+        char c = opp->name[i];
+        if (c && (c < 0x20 || c > 0x7e)) {
+            opp->name[i] = '.';
+        }
+    }
+    opp->name[sizeof opp->name - 1] = '\0';
+}
+
+static int
+port_no_to_pw_idx(int port_no)
+{
+    return (port_no < OFPP_MAX ? port_no
+            : port_no == OFPP_LOCAL ? OFPP_MAX
+            : -1);
+}
+
+static void
+call_pw_callbacks(struct port_watcher *pw, int port_no,
+                  const struct ofp_phy_port *old,
+                  const struct ofp_phy_port *new)
+{
+    if (opp_differs(old, new)) {
+        int i;
+        for (i = 0; i < pw->n_cbs; i++) {
+            pw->cbs[i].function(port_no, old, new, pw->cbs[i].aux);
+        }
+    }
+}
+
+static void
+update_phy_port(struct port_watcher *pw, struct ofp_phy_port *opp,
+                uint8_t reason, bool seen[OFPP_MAX + 1])
+{
+    struct ofp_phy_port *pw_opp;
+    struct ofp_phy_port old;
+    uint16_t port_no;
+    int idx;
+
+    port_no = ntohs(opp->port_no);
+    idx = port_no_to_pw_idx(port_no);
+    if (idx < 0) {
+        return;
+    }
+
+    if (seen) {
+        seen[idx] = true;
+    }
+
+    pw_opp = &pw->ports[idx];
+    old = *pw_opp;
+    if (reason == OFPPR_DELETE) {
+        memset(pw_opp, 0, sizeof *pw_opp);
+        pw_opp->port_no = htons(OFPP_NONE);
+    } else if (reason == OFPPR_MOD || reason == OFPPR_ADD) {
+        *pw_opp = *opp;
+        sanitize_opp(pw_opp);
+    }
+    call_pw_callbacks(pw, port_no, &old, pw_opp);
+}
+
+static bool
+port_watcher_local_packet_cb(struct relay *r, void *pw_)
+{
+    struct port_watcher *pw = pw_;
+    struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
+    struct ofp_header *oh = msg->data;
+
+    if (oh->type == OFPT_FEATURES_REPLY
+        && msg->size >= offsetof(struct ofp_switch_features, ports)) {
+        struct ofp_switch_features *osf = msg->data;
+        bool seen[ARRAY_SIZE(pw->ports)];
+        size_t n_ports;
+        size_t i;
+
+        pw->got_feature_reply = true;
+
+        /* Update each port included in the message. */
+        memset(seen, 0, sizeof seen);
+        n_ports = ((msg->size - offsetof(struct ofp_switch_features, ports))
+                   / sizeof *osf->ports);
+        for (i = 0; i < n_ports; i++) {
+            update_phy_port(pw, &osf->ports[i], OFPPR_MOD, seen);
+        }
+
+        /* Delete all the ports not included in the message. */
+        for (i = 0; i < ARRAY_SIZE(pw->ports); i++) {
+            if (!seen[i]) {
+                update_phy_port(pw, &pw->ports[i], OFPPR_DELETE, NULL);
+            }
+        }
+    } else if (oh->type == OFPT_PORT_STATUS
+               && msg->size >= sizeof(struct ofp_port_status)) {
+        struct ofp_port_status *ops = msg->data;
+        update_phy_port(pw, &ops->desc, ops->reason, NULL);
+    }
+    return false;
+}
+
+static bool
+port_watcher_remote_packet_cb(struct relay *r, void *pw_)
+{
+    struct port_watcher *pw = pw_;
+    struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
+    struct ofp_header *oh = msg->data;
+
+    if (oh->type == OFPT_PORT_MOD
+        && msg->size >= sizeof(struct ofp_port_mod)) {
+        struct ofp_port_mod *opm = msg->data;
+        uint16_t port_no = ntohs(opm->desc.port_no);
+        int idx = port_no_to_pw_idx(port_no);
+        if (idx >= 0) {
+            struct ofp_phy_port *pw_opp = &pw->ports[idx];
+            if (pw_opp->port_no != htons(OFPP_NONE)) {
+                struct ofp_phy_port old = *pw_opp;
+                pw_opp->flags = ((pw_opp->flags & ~opm->mask)
+                                 | (opm->desc.flags & opm->mask));
+                call_pw_callbacks(pw, port_no, &old, pw_opp);
+            }
+        }
+    }
+    return false;
+}
+
+static void
+port_watcher_periodic_cb(void *pw_)
+{
+    struct port_watcher *pw = pw_;
+
+    if (!pw->got_feature_reply && time_now() >= pw->last_feature_request + 5) {
+        struct ofpbuf *b;
+        make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
+        rconn_send_with_limit(pw->local_rconn, b, &pw->n_txq, 1);
+        pw->last_feature_request = time_now();
+    }
+}
+
+static void
+put_duplexes(struct ds *ds, const char *name, uint32_t features,
+             uint32_t hd_bit, uint32_t fd_bit)
+{
+    if (features & (hd_bit | fd_bit)) {
+        ds_put_format(ds, " %s", name);
+        if (features & hd_bit) {
+            ds_put_cstr(ds, "(HD)");
+        }
+        if (features & fd_bit) {
+            ds_put_cstr(ds, "(FD)");
+        }
+    }
+}
+
+static void
+log_port_status(uint16_t port_no,
+                const struct ofp_phy_port *old,
+                const struct ofp_phy_port *new,
+                void *aux)
+{
+    if (VLOG_IS_DBG_ENABLED()) {
+        bool was_enabled = old->port_no != htons(OFPP_NONE);
+        bool now_enabled = new->port_no != htons(OFPP_NONE);
+        uint32_t features = ntohl(new->features);
+        struct ds ds;
+
+        if (old->flags != new->flags && opp_differs(old, new) == 1) {
+            /* Don't care if only flags changed. */
+            return;
+        }
+
+        ds_init(&ds);
+        ds_put_format(&ds, "\"%s\", "ETH_ADDR_FMT, new->name,
+                      ETH_ADDR_ARGS(new->hw_addr));
+        if (ntohl(new->speed)) {
+            ds_put_format(&ds, ", speed %"PRIu32, ntohl(new->speed));
+        }
+        if (features & (OFPPF_10MB_HD | OFPPF_10MB_FD
+                        | OFPPF_100MB_HD | OFPPF_100MB_FD
+                        | OFPPF_1GB_HD | OFPPF_1GB_FD | OFPPF_10GB_FD)) {
+            ds_put_cstr(&ds, ", supports");
+            put_duplexes(&ds, "10M", features, OFPPF_10MB_HD, OFPPF_10MB_FD);
+            put_duplexes(&ds, "100M", features,
+                         OFPPF_100MB_HD, OFPPF_100MB_FD);
+            put_duplexes(&ds, "1G", features, OFPPF_100MB_HD, OFPPF_100MB_FD);
+            if (features & OFPPF_10GB_FD) {
+                ds_put_cstr(&ds, " 10G");
+            }
+        }
+        if (was_enabled != now_enabled) {
+            if (now_enabled) {
+                VLOG_DBG("Port %d added: %s", port_no, ds_cstr(&ds));
+            } else {
+                VLOG_DBG("Port %d deleted", port_no);
+            }
+        } else {
+            VLOG_DBG("Port %d changed: %s", port_no, ds_cstr(&ds));
+        }
+        ds_destroy(&ds);
+    }
+}
+
+static void
+port_watcher_register_callback(struct port_watcher *pw,
+                               port_watcher_cb_func *function,
+                               void *aux)
+{
+    assert(pw->n_cbs < ARRAY_SIZE(pw->cbs));
+    pw->cbs[pw->n_cbs].function = function;
+    pw->cbs[pw->n_cbs].aux = aux;
+    pw->n_cbs++;
+}
+
+static uint32_t
+port_watcher_get_flags(const struct port_watcher *pw, int port_no)
+{
+    int idx = port_no_to_pw_idx(port_no);
+    return idx >= 0 ? ntohl(pw->ports[idx].flags) : 0;
+}
+
+static void
+port_watcher_set_flags(struct port_watcher *pw,
+                       int port_no, uint32_t flags, uint32_t mask)
+{
+    struct ofp_phy_port old;
+    struct ofp_phy_port *p;
+    struct ofp_port_mod *opm;
+    struct ofp_port_status *ops;
+    struct ofpbuf *b;
+    int idx;
+
+    idx = port_no_to_pw_idx(port_no);
+    if (idx < 0) {
+        return;
+    }
+
+    p = &pw->ports[idx];
+    if (!((ntohl(p->flags) ^ flags) & mask)) {
+        return;
+    }
+    old = *p;
+
+    /* Update our idea of the flags. */
+    p->flags = htonl((ntohl(p->flags) & ~mask) | (flags & mask));
+    call_pw_callbacks(pw, port_no, &old, p);
+
+    /* Change the flags in the datapath. */
+    opm = make_openflow(sizeof *opm, OFPT_PORT_MOD, &b);
+    opm->mask = htonl(mask);
+    opm->desc = *p;
+    rconn_send(pw->local_rconn, b, NULL);
+
+    /* Notify the controller that the flags changed. */
+    ops = make_openflow(sizeof *ops, OFPT_PORT_STATUS, &b);
+    ops->reason = OFPPR_MOD;
+    ops->desc = *p;
+    rconn_send(pw->remote_rconn, b, NULL);
+}
+
+static bool
+port_watcher_is_ready(const struct port_watcher *pw)
+{
+    return pw->got_feature_reply;
+}
+
+static struct hook
+port_watcher_create(struct rconn *local_rconn, struct rconn *remote_rconn,
+                    struct port_watcher **pwp)
+{
+    struct port_watcher *pw;
+    int i;
+
+    pw = *pwp = xcalloc(1, sizeof *pw);
+    pw->local_rconn = local_rconn;
+    pw->remote_rconn = remote_rconn;
+    pw->last_feature_request = TIME_MIN;
+    for (i = 0; i < OFPP_MAX; i++) {
+        pw->ports[i].port_no = htons(OFPP_NONE);
+    }
+    port_watcher_register_callback(pw, log_port_status, NULL);
+    return make_hook(port_watcher_local_packet_cb,
+                     port_watcher_remote_packet_cb,
+                     port_watcher_periodic_cb, NULL, pw);
+}
+\f
+/* Spanning tree protocol. */
+
+/* Extra time, in seconds, at boot before going into fail-open, to give the
+ * spanning tree protocol time to figure out the network layout. */
+#define STP_EXTRA_BOOT_TIME 30
+
+struct stp_data {
+    struct stp *stp;
+    struct port_watcher *pw;
+    struct rconn *local_rconn;
+    struct rconn *remote_rconn;
+    uint8_t dpid[ETH_ADDR_LEN];
+    long long int last_tick_256ths;
+    int n_txq;
+};
+
+static bool
+stp_local_packet_cb(struct relay *r, void *stp_)
+{
+    struct stp_data *stp = stp_;
+    struct ofp_packet_in *opi;
+    struct eth_header *eth;
+    struct llc_header *llc;
+    struct ofpbuf payload;
+    uint16_t port_no;
+    struct flow flow;
+
+    if (!get_ofp_packet_eth_header(r, &opi, &eth)
+        || !eth_addr_equals(eth->eth_dst, stp_eth_addr)) {
+        return false;
+    }
+
+    port_no = ntohs(opi->in_port);
+    if (port_no >= STP_MAX_PORTS) {
+        /* STP only supports 255 ports. */
+        return false;
+    }
+    if (port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP) {
+        /* We're not doing STP on this port. */
+        return false;
+    }
+
+    if (opi->reason == OFPR_ACTION) {
+        /* The controller set up a flow for this, so we won't intercept it. */
+        return false;
+    }
+
+    get_ofp_packet_payload(opi, &payload);
+    flow_extract(&payload, port_no, &flow);
+    if (flow.dl_type != htons(OFP_DL_TYPE_NOT_ETH_TYPE)) {
+        VLOG_DBG("non-LLC frame received on STP multicast address");
+        return false;
+    }
+    llc = ofpbuf_at_assert(&payload, sizeof *eth, sizeof *llc);
+    if (llc->llc_dsap != STP_LLC_DSAP) {
+        VLOG_DBG("bad DSAP 0x%02"PRIx8" received on STP multicast address",
+                 llc->llc_dsap);
+        return false;
+    }
+
+    /* Trim off padding on payload. */
+    if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
+        payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
+    }
+    if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
+        struct stp_port *p = stp_get_port(stp->stp, port_no);
+        stp_received_bpdu(p, payload.data, payload.size);
+    }
+
+    return true;
+}
+
+static long long int
+time_256ths(void)
+{
+    return time_msec() * 256 / 1000;
+}
+
+static void
+stp_periodic_cb(void *stp_)
+{
+    struct stp_data *stp = stp_;
+    long long int now_256ths = time_256ths();
+    long long int elapsed_256ths = now_256ths - stp->last_tick_256ths;
+    struct stp_port *p;
+
+    if (!port_watcher_is_ready(stp->pw)) {
+        /* Can't start STP until we know port flags, because port flags can
+         * disable STP. */
+        return;
+    }
+    if (elapsed_256ths <= 0) {
+        return;
+    }
+
+    stp_tick(stp->stp, MIN(INT_MAX, elapsed_256ths));
+    stp->last_tick_256ths = now_256ths;
+
+    while (stp_get_changed_port(stp->stp, &p)) {
+        int port_no = stp_port_no(p);
+        enum stp_state state = stp_port_get_state(p);
+
+        if (state != STP_DISABLED) {
+            VLOG_WARN("STP: Port %d entered %s state",
+                      port_no, stp_state_name(state));
+        }
+        if (!(port_watcher_get_flags(stp->pw, port_no) & OFPPFL_NO_STP)) {
+            uint32_t flags;
+            switch (state) {
+            case STP_LISTENING:
+                flags = OFPPFL_STP_LISTEN;
+                break;
+            case STP_LEARNING:
+                flags = OFPPFL_STP_LEARN;
+                break;
+            case STP_DISABLED:
+            case STP_FORWARDING:
+                flags = OFPPFL_STP_FORWARD;
+                break;
+            case STP_BLOCKING:
+                flags = OFPPFL_STP_BLOCK;
+                break;
+            default:
+                VLOG_DBG_RL(&vrl, "STP: Port %d has bad state %x",
+                            port_no, state);
+                flags = OFPPFL_STP_FORWARD;
+                break;
+            }
+            if (!stp_forward_in_state(state)) {
+                flags |= OFPPFL_NO_FLOOD;
+            }
+            port_watcher_set_flags(stp->pw, port_no, flags,
+                                   OFPPFL_STP_MASK | OFPPFL_NO_FLOOD);
+        } else {
+            /* We don't own those flags. */
+        }
+    }
+}
+
+static void
+stp_wait_cb(void *stp_ UNUSED)
+{
+    poll_timer_wait(1000);
+}
+
+static void
+send_bpdu(const void *bpdu, size_t bpdu_size, int port_no, void *stp_)
+{
+    struct stp_data *stp = stp_;
+    struct eth_header *eth;
+    struct llc_header *llc;
+    struct ofpbuf pkt, *opo;
+
+    /* Packet skeleton. */
+    ofpbuf_init(&pkt, ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
+    eth = ofpbuf_put_uninit(&pkt, sizeof *eth);
+    llc = ofpbuf_put_uninit(&pkt, sizeof *llc);
+    ofpbuf_put(&pkt, bpdu, bpdu_size);
+
+    /* 802.2 header. */
+    memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
+    memcpy(eth->eth_src, stp->pw->ports[port_no].hw_addr, ETH_ADDR_LEN);
+    eth->eth_type = htons(pkt.size - ETH_HEADER_LEN);
+
+    /* LLC header. */
+    llc->llc_dsap = STP_LLC_DSAP;
+    llc->llc_ssap = STP_LLC_SSAP;
+    llc->llc_cntl = STP_LLC_CNTL;
+
+    opo = make_unbuffered_packet_out(&pkt, OFPP_NONE, port_no);
+    ofpbuf_uninit(&pkt);
+    rconn_send_with_limit(stp->local_rconn, opo, &stp->n_txq, OFPP_MAX);
+}
+
+static void
+stp_port_watcher_cb(uint16_t port_no,
+                    const struct ofp_phy_port *old,
+                    const struct ofp_phy_port *new,
+                    void *stp_)
+{
+    struct stp_data *stp = stp_;
+    struct stp_port *p;
+
+    /* STP only supports a maximum of 255 ports, one less than OpenFlow.  We
+     * don't support STP on OFPP_LOCAL, either.  */
+    if (port_no >= STP_MAX_PORTS) {
+        return;
+    }
+
+    p = stp_get_port(stp->stp, port_no);
+    if (new->port_no == htons(OFPP_NONE)
+        || new->flags & htonl(OFPPFL_NO_STP)) {
+        stp_port_disable(p);
+    } else {
+        stp_port_enable(p);
+        stp_port_set_speed(p, new->speed);
+    }
+}
+
+static struct hook
+stp_hook_create(const struct settings *s, struct port_watcher *pw,
+                struct rconn *local, struct rconn *remote)
+{
+    uint8_t dpid[ETH_ADDR_LEN];
+    struct netdev *netdev;
+    struct stp_data *stp;
+    int retval;
+
+    retval = netdev_open(s->of_name, NETDEV_ETH_TYPE_NONE, &netdev);
+    if (retval) {
+        ofp_fatal(retval, "Could not open %s device", s->of_name);
+    }
+    memcpy(dpid, netdev_get_etheraddr(netdev), ETH_ADDR_LEN);
+    netdev_close(netdev);
+
+    stp = xcalloc(1, sizeof *stp);
+    stp->stp = stp_create("stp", eth_addr_to_uint64(dpid), send_bpdu, stp);
+    stp->pw = pw;
+    memcpy(stp->dpid, dpid, ETH_ADDR_LEN);
+    stp->local_rconn = local;
+    stp->remote_rconn = remote;
+    stp->last_tick_256ths = time_256ths();
+
+    port_watcher_register_callback(pw, stp_port_watcher_cb, stp);
+    return make_hook(stp_local_packet_cb, NULL,
+                     stp_periodic_cb, stp_wait_cb, stp);
+}
+\f
 /* In-band control. */
 
 struct in_band_data {
@@ -571,79 +1210,71 @@ is_controller_mac(const uint8_t dl_addr[ETH_ADDR_LEN],
     return mac && eth_addr_equals(mac, dl_addr);
 }
 
+static void
+in_band_learn_mac(struct in_band_data *in_band,
+                  uint16_t in_port, const uint8_t src_mac[ETH_ADDR_LEN])
+{
+    if (mac_learning_learn(in_band->ml, src_mac, in_port)) {
+        VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
+                    ETH_ADDR_ARGS(src_mac), in_port);
+    }
+}
+
 static bool
-in_band_packet_cb(struct relay *r, int half, void *in_band_)
+in_band_local_packet_cb(struct relay *r, void *in_band_)
 {
     struct in_band_data *in_band = in_band_;
     struct rconn *rc = r->halves[HALF_LOCAL].rconn;
-    struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
     struct ofp_packet_in *opi;
-    struct ofp_header *oh;
-    size_t pkt_ofs, pkt_len;
-    struct ofpbuf pkt;
+    struct eth_header *eth;
+    struct ofpbuf payload;
     struct flow flow;
-    uint16_t in_port, out_port;
-    const uint8_t *controller_mac;
+    uint16_t in_port;
+    int out_port;
 
-    if (half != HALF_LOCAL || r->is_mgmt_conn) {
+    if (!get_ofp_packet_eth_header(r, &opi, &eth)) {
         return false;
     }
-
-    oh = msg->data;
-    if (oh->type != OFPT_PACKET_IN) {
-        return false;
-    }
-    if (msg->size < offsetof(struct ofp_packet_in, data)) {
-        VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
-                     msg->size);
-        return false;
-    }
-
-    /* Extract flow data from 'opi' into 'flow'. */
-    opi = msg->data;
     in_port = ntohs(opi->in_port);
-    pkt_ofs = offsetof(struct ofp_packet_in, data);
-    pkt_len = ntohs(opi->header.length) - pkt_ofs;
-    pkt.data = opi->data;
-    pkt.size = pkt_len;
-    flow_extract(&pkt, in_port, &flow);
 
     /* Deal with local stuff. */
-    controller_mac = get_controller_mac(in_band);
     if (in_port == OFPP_LOCAL) {
         /* Sent by secure channel. */
-        out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
-    } else if (eth_addr_equals(flow.dl_dst, in_band->mac)) {
+        out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
+    } else if (eth_addr_equals(eth->eth_dst, in_band->mac)) {
         /* Sent to secure channel. */
         out_port = OFPP_LOCAL;
-        if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
-            VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
-                        ETH_ADDR_ARGS(flow.dl_src), in_port);
-        }
-    } else if (flow.dl_type == htons(ETH_TYPE_ARP)
-               && eth_addr_is_broadcast(flow.dl_dst)
-               && is_controller_mac(flow.dl_src, in_band)) {
+        in_band_learn_mac(in_band, in_port, eth->eth_src);
+    } else if (eth->eth_type == htons(ETH_TYPE_ARP)
+               && eth_addr_is_broadcast(eth->eth_dst)
+               && is_controller_mac(eth->eth_src, in_band)) {
         /* ARP sent by controller. */
         out_port = OFPP_FLOOD;
-    } else if (is_controller_mac(flow.dl_dst, in_band)) {
-        if (mac_learning_learn(in_band->ml, flow.dl_src, in_port)) {
-            VLOG_DBG_RL(&vrl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
-                        ETH_ADDR_ARGS(flow.dl_src), in_port);
-        }
-
-        out_port = mac_learning_lookup(in_band->ml, controller_mac);
-        if (in_port != out_port) {
+    } else if (is_controller_mac(eth->eth_dst, in_band)
+               || is_controller_mac(eth->eth_src, in_band)) {
+        /* Traffic to or from controller.  Switch it by hand. */
+        in_band_learn_mac(in_band, in_port, eth->eth_src);
+        out_port = mac_learning_lookup(in_band->ml, eth->eth_dst);
+    } else {
+        const uint8_t *controller_mac;
+        controller_mac = get_controller_mac(in_band);
+        if (eth->eth_type == htons(ETH_TYPE_ARP)
+            && eth_addr_is_broadcast(eth->eth_dst)
+            && is_controller_mac(eth->eth_src, in_band)) {
+            /* ARP sent by controller. */
+            out_port = OFPP_FLOOD;
+        } else if (is_controller_mac(eth->eth_dst, in_band)
+                   && in_port == mac_learning_lookup(in_band->ml,
+                                                     controller_mac)) {
+            /* Drop controller traffic that arrives on the controller port. */
+            out_port = -1;
+        } else {
             return false;
         }
-
-        /* This is controller traffic that arrived on the controller port.
-         * It will get dropped below. */
-    } else if (is_controller_mac(flow.dl_src, in_band)) {
-        out_port = mac_learning_lookup(in_band->ml, flow.dl_dst);
-    } else {
-        return false;
     }
 
+    get_ofp_packet_payload(opi, &payload);
+    flow_extract(&payload, in_port, &flow);
     if (in_port == out_port) {
         /* The input and output port match.  Set up a flow to drop packets. */
         queue_tx(rc, in_band, make_add_flow(&flow, ntohl(opi->buffer_id),
@@ -657,14 +1288,14 @@ in_band_packet_cb(struct relay *r, int half, void *in_band_)
         /* If the switch didn't buffer the packet, we need to send a copy. */
         if (ntohl(opi->buffer_id) == UINT32_MAX) {
             queue_tx(rc, in_band,
-                     make_unbuffered_packet_out(&pkt, in_port, out_port));
+                     make_unbuffered_packet_out(&payload, in_port, out_port));
         }
     } else {
         /* We don't know that MAC.  Send along the packet without setting up a
          * flow. */
         struct ofpbuf *b;
         if (ntohl(opi->buffer_id) == UINT32_MAX) {
-            b = make_unbuffered_packet_out(&pkt, in_port, out_port);
+            b = make_unbuffered_packet_out(&payload, in_port, out_port);
         } else {
             b = make_buffered_packet_out(ntohl(opi->buffer_id),
                                          in_port, out_port);
@@ -700,6 +1331,14 @@ in_band_status_cb(struct status_reply *sr, void *in_band_)
     }
 }
 
+static void
+get_ofp_packet_payload(struct ofp_packet_in *opi, struct ofpbuf *payload)
+{
+    payload->data = opi->data;
+    payload->size = ntohs(opi->header.length) - offsetof(struct ofp_packet_in,
+                                                         data);
+}
+
 static struct hook
 in_band_hook_create(const struct settings *s, struct switch_status *ss,
                     struct rconn *remote)
@@ -719,7 +1358,7 @@ in_band_hook_create(const struct settings *s, struct switch_status *ss,
            ETH_ADDR_LEN);
     in_band->controller = remote;
     switch_status_register_category(ss, "in-band", in_band_status_cb, in_band);
-    return make_hook(in_band_packet_cb, NULL, NULL, in_band);
+    return make_hook(in_band_local_packet_cb, NULL, NULL, NULL, in_band);
 }
 \f
 /* Fail open support. */
@@ -730,6 +1369,7 @@ struct fail_open_data {
     struct rconn *remote_rconn;
     struct lswitch *lswitch;
     int last_disconn_secs;
+    time_t boot_deadline;
 };
 
 /* Causes 'r' to enter or leave fail-open mode, if appropriate. */
@@ -740,6 +1380,9 @@ fail_open_periodic_cb(void *fail_open_)
     int disconn_secs;
     bool open;
 
+    if (time_now() < fail_open->boot_deadline) {
+        return;
+    }
     disconn_secs = rconn_disconnected_duration(fail_open->remote_rconn);
     open = disconn_secs >= fail_open->s->probe_interval * 3;
     if (open != (fail_open->lswitch != NULL)) {
@@ -762,10 +1405,10 @@ fail_open_periodic_cb(void *fail_open_)
 }
 
 static bool
-fail_open_packet_cb(struct relay *r, int half, void *fail_open_)
+fail_open_local_packet_cb(struct relay *r, void *fail_open_)
 {
     struct fail_open_data *fail_open = fail_open_;
-    if (half != HALF_LOCAL || r->is_mgmt_conn || !fail_open->lswitch) {
+    if (!fail_open->lswitch) {
         return false;
     } else {
         lswitch_process_packet(fail_open->lswitch, fail_open->local_rconn,
@@ -799,10 +1442,12 @@ fail_open_hook_create(const struct settings *s, struct switch_status *ss,
     fail_open->local_rconn = local_rconn;
     fail_open->remote_rconn = remote_rconn;
     fail_open->lswitch = NULL;
+    fail_open->boot_deadline = time_now() + s->probe_interval * 3;
+    fail_open->boot_deadline += STP_EXTRA_BOOT_TIME;
     switch_status_register_category(ss, "fail-open",
                                     fail_open_status_cb, fail_open);
-    return make_hook(fail_open_packet_cb, fail_open_periodic_cb, NULL,
-                     fail_open);
+    return make_hook(fail_open_local_packet_cb, NULL,
+                     fail_open_periodic_cb, NULL, fail_open);
 }
 \f
 struct rate_limiter {
@@ -909,24 +1554,14 @@ get_token(struct rate_limiter *rl)
 }
 
 static bool
-rate_limit_packet_cb(struct relay *r, int half, void *rl_)
+rate_limit_local_packet_cb(struct relay *r, void *rl_)
 {
     struct rate_limiter *rl = rl_;
     const struct settings *s = rl->s;
-    struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
-    struct ofp_header *oh;
+    struct ofp_packet_in *opi;
 
-    if (half == HALF_REMOTE) {
-        return false;
-    }
-
-    oh = msg->data;
-    if (oh->type != OFPT_PACKET_IN) {
-        return false;
-    }
-    if (msg->size < offsetof(struct ofp_packet_in, data)) {
-        VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for packet_in",
-                     msg->size);
+    opi = get_ofp_packet_in(r);
+    if (!opi) {
         return false;
     }
 
@@ -937,7 +1572,7 @@ rate_limit_packet_cb(struct relay *r, int half, void *rl_)
         return false;
     } else {
         /* Otherwise queue it up for the periodic callback to drain out. */
-        struct ofp_packet_in *opi = msg->data;
+        struct ofpbuf *msg = r->halves[HALF_LOCAL].rxbuf;
         int port = ntohs(opi->in_port) % OFPP_MAX;
         if (rl->n_queued >= s->burst_limit) {
             drop_packet(rl);
@@ -1014,7 +1649,7 @@ rate_limit_hook_create(const struct settings *s, struct switch_status *ss,
     rl->tokens = s->rate_limit * 100;
     switch_status_register_category(ss, "rate-limit",
                                     rate_limit_status_cb, rl);
-    return make_hook(rate_limit_packet_cb, rate_limit_periodic_cb,
+    return make_hook(rate_limit_local_packet_cb, NULL, rate_limit_periodic_cb,
                      rate_limit_wait_cb, rl);
 }
 \f
@@ -1040,40 +1675,30 @@ struct status_reply {
 };
 
 static bool
-switch_status_packet_cb(struct relay *r, int half, void *ss_)
+switch_status_remote_packet_cb(struct relay *r, void *ss_)
 {
     struct switch_status *ss = ss_;
     struct rconn *rc = r->halves[HALF_REMOTE].rconn;
     struct ofpbuf *msg = r->halves[HALF_REMOTE].rxbuf;
     struct switch_status_category *c;
-    struct ofp_stats_request *osr;
-    struct ofp_stats_reply *reply;
+    struct nicira_header *request;
+    struct nicira_header *reply;
     struct status_reply sr;
-    struct ofp_header *oh;
     struct ofpbuf *b;
     int retval;
 
-    if (half == HALF_LOCAL) {
+    if (msg->size < sizeof(struct nicira_header)) {
         return false;
     }
-
-    oh = msg->data;
-    if (oh->type != OFPT_STATS_REQUEST) {
-        return false;
-    }
-    if (msg->size < sizeof(struct ofp_stats_request)) {
-        VLOG_WARN_RL(&vrl, "packet too short (%zu bytes) for stats_request",
-                     msg->size);
-        return false;
-    }
-
-    osr = msg->data;
-    if (osr->type != htons(OFPST_SWITCH)) {
+    request = msg->data;
+    if (request->header.type != OFPT_VENDOR
+        || request->vendor_id != htonl(NX_VENDOR_ID)
+        || request->subtype != htonl(NXT_STATUS_REQUEST)) {
         return false;
     }
 
-    sr.request.string = (void *) (osr + 1);
-    sr.request.length = msg->size - sizeof *osr;
+    sr.request.string = (void *) (request + 1);
+    sr.request.length = msg->size - sizeof *request;
     ds_init(&sr.output);
     for (c = ss->categories; c < &ss->categories[ss->n_categories]; c++) {
         if (!memcmp(c->name, sr.request.string,
@@ -1082,12 +1707,11 @@ switch_status_packet_cb(struct relay *r, int half, void *ss_)
             c->cb(&sr, c->aux);
         }
     }
-    reply = make_openflow_xid((offsetof(struct ofp_stats_reply, body)
-                               + sr.output.length),
-                              OFPT_STATS_REPLY, osr->header.xid, &b);
-    reply->type = htons(OFPST_SWITCH);
-    reply->flags = 0;
-    memcpy(reply->body, sr.output.string, sr.output.length);
+    reply = make_openflow_xid(sizeof *reply + sr.output.length,
+                              OFPT_VENDOR, request->header.xid, &b);
+    reply->vendor_id = htonl(NX_VENDOR_ID);
+    reply->subtype = htonl(NXT_STATUS_REPLY);
+    memcpy(reply + 1, sr.output.string, sr.output.length);
     retval = rconn_send(rc, b, NULL);
     if (retval && retval != EAGAIN) {
         VLOG_WARN("send failed (%s)", strerror(retval));
@@ -1158,7 +1782,7 @@ switch_status_hook_create(const struct settings *s, struct switch_status **ssp)
                                     config_status_cb, (void *) s);
     switch_status_register_category(ss, "switch", switch_status_cb, ss);
     *ssp = ss;
-    return make_hook(switch_status_packet_cb, NULL, NULL, ss);
+    return make_hook(NULL, switch_status_remote_packet_cb, NULL, NULL, ss);
 }
 
 static void
@@ -1379,6 +2003,7 @@ parse_options(int argc, char *argv[], struct settings *s)
         {"max-idle",    required_argument, 0, OPT_MAX_IDLE},
         {"max-backoff", required_argument, 0, OPT_MAX_BACKOFF},
         {"listen",      required_argument, 0, 'l'},
+        {"monitor",     required_argument, 0, 'm'},
         {"rate-limit",  optional_argument, 0, OPT_RATE_LIMIT},
         {"burst-limit", required_argument, 0, OPT_BURST_LIMIT},
         {"detach",      no_argument, 0, 'D'},
@@ -1396,6 +2021,7 @@ parse_options(int argc, char *argv[], struct settings *s)
 
     /* Set defaults that we can figure out before parsing options. */
     s->n_listeners = 0;
+    s->monitor_name = NULL;
     s->fail_mode = FAIL_OPEN;
     s->max_idle = 15;
     s->probe_interval = 15;
@@ -1498,6 +2124,13 @@ parse_options(int argc, char *argv[], struct settings *s)
             s->listener_names[s->n_listeners++] = optarg;
             break;
 
+        case 'm':
+            if (s->monitor_name) {
+                ofp_fatal(0, "-m or --monitor may only be specified once");
+            }
+            s->monitor_name = optarg;
+            break;
+
         case 'h':
             usage();
 
@@ -1616,6 +2249,8 @@ usage(void)
            "                          attempts (default: 15 seconds)\n"
            "  -l, --listen=METHOD     allow management connections on METHOD\n"
            "                          (a passive OpenFlow connection method)\n"
+           "  -m, --monitor=METHOD    copy traffic to/from kernel to METHOD\n"
+           "                          (a passive OpenFlow connection method)\n"
            "\nRate-limiting of \"packet-in\" messages to the controller:\n"
            "  --rate-limit[=PACKETS]  max rate, in packets/s (default: 1000)\n"
            "  --burst-limit=BURST     limit on packet credit for idle time\n"
index 5eeefa7..0e715f1 100644 (file)
@@ -48,6 +48,7 @@
 #include "packets.h"
 #include "poll-loop.h"
 #include "rconn.h"
+#include "stp.h"
 #include "switch-flow.h"
 #include "table.h"
 #include "timeval.h"
 #define THIS_MODULE VLM_datapath
 #include "vlog.h"
 
-enum br_port_flags {
-    BRPF_NO_FLOOD = 1 << 0,
-};
-
-enum br_port_status {
-    BRPS_PORT_DOWN = 1 << 0,
-    BRPS_LINK_DOWN = 1 << 1,
-};
-
 extern char mfr_desc;
 extern char hw_desc;
 extern char sw_desc;
@@ -87,9 +79,12 @@ extern char serial_num;
                                 | (1 << OFPAT_SET_TP_SRC)   \
                                 | (1 << OFPAT_SET_TP_DST) )
 
+#define PORT_STATUS_BITS (OFPPFL_PORT_DOWN | OFPPFL_LINK_DOWN)
+#define PORT_FLAG_BITS (~PORT_STATUS_BITS)
+
 struct sw_port {
-    uint32_t flags;                    /* BRPF_* flags */
-    uint32_t status;                   /* BRPS_* flags */
+    uint32_t flags;             /* Some subset of PORT_FLAG_BITS. */
+    uint32_t status;            /* Some subset of PORT_STATUS_BITS. */
     struct datapath *dp;
     struct netdev *netdev;
     struct list node; /* Element in datapath.ports. */
@@ -125,7 +120,7 @@ struct datapath {
     /* Remote connections. */
     struct remote *controller;  /* Connection to controller. */
     struct list remotes;        /* All connections (including controller). */
-    struct vconn *listen_vconn;
+    struct pvconn *listen_pvconn;
 
     time_t last_timeout;
 
@@ -151,7 +146,7 @@ static void remote_wait(struct remote *);
 static void remote_destroy(struct remote *);
 
 void dp_output_port(struct datapath *, struct ofpbuf *,
-                    int in_port, int out_port);
+                    int in_port, int out_port, bool ignore_no_fwd);
 void dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
 void dp_output_control(struct datapath *, struct ofpbuf *, int in_port,
                        size_t max_len, int reason);
@@ -162,7 +157,8 @@ static void send_port_status(struct sw_port *p, uint8_t status);
 static void del_switch_port(struct sw_port *p);
 static void execute_actions(struct datapath *, struct ofpbuf *,
                             int in_port, const struct sw_flow_key *,
-                            const struct ofp_action *, int n_actions);
+                            const struct ofp_action *, int n_actions,
+                            bool ignore_no_fwd);
 static void modify_vlan(struct ofpbuf *buffer, const struct sw_flow_key *key,
                         const struct ofp_action *a);
 static void modify_nh(struct ofpbuf *buffer, uint16_t eth_proto,
@@ -181,8 +177,9 @@ static void modify_th(struct ofpbuf *buffer, uint16_t eth_proto,
 
 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
 
-int run_flow_through_tables(struct datapath *, struct ofpbuf *, int in_port);
-void fwd_port_input(struct datapath *, struct ofpbuf *, int in_port);
+int run_flow_through_tables(struct datapath *, struct ofpbuf *,
+                            struct sw_port *);
+void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
 int fwd_control_input(struct datapath *, const struct sender *,
                       const void *, size_t);
 
@@ -218,7 +215,7 @@ dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
     dp->last_timeout = time_now();
     list_init(&dp->remotes);
     dp->controller = remote_create(dp, rconn);
-    dp->listen_vconn = NULL;
+    dp->listen_pvconn = NULL;
     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
     dp->chain = chain_create();
     if (!dp->chain) {
@@ -283,10 +280,10 @@ dp_add_port(struct datapath *dp, const char *name)
 }
 
 void
-dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
+dp_add_listen_pvconn(struct datapath *dp, struct pvconn *listen_pvconn)
 {
-    assert(!dp->listen_vconn);
-    dp->listen_vconn = listen_vconn;
+    assert(!dp->listen_pvconn);
+    dp->listen_pvconn = listen_pvconn;
 }
 
 void
@@ -334,7 +331,7 @@ dp_run(struct datapath *dp)
         if (!error) {
             p->rx_packets++;
             p->rx_bytes += buffer->size;
-            fwd_port_input(dp, buffer, port_no(dp, p));
+            fwd_port_input(dp, buffer, p);
             buffer = NULL;
         } else if (error != EAGAIN) {
             VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
@@ -347,12 +344,12 @@ dp_run(struct datapath *dp)
     LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
         remote_run(dp, r);
     }
-    if (dp->listen_vconn) {
+    if (dp->listen_pvconn) {
         for (;;) {
             struct vconn *new_vconn;
             int retval;
 
-            retval = vconn_accept(dp->listen_vconn, &new_vconn);
+            retval = pvconn_accept(dp->listen_pvconn, OFP_VERSION, &new_vconn);
             if (retval) {
                 if (retval != EAGAIN) {
                     VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
@@ -485,8 +482,8 @@ dp_wait(struct datapath *dp)
     LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
         remote_wait(r);
     }
-    if (dp->listen_vconn) {
-        vconn_accept_wait(dp->listen_vconn);
+    if (dp->listen_pvconn) {
+        pvconn_wait(dp->listen_pvconn);
     }
 }
 
@@ -530,16 +527,17 @@ output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
         if (port_no(dp, p) == in_port) {
             continue;
         }
-        if (flood && p->flags & BRPF_NO_FLOOD) {
+        if (flood && p->flags & OFPPFL_NO_FLOOD) {
             continue;
         }
         if (prev_port != -1) {
-            dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port);
+            dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
+                           false);
         }
         prev_port = port_no(dp, p);
     }
     if (prev_port != -1)
-        dp_output_port(dp, buffer, in_port, prev_port);
+        dp_output_port(dp, buffer, in_port, prev_port, false);
     else
         ofpbuf_delete(buffer);
 
@@ -551,7 +549,7 @@ output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port)
 {
     if (out_port >= 0 && out_port < OFPP_MAX) { 
         struct sw_port *p = &dp->ports[out_port];
-        if (p->netdev != NULL && !(p->status & BRPS_PORT_DOWN)) {
+        if (p->netdev != NULL && !(p->status & OFPPFL_PORT_DOWN)) {
             if (!netdev_send(p->netdev, buffer)) {
                 p->tx_packets++;
                 p->tx_bytes += buffer->size;
@@ -570,7 +568,7 @@ output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port)
  */
 void
 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
-               int in_port, int out_port)
+               int in_port, int out_port, bool ignore_no_fwd)
 {
 
     assert(buffer);
@@ -583,7 +581,8 @@ dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
     } else if (out_port == OFPP_IN_PORT) {
         output_packet(dp, buffer, in_port);
     } else if (out_port == OFPP_TABLE) {
-               if (run_flow_through_tables(dp, buffer, in_port)) {
+        struct sw_port *p = in_port < OFPP_MAX ? &dp->ports[in_port] : 0;
+               if (run_flow_through_tables(dp, buffer, p)) {
                        ofpbuf_delete(buffer);
         }
     } else {
@@ -664,14 +663,7 @@ static void fill_port_desc(struct datapath *dp, struct sw_port *p,
     desc->flags = 0;
     desc->features = htonl(netdev_get_features(p->netdev));
     desc->speed = htonl(netdev_get_speed(p->netdev));
-
-    if (p->flags & BRPF_NO_FLOOD) {
-        desc->flags |= htonl(OFPPFL_NO_FLOOD);
-    } else if (p->status & BRPS_PORT_DOWN) {
-        desc->flags |= htonl(OFPPFL_PORT_DOWN);
-    } else if (p->status & BRPS_LINK_DOWN) { 
-        desc->flags |= htonl(OFPPFL_LINK_DOWN);
-    }
+    desc->flags = htonl(p->flags | p->status);
 }
 
 static void
@@ -683,14 +675,11 @@ dp_send_features_reply(struct datapath *dp, const struct sender *sender)
 
     ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
                                sender, &buffer);
-    ofr->datapath_id    = htonll(dp->id); 
-    ofr->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
-    ofr->n_compression  = 0;         /* Not supported */
-    ofr->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
-    ofr->buffer_mb      = htonl(UINT32_MAX);
-    ofr->n_buffers      = htonl(N_PKT_BUFFERS);
-    ofr->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
-    ofr->actions        = htonl(OFP_SUPPORTED_ACTIONS);
+    ofr->datapath_id  = htonll(dp->id); 
+    ofr->n_tables     = dp->chain->n_tables;
+    ofr->n_buffers    = htonl(N_PKT_BUFFERS);
+    ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
+    ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
         struct ofp_phy_port *opp = ofpbuf_put_uninit(buffer, sizeof *opp);
         memset(opp, 0, sizeof *opp);
@@ -706,6 +695,7 @@ dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
     int port_no = ntohs(opp->port_no);
     if (port_no < OFPP_MAX) {
         struct sw_port *p = &dp->ports[port_no];
+        uint32_t flag_mask;
 
         /* Make sure the port id hasn't changed since this was sent */
         if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
@@ -714,21 +704,20 @@ dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
         }
 
 
-        if (opm->mask & htonl(OFPPFL_NO_FLOOD)) {
-            if (opp->flags & htonl(OFPPFL_NO_FLOOD))
-                p->flags |= BRPF_NO_FLOOD;
-            else 
-                p->flags &= ~BRPF_NO_FLOOD;
+        flag_mask = ntohl(opm->mask) & PORT_FLAG_BITS;
+        if (flag_mask) {
+            p->flags &= ~flag_mask;
+            p->flags |= ntohl(opp->flags) & flag_mask;
         }
 
         if (opm->mask & htonl(OFPPFL_PORT_DOWN)) {
             if ((opp->flags & htonl(OFPPFL_PORT_DOWN))
-                            && (p->status & BRPS_PORT_DOWN) == 0) {
-                p->status |= BRPS_PORT_DOWN;
+                && (p->status & OFPPFL_PORT_DOWN) == 0) {
+                p->status |= OFPPFL_PORT_DOWN;
                 netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
             } else if ((opp->flags & htonl(OFPPFL_PORT_DOWN)) == 0
-                            && (p->status & BRPS_PORT_DOWN)) {
-                p->status &= ~BRPS_PORT_DOWN;
+                       && (p->status & OFPPFL_PORT_DOWN)) {
+                p->status &= ~OFPPFL_PORT_DOWN;
                 netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
             }
         }
@@ -754,9 +743,9 @@ update_port_status(struct sw_port *p)
         return 0;
     } else {
         if (flags & NETDEV_UP) {
-            p->status &= ~BRPS_PORT_DOWN;
+            p->status &= ~OFPPFL_PORT_DOWN;
         } else {
-            p->status |= BRPS_PORT_DOWN;
+            p->status |= OFPPFL_PORT_DOWN;
         } 
     }
 
@@ -764,9 +753,9 @@ update_port_status(struct sw_port *p)
      * error. */
     retval = netdev_get_link_status(p->netdev);
     if (retval == 1) {
-        p->status &= ~BRPS_LINK_DOWN;
+        p->status &= ~OFPPFL_LINK_DOWN;
     } else if (retval == 0) {
-        p->status |= BRPS_LINK_DOWN;
+        p->status |= OFPPFL_LINK_DOWN;
     } 
 
     return (orig_status != p->status);
@@ -807,12 +796,11 @@ send_flow_expired(struct datapath *dp, struct sw_flow *flow,
 
 void
 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
-        uint16_t type, uint16_t code, const uint8_t *data, size_t len)
+                  uint16_t type, uint16_t code, const void *data, size_t len)
 {
     struct ofpbuf *buffer;
     struct ofp_error_msg *oem;
-    oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG, 
-                              sender, &buffer);
+    oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
     oem->type = htons(type);
     oem->code = htons(code);
     memcpy(oem->data, data, len);
@@ -853,52 +841,59 @@ fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
 }
 
 \f
-/* 'buffer' was received on 'in_port', a physical switch port between 0 and
- * OFPP_MAX.  Process it according to 'dp''s flow table.  Returns 0 if
+/* 'buffer' was received on 'p', which may be a a physical switch port or a
+ * null pointer.  Process it according to 'dp''s flow table.  Returns 0 if
  * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
  * matching flow, in which case 'buffer' still belongs to the caller. */
 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
-                            int in_port)
+                            struct sw_port *p)
 {
     struct sw_flow_key key;
     struct sw_flow *flow;
 
     key.wildcards = 0;
-    if (flow_extract(buffer, in_port, &key.flow)
+    if (flow_extract(buffer, p ? port_no(dp, p) : OFPP_NONE, &key.flow)
         && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
         /* Drop fragment. */
         ofpbuf_delete(buffer);
         return 0;
     }
+       if (p && p->flags & (OFPPFL_NO_RECV | OFPPFL_NO_RECV_STP)
+        && p->flags & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
+                       ? OFPPFL_NO_RECV : OFPPFL_NO_RECV_STP)) {
+               ofpbuf_delete(buffer);
+               return 0;
+       }
 
     flow = chain_lookup(dp->chain, &key);
     if (flow != NULL) {
         flow_used(flow, buffer);
-        execute_actions(dp, buffer, in_port, &key,
-                        flow->actions, flow->n_actions);
+        execute_actions(dp, buffer, port_no(dp, p),
+                        &key, flow->actions, flow->n_actions, false);
         return 0;
     } else {
         return -ESRCH;
     }
 }
 
-/* 'buffer' was received on 'in_port', a physical switch port between 0 and
- * OFPP_MAX.  Process it according to 'dp''s flow table, sending it up to the
- * controller if no flow matches.  Takes ownership of 'buffer'. */
-void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer, int in_port) 
+/* 'buffer' was received on 'p', which may be a a physical switch port or a
+ * null pointer.  Process it according to 'dp''s flow table, sending it up to
+ * the controller if no flow matches.  Takes ownership of 'buffer'. */
+void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
+                    struct sw_port *p)
 {
-    if (run_flow_through_tables(dp, buffer, in_port)) {
-        dp_output_control(dp, buffer, in_port, dp->miss_send_len,
-                          OFPR_NO_MATCH);
+    if (run_flow_through_tables(dp, buffer, p)) {
+        dp_output_control(dp, buffer, port_no(dp, p),
+                          dp->miss_send_len, OFPR_NO_MATCH);
     }
 }
 
 static void
 do_output(struct datapath *dp, struct ofpbuf *buffer, int in_port,
-          size_t max_len, int out_port)
+          size_t max_len, int out_port, bool ignore_no_fwd)
 {
     if (out_port != OFPP_CONTROLLER) {
-        dp_output_port(dp, buffer, in_port, out_port);
+        dp_output_port(dp, buffer, in_port, out_port, ignore_no_fwd);
     } else {
         dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
     }
@@ -907,7 +902,8 @@ do_output(struct datapath *dp, struct ofpbuf *buffer, int in_port,
 static void
 execute_actions(struct datapath *dp, struct ofpbuf *buffer,
                 int in_port, const struct sw_flow_key *key,
-                const struct ofp_action *actions, int n_actions)
+                const struct ofp_action *actions, int n_actions,
+                bool ignore_no_fwd)
 {
     /* Every output action needs a separate clone of 'buffer', but the common
      * case is just a single output action, so that doing a clone and then
@@ -926,7 +922,8 @@ execute_actions(struct datapath *dp, struct ofpbuf *buffer,
         struct eth_header *eh = buffer->l2;
 
         if (prev_port != -1) {
-            do_output(dp, ofpbuf_clone(buffer), in_port, max_len, prev_port);
+            do_output(dp, ofpbuf_clone(buffer), in_port, max_len, prev_port,
+                      ignore_no_fwd);
             prev_port = -1;
         }
 
@@ -963,7 +960,7 @@ execute_actions(struct datapath *dp, struct ofpbuf *buffer,
         }
     }
     if (prev_port != -1)
-        do_output(dp, buffer, in_port, max_len, prev_port);
+        do_output(dp, buffer, in_port, max_len, prev_port, ignore_no_fwd);
     else
         ofpbuf_delete(buffer);
 }
@@ -1131,7 +1128,7 @@ recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
  
     flow_extract(buffer, ntohs(opo->in_port), &key.flow);
     execute_actions(dp, buffer, ntohs(opo->in_port),
-                    &key, opo->actions, n_actions);
+                    &key, opo->actions, n_actions, true);
 
    return 0;
 }
@@ -1202,7 +1199,8 @@ add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
             uint16_t in_port = ntohs(ofm->match.in_port);
             flow_used(flow, buffer);
             flow_extract(buffer, in_port, &key.flow);
-            execute_actions(dp, buffer, in_port, &key, ofm->actions, n_actions);
+            execute_actions(dp, buffer, in_port, &key,
+                            ofm->actions, n_actions, false);
         } else {
             error = -ESRCH; 
         }
@@ -1389,6 +1387,7 @@ static int table_stats_dump(struct datapath *dp, void *state,
         dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
         strncpy(ots->name, stats.name, sizeof ots->name);
         ots->table_id = i;
+        ots->wildcards = htonl(stats.wildcards);
         memset(ots->pad, 0, sizeof ots->pad);
         ots->max_entries = htonl(stats.max_flows);
         ots->active_count = htonl(stats.n_flows);
@@ -1700,7 +1699,9 @@ fwd_control_input(struct datapath *dp, const struct sender *sender,
         handler = recv_echo_reply;
         break;
     default:
-        return -ENOSYS;
+        dp_send_error_msg(dp, sender, OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE,
+                          msg, length);
+        return -EINVAL;
     }
 
     /* Handle it. */
index 260d10d..f0423de 100644 (file)
 
 struct datapath;
 struct rconn;
-struct vconn;
+struct pvconn;
 
 int dp_new(struct datapath **, uint64_t dpid, struct rconn *);
 int dp_add_port(struct datapath *, const char *netdev);
-void dp_add_listen_vconn(struct datapath *, struct vconn *);
+void dp_add_listen_pvconn(struct datapath *, struct pvconn *);
 void dp_run(struct datapath *);
 void dp_wait(struct datapath *);
 
index babcd6c..853fe40 100644 (file)
@@ -191,7 +191,9 @@ flow_free(struct sw_flow *flow)
     if (!flow) {
         return; 
     }
-    free(flow->actions);
+    if (flow->actions) {
+        free(flow->actions);
+    }
     free(flow);
 }
 
index cd14f05..4c75061 100644 (file)
@@ -68,7 +68,7 @@ char serial_num[SERIAL_NUM_LEN] = "None";
 static void parse_options(int argc, char *argv[]);
 static void usage(void) NO_RETURN;
 
-static const char *listen_vconn_name;
+static const char *listen_pvconn_name;
 static struct datapath *dp;
 static uint64_t dpid = UINT64_MAX;
 static char *port_list;
@@ -102,18 +102,15 @@ main(int argc, char *argv[])
         ofp_fatal(0, "no support for %s vconn", argv[optind]);
     }
     error = dp_new(&dp, dpid, rconn);
-    if (listen_vconn_name) {
-        struct vconn *listen_vconn;
+    if (listen_pvconn_name) {
+        struct pvconn *listen_pvconn;
         int retval;
-        
-        retval = vconn_open(listen_vconn_name, &listen_vconn);
+
+        retval = pvconn_open(listen_pvconn_name, &listen_pvconn);
         if (retval && retval != EAGAIN) {
-            ofp_fatal(retval, "opening %s", listen_vconn_name);
-        }
-        if (!vconn_is_passive(listen_vconn)) {
-            ofp_fatal(0, "%s is not a passive vconn", listen_vconn_name);
+            ofp_fatal(retval, "opening %s", listen_pvconn_name);
         }
-        dp_add_listen_vconn(dp, listen_vconn);
+        dp_add_listen_pvconn(dp, listen_pvconn);
     }
     if (error) {
         ofp_fatal(error, "could not create datapath");
@@ -268,10 +265,10 @@ parse_options(int argc, char *argv[])
             break;
 
         case 'l':
-            if (listen_vconn_name) {
+            if (listen_pvconn_name) {
                 ofp_fatal(0, "-l or --listen may be only specified once");
             }
-            listen_vconn_name = optarg;
+            listen_pvconn_name = optarg;
             break;
 
         VCONN_SSL_OPTION_HANDLERS
index 175b840..ba8ebff 100644 (file)
@@ -82,6 +82,12 @@ static int table_hash_insert(struct sw_table *swt, struct sw_flow *flow)
     } else {
         struct sw_flow *old_flow = *bucket;
         if (!flow_compare(&old_flow->key.flow, &flow->key.flow)) {
+            /* Keep stats from the original flow */
+            flow->used = old_flow->used;
+            flow->created = old_flow->created;
+            flow->packet_count = old_flow->packet_count;
+            flow->byte_count = old_flow->byte_count;
+
             *bucket = flow;
             flow_free(old_flow);
             retval = 1;
@@ -199,7 +205,8 @@ static void table_hash_stats(struct sw_table *swt,
 {
     struct sw_table_hash *th = (struct sw_table_hash *) swt;
     stats->name = "hash";
-    stats->n_flows = th->n_flows;
+    stats->wildcards = 0;        /* No wildcards are supported. */
+    stats->n_flows   = th->n_flows;
     stats->max_flows = th->bucket_mask + 1;
     stats->n_matched = swt->n_matched;
 }
@@ -324,7 +331,8 @@ static void table_hash2_stats(struct sw_table *swt,
     for (i = 0; i < 2; i++)
         table_hash_stats(t2->subtable[i], &substats[i]);
     stats->name = "hash2";
-    stats->n_flows = substats[0].n_flows + substats[1].n_flows;
+    stats->wildcards = 0;        /* No wildcards are supported. */
+    stats->n_flows   = substats[0].n_flows + substats[1].n_flows;
     stats->max_flows = substats[0].max_flows + substats[1].max_flows;
     stats->n_matched = swt->n_matched;
 }
index ea3777f..1894577 100644 (file)
@@ -36,6 +36,7 @@
 #include <stdlib.h>
 #include "flow.h"
 #include "list.h"
+#include "openflow.h"
 #include "switch-flow.h"
 #include "datapath.h"
 
@@ -74,6 +75,12 @@ static int table_linear_insert(struct sw_table *swt, struct sw_flow *flow)
         if (f->priority == flow->priority
                 && f->key.wildcards == flow->key.wildcards
                 && flow_matches_2wild(&f->key, &flow->key)) {
+            /* Keep stats from the original flow */
+            flow->used = f->used;
+            flow->created = f->created;
+            flow->packet_count = f->packet_count;
+            flow->byte_count = f->byte_count;
+
             flow->serial = f->serial;
             list_replace(&flow->node, &f->node);
             list_replace(&flow->iter_node, &f->iter_node);
@@ -182,7 +189,8 @@ static void table_linear_stats(struct sw_table *swt,
 {
     struct sw_table_linear *tl = (struct sw_table_linear *) swt;
     stats->name = "linear";
-    stats->n_flows = tl->n_flows;
+    stats->wildcards = OFPFW_ALL;
+    stats->n_flows   = tl->n_flows;
     stats->max_flows = tl->max_flows;
     stats->n_matched = swt->n_matched;
 }
index c31ffa6..1068a48 100644 (file)
@@ -46,6 +46,8 @@ struct list;
 /* Table statistics. */
 struct sw_table_stats {
     const char *name;            /* Human-readable name. */
+    uint32_t wildcards;          /* Bitmap of OFPFW_* wildcards that are
+                                    supported by the table. */
     unsigned int n_flows;        /* Number of active flows. */
     unsigned int max_flows;      /* Flow capacity. */
     unsigned long int n_matched; /* Number of packets that have hit. */
index 2548ea0..e3981bf 100644 (file)
@@ -1,17 +1,37 @@
 include ../Make.vars
 
 TESTS = test-list
-
-check_PROGRAMS = test-list
-
+noinst_PROGRAMS = test-list
 test_list_SOURCES = test-list.c
 test_list_LDADD = ../lib/libopenflow.a
 
 TESTS += test-type-props
-check_PROGRAMS += test-type-props
+noinst_PROGRAMS += test-type-props
 test_type_props_SOURCES = test-type-props.c
 
-noinst_PROGRAMS = test-dhcp-client
+noinst_PROGRAMS += test-dhcp-client
 test_dhcp_client_SOURCES = test-dhcp-client.c
 test_dhcp_client_LDADD = ../lib/libopenflow.a $(FAULT_LIBS)
 
+TESTS += test-stp.sh
+EXTRA_DIST = test-stp.sh
+noinst_PROGRAMS += test-stp
+
+test_stp_SOURCES = test-stp.c
+test_stp_LDADD = ../lib/libopenflow.a
+stp_files = \
+       test-stp-ieee802.1d-1998 \
+       test-stp-ieee802.1d-2004-fig17.4 \
+       test-stp-ieee802.1d-2004-fig17.6 \
+       test-stp-ieee802.1d-2004-fig17.7 \
+       test-stp-iol-op-1.1 \
+       test-stp-iol-op-1.4 \
+       test-stp-iol-op-3.1 \
+       test-stp-iol-op-3.3 \
+       test-stp-iol-io-1.1 \
+       test-stp-iol-io-1.2 \
+       test-stp-iol-io-1.4 \
+       test-stp-iol-io-1.5
+TESTS_ENVIRONMENT = stp_files='$(stp_files)'
+
+EXTRA_DIST += $(stp_files)
diff --git a/tests/test-stp-ieee802.1d-1998 b/tests/test-stp-ieee802.1d-1998
new file mode 100644 (file)
index 0000000..88aedb4
--- /dev/null
@@ -0,0 +1,12 @@
+# This is the STP example from IEEE 802.1D-1998.
+bridge 0 0x42 = a b
+bridge 1 0x97 = c:5 a d:5
+bridge 2 0x45 = b e
+bridge 3 0x57 = b:5 e:5
+bridge 4 0x83 = a:5 e:5
+run 256
+check 0 = root
+check 1 = F F:10 F
+check 2 = F:10 B
+check 3 = F:5 F
+check 4 = F:5 B
diff --git a/tests/test-stp-ieee802.1d-2004-fig17.4 b/tests/test-stp-ieee802.1d-2004-fig17.4
new file mode 100644 (file)
index 0000000..29b13ff
--- /dev/null
@@ -0,0 +1,31 @@
+# This is the STP example from IEEE 802.1D-2004 figures 17.4 and 17.5.
+bridge 0 0x111 = a b e c
+bridge 1 0x222 = a b d f
+bridge 2 0x333 = c d l j h g
+bridge 3 0x444 = e f n m k i
+bridge 4 0x555 = g i 0 0
+bridge 5 0x666 = h k 0 0
+bridge 6 0x777 = j m 0 0
+bridge 7 0x888 = l n 0 0
+run 256
+check 0 = root
+check 1 = F:10 B F F
+check 2 = F:10 B F F F F
+check 3 = F:10 B F F F F
+check 4 = F:20 B F F
+check 5 = F:20 B F F
+check 6 = F:20 B F F
+check 7 = F:20 B F F
+
+# Now connect two ports of bridge 7 to the same LAN.
+bridge 7 = l n o o
+# Same results except for bridge 7:
+run 256
+check 0 = root
+check 1 = F:10 B F F
+check 2 = F:10 B F F F F
+check 3 = F:10 B F F F F
+check 4 = F:20 B F F
+check 5 = F:20 B F F
+check 6 = F:20 B F F
+check 7 = F:20 B F B
diff --git a/tests/test-stp-ieee802.1d-2004-fig17.6 b/tests/test-stp-ieee802.1d-2004-fig17.6
new file mode 100644 (file)
index 0000000..694d238
--- /dev/null
@@ -0,0 +1,14 @@
+# This is the STP example from IEEE 802.1D-2004 figure 17.6.
+bridge 0 0x111 = a b l
+bridge 1 0x222 = b c d
+bridge 2 0x333 = d e f
+bridge 3 0x444 = f g h
+bridge 4 0x555 = j h i
+bridge 5 0x666 = l j k
+run 256
+check 0 = root
+check 1 = F:10 F F
+check 2 = F:20 F F
+check 3 = F:30 F B
+check 4 = F:20 F F
+check 5 = F:10 F F
diff --git a/tests/test-stp-ieee802.1d-2004-fig17.7 b/tests/test-stp-ieee802.1d-2004-fig17.7
new file mode 100644 (file)
index 0000000..278655e
--- /dev/null
@@ -0,0 +1,17 @@
+# This is the STP example from IEEE 802.1D-2004 figure 17.7.
+bridge 0 0xaa = b
+bridge 1 0x111 = a b d f h g e c
+bridge 2 0x222 = g h j l n m k i
+run 256
+check 0 = root
+check 1 = F F:10 F F F F F F
+check 2 = B F:20 F F F F F F
+
+# This is not the port priority change described in that figure,
+# but I don't understand what port priority change would cause
+# that change.
+bridge 2 = g X j l n m k i
+run 256
+check 0 = root
+check 1 = F F:10 F F F F F F
+check 2 = F:20 D F F F F F F
diff --git a/tests/test-stp-iol-io-1.1 b/tests/test-stp-iol-io-1.1
new file mode 100644 (file)
index 0000000..1b53fed
--- /dev/null
@@ -0,0 +1,25 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Interoperability Test Suite
+# Version 1.5":
+# STP.io.1.1: Link Failure
+bridge 0 0x111 = a b c
+bridge 1 0x222 = a b c
+run 256
+check 0 = root
+check 1 = F:10 B B
+bridge 1 = 0 _ _
+run 256
+check 0 = root
+check 1 = F F:10 B
+bridge 1 = X _ _
+run 256
+check 0 = root
+check 1 = D F:10 B
+bridge 1 = _ 0 _
+run 256
+check 0 = root
+check 1 = D F F:10
+bridge 1 = _ X _
+run 256
+check 0 = root
+check 1 = D D F:10
diff --git a/tests/test-stp-iol-io-1.2 b/tests/test-stp-iol-io-1.2
new file mode 100644 (file)
index 0000000..a2ed48c
--- /dev/null
@@ -0,0 +1,14 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Interoperability Test Suite
+# Version 1.5":
+# STP.io.1.2: Repeated Network
+bridge 0 0x111 = a a
+bridge 1 0x222 = a a
+run 256
+check 0 = rootid:0x111 F B
+check 1 = rootid:0x111 F:10 B
+bridge 1 = a^0x90 _
+run 256
+check 0 = rootid:0x111 F B
+check 1 = rootid:0x111 B F:10
+
diff --git a/tests/test-stp-iol-io-1.4 b/tests/test-stp-iol-io-1.4
new file mode 100644 (file)
index 0000000..f8b0b72
--- /dev/null
@@ -0,0 +1,13 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Interoperability Test Suite
+# Version 1.5":
+# STP.io.1.4: Network Initialization
+bridge 0 0x111 = a b c
+bridge 1 0x222 = b d e
+bridge 2 0x333 = a d f
+bridge 3 0x444 = c e f
+run 256
+check 0 = root
+check 1 = F:10 F F
+check 2 = F:10 B F
+check 3 = F:10 B B
diff --git a/tests/test-stp-iol-io-1.5 b/tests/test-stp-iol-io-1.5
new file mode 100644 (file)
index 0000000..c5f08b8
--- /dev/null
@@ -0,0 +1,40 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Interoperability Test Suite
+# Version 1.5":
+# STP.io.1.5: Topology Change
+bridge 0 0x111 = a b d c
+bridge 1 0x222 = a b f e
+bridge 2 0x333 = c d g h
+bridge 3 0x444 = e f g h
+run 256
+check 0 = root
+check 1 = F:10 B F F
+check 2 = B F:10 F F
+check 3 = B F:20 B B
+bridge 1^0x7000
+run 256
+check 0 = F:10 B F F
+check 1 = root
+check 2 = B F:20 B B
+check 3 = B F:10 F F
+bridge 2^0x6000
+run 256
+check 0 = F F B F:10
+check 1 = F:20 B B B
+check 2 = root
+check 3 = F F F:10 B
+bridge 3^0x5000
+run 256
+check 0 = B B B F:20
+check 1 = F F B F:10
+check 2 = F F F:10 B
+check 3 = root
+bridge 0^0x4000
+bridge 1^0x4001
+bridge 2^0x4002
+bridge 3^0x4003
+run 256
+check 0 = root
+check 1 = F:10 B F F
+check 2 = B F:10 F F
+check 3 = B F:20 B B
diff --git a/tests/test-stp-iol-op-1.1 b/tests/test-stp-iol-op-1.1
new file mode 100644 (file)
index 0000000..8432bf3
--- /dev/null
@@ -0,0 +1,7 @@
+# This test file approximates the following tests from "Bridge
+# Functions Consortium Spanning Tree Protocol Operations Test Suite
+# Version 2.3":
+# Test STP.op.1.1 Â­ Root ID Initialized to Bridge ID
+# Test STP.op.1.2 Â­ Root Path Cost Initialized to Zero
+bridge 0 0x123 =
+check 0 = root
diff --git a/tests/test-stp-iol-op-1.4 b/tests/test-stp-iol-op-1.4
new file mode 100644 (file)
index 0000000..18c09b8
--- /dev/null
@@ -0,0 +1,8 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Protocol Operations Test Suite
+# Version 2.3":
+# Test STP.op.1.4 Â­ All Ports Initialized to Designated Ports
+bridge 0 0x123 = a b c d e f
+check 0 = Li Li Li Li Li Li
+run 256
+check 0 = F F F F F F
diff --git a/tests/test-stp-iol-op-3.1 b/tests/test-stp-iol-op-3.1
new file mode 100644 (file)
index 0000000..2e0a2f2
--- /dev/null
@@ -0,0 +1,11 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Protocol Operations Test Suite
+# Version 2.3":
+# Test STP.op.3.1 Â­ Root Bridge Selection: Root ID Values
+bridge 0 0x111 = a
+bridge 1 0x222 = a
+check 0 = rootid:0x111 Li
+check 1 = rootid:0x222 Li
+run 256
+check 0 = rootid:0x111 root
+check 1 = rootid:0x111 F:10
diff --git a/tests/test-stp-iol-op-3.3 b/tests/test-stp-iol-op-3.3
new file mode 100644 (file)
index 0000000..093c64e
--- /dev/null
@@ -0,0 +1,11 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Protocol Operations Test Suite
+# Version 2.3":
+# Test STP.op.3.3 Â­ Root Bridge Selection: Bridge ID Values
+bridge 0 0x333^0x6000 = a
+bridge 1 0x222^0x7000 = b
+bridge 2 0x111 = a b
+run 256
+check 0 = rootid:0x333^0x6000 root
+check 1 = rootid:0x333^0x6000 F:20
+check 2 = rootid:0x333^0x6000 F:10 F
diff --git a/tests/test-stp-iol-op-3.4 b/tests/test-stp-iol-op-3.4
new file mode 100644 (file)
index 0000000..093c64e
--- /dev/null
@@ -0,0 +1,11 @@
+# This test file approximates the following test from "Bridge
+# Functions Consortium Spanning Tree Protocol Operations Test Suite
+# Version 2.3":
+# Test STP.op.3.3 Â­ Root Bridge Selection: Bridge ID Values
+bridge 0 0x333^0x6000 = a
+bridge 1 0x222^0x7000 = b
+bridge 2 0x111 = a b
+run 256
+check 0 = rootid:0x333^0x6000 root
+check 1 = rootid:0x333^0x6000 F:20
+check 2 = rootid:0x333^0x6000 F:10 F
diff --git a/tests/test-stp.c b/tests/test-stp.c
new file mode 100644 (file)
index 0000000..9b87c0e
--- /dev/null
@@ -0,0 +1,661 @@
+/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
+ * Junior University
+ *
+ * We are making the OpenFlow specification and associated documentation
+ * (Software) available for public use and benefit with the expectation
+ * that others will use, modify and enhance the Software and contribute
+ * those enhancements back to the community. However, since we would
+ * like to make the Software available for broadest use, with as few
+ * restrictions as possible permission is hereby granted, free of
+ * charge, to any person obtaining a copy of this Software to deal in
+ * the Software under the copyrights without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ * The name and trademarks of copyright holder(s) may NOT be used in
+ * advertising or publicity pertaining to the Software or any
+ * derivatives without specific, written prior permission.
+ */
+
+#include "stp.h"
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include "packets.h"
+
+struct bpdu {
+    int port_no;
+    void *data;
+    size_t size;
+};
+
+struct bridge {
+    struct test_case *tc;
+    int id;
+    bool reached;
+
+    struct stp *stp;
+
+    struct lan *ports[STP_MAX_PORTS];
+    int n_ports;
+
+#define RXQ_SIZE 16
+    struct bpdu rxq[RXQ_SIZE];
+    int rxq_head, rxq_tail;
+};
+
+struct lan_conn {
+    struct bridge *bridge;
+    int port_no;
+};
+
+struct lan {
+    struct test_case *tc;
+    const char *name;
+    bool reached;
+    struct lan_conn conns[16];
+    int n_conns;
+};
+
+struct test_case {
+    struct bridge *bridges[16];
+    int n_bridges;
+    struct lan *lans[26];
+    int n_lans;
+};
+
+static const char *file_name;
+static int line_number;
+static char line[128];
+static char *pos, *token;
+static int n_warnings;
+
+static struct test_case *
+new_test_case(void)
+{
+    struct test_case *tc = xmalloc(sizeof *tc);
+    tc->n_bridges = 0;
+    tc->n_lans = 0;
+    return tc;
+}
+
+static void
+send_bpdu(const void *data, size_t size, int port_no, void *b_)
+{
+    struct bridge *b = b_;
+    struct lan *lan;
+    int i;
+
+    assert(port_no < b->n_ports);
+    lan = b->ports[port_no];
+    if (!lan) {
+        return;
+    }
+    for (i = 0; i < lan->n_conns; i++) {
+        struct lan_conn *conn = &lan->conns[i];
+        if (conn->bridge != b || conn->port_no != port_no) {
+            struct bridge *dst = conn->bridge;
+            struct bpdu *bpdu = &dst->rxq[dst->rxq_head++ % RXQ_SIZE];
+            assert(dst->rxq_head - dst->rxq_tail <= RXQ_SIZE);
+            bpdu->data = xmemdup(data, size);
+            bpdu->size = size;
+            bpdu->port_no = conn->port_no;
+        }
+    }
+}
+
+static struct bridge *
+new_bridge(struct test_case *tc, int id)
+{
+    struct bridge *b = xmalloc(sizeof *b);
+    char name[16];
+    b->tc = tc;
+    b->id = id;
+    snprintf(name, sizeof name, "stp%x", id);
+    b->stp = stp_create(name, id, send_bpdu, b);
+    assert(tc->n_bridges < ARRAY_SIZE(tc->bridges));
+    b->n_ports = 0;
+    b->rxq_head = b->rxq_tail = 0;
+    tc->bridges[tc->n_bridges++] = b;
+    return b;
+}
+
+static struct lan *
+new_lan(struct test_case *tc, const char *name)
+{
+    struct lan *lan = xmalloc(sizeof *lan);
+    lan->tc = tc;
+    lan->name = xstrdup(name);
+    lan->n_conns = 0;
+    assert(tc->n_lans < ARRAY_SIZE(tc->lans));
+    tc->lans[tc->n_lans++] = lan;
+    return lan;
+}
+
+static void
+reconnect_port(struct bridge *b, int port_no, struct lan *new_lan)
+{
+    struct lan *old_lan;
+    int j;
+
+    assert(port_no < b->n_ports);
+    old_lan = b->ports[port_no];
+    if (old_lan == new_lan) {
+        return;
+    }
+
+    /* Disconnect from old_lan. */
+    if (old_lan) {
+        for (j = 0; j < old_lan->n_conns; j++) {
+            struct lan_conn *c = &old_lan->conns[j];
+            if (c->bridge == b && c->port_no == port_no) {
+                memmove(c, c + 1, sizeof *c * (old_lan->n_conns - j - 1));
+                old_lan->n_conns--;
+                break;
+            }
+        }
+    }
+
+    /* Connect to new_lan. */
+    b->ports[port_no] = new_lan;
+    if (new_lan) {
+        int conn_no = new_lan->n_conns++;
+        assert(conn_no < ARRAY_SIZE(new_lan->conns));
+        new_lan->conns[conn_no].bridge = b;
+        new_lan->conns[conn_no].port_no = port_no;
+    }
+}
+
+static void
+new_port(struct bridge *b, struct lan *lan, int path_cost)
+{
+    int port_no = b->n_ports++;
+    struct stp_port *p = stp_get_port(b->stp, port_no);
+    assert(port_no < ARRAY_SIZE(b->ports));
+    b->ports[port_no] = NULL;
+    stp_port_set_path_cost(p, path_cost);
+    stp_port_enable(p);
+    reconnect_port(b, port_no, lan);
+}
+
+static void
+dump(struct test_case *tc)
+{
+    int i;
+
+    for (i = 0; i < tc->n_bridges; i++) {
+        struct bridge *b = tc->bridges[i];
+        struct stp *stp = b->stp;
+        int j;
+
+        printf("%s:", stp_get_name(stp));
+        if (stp_is_root_bridge(stp)) {
+            printf(" root");
+        }
+        printf("\n");
+        for (j = 0; j < b->n_ports; j++) {
+            struct stp_port *p = stp_get_port(stp, j);
+            enum stp_state state = stp_port_get_state(p);
+
+            printf("\tport %d", j);
+            if (b->ports[j]) {
+                printf(" (lan %s)", b->ports[j]->name);
+            } else {
+                printf(" (disconnected)");
+            }
+            printf(": %s", stp_state_name(state));
+            if (p == stp_get_root_port(stp)) {
+                printf(" (root port, root_path_cost=%u)", stp_get_root_path_cost(stp));
+            }
+            printf("\n");
+        }
+    }
+}
+
+static void dump_lan_tree(struct test_case *, struct lan *, int level);
+
+static void
+dump_bridge_tree(struct test_case *tc, struct bridge *b, int level)
+{
+    int i;
+
+    if (b->reached) {
+        return;
+    }
+    b->reached = true;
+    for (i = 0; i < level; i++) {
+        printf("\t");
+    }
+    printf("%s\n", stp_get_name(b->stp));
+    for (i = 0; i < b->n_ports; i++) {
+        struct lan *lan = b->ports[i];
+        struct stp_port *p = stp_get_port(b->stp, i);
+        if (stp_port_get_state(p) == STP_FORWARDING && lan) {
+            dump_lan_tree(tc, lan, level + 1);
+        }
+    }
+}
+
+static void
+dump_lan_tree(struct test_case *tc, struct lan *lan, int level) 
+{
+    int i;
+
+    if (lan->reached) {
+        return;
+    }
+    lan->reached = true;
+    for (i = 0; i < level; i++) {
+        printf("\t");
+    }
+    printf("%s\n", lan->name);
+    for (i = 0; i < lan->n_conns; i++) {
+        struct bridge *b = lan->conns[i].bridge;
+        dump_bridge_tree(tc, b, level + 1);
+    }
+}
+
+static void
+tree(struct test_case *tc)
+{
+    int i;
+
+    for (i = 0; i < tc->n_bridges; i++) {
+        struct bridge *b = tc->bridges[i];
+        b->reached = false;
+    }
+    for (i = 0; i < tc->n_lans; i++) {
+        struct lan *lan = tc->lans[i];
+        lan->reached = false;
+    }
+    for (i = 0; i < tc->n_bridges; i++) {
+        struct bridge *b = tc->bridges[i];
+        struct stp *stp = b->stp;
+        if (stp_is_root_bridge(stp)) {
+            dump_bridge_tree(tc, b, 0);
+        }
+    }
+}
+
+static void
+simulate(struct test_case *tc, int granularity)
+{
+    int time;
+
+    for (time = 0; time < 256 * 180; time += granularity) {
+        int round_trips;
+        int i;
+
+        for (i = 0; i < tc->n_bridges; i++) {
+            stp_tick(tc->bridges[i]->stp, granularity);
+        }
+        for (round_trips = 0; round_trips < granularity; round_trips++) {
+            bool any = false;
+            for (i = 0; i < tc->n_bridges; i++) {
+                struct bridge *b = tc->bridges[i];
+                for (; b->rxq_tail != b->rxq_head; b->rxq_tail++) {
+                    struct bpdu *bpdu = &b->rxq[b->rxq_tail % RXQ_SIZE];
+                    stp_received_bpdu(stp_get_port(b->stp, bpdu->port_no),
+                                      bpdu->data, bpdu->size);
+                    any = true;
+                }
+            }
+            if (!any) {
+                break;
+            }
+        }
+    }
+}
+
+static void
+err(const char *message, ...)
+    PRINTF_FORMAT(1, 2)
+    NO_RETURN;
+
+static void
+err(const char *message, ...)
+{
+    va_list args;
+
+    fprintf(stderr, "%s:%d:%td: ", file_name, line_number, pos - line);
+    va_start(args, message);
+    vfprintf(stderr, message, args);
+    va_end(args);
+    putc('\n', stderr);
+
+    exit(EXIT_FAILURE);
+}
+
+static void
+warn(const char *message, ...)
+    PRINTF_FORMAT(1, 2);
+
+static void
+warn(const char *message, ...)
+{
+    va_list args;
+
+    fprintf(stderr, "%s:%d: ", file_name, line_number);
+    va_start(args, message);
+    vfprintf(stderr, message, args);
+    va_end(args);
+    putc('\n', stderr);
+
+    n_warnings++;
+}
+
+static bool
+get_token(void)
+{
+    char *start;
+
+    while (isspace((unsigned char) *pos)) {
+        pos++;
+    }
+    if (*pos == '\0') {
+        token = NULL;
+        return false;
+    }
+
+    start = pos;
+    if (isalpha((unsigned char) *pos)) {
+        while (isalpha((unsigned char) *++pos)) {
+            continue;
+        }
+    } else if (isdigit((unsigned char) *pos)) {
+        if (*pos == '0' && (pos[1] == 'x' || pos[1] == 'X')) {
+            pos += 2;
+            while (isxdigit((unsigned char) *pos)) {
+                pos++;
+            }
+        } else {
+            while (isdigit((unsigned char) *++pos)) {
+                continue;
+            }
+        }
+    } else {
+        pos++;
+    }
+
+    free(token);
+    token = xmemdup0(start, pos - start);
+    return true;
+}
+
+static bool
+get_int(int *intp)
+{
+    char *save_pos = pos;
+    if (token && isdigit((unsigned char) *token)) {
+        *intp = strtol(token, NULL, 0);
+        get_token();
+        return true;
+    } else {
+        pos = save_pos;
+        return false;
+    }
+}
+
+static bool
+match(const char *want)
+{
+    if (token && !strcmp(want, token)) {
+        get_token();
+        return true;
+    } else {
+        return false;
+    }
+}
+
+static int
+must_get_int(void)
+{
+    int x;
+    if (!get_int(&x)) {
+        err("expected integer");
+    }
+    return x;
+}
+
+static void
+must_match(const char *want)
+{
+    if (!match(want)) {
+        err("expected \"%s\"", want);
+    }
+}
+
+int
+main(int argc, char *argv[])
+{
+    struct test_case *tc;
+    FILE *input_file;
+    int i;
+
+    if (argc != 2) {
+        ofp_fatal(0, "usage: test-stp INPUT.STP\n");
+    }
+    file_name = argv[1];
+
+    input_file = fopen(file_name, "r");
+    if (!input_file) {
+        ofp_fatal(errno, "error opening \"%s\"", file_name);
+    }
+
+    tc = new_test_case();
+    for (i = 0; i < 26; i++) {
+        char name[2];
+        name[0] = 'a' + i;
+        name[1] = '\0';
+        new_lan(tc, name);
+    }
+
+    for (line_number = 1; fgets(line, sizeof line, input_file);
+         line_number++)
+    {
+        char *newline, *hash;
+
+        newline = strchr(line, '\n');
+        if (newline) {
+            *newline = '\0';
+        }
+        hash = strchr(line, '#');
+        if (hash) {
+            *hash = '\0';
+        }
+
+        pos = line;
+        if (!get_token()) {
+            continue;
+        }
+        if (match("bridge")) {
+            struct bridge *bridge;
+            int bridge_no, port_no;
+
+            bridge_no = must_get_int();
+            if (bridge_no < tc->n_bridges) {
+                bridge = tc->bridges[bridge_no];
+            } else if (bridge_no == tc->n_bridges) {
+                bridge = new_bridge(tc, must_get_int());
+            } else {
+                err("bridges must be numbered consecutively from 0");
+            }
+            if (match("^")) {
+                stp_set_bridge_priority(bridge->stp, must_get_int());
+            }
+
+            if (match("=")) {
+                for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) {
+                    struct stp_port *p = stp_get_port(bridge->stp, port_no);
+                    if (!token || match("X")) {
+                        stp_port_disable(p);
+                    } else if (match("_")) {
+                        /* Nothing to do. */
+                    } else {
+                        struct lan *lan;
+                        int path_cost;
+
+                        if (!strcmp(token, "0")) {
+                            lan = NULL;
+                        } else if (strlen(token) == 1 && islower(*token)) {
+                            lan = tc->lans[*token - 'a']; 
+                        } else {
+                            err("%s is not a valid LAN name "
+                                "(0 or a lowercase letter)", token);
+                        }
+                        get_token();
+
+                        path_cost = match(":") ? must_get_int() : 10;
+                        if (port_no < bridge->n_ports) {
+                            stp_port_set_path_cost(p, path_cost);
+                            stp_port_enable(p);
+                            reconnect_port(bridge, port_no, lan);
+                        } else if (port_no == bridge->n_ports) {
+                            new_port(bridge, lan, path_cost);
+                        } else {
+                            err("ports must be numbered consecutively");
+                        }
+                        if (match("^")) {
+                            stp_port_set_priority(p, must_get_int());
+                        }
+                    }
+                }
+            }
+        } else if (match("run")) {
+            simulate(tc, must_get_int());
+        } else if (match("dump")) {
+            dump(tc);
+        } else if (match("tree")) {
+            tree(tc);
+        } else if (match("check")) {
+            struct bridge *b;
+            struct stp *stp;
+            int bridge_no, port_no;
+
+            bridge_no = must_get_int();
+            if (bridge_no >= tc->n_bridges) {
+                err("no bridge numbered %d", bridge_no);
+            }
+            b = tc->bridges[bridge_no];
+            stp = b->stp;
+
+            must_match("=");
+
+            if (match("rootid")) {
+                uint64_t rootid;
+                must_match(":");
+                rootid = must_get_int();
+                if (match("^")) {
+                    rootid |= (uint64_t) must_get_int() << 48;
+                } else {
+                    rootid |= UINT64_C(0x8000) << 48;
+                }
+                if (stp_get_designated_root(stp) != rootid) {
+                    warn("%s: root %"PRIx64", not %"PRIx64,
+                         stp_get_name(stp), stp_get_designated_root(stp),
+                         rootid);
+                }
+            }
+
+            if (match("root")) {
+                if (stp_get_root_path_cost(stp)) {
+                    warn("%s: root path cost of root is %u but should be 0",
+                         stp_get_name(stp), stp_get_root_path_cost(stp));
+                }
+                if (!stp_is_root_bridge(stp)) {
+                    warn("%s: root is %"PRIx64", not %"PRIx64,
+                         stp_get_name(stp),
+                         stp_get_designated_root(stp), stp_get_bridge_id(stp));
+                }
+                for (port_no = 0; port_no < b->n_ports; port_no++) {
+                    struct stp_port *p = stp_get_port(stp, port_no);
+                    enum stp_state state = stp_port_get_state(p);
+                    if (!(state & (STP_DISABLED | STP_FORWARDING))) {
+                        warn("%s: root port %d in state %s",
+                             stp_get_name(b->stp), port_no,
+                             stp_state_name(state));
+                    }
+                }
+            } else {
+                for (port_no = 0; port_no < STP_MAX_PORTS; port_no++) {
+                    struct stp_port *p = stp_get_port(stp, port_no);
+                    enum stp_state state;
+                    if (token == NULL || match("D")) {
+                        state = STP_DISABLED;
+                    } else if (match("B")) {
+                        state = STP_BLOCKING;
+                    } else if (match("Li")) {
+                        state = STP_LISTENING;
+                    } else if (match("Le")) {
+                        state = STP_LEARNING;
+                    } else if (match("F")) {
+                        state = STP_FORWARDING;
+                    } else if (match("_")) {
+                        continue;
+                    } else {
+                        err("unknown port state %s", token);
+                    }
+                    if (stp_port_get_state(p) != state) {
+                        warn("%s port %d: state is %s but should be %s",
+                             stp_get_name(stp), port_no,
+                             stp_state_name(stp_port_get_state(p)),
+                             stp_state_name(state));
+                    }
+                    if (state == STP_FORWARDING) {
+                        struct stp_port *root_port = stp_get_root_port(stp);
+                        if (match(":")) {
+                            int root_path_cost = must_get_int();
+                            if (p != root_port) {
+                                warn("%s: port %d is not the root port",
+                                     stp_get_name(stp), port_no);
+                                if (!root_port) {
+                                    warn("%s: (there is no root port)",
+                                         stp_get_name(stp));
+                                } else {
+                                    warn("%s: (port %d is the root port)",
+                                         stp_get_name(stp),
+                                         stp_port_no(root_port));
+                                }
+                            } else if (root_path_cost
+                                       != stp_get_root_path_cost(stp)) {
+                                warn("%s: root path cost is %u, should be %d",
+                                     stp_get_name(stp),
+                                     stp_get_root_path_cost(stp),
+                                     root_path_cost);
+                            }
+                        } else if (p == root_port) {
+                            warn("%s: port %d is the root port but "
+                                 "not expected to be",
+                                 stp_get_name(stp), port_no);
+                        }
+                    }
+                }
+            }
+            if (n_warnings) {
+                exit(EXIT_FAILURE);
+            }
+        }
+        if (get_token()) {
+            err("trailing garbage on line");
+        }
+    }
+
+    return 0;
+}
diff --git a/tests/test-stp.sh b/tests/test-stp.sh
new file mode 100755 (executable)
index 0000000..8d0f538
--- /dev/null
@@ -0,0 +1,7 @@
+#! /bin/sh
+set -e
+progress=
+for d in ${stp_files}; do
+    echo "Testing $d..."
+    $SUPERVISOR ./test-stp ${srcdir}/$d
+done
index 2af2f27..4c863e5 100644 (file)
@@ -44,7 +44,7 @@ The Unix domain server socket named \fIfile\fR.
 .SH COMMANDS
 
 With the \fBdpctl\fR program, datapaths running in the kernel can be 
-created, deleted, modified, and monitored.  A single machine may 
+created, deleted, and modified.  A single machine may 
 host up to 32 datapaths (numbered 0 to 31).  In most situations, 
 a machine hosts only one datapath.
 
@@ -83,12 +83,6 @@ traffic and the network device appears silent to the rest of the system.
 Removes each \fInetdev\fR from the list of network devices datapath
 \fIdp_idx\fR monitors.
 
-.TP
-\fBmonitor nl:\fIdp_idx\fR
-Prints to the console all OpenFlow packets sent by datapath
-\fIdp_idx\fR to its controller, where \fIdp_idx\fR is the ID of an
-existing datapath.
-
 .PP
 The following commands can be apply to OpenFlow switches regardless of
 the connection method.
@@ -182,6 +176,19 @@ Deletes entries from the datapath \fIswitch\fR's tables that match
 tables are removed.  See \fBFLOW SYNTAX\fR, below, for the syntax of
 \fIflows\fR.
 
+.TP
+\fBmonitor \fIswitch\fR
+Connects to \fIswitch\fR and prints to the console all OpenFlow
+messages received.  Usually, \fIswitch\fR should specify a connection
+named on \fBsecchan\fR(8)'s \fB-m\fR or \fB--monitor\fR command line
+option, in which the messages printed will be all those sent or
+received by \fBsecchan\fR to or from the kernel datapath module.  A
+\fIswitch\fR of the form \fBnl:\fIdp_idx\fR will print all
+asynchronously generated OpenFlow messages (such as packet-in
+messages), but it will not print any messages sent to the kernel by
+\fBsecchan\fR and other processes, nor will it print replies sent by
+the kernel in response to those messages.
+
 .PP
 The following commands can be used regardless of the connection
 method.  They apply to OpenFlow switches and controllers.
index 302d4d1..1d9897d 100644 (file)
@@ -53,6 +53,7 @@
 #include "command-line.h"
 #include "compiler.h"
 #include "dpif.h"
+#include "nicira-ext.h"
 #include "ofp-print.h"
 #include "ofpbuf.h"
 #include "openflow.h"
@@ -189,7 +190,6 @@ usage(void)
            "  deldp nl:DP_ID              delete local datapath DP_ID\n"
            "  addif nl:DP_ID IFACE...     add each IFACE as a port on DP_ID\n"
            "  delif nl:DP_ID IFACE...     delete each IFACE from DP_ID\n"
-           "  monitor nl:DP_ID            print packets received\n"
 #endif
            "\nFor local datapaths and remote switches:\n"
            "  show SWITCH                 show basic information\n"
@@ -205,6 +205,7 @@ usage(void)
            "  add-flow SWITCH FLOW        add flow described by FLOW\n"
            "  add-flows SWITCH FILE       add flows from FILE\n"
            "  del-flows SWITCH FLOW       delete matching FLOWs\n"
+           "  monitor SWITCH              print packets received from SWITCH\n"
            "\nFor local datapaths, remote switches, and controllers:\n"
            "  probe VCONN                 probe whether VCONN is up\n"
            "  ping VCONN [N]              latency of N-byte echos\n"
@@ -323,22 +324,16 @@ static void do_del_port(int argc UNUSED, char *argv[])
 {
     add_del_ports(argc, argv, dpif_del_port, "remove", "from");
 }
-
-static void do_monitor(int argc UNUSED, char *argv[])
-{
-    struct dpif dp;
-    open_nl_vconn(argv[1], true, &dp);
-    for (;;) {
-        struct ofpbuf *b;
-        run(dpif_recv_openflow(&dp, &b, true), "dpif_recv_openflow");
-        ofp_print(stderr, b->data, b->size, 2);
-        ofpbuf_delete(b);
-    }
-}
 #endif /* HAVE_NETLINK */
 \f
 /* Generic commands. */
 
+static void
+open_vconn(const char *name, struct vconn **vconnp)
+{
+    run(vconn_open_block(name, OFP_VERSION, vconnp), "connecting to %s", name);
+}
+
 static void *
 alloc_stats_request(size_t body_len, uint16_t type, struct ofpbuf **bufferp)
 {
@@ -364,7 +359,7 @@ dump_transaction(const char *vconn_name, struct ofpbuf *request)
     struct ofpbuf *reply;
 
     update_openflow_length(request);
-    run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
+    open_vconn(vconn_name, &vconn);
     run(vconn_transact(vconn, request, &reply), "talking to %s", vconn_name);
     ofp_print(stdout, reply->data, reply->size, 1);
     vconn_close(vconn);
@@ -385,7 +380,7 @@ dump_stats_transaction(const char *vconn_name, struct ofpbuf *request)
     struct vconn *vconn;
     bool done = false;
 
-    run(vconn_open_block(vconn_name, &vconn), "connecting to %s", vconn_name);
+    open_vconn(vconn_name, &vconn);
     send_openflow_buffer(vconn, request);
     while (!done) {
         uint32_t recv_xid;
@@ -427,12 +422,32 @@ do_show(int argc UNUSED, char *argv[])
 static void
 do_status(int argc, char *argv[])
 {
-    struct ofpbuf *request;
-    alloc_stats_request(0, OFPST_SWITCH, &request);
+    struct nicira_header *request, *reply;
+    struct vconn *vconn;
+    struct ofpbuf *b;
+
+    request = make_openflow(sizeof *request, OFPT_VENDOR, &b);
+    request->vendor_id = htonl(NX_VENDOR_ID);
+    request->subtype = htonl(NXT_STATUS_REQUEST);
     if (argc > 2) {
-        ofpbuf_put(request, argv[2], strlen(argv[2]));
+        ofpbuf_put(b, argv[2], strlen(argv[2]));
     }
-    dump_stats_transaction(argv[1], request);
+    open_vconn(argv[1], &vconn);
+    run(vconn_transact(vconn, b, &b), "talking to %s", argv[1]);
+    vconn_close(vconn);
+
+    if (b->size < sizeof *reply) {
+        ofp_fatal(0, "short reply (%zu bytes)", b->size);
+    }
+    reply = b->data;
+    if (reply->header.type != OFPT_VENDOR
+        || reply->vendor_id != ntohl(NX_VENDOR_ID)
+        || reply->subtype != ntohl(NXT_STATUS_REPLY)) {
+        ofp_print(stderr, b->data, b->size, 2);
+        ofp_fatal(0, "bad reply");
+    }
+
+    fwrite(reply + 1, b->size, 1, stdout);
 }
 
 static void
@@ -786,7 +801,7 @@ static void do_add_flow(int argc, char *argv[])
     size_t size;
     int n_actions = MAX_ADD_ACTS;
 
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
 
     /* Parse and send. */
     size = sizeof *ofm + (sizeof ofm->actions[0] * MAX_ADD_ACTS);
@@ -819,7 +834,7 @@ static void do_add_flows(int argc, char *argv[])
         ofp_fatal(errno, "%s: open", argv[2]);
     }
 
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     while (fgets(line, sizeof line, file)) {
         struct ofpbuf *buffer;
         struct ofp_flow_mod *ofm;
@@ -866,7 +881,7 @@ static void do_del_flows(int argc, char *argv[])
     struct vconn *vconn;
     uint16_t priority;
 
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     struct ofpbuf *buffer;
     struct ofp_flow_mod *ofm;
     size_t size;
@@ -889,6 +904,29 @@ static void do_del_flows(int argc, char *argv[])
     vconn_close(vconn);
 }
 
+static void
+do_monitor(int argc UNUSED, char *argv[])
+{
+    struct vconn *vconn;
+    const char *name;
+
+    /* If the user specified, e.g., "nl:0", append ":1" to it to ensure that
+     * the connection will subscribe to listen for asynchronous messages, such
+     * as packet-in messages. */
+    if (!strncmp(argv[1], "nl:", 3) && strrchr(argv[1], ':') == &argv[1][2]) {
+        name = xasprintf("%s:1", argv[1]);
+    } else {
+        name = argv[1];
+    }
+    open_vconn(argv[1], &vconn);
+    for (;;) {
+        struct ofpbuf *b;
+        run(vconn_recv_block(vconn, &b), "vconn_recv");
+        ofp_print(stderr, b->data, b->size, 2);
+        ofpbuf_delete(b);
+    }
+}
+
 static void
 do_dump_ports(int argc, char *argv[])
 {
@@ -903,7 +941,7 @@ do_probe(int argc, char *argv[])
     struct ofpbuf *reply;
 
     make_openflow(sizeof(struct ofp_header), OFPT_ECHO_REQUEST, &request);
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
     if (reply->size != request->size) {
         ofp_fatal(0, "reply does not match request");
@@ -935,7 +973,7 @@ do_mod_port(int argc, char *argv[])
     /* Send a "Features Request" to get the information we need in order 
      * to modify the port. */
     make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &request);
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     run(vconn_transact(vconn, request, &reply), "talking to %s", argv[1]);
 
     osf = reply->data;
@@ -1003,7 +1041,7 @@ do_ping(int argc, char *argv[])
         ofp_fatal(0, "payload must be between 0 and %zu bytes", max_payload);
     }
 
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     for (i = 0; i < 10; i++) {
         struct timeval start, end;
         struct ofpbuf *request, *reply;
@@ -1059,7 +1097,7 @@ do_benchmark(int argc, char *argv[])
     printf("Sending %d packets * %u bytes (with header) = %u bytes total\n",
            count, message_size, count * message_size);
 
-    run(vconn_open_block(argv[1], &vconn), "connecting to %s", argv[1]);
+    open_vconn(argv[1], &vconn);
     gettimeofday(&start, NULL);
     for (i = 0; i < count; i++) {
         struct ofpbuf *request, *reply;