Implement 802.1D Spanning Tree Protocol.
[sliver-openvswitch.git] / switch / datapath.c
index 521150b..e91fc99 100644 (file)
 #include <arpa/inet.h>
 #include <assert.h>
 #include <errno.h>
+#include <inttypes.h>
 #include <stdlib.h>
 #include <string.h>
 #include "buffer.h"
 #include "chain.h"
+#include "csum.h"
 #include "flow.h"
 #include "netdev.h"
 #include "packets.h"
 #include "poll-loop.h"
 #include "rconn.h"
+#include "stp.h"
 #include "vconn.h"
 #include "table.h"
+#include "timeval.h"
 #include "xtoxll.h"
 
 #define THIS_MODULE VLM_datapath
 #include "vlog.h"
 
-#define BRIDGE_PORT_NO_FLOOD    0x00000001
+extern char mfr_desc;
+extern char hw_desc;
+extern char sw_desc;
+extern char serial_num;
 
 /* Capabilities supported by this implementation. */
-#define OFP_SUPPORTED_CAPABILITIES (OFPC_MULTI_PHY_TX)
+#define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
+        | OFPC_TABLE_STATS \
+        | OFPC_PORT_STATS \
+        | OFPC_MULTI_PHY_TX )
 
 /* Actions supported by this implementation. */
 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
                                 | (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;
+    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. */
-    unsigned long long int rx_count, tx_count, drop_count;
+    unsigned long long int rx_packets, tx_packets;
+    unsigned long long int rx_bytes, tx_bytes;
+    unsigned long long int tx_dropped;
 };
 
 /* The origin of a received OpenFlow message, to enable sending a reply. */
@@ -84,6 +100,8 @@ struct sender {
 struct remote {
     struct list node;
     struct rconn *rconn;
+#define TXQ_LIMIT 128           /* Max number of packets to queue for tx. */
+    int n_txq;                  /* Number of packets queued for tx on rconn. */
 
     /* Support for reliable, multi-message replies to requests.
      *
@@ -108,29 +126,36 @@ struct datapath {
 
     struct sw_chain *chain;  /* Forwarding rules. */
 
-    struct ofp_switch_config config;
+    /* Configuration set from controller. */
+    uint16_t flags;
+    uint16_t miss_send_len;
 
     /* Switch ports. */
     struct sw_port ports[OFPP_MAX];
     struct list port_list; /* List of ports, for flooding. */
 };
 
+static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
+
 static struct remote *remote_create(struct datapath *, struct rconn *);
 static void remote_run(struct datapath *, struct remote *);
 static void remote_wait(struct remote *);
 static void remote_destroy(struct remote *);
 
 void dp_output_port(struct datapath *, struct buffer *,
-                    int in_port, int out_port);
-void dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp);
+                    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 buffer *, int in_port,
                        size_t max_len, int reason);
-static void send_flow_expired(struct datapath *, struct sw_flow *);
+static void send_flow_expired(struct datapath *, struct sw_flow *,
+                              enum ofp_flow_expired_reason);
+static int update_port_status(struct sw_port *p);
 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 buffer *,
                             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 buffer *buffer, const struct sw_flow_key *key,
                         const struct ofp_action *a);
 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
@@ -149,7 +174,9 @@ static void modify_th(struct buffer *buffer, uint16_t eth_proto,
 
 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
 
-void fwd_port_input(struct datapath *, struct buffer *, int in_port);
+int run_flow_through_tables(struct datapath *, struct buffer *,
+                            struct sw_port *);
+void fwd_port_input(struct datapath *, struct buffer *, struct sw_port *);
 int fwd_control_input(struct datapath *, const struct sender *,
                       const void *, size_t);
 
@@ -163,24 +190,13 @@ static int port_no(struct datapath *dp, struct sw_port *p)
     return p - dp->ports;
 }
 
-/* Generates a unique datapath id.  It incorporates the datapath index
- * and a hardware address, if available.  If not, it generates a random
- * one.
- */
+/* Generates and returns a random datapath id. */
 static uint64_t
 gen_datapath_id(void)
 {
-    /* Choose a random datapath id. */
-    uint64_t id = 0;
-    int i;
-
-    srand(time(0));
-
-    for (i = 0; i < ETH_ADDR_LEN; i++) {
-        id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
-    }
-
-    return id;
+    uint8_t ea[ETH_ADDR_LEN];
+    eth_addr_random(ea);
+    return eth_addr_to_uint64(ea);
 }
 
 int
@@ -193,7 +209,7 @@ dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
         return ENOMEM;
     }
 
-    dp->last_timeout = time(0);
+    dp->last_timeout = time_now();
     list_init(&dp->remotes);
     dp->controller = remote_create(dp, rconn);
     dp->listen_vconn = NULL;
@@ -206,8 +222,8 @@ dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
     }
 
     list_init(&dp->port_list);
-    dp->config.flags = 0;
-    dp->config.miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
+    dp->flags = 0;
+    dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
     *dp_ = dp;
     return 0;
 }
@@ -216,13 +232,29 @@ int
 dp_add_port(struct datapath *dp, const char *name)
 {
     struct netdev *netdev;
+    struct in6_addr in6;
+    struct in_addr in4;
     struct sw_port *p;
     int error;
 
-    error = netdev_open(name, &netdev);
+    error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
+    if (error) {
+        return error;
+    }
+    error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
     if (error) {
+        VLOG_ERR("couldn't set promiscuous mode on %s device", name);
+        netdev_close(netdev);
         return error;
     }
+    if (netdev_get_in4(netdev, &in4)) {
+        VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
+    }
+    if (netdev_get_in6(netdev, &in6)) {
+        char in6_name[INET6_ADDRSTRLEN + 1];
+        inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
+        VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
+    }
 
     for (p = dp->ports; ; p++) {
         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
@@ -232,11 +264,10 @@ dp_add_port(struct datapath *dp, const char *name)
         }
     }
 
+    memset(p, '\0', sizeof *p);
+
     p->dp = dp;
     p->netdev = netdev;
-    p->tx_count = 0;
-    p->rx_count = 0;
-    p->drop_count = 0;
     list_push_back(&dp->port_list, &p->node);
 
     /* Notify the ctlpath that this port has been added */
@@ -255,7 +286,7 @@ dp_add_listen_vconn(struct datapath *dp, struct vconn *listen_vconn)
 void
 dp_run(struct datapath *dp)
 {
-    time_t now = time(0);
+    time_t now = time_now();
     struct sw_port *p, *pn;
     struct remote *r, *rn;
     struct buffer *buffer = NULL;
@@ -264,9 +295,15 @@ dp_run(struct datapath *dp)
         struct list deleted = LIST_INITIALIZER(&deleted);
         struct sw_flow *f, *n;
 
+        LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
+            if (update_port_status(p)) {
+                send_port_status(p, OFPPR_MOD);
+            }
+        }
+
         chain_timeout(dp->chain, &deleted);
         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
-            send_flow_expired(dp, f);
+            send_flow_expired(dp, f, f->reason);
             list_remove(&f->node);
             flow_free(f);
         }
@@ -289,13 +326,13 @@ dp_run(struct datapath *dp)
         }
         error = netdev_recv(p->netdev, buffer);
         if (!error) {
-            p->rx_count++;
-            fwd_port_input(dp, buffer, port_no(dp, p));
+            p->rx_packets++;
+            p->rx_bytes += buffer->size;
+            fwd_port_input(dp, buffer, p);
             buffer = NULL;
         } else if (error != EAGAIN) {
-            VLOG_ERR("Error receiving data from %s: %s",
-                     netdev_get_name(p->netdev), strerror(error));
-            del_switch_port(p);
+            VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
+                        netdev_get_name(p->netdev), strerror(error));
         }
     }
     buffer_delete(buffer);
@@ -312,11 +349,11 @@ dp_run(struct datapath *dp)
             retval = vconn_accept(dp->listen_vconn, &new_vconn);
             if (retval) {
                 if (retval != EAGAIN) {
-                    VLOG_WARN("accept failed (%s)", strerror(retval));
+                    VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
                 }
                 break;
             }
-            remote_create(dp, rconn_new_from_vconn("passive", 128, new_vconn));
+            remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
         }
     }
 }
@@ -348,15 +385,16 @@ remote_run(struct datapath *dp, struct remote *r)
                 sender.xid = oh->xid;
                 fwd_control_input(dp, &sender, buffer->data, buffer->size);
             } else {
-                VLOG_WARN("received too-short OpenFlow message");
+                VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
             }
             buffer_delete(buffer); 
         } else {
-            if (!rconn_is_full(r->rconn)) {
+            if (r->n_txq < TXQ_LIMIT) {
                 int error = r->cb_dump(dp, r->cb_aux);
                 if (error <= 0) {
                     if (error) {
-                        VLOG_WARN("dump callback error: %s", strerror(-error));
+                        VLOG_WARN_RL(&rl, "dump callback error: %s",
+                                     strerror(-error));
                     }
                     r->cb_done(r->cb_aux);
                     r->cb_dump = NULL;
@@ -399,6 +437,7 @@ remote_create(struct datapath *dp, struct rconn *rconn)
     list_push_back(&dp->remotes, &remote->node);
     remote->rconn = rconn;
     remote->cb_dump = NULL;
+    remote->n_txq = 0;
     return remote;
 }
 
@@ -471,24 +510,31 @@ dp_destroy(struct datapath *dp)
     free(dp);
 }
 
+/* Send packets out all the ports except the originating one.  If the
+ * "flood" argument is set, don't send out ports with flooding disabled.
+ */
 static int
-flood(struct datapath *dp, struct buffer *buffer, int in_port)
+output_all(struct datapath *dp, struct buffer *buffer, int in_port, int flood)
 {
     struct sw_port *p;
     int prev_port;
 
     prev_port = -1;
     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
-        if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
+        if (port_no(dp, p) == in_port) {
+            continue;
+        }
+        if (flood && p->flags & OFPPFL_NO_FLOOD) {
             continue;
         }
         if (prev_port != -1) {
-            dp_output_port(dp, buffer_clone(buffer), in_port, prev_port);
+            dp_output_port(dp, buffer_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
         buffer_delete(buffer);
 
@@ -500,64 +546,57 @@ output_packet(struct datapath *dp, struct buffer *buffer, int out_port)
 {
     if (out_port >= 0 && out_port < OFPP_MAX) { 
         struct sw_port *p = &dp->ports[out_port];
-        if (p->netdev != NULL) {
+        if (p->netdev != NULL && !(p->status & OFPPFL_PORT_DOWN)) {
             if (!netdev_send(p->netdev, buffer)) {
-                p->tx_count++;
+                p->tx_packets++;
+                p->tx_bytes += buffer->size;
             } else {
-                p->drop_count++;
+                p->tx_dropped++;
             }
             return;
         }
     }
 
     buffer_delete(buffer);
-    /* FIXME: ratelimit */
-    VLOG_DBG("can't forward to bad port %d\n", out_port);
+    VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
 }
 
 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
  */
 void
 dp_output_port(struct datapath *dp, struct buffer *buffer,
-               int in_port, int out_port)
+               int in_port, int out_port, bool ignore_no_fwd)
 {
 
     assert(buffer);
     if (out_port == OFPP_FLOOD) {
-        flood(dp, buffer, in_port); 
+        output_all(dp, buffer, in_port, 1); 
+    } else if (out_port == OFPP_ALL) {
+        output_all(dp, buffer, in_port, 0); 
     } else if (out_port == OFPP_CONTROLLER) {
         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION); 
+    } else if (out_port == OFPP_IN_PORT) {
+        output_packet(dp, buffer, in_port);
     } else if (out_port == OFPP_TABLE) {
-        struct sw_flow_key key;
-        struct sw_flow *flow;
-
-        key.wildcards = 0;
-        flow_extract(buffer, in_port, &key.flow);
-        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);
+        struct sw_port *p = in_port < OFPP_MAX ? &dp->ports[in_port] : 0;
+               if (run_flow_through_tables(dp, buffer, p)) {
+                       buffer_delete(buffer);
         }
     } else {
+        if (in_port == out_port) {
+            VLOG_DBG_RL(&rl, "can't directly forward to input port");
+            return;
+        }
         output_packet(dp, buffer, out_port);
     }
 }
 
 static void *
-alloc_openflow_buffer(struct datapath *dp, size_t openflow_len, uint8_t type,
-                      const struct sender *sender, struct buffer **bufferp)
+make_openflow_reply(size_t openflow_len, uint8_t type,
+                    const struct sender *sender, struct buffer **bufferp)
 {
-       struct buffer *buffer;
-       struct ofp_header *oh;
-
-       buffer = *bufferp = buffer_new(openflow_len);
-       oh = buffer_put_uninit(buffer, openflow_len);
-       oh->version = OFP_VERSION;
-       oh->type = type;
-       oh->length = 0;             /* Filled in by send_openflow_buffer(). */
-       oh->xid = sender ? sender->xid : 0;
-       return oh;
+    return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
+                             bufferp);
 }
 
 static int
@@ -566,17 +605,13 @@ send_openflow_buffer(struct datapath *dp, struct buffer *buffer,
 {
     struct remote *remote = sender ? sender->remote : dp->controller;
     struct rconn *rconn = remote->rconn;
-    struct ofp_header *oh;
     int retval;
 
-    oh = buffer_at_assert(buffer, 0, sizeof *oh);
-    oh->length = htons(buffer->size);
-
-    retval = rconn_send(rconn, buffer);
+    update_openflow_length(buffer);
+    retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT);
     if (retval) {
-        VLOG_WARN("send to %s failed: %s",
-                  rconn_get_name(rconn), strerror(retval));
-        buffer_delete(buffer);
+        VLOG_WARN_RL(&rl, "send to %s failed: %s",
+                     rconn_get_name(rconn), strerror(retval));
     }
     return retval;
 }
@@ -622,9 +657,10 @@ static void fill_port_desc(struct datapath *dp, struct sw_port *p,
             sizeof desc->name);
     desc->name[sizeof desc->name - 1] = '\0';
     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
-    desc->flags = htonl(p->flags);
+    desc->flags = 0;
     desc->features = htonl(netdev_get_features(p->netdev));
     desc->speed = htonl(netdev_get_speed(p->netdev));
+    desc->flags = htonl(p->flags | p->status);
 }
 
 static void
@@ -634,8 +670,8 @@ dp_send_features_reply(struct datapath *dp, const struct sender *sender)
     struct ofp_switch_features *ofr;
     struct sw_port *p;
 
-    ofr = alloc_openflow_buffer(dp, sizeof *ofr, OFPT_FEATURES_REPLY,
-                                sender, &buffer);
+    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 */
@@ -653,18 +689,76 @@ dp_send_features_reply(struct datapath *dp, const struct sender *sender)
 }
 
 void
-dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
+dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
 {
-    struct sw_port *p;
+    const struct ofp_phy_port *opp = &opm->desc;
+    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),
+                         ETH_ADDR_LEN) != 0) {
+            return;
+        }
 
-    p = &dp->ports[htons(opp->port_no)];
 
-    /* Make sure the port id hasn't changed since this was sent */
-    if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
-                     ETH_ADDR_LEN) != 0) 
-        return;
-        
-    p->flags = htonl(opp->flags);
+        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 & 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 & OFPPFL_PORT_DOWN)) {
+                p->status &= ~OFPPFL_PORT_DOWN;
+                netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
+            }
+        }
+    }
+}
+
+/* Update the port status field of the bridge port.  A non-zero return
+ * value indicates some field has changed. 
+ *
+ * NB: Callers of this function may hold the RCU read lock, so any
+ * additional checks must not sleep.
+ */
+static int
+update_port_status(struct sw_port *p)
+{
+    int retval;
+    enum netdev_flags flags;
+    uint32_t orig_status = p->status;
+
+    if (netdev_get_flags(p->netdev, &flags) < 0) {
+        VLOG_WARN_RL(&rl, "could not get netdev flags for %s", 
+                     netdev_get_name(p->netdev));
+        return 0;
+    } else {
+        if (flags & NETDEV_UP) {
+            p->status &= ~OFPPFL_PORT_DOWN;
+        } else {
+            p->status |= OFPPFL_PORT_DOWN;
+        } 
+    }
+
+    /* Not all cards support this getting link status, so don't warn on
+     * error. */
+    retval = netdev_get_link_status(p->netdev);
+    if (retval == 1) {
+        p->status &= ~OFPPFL_LINK_DOWN;
+    } else if (retval == 0) {
+        p->status |= OFPPFL_LINK_DOWN;
+    } 
+
+    return (orig_status != p->status);
 }
 
 static void
@@ -672,24 +766,31 @@ send_port_status(struct sw_port *p, uint8_t status)
 {
     struct buffer *buffer;
     struct ofp_port_status *ops;
-    ops = alloc_openflow_buffer(p->dp, sizeof *ops, OFPT_PORT_STATUS, NULL,
-                                &buffer);
-    ops->reason         = status;
+    ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
+    ops->reason = status;
+    memset(ops->pad, 0, sizeof ops->pad);
     fill_port_desc(p->dp, p, &ops->desc);
+
     send_openflow_buffer(p->dp, buffer, NULL);
 }
 
 void
-send_flow_expired(struct datapath *dp, struct sw_flow *flow)
+send_flow_expired(struct datapath *dp, struct sw_flow *flow,
+                  enum ofp_flow_expired_reason reason)
 {
     struct buffer *buffer;
     struct ofp_flow_expired *ofe;
-    ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
-                                &buffer);
+    ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
     flow_fill_match(&ofe->match, &flow->key);
-    ofe->duration   = htonl(flow->timeout - flow->max_idle - flow->created);
-    ofe->packet_count   = htonll(flow->packet_count);
-    ofe->byte_count     = htonll(flow->byte_count);
+
+    ofe->priority = htons(flow->priority);
+    ofe->reason = reason;
+    memset(ofe->pad, 0, sizeof ofe->pad);
+
+    ofe->duration     = htonl(time_now() - flow->created);
+    memset(ofe->pad2, 0, sizeof ofe->pad2);
+    ofe->packet_count = htonll(flow->packet_count);
+    ofe->byte_count   = htonll(flow->byte_count);
     send_openflow_buffer(dp, buffer, NULL);
 }
 
@@ -699,8 +800,8 @@ dp_send_error_msg(struct datapath *dp, const struct sender *sender,
 {
     struct buffer *buffer;
     struct ofp_error_msg *oem;
-    oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
-                                sender, &buffer);
+    oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR_MSG, 
+                              sender, &buffer);
     oem->type = htons(type);
     oem->code = htons(code);
     memcpy(oem->data, data, len);
@@ -708,56 +809,92 @@ dp_send_error_msg(struct datapath *dp, const struct sender *sender,
 }
 
 static void
-fill_flow_stats(struct ofp_flow_stats *ofs, struct sw_flow *flow,
+fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
                 int table_idx, time_t now)
 {
-       ofs->match.wildcards = htons(flow->key.wildcards);
-       ofs->match.in_port   = flow->key.flow.in_port;
-       memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
-       memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
-       ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
-       ofs->match.dl_type   = flow->key.flow.dl_type;
-       ofs->match.nw_src    = flow->key.flow.nw_src;
-       ofs->match.nw_dst    = flow->key.flow.nw_dst;
-       ofs->match.nw_proto  = flow->key.flow.nw_proto;
-       memset(ofs->match.pad, 0, sizeof ofs->match.pad);
-       ofs->match.tp_src    = flow->key.flow.tp_src;
-       ofs->match.tp_dst    = flow->key.flow.tp_dst;
-       ofs->duration        = htonl(now - flow->created);
-       ofs->packet_count    = htonll(flow->packet_count);
-       ofs->byte_count      = htonll(flow->byte_count);
-       ofs->priority        = htons(flow->priority);
-       ofs->table_id        = table_idx;
-    memset(ofs->pad, 0, sizeof ofs->pad);
+    struct ofp_flow_stats *ofs;
+    int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
+    ofs = buffer_put_uninit(buffer, length);
+    ofs->length          = htons(length);
+    ofs->table_id        = table_idx;
+    ofs->pad             = 0;
+    ofs->match.wildcards = htonl(flow->key.wildcards);
+    ofs->match.in_port   = flow->key.flow.in_port;
+    memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
+    memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
+    ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
+    ofs->match.dl_type   = flow->key.flow.dl_type;
+    ofs->match.nw_src    = flow->key.flow.nw_src;
+    ofs->match.nw_dst    = flow->key.flow.nw_dst;
+    ofs->match.nw_proto  = flow->key.flow.nw_proto;
+    ofs->match.pad       = 0;
+    ofs->match.tp_src    = flow->key.flow.tp_src;
+    ofs->match.tp_dst    = flow->key.flow.tp_dst;
+    ofs->duration        = htonl(now - flow->created);
+    ofs->priority        = htons(flow->priority);
+    ofs->idle_timeout    = htons(flow->idle_timeout);
+    ofs->hard_timeout    = htons(flow->hard_timeout);
+    memset(ofs->pad2, 0, sizeof ofs->pad2);
+    ofs->packet_count    = htonll(flow->packet_count);
+    ofs->byte_count      = htonll(flow->byte_count);
+    memcpy(ofs->actions, flow->actions,
+           sizeof *ofs->actions * flow->n_actions);
 }
 
 \f
-/* 'buffer' was received on 'in_port', a physical switch port between 0 and
- * OFPP_MAX.  Process it according to 'chain'. */
-void fwd_port_input(struct datapath *dp, struct buffer *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.  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 buffer *buffer,
+                            struct sw_port *p)
 {
     struct sw_flow_key key;
     struct sw_flow *flow;
 
     key.wildcards = 0;
-    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. */
+        buffer_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)) {
+               buffer_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 {
-        dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
-                          OFPR_NO_MATCH);
+        return -ESRCH;
+    }
+}
+
+/* '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 buffer *buffer,
+                    struct sw_port *p)
+{
+    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 buffer *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);
     }
@@ -766,7 +903,8 @@ do_output(struct datapath *dp, struct buffer *buffer, int in_port,
 static void
 execute_actions(struct datapath *dp, struct buffer *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
@@ -785,7 +923,8 @@ execute_actions(struct datapath *dp, struct buffer *buffer,
         struct eth_header *eh = buffer->l2;
 
         if (prev_port != -1) {
-            do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
+            do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port,
+                      ignore_no_fwd);
             prev_port = -1;
         }
 
@@ -822,39 +961,11 @@ execute_actions(struct datapath *dp, struct buffer *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
         buffer_delete(buffer);
 }
 
-/* Returns the new checksum for a packet in which the checksum field previously
- * contained 'old_csum' and in which a field that contained 'old_u16' was
- * changed to contain 'new_u16'. */
-static uint16_t
-recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
-{
-    /* Ones-complement arithmetic is endian-independent, so this code does not
-     * use htons() or ntohs().
-     *
-     * See RFC 1624 for formula and explanation. */
-    uint16_t hc_complement = ~old_csum;
-    uint16_t m_complement = ~old_u16;
-    uint16_t m_prime = new_u16;
-    uint32_t sum = hc_complement + m_complement + m_prime;
-    uint16_t hc_prime_complement = sum + (sum >> 16);
-    return ~hc_prime_complement;
-}
-
-/* Returns the new checksum for a packet in which the checksum field previously
- * contained 'old_csum' and in which a field that contained 'old_u32' was
- * changed to contain 'new_u32'. */
-static uint16_t
-recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
-{
-    return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
-                         old_u32 >> 16, new_u32 >> 16);
-}
-
 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
                       uint8_t nw_proto, const struct ofp_action *a)
 {
@@ -910,12 +1021,12 @@ modify_vlan(struct buffer *buffer,
     uint16_t new_id = a->arg.vlan_id;
     struct vlan_eth_header *veh;
 
-    if (new_id != OFP_VLAN_NONE) {
+    if (new_id != htons(OFP_VLAN_NONE)) {
         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
             /* Modify vlan id, but maintain other TCI values */
             veh = buffer->l2;
             veh->veth_tci &= ~htons(VLAN_VID);
-            veh->veth_tci |= htons(new_id);
+            veh->veth_tci |= new_id;
         } else {
             /* Insert new vlan id. */
             struct eth_header *eh = buffer->l2;
@@ -963,13 +1074,11 @@ recv_get_config_request(struct datapath *dp, const struct sender *sender,
     struct buffer *buffer;
     struct ofp_switch_config *osc;
 
-    osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
-                                sender, &buffer);
+    osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
+                              sender, &buffer);
 
-    assert(sizeof *osc == sizeof dp->config);
-       memcpy(((char *)osc) + sizeof osc->header,
-              ((char *)&dp->config) + sizeof dp->config.header,
-              sizeof dp->config - sizeof dp->config.header);
+    osc->flags = htons(dp->flags);
+    osc->miss_send_len = htons(dp->miss_send_len);
 
     return send_openflow_buffer(dp, buffer, sender);
 }
@@ -979,7 +1088,15 @@ recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
                 const void *msg)
 {
     const struct ofp_switch_config *osc = msg;
-    dp->config = *osc;
+    int flags;
+
+    flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
+    if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
+        && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
+        flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
+    }
+    dp->flags = flags;
+    dp->miss_send_len = ntohs(osc->miss_send_len);
     return 0;
 }
 
@@ -988,31 +1105,33 @@ recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
                 const void *msg)
 {
     const struct ofp_packet_out *opo = msg;
+    struct sw_flow_key key;
+    struct buffer *buffer;
+    int n_actions = ntohs(opo->n_actions);
+    int act_len = n_actions * sizeof opo->actions[0];
+
+    if (act_len > (ntohs(opo->header.length) - sizeof *opo)) {
+        VLOG_DBG_RL(&rl, "message too short for number of actions");
+        return -EINVAL;
+    }
 
     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
         /* FIXME: can we avoid copying data here? */
-        int data_len = ntohs(opo->header.length) - sizeof *opo;
-        struct buffer *buffer = buffer_new(data_len);
-        buffer_put(buffer, opo->u.data, data_len);
-        dp_output_port(dp, buffer,
-                       ntohs(opo->in_port), ntohs(opo->out_port));
+        int data_len = ntohs(opo->header.length) - sizeof *opo - act_len;
+        buffer = buffer_new(data_len);
+        buffer_put(buffer, &opo->actions[n_actions], data_len);
     } else {
-        struct sw_flow_key key;
-        struct buffer *buffer;
-        int n_acts;
-
         buffer = retrieve_buffer(ntohl(opo->buffer_id));
         if (!buffer) {
             return -ESRCH; 
         }
-
-        n_acts = (ntohs(opo->header.length) - sizeof *opo) 
-            / sizeof *opo->u.actions;
-        flow_extract(buffer, ntohs(opo->in_port), &key.flow);
-        execute_actions(dp, buffer, ntohs(opo->in_port),
-                        &key, opo->u.actions, n_acts);
     }
-    return 0;
+    flow_extract(buffer, ntohs(opo->in_port), &key.flow);
+    execute_actions(dp, buffer, ntohs(opo->in_port),
+                    &key, opo->actions, n_actions, true);
+
+   return 0;
 }
 
 static int
@@ -1021,7 +1140,7 @@ recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
 {
     const struct ofp_port_mod *opm = msg;
 
-    dp_update_port_flags(dp, &opm->desc);
+    dp_update_port_flags(dp, opm);
 
     return 0;
 }
@@ -1030,46 +1149,43 @@ static int
 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
 {
     int error = -ENOMEM;
-    int n_acts;
+    int n_actions;
     int i;
     struct sw_flow *flow;
 
 
-    /* Check number of actions. */
-    n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
-    if (n_acts > MAX_ACTIONS) {
-        error = -E2BIG;
-        goto error;
-    }
-
     /* To prevent loops, make sure there's no action to send to the
      * OFP_TABLE virtual port.
      */
-    for (i=0; i<n_acts; i++) {
+    n_actions = (ntohs(ofm->header.length) - sizeof *ofm) 
+            / sizeof *ofm->actions;
+    for (i=0; i<n_actions; i++) {
         const struct ofp_action *a = &ofm->actions[i];
 
         if (a->type == htons(OFPAT_OUTPUT)
-                    && a->arg.output.port == htons(OFPP_TABLE)) {
+                    && (a->arg.output.port == htons(OFPP_TABLE)
+                        || a->arg.output.port == htons(OFPP_NONE)
+                        || a->arg.output.port == ofm->match.in_port)) {
             /* xxx Send fancy new error message? */
             goto error;
         }
     }
 
     /* Allocate memory. */
-    flow = flow_alloc(n_acts);
+    flow = flow_alloc(n_actions);
     if (flow == NULL)
         goto error;
 
     /* Fill out flow. */
     flow_extract_match(&flow->key, &ofm->match);
-    flow->max_idle = ntohs(ofm->max_idle);
-    flow->priority = ntohs(ofm->priority);
-    flow->timeout = time(0) + flow->max_idle; /* FIXME */
-    flow->n_actions = n_acts;
-    flow->created = time(0);    /* FIXME */
+    flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
+    flow->idle_timeout = ntohs(ofm->idle_timeout);
+    flow->hard_timeout = ntohs(ofm->hard_timeout);
+    flow->used = flow->created = time_now();
+    flow->n_actions = n_actions;
     flow->byte_count = 0;
     flow->packet_count = 0;
-    memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
+    memcpy(flow->actions, ofm->actions, n_actions * sizeof *flow->actions);
 
     /* Act. */
     error = chain_insert(dp->chain, flow);
@@ -1084,7 +1200,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_acts);
+            execute_actions(dp, buffer, in_port, &key,
+                            ofm->actions, n_actions, false);
         } else {
             error = -ESRCH; 
         }
@@ -1114,185 +1231,282 @@ recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
         return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
     } else if (command == OFPFC_DELETE_STRICT) {
         struct sw_flow_key key;
+        uint16_t priority;
         flow_extract_match(&key, &ofm->match);
-        return chain_delete(dp->chain, &key, 
-                    ntohs(ofm->priority), 1) ? 0 : -ESRCH;
+        priority = key.wildcards ? ntohs(ofm->priority) : -1;
+        return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
     } else {
         return -ENODEV;
     }
 }
 
+static int desc_stats_dump(struct datapath *dp, void *state,
+                              struct buffer *buffer)
+{
+    struct ofp_desc_stats *ods = buffer_put_uninit(buffer, sizeof *ods);
+
+    strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
+    strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
+    strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
+    strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
+
+    return 0;
+}
+
 struct flow_stats_state {
-       int table_idx;
-       struct sw_table_position position;
-       struct ofp_flow_stats_request rq;
+    int table_idx;
+    struct sw_table_position position;
+    struct ofp_flow_stats_request rq;
     time_t now;
 
     struct buffer *buffer;
-       int n_flows, max_flows;
 };
 
+#define MAX_FLOW_STATS_BYTES 4096
+
 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
                            void **state)
 {
-       const struct ofp_flow_stats_request *fsr = body;
-       struct flow_stats_state *s = xmalloc(sizeof *s);
-       s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
-       memset(&s->position, 0, sizeof s->position);
-       s->rq = *fsr;
-       *state = s;
-       return 0;
+    const struct ofp_flow_stats_request *fsr = body;
+    struct flow_stats_state *s = xmalloc(sizeof *s);
+    s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
+    memset(&s->position, 0, sizeof s->position);
+    s->rq = *fsr;
+    *state = s;
+    return 0;
 }
 
 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
 {
-       struct flow_stats_state *s = private;
-    struct ofp_flow_stats *ofs = buffer_put_uninit(s->buffer, sizeof *ofs);
-       fill_flow_stats(ofs, flow, s->table_idx, s->now);
-       return ++s->n_flows >= s->max_flows;
+    struct flow_stats_state *s = private;
+    fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
+    return s->buffer->size >= MAX_FLOW_STATS_BYTES;
 }
 
 static int flow_stats_dump(struct datapath *dp, void *state,
                            struct buffer *buffer)
 {
-       struct flow_stats_state *s = state;
-       struct ofp_flow_stats *ofs;
-       struct sw_flow_key match_key;
+    struct flow_stats_state *s = state;
+    struct sw_flow_key match_key;
 
-       s->max_flows = 4096 / sizeof *ofs;
-       if (!s->max_flows)
-               return -ENOMEM;
-
-       flow_extract_match(&match_key, &s->rq.match);
+    flow_extract_match(&match_key, &s->rq.match);
     s->buffer = buffer;
-       s->n_flows = 0;
-    s->now = time(0);
-       while (s->table_idx < dp->chain->n_tables
-              && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
-       {
-               struct sw_table *table = dp->chain->tables[s->table_idx];
-
-               if (table->iterate(table, &match_key, &s->position,
+    s->now = time_now();
+    while (s->table_idx < dp->chain->n_tables
+           && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
+    {
+        struct sw_table *table = dp->chain->tables[s->table_idx];
+
+        if (table->iterate(table, &match_key, &s->position,
                            flow_stats_dump_callback, s))
-                       break;
+            break;
 
-               s->table_idx++;
-               memset(&s->position, 0, sizeof s->position);
-       }
-       return s->n_flows >= s->max_flows;
+        s->table_idx++;
+        memset(&s->position, 0, sizeof s->position);
+    }
+    return s->buffer->size >= MAX_FLOW_STATS_BYTES;
 }
 
 static void flow_stats_done(void *state)
 {
-       free(state);
+    free(state);
+}
+
+struct aggregate_stats_state {
+    struct ofp_aggregate_stats_request rq;
+};
+
+static int aggregate_stats_init(struct datapath *dp,
+                                const void *body, int body_len,
+                                void **state)
+{
+    const struct ofp_aggregate_stats_request *rq = body;
+    struct aggregate_stats_state *s = xmalloc(sizeof *s);
+    s->rq = *rq;
+    *state = s;
+    return 0;
+}
+
+static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
+{
+    struct ofp_aggregate_stats_reply *rpy = private;
+    rpy->packet_count += flow->packet_count;
+    rpy->byte_count += flow->byte_count;
+    rpy->flow_count++;
+    return 0;
+}
+
+static int aggregate_stats_dump(struct datapath *dp, void *state,
+                                struct buffer *buffer)
+{
+    struct aggregate_stats_state *s = state;
+    struct ofp_aggregate_stats_request *rq = &s->rq;
+    struct ofp_aggregate_stats_reply *rpy;
+    struct sw_table_position position;
+    struct sw_flow_key match_key;
+    int table_idx;
+
+    rpy = buffer_put_uninit(buffer, sizeof *rpy);
+    memset(rpy, 0, sizeof *rpy);
+
+    flow_extract_match(&match_key, &rq->match);
+    table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
+    memset(&position, 0, sizeof position);
+    while (table_idx < dp->chain->n_tables
+           && (rq->table_id == 0xff || rq->table_id == table_idx))
+    {
+        struct sw_table *table = dp->chain->tables[table_idx];
+        int error;
+
+        error = table->iterate(table, &match_key, &position,
+                               aggregate_stats_dump_callback, rpy);
+        if (error)
+            return error;
+
+        table_idx++;
+        memset(&position, 0, sizeof position);
+    }
+
+    rpy->packet_count = htonll(rpy->packet_count);
+    rpy->byte_count = htonll(rpy->byte_count);
+    rpy->flow_count = htonl(rpy->flow_count);
+    return 0;
+}
+
+static void aggregate_stats_done(void *state) 
+{
+    free(state);
 }
 
 static int table_stats_dump(struct datapath *dp, void *state,
                             struct buffer *buffer)
 {
-       int i;
-       for (i = 0; i < dp->chain->n_tables; i++) {
+    int i;
+    for (i = 0; i < dp->chain->n_tables; i++) {
         struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
-               struct sw_table_stats stats;
-               dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
-               strncpy(ots->name, stats.name, sizeof ots->name);
-               ots->table_id = i;
-               memset(ots->pad, 0, sizeof ots->pad);
-               ots->max_entries = htonl(stats.max_flows);
-               ots->active_count = htonl(stats.n_flows);
-               ots->matched_count = htonll(0); /* FIXME */
-       }
-       return 0;
+        struct sw_table_stats stats;
+        dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
+        strncpy(ots->name, stats.name, sizeof ots->name);
+        ots->table_id = i;
+        memset(ots->pad, 0, sizeof ots->pad);
+        ots->max_entries = htonl(stats.max_flows);
+        ots->active_count = htonl(stats.n_flows);
+        ots->matched_count = htonll(stats.n_matched);
+    }
+    return 0;
 }
 
 struct port_stats_state {
-       int port;
+    int port;
 };
 
 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
-                          void **state)
+               void **state)
 {
-       struct port_stats_state *s = xmalloc(sizeof *s);
-       s->port = 0;
-       *state = s;
-       return 0;
+    struct port_stats_state *s = xmalloc(sizeof *s);
+    s->port = 0;
+    *state = s;
+    return 0;
 }
 
 static int port_stats_dump(struct datapath *dp, void *state,
                            struct buffer *buffer)
 {
-       struct port_stats_state *s = state;
-       int i;
+    struct port_stats_state *s = state;
+    int i;
 
-       for (i = s->port; i < OFPP_MAX; i++) {
-               struct sw_port *p = &dp->ports[i];
+    for (i = s->port; i < OFPP_MAX; i++) {
+        struct sw_port *p = &dp->ports[i];
         struct ofp_port_stats *ops;
-               if (!p->netdev) {
-                       continue;
+        if (!p->netdev) {
+            continue;
         }
         ops = buffer_put_uninit(buffer, sizeof *ops);
-               ops->port_no = htons(port_no(dp, p));
-               memset(ops->pad, 0, sizeof ops->pad);
-               ops->rx_count = htonll(p->rx_count);
-               ops->tx_count = htonll(p->tx_count);
-               ops->drop_count = htonll(p->drop_count);
-               ops++;
-       }
-       s->port = i;
-       return 0;
+        ops->port_no = htons(port_no(dp, p));
+        memset(ops->pad, 0, sizeof ops->pad);
+        ops->rx_packets   = htonll(p->rx_packets);
+        ops->tx_packets   = htonll(p->tx_packets);
+        ops->rx_bytes     = htonll(p->rx_bytes);
+        ops->tx_bytes     = htonll(p->tx_bytes);
+        ops->rx_dropped   = htonll(-1);
+        ops->tx_dropped   = htonll(p->tx_dropped);
+        ops->rx_errors    = htonll(-1);
+        ops->tx_errors    = htonll(-1);
+        ops->rx_frame_err = htonll(-1);
+        ops->rx_over_err  = htonll(-1);
+        ops->rx_crc_err   = htonll(-1);
+        ops->collisions   = htonll(-1);
+        ops++;
+    }
+    s->port = i;
+    return 0;
 }
 
 static void port_stats_done(void *state)
 {
-       free(state);
+    free(state);
 }
 
 struct stats_type {
-       /* Minimum and maximum acceptable number of bytes in body member of
-        * struct ofp_stats_request. */
-       size_t min_body, max_body;
-
-       /* Prepares to dump some kind of statistics on 'dp'.  'body' and
-        * 'body_len' are the 'body' member of the struct ofp_stats_request.
-        * Returns zero if successful, otherwise a negative error code.
-        * May initialize '*state' to state information.  May be null if no
-        * initialization is required.*/
-       int (*init)(struct datapath *dp, const void *body, int body_len,
-                   void **state);
-
-       /* Appends statistics for 'dp' to 'buffer', which initially contains a
+    /* Minimum and maximum acceptable number of bytes in body member of
+     * struct ofp_stats_request. */
+    size_t min_body, max_body;
+
+    /* Prepares to dump some kind of statistics on 'dp'.  'body' and
+     * 'body_len' are the 'body' member of the struct ofp_stats_request.
+     * Returns zero if successful, otherwise a negative error code.
+     * May initialize '*state' to state information.  May be null if no
+     * initialization is required.*/
+    int (*init)(struct datapath *dp, const void *body, int body_len,
+            void **state);
+
+    /* Appends statistics for 'dp' to 'buffer', which initially contains a
      * struct ofp_stats_reply.  On success, it should return 1 if it should be
      * called again later with another buffer, 0 if it is done, or a negative
      * errno value on failure. */
-       int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
+    int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
 
-       /* Cleans any state created by the init or dump functions.  May be null
-        * if no cleanup is required. */
-       void (*done)(void *state);
+    /* Cleans any state created by the init or dump functions.  May be null
+     * if no cleanup is required. */
+    void (*done)(void *state);
 };
 
 static const struct stats_type stats[] = {
-       [OFPST_FLOW] = {
-               sizeof(struct ofp_flow_stats_request),
-               sizeof(struct ofp_flow_stats_request),
-               flow_stats_init,
-               flow_stats_dump,
-               flow_stats_done
-       },
-       [OFPST_TABLE] = {
-               0,
-               0,
-               NULL,
-               table_stats_dump,
-               NULL
-       },
-       [OFPST_PORT] = {
-               0,
-               0,
-               port_stats_init,
-               port_stats_dump,
-               port_stats_done
-       },
+    [OFPST_DESC] = {
+        0,
+        0,
+        NULL,
+        desc_stats_dump,
+        NULL
+    },
+    [OFPST_FLOW] = {
+        sizeof(struct ofp_flow_stats_request),
+        sizeof(struct ofp_flow_stats_request),
+        flow_stats_init,
+        flow_stats_dump,
+        flow_stats_done
+    },
+    [OFPST_AGGREGATE] = {
+        sizeof(struct ofp_aggregate_stats_request),
+        sizeof(struct ofp_aggregate_stats_request),
+        aggregate_stats_init,
+        aggregate_stats_dump,
+        aggregate_stats_done
+    },
+    [OFPST_TABLE] = {
+        0,
+        0,
+        NULL,
+        table_stats_dump,
+        NULL
+    },
+    [OFPST_PORT] = {
+        0,
+        0,
+        port_stats_init,
+        port_stats_dump,
+        port_stats_done
+    },
 };
 
 struct stats_dump_cb {
@@ -1307,36 +1521,36 @@ static int
 stats_dump(struct datapath *dp, void *cb_)
 {
     struct stats_dump_cb *cb = cb_;
-       struct ofp_stats_reply *osr;
+    struct ofp_stats_reply *osr;
     struct buffer *buffer;
-       int err;
+    int err;
 
     if (cb->done) {
         return 0;
-       }
+    }
 
-       osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
-                                &buffer);
-       osr->type = htons(cb->s - stats);
-       osr->flags = 0;
+    osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
+                              &buffer);
+    osr->type = htons(cb->s - stats);
+    osr->flags = 0;
 
-       err = cb->s->dump(dp, cb->state, buffer);
-       if (err >= 0) {
+    err = cb->s->dump(dp, cb->state, buffer);
+    if (err >= 0) {
         int err2;
-               if (!err) {
-                       cb->done = true;
+        if (!err) {
+            cb->done = true;
         } else {
             /* Buffer might have been reallocated, so find our data again. */
             osr = buffer_at_assert(buffer, 0, sizeof *osr);
-                       osr->flags = ntohs(OFPSF_REPLY_MORE);
+            osr->flags = ntohs(OFPSF_REPLY_MORE);
         }
         err2 = send_openflow_buffer(dp, buffer, &cb->sender);
         if (err2) {
             err = err2;
         }
-       }
+    }
 
-       return err;
+    return err;
 }
 
 static void
@@ -1344,11 +1558,11 @@ stats_done(void *cb_)
 {
     struct stats_dump_cb *cb = cb_;
     if (cb) {
-               if (cb->s->done) {
-                       cb->s->done(cb->state);
+        if (cb->s->done) {
+            cb->s->done(cb->state);
         }
         free(cb);
-       }
+    }
 }
 
 static int
@@ -1363,7 +1577,7 @@ recv_stats_request(struct datapath *dp, const struct sender *sender,
 
     type = ntohs(rq->type);
     if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
-        VLOG_WARN("received stats request of unknown type %d", type);
+        VLOG_WARN_RL(&rl, "received stats request of unknown type %d", type);
         return -EINVAL;
     }
 
@@ -1376,8 +1590,8 @@ recv_stats_request(struct datapath *dp, const struct sender *sender,
     
     body_len = rq_len - offsetof(struct ofp_stats_request, body);
     if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
-        VLOG_WARN("stats request type %d with bad body length %d",
-                  type, body_len);
+        VLOG_WARN_RL(&rl, "stats request type %d with bad body length %d",
+                     type, body_len);
         err = -EINVAL;
         goto error;
     }
@@ -1385,8 +1599,9 @@ recv_stats_request(struct datapath *dp, const struct sender *sender,
     if (cb->s->init) {
         err = cb->s->init(dp, rq->body, body_len, &cb->state);
         if (err) {
-            VLOG_WARN("failed initialization of stats request type %d: %s",
-                      type, strerror(-err));
+            VLOG_WARN_RL(&rl,
+                         "failed initialization of stats request type %d: %s",
+                         type, strerror(-err));
             goto error;
         }
     }
@@ -1400,6 +1615,20 @@ error:
     return err;
 }
 
+static int
+recv_echo_request(struct datapath *dp, const struct sender *sender,
+                  const void *oh)
+{
+    return send_openflow_buffer(dp, make_echo_reply(oh), sender);
+}
+
+static int
+recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
+                  const void *oh UNUSED)
+{
+    return 0;
+}
+
 /* 'msg', which is 'length' bytes long, was received from the control path.
  * Apply it to 'chain'. */
 int
@@ -1436,18 +1665,26 @@ fwd_control_input(struct datapath *dp, const struct sender *sender,
             sizeof (struct ofp_port_mod),
             recv_port_mod,
         },
-               [OFPT_STATS_REQUEST] = {
-                       sizeof (struct ofp_stats_request),
-                       recv_stats_request,
-               },
+        [OFPT_STATS_REQUEST] = {
+            sizeof (struct ofp_stats_request),
+            recv_stats_request,
+        },
+        [OFPT_ECHO_REQUEST] = {
+            sizeof (struct ofp_header),
+            recv_echo_request,
+        },
+        [OFPT_ECHO_REPLY] = {
+            sizeof (struct ofp_header),
+            recv_echo_reply,
+        },
     };
 
     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)
+    assert(oh->version == OFP_VERSION);
+    if (oh->type >= ARRAY_SIZE(packets) || ntohs(oh->length) > length)
         return -EINVAL;
 
     pkt = &packets[oh->type];
@@ -1482,7 +1719,7 @@ uint32_t save_buffer(struct buffer *buffer)
     if (p->buffer) {
         /* Don't buffer packet if existing entry is less than
          * OVERWRITE_SECS old. */
-        if (time(0) < p->timeout) { /* FIXME */
+        if (time_now() < p->timeout) { /* FIXME */
             return -1;
         } else {
             buffer_delete(p->buffer); 
@@ -1493,7 +1730,7 @@ uint32_t save_buffer(struct buffer *buffer)
     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
         p->cookie = 0;
     p->buffer = buffer_clone(buffer);      /* FIXME */
-    p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
+    p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
 
     return id;