Return error message when a flow can't be added due to full tables.
[sliver-openvswitch.git] / switch / datapath.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "datapath.h"
35 #include <arpa/inet.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "chain.h"
42 #include "csum.h"
43 #include "flow.h"
44 #include "list.h"
45 #include "netdev.h"
46 #include "ofpbuf.h"
47 #include "openflow.h"
48 #include "packets.h"
49 #include "poll-loop.h"
50 #include "rconn.h"
51 #include "stp.h"
52 #include "switch-flow.h"
53 #include "table.h"
54 #include "timeval.h"
55 #include "vconn.h"
56 #include "xtoxll.h"
57 #include "dp_act.h"
58
59 #define THIS_MODULE VLM_datapath
60 #include "vlog.h"
61
62 extern char mfr_desc;
63 extern char hw_desc;
64 extern char sw_desc;
65 extern char serial_num;
66
67 /* Capabilities supported by this implementation. */
68 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
69         | OFPC_TABLE_STATS \
70         | OFPC_PORT_STATS \
71         | OFPC_MULTI_PHY_TX )
72
73 /* Actions supported by this implementation. */
74 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
75                                 | (1 << OFPAT_SET_VLAN_VID) \
76                                 | (1 << OFPAT_SET_VLAN_PCP) \
77                                 | (1 << OFPAT_STRIP_VLAN)   \
78                                 | (1 << OFPAT_SET_DL_SRC)   \
79                                 | (1 << OFPAT_SET_DL_DST)   \
80                                 | (1 << OFPAT_SET_NW_SRC)   \
81                                 | (1 << OFPAT_SET_NW_DST)   \
82                                 | (1 << OFPAT_SET_TP_SRC)   \
83                                 | (1 << OFPAT_SET_TP_DST) )
84
85 struct sw_port {
86     uint32_t config;            /* Some subset of OFPPC_* flags. */
87     uint32_t state;             /* Some subset of OFPPS_* flags. */
88     struct datapath *dp;
89     struct netdev *netdev;
90     struct list node; /* Element in datapath.ports. */
91     unsigned long long int rx_packets, tx_packets;
92     unsigned long long int rx_bytes, tx_bytes;
93     unsigned long long int tx_dropped;
94 };
95
96 /* The origin of a received OpenFlow message, to enable sending a reply. */
97 struct sender {
98     struct remote *remote;      /* The device that sent the message. */
99     uint32_t xid;               /* The OpenFlow transaction ID. */
100 };
101
102 /* A connection to a controller or a management device. */
103 struct remote {
104     struct list node;
105     struct rconn *rconn;
106 #define TXQ_LIMIT 128           /* Max number of packets to queue for tx. */
107     int n_txq;                  /* Number of packets queued for tx on rconn. */
108
109     /* Support for reliable, multi-message replies to requests.
110      *
111      * If an incoming request needs to have a reliable reply that might
112      * require multiple messages, it can use remote_start_dump() to set up
113      * a callback that will be called as buffer space for replies. */
114     int (*cb_dump)(struct datapath *, void *aux);
115     void (*cb_done)(void *aux);
116     void *cb_aux;
117 };
118
119 struct datapath {
120     /* Remote connections. */
121     struct remote *controller;  /* Connection to controller. */
122     struct list remotes;        /* All connections (including controller). */
123     struct pvconn *listen_pvconn;
124
125     time_t last_timeout;
126
127     /* Unique identifier for this datapath */
128     uint64_t  id;
129
130     struct sw_chain *chain;  /* Forwarding rules. */
131
132     /* Configuration set from controller. */
133     uint16_t flags;
134     uint16_t miss_send_len;
135
136     /* Switch ports. */
137     struct sw_port ports[OFPP_MAX];
138     struct list port_list; /* List of ports, for flooding. */
139 };
140
141 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
142
143 static struct remote *remote_create(struct datapath *, struct rconn *);
144 static void remote_run(struct datapath *, struct remote *);
145 static void remote_wait(struct remote *);
146 static void remote_destroy(struct remote *);
147
148 void dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm);
149 static void send_flow_expired(struct datapath *, struct sw_flow *,
150                               enum ofp_flow_expired_reason);
151 static int update_port_status(struct sw_port *p);
152 static void send_port_status(struct sw_port *p, uint8_t status);
153 static void del_switch_port(struct sw_port *p);
154
155 /* Buffers are identified to userspace by a 31-bit opaque ID.  We divide the ID
156  * into a buffer number (low bits) and a cookie (high bits).  The buffer number
157  * is an index into an array of buffers.  The cookie distinguishes between
158  * different packets that have occupied a single buffer.  Thus, the more
159  * buffers we have, the lower-quality the cookie... */
160 #define PKT_BUFFER_BITS 8
161 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
162 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
163
164 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
165
166 int run_flow_through_tables(struct datapath *, struct ofpbuf *,
167                             struct sw_port *);
168 void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
169 int fwd_control_input(struct datapath *, const struct sender *,
170                       const void *, size_t);
171
172 uint32_t save_buffer(struct ofpbuf *);
173 static struct ofpbuf *retrieve_buffer(uint32_t id);
174 static void discard_buffer(uint32_t id);
175
176 static int port_no(struct datapath *dp, struct sw_port *p) 
177 {
178     assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
179     return p - dp->ports;
180 }
181
182 /* Generates and returns a random datapath id. */
183 static uint64_t
184 gen_datapath_id(void)
185 {
186     uint8_t ea[ETH_ADDR_LEN];
187     eth_addr_random(ea);
188     return eth_addr_to_uint64(ea);
189 }
190
191 int
192 dp_new(struct datapath **dp_, uint64_t dpid, struct rconn *rconn)
193 {
194     struct datapath *dp;
195
196     dp = calloc(1, sizeof *dp);
197     if (!dp) {
198         return ENOMEM;
199     }
200
201     dp->last_timeout = time_now();
202     list_init(&dp->remotes);
203     dp->controller = remote_create(dp, rconn);
204     dp->listen_pvconn = NULL;
205     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
206     dp->chain = chain_create();
207     if (!dp->chain) {
208         VLOG_ERR("could not create chain");
209         free(dp);
210         return ENOMEM;
211     }
212
213     list_init(&dp->port_list);
214     dp->flags = 0;
215     dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
216     *dp_ = dp;
217     return 0;
218 }
219
220 int
221 dp_add_port(struct datapath *dp, const char *name)
222 {
223     struct netdev *netdev;
224     struct in6_addr in6;
225     struct in_addr in4;
226     struct sw_port *p;
227     int error;
228
229     error = netdev_open(name, NETDEV_ETH_TYPE_ANY, &netdev);
230     if (error) {
231         return error;
232     }
233     error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
234     if (error) {
235         VLOG_ERR("couldn't set promiscuous mode on %s device", name);
236         netdev_close(netdev);
237         return error;
238     }
239     if (netdev_get_in4(netdev, &in4)) {
240         VLOG_ERR("%s device has assigned IP address %s", name, inet_ntoa(in4));
241     }
242     if (netdev_get_in6(netdev, &in6)) {
243         char in6_name[INET6_ADDRSTRLEN + 1];
244         inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
245         VLOG_ERR("%s device has assigned IPv6 address %s", name, in6_name);
246     }
247
248     for (p = dp->ports; ; p++) {
249         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
250             return EXFULL;
251         } else if (!p->netdev) {
252             break;
253         }
254     }
255
256     memset(p, '\0', sizeof *p);
257
258     p->dp = dp;
259     p->netdev = netdev;
260     list_push_back(&dp->port_list, &p->node);
261
262     /* Notify the ctlpath that this port has been added */
263     send_port_status(p, OFPPR_ADD);
264
265     return 0;
266 }
267
268 void
269 dp_add_listen_pvconn(struct datapath *dp, struct pvconn *listen_pvconn)
270 {
271     assert(!dp->listen_pvconn);
272     dp->listen_pvconn = listen_pvconn;
273 }
274
275 void
276 dp_run(struct datapath *dp)
277 {
278     time_t now = time_now();
279     struct sw_port *p, *pn;
280     struct remote *r, *rn;
281     struct ofpbuf *buffer = NULL;
282
283     if (now != dp->last_timeout) {
284         struct list deleted = LIST_INITIALIZER(&deleted);
285         struct sw_flow *f, *n;
286
287         LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
288             if (update_port_status(p)) {
289                 send_port_status(p, OFPPR_MODIFY);
290             }
291         }
292
293         chain_timeout(dp->chain, &deleted);
294         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
295             send_flow_expired(dp, f, f->reason);
296             list_remove(&f->node);
297             flow_free(f);
298         }
299         dp->last_timeout = now;
300     }
301     poll_timer_wait(1000);
302     
303     LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
304         int error;
305
306         if (!buffer) {
307             /* Allocate buffer with some headroom to add headers in forwarding
308              * to the controller or adding a vlan tag, plus an extra 2 bytes to
309              * allow IP headers to be aligned on a 4-byte boundary.  */
310             const int headroom = 128 + 2;
311             const int hard_header = VLAN_ETH_HEADER_LEN;
312             const int mtu = netdev_get_mtu(p->netdev);
313             buffer = ofpbuf_new(headroom + hard_header + mtu);
314             buffer->data = (char*)buffer->data + headroom;
315         }
316         error = netdev_recv(p->netdev, buffer);
317         if (!error) {
318             p->rx_packets++;
319             p->rx_bytes += buffer->size;
320             fwd_port_input(dp, buffer, p);
321             buffer = NULL;
322         } else if (error != EAGAIN) {
323             VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
324                         netdev_get_name(p->netdev), strerror(error));
325         }
326     }
327     ofpbuf_delete(buffer);
328
329     /* Talk to remotes. */
330     LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
331         remote_run(dp, r);
332     }
333     if (dp->listen_pvconn) {
334         for (;;) {
335             struct vconn *new_vconn;
336             int retval;
337
338             retval = pvconn_accept(dp->listen_pvconn, OFP_VERSION, &new_vconn);
339             if (retval) {
340                 if (retval != EAGAIN) {
341                     VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
342                 }
343                 break;
344             }
345             remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
346         }
347     }
348 }
349
350 static void
351 remote_run(struct datapath *dp, struct remote *r)
352 {
353     int i;
354
355     rconn_run(r->rconn);
356
357     /* Do some remote processing, but cap it at a reasonable amount so that
358      * other processing doesn't starve. */
359     for (i = 0; i < 50; i++) {
360         if (!r->cb_dump) {
361             struct ofpbuf *buffer;
362             struct ofp_header *oh;
363
364             buffer = rconn_recv(r->rconn);
365             if (!buffer) {
366                 break;
367             }
368
369             if (buffer->size >= sizeof *oh) {
370                 struct sender sender;
371
372                 oh = buffer->data;
373                 sender.remote = r;
374                 sender.xid = oh->xid;
375                 fwd_control_input(dp, &sender, buffer->data, buffer->size);
376             } else {
377                 VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
378             }
379             ofpbuf_delete(buffer); 
380         } else {
381             if (r->n_txq < TXQ_LIMIT) {
382                 int error = r->cb_dump(dp, r->cb_aux);
383                 if (error <= 0) {
384                     if (error) {
385                         VLOG_WARN_RL(&rl, "dump callback error: %s",
386                                      strerror(-error));
387                     }
388                     r->cb_done(r->cb_aux);
389                     r->cb_dump = NULL;
390                 }
391             } else {
392                 break;
393             }
394         }
395     }
396
397     if (!rconn_is_alive(r->rconn)) {
398         remote_destroy(r);
399     }
400 }
401
402 static void
403 remote_wait(struct remote *r) 
404 {
405     rconn_run_wait(r->rconn);
406     rconn_recv_wait(r->rconn);
407 }
408
409 static void
410 remote_destroy(struct remote *r)
411 {
412     if (r) {
413         if (r->cb_dump && r->cb_done) {
414             r->cb_done(r->cb_aux);
415         }
416         list_remove(&r->node);
417         rconn_destroy(r->rconn);
418         free(r);
419     }
420 }
421
422 static struct remote *
423 remote_create(struct datapath *dp, struct rconn *rconn) 
424 {
425     struct remote *remote = xmalloc(sizeof *remote);
426     list_push_back(&dp->remotes, &remote->node);
427     remote->rconn = rconn;
428     remote->cb_dump = NULL;
429     remote->n_txq = 0;
430     return remote;
431 }
432
433 /* Starts a callback-based, reliable, possibly multi-message reply to a
434  * request made by 'remote'.
435  *
436  * 'dump' designates a function that will be called when the 'remote' send
437  * queue has an empty slot.  It should compose a message and send it on
438  * 'remote'.  On success, it should return 1 if it should be called again when
439  * another send queue slot opens up, 0 if its transmissions are complete, or a
440  * negative errno value on failure.
441  *
442  * 'done' designates a function to clean up any resources allocated for the
443  * dump.  It must handle being called before the dump is complete (which will
444  * happen if 'remote' is closed unexpectedly).
445  *
446  * 'aux' is passed to 'dump' and 'done'. */
447 static void
448 remote_start_dump(struct remote *remote,
449                   int (*dump)(struct datapath *, void *),
450                   void (*done)(void *),
451                   void *aux) 
452 {
453     assert(!remote->cb_dump);
454     remote->cb_dump = dump;
455     remote->cb_done = done;
456     remote->cb_aux = aux;
457 }
458
459 void
460 dp_wait(struct datapath *dp) 
461 {
462     struct sw_port *p;
463     struct remote *r;
464
465     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
466         netdev_recv_wait(p->netdev);
467     }
468     LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
469         remote_wait(r);
470     }
471     if (dp->listen_pvconn) {
472         pvconn_wait(dp->listen_pvconn);
473     }
474 }
475
476 /* Delete 'p' from switch. */
477 static void
478 del_switch_port(struct sw_port *p)
479 {
480     send_port_status(p, OFPPR_DELETE);
481     netdev_close(p->netdev);
482     p->netdev = NULL;
483     list_remove(&p->node);
484 }
485
486 void
487 dp_destroy(struct datapath *dp)
488 {
489     struct sw_port *p, *n;
490
491     if (!dp) {
492         return;
493     }
494
495     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
496         del_switch_port(p); 
497     }
498     chain_destroy(dp->chain);
499     free(dp);
500 }
501
502 /* Send packets out all the ports except the originating one.  If the
503  * "flood" argument is set, don't send out ports with flooding disabled.
504  */
505 static int
506 output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
507 {
508     struct sw_port *p;
509     int prev_port;
510
511     prev_port = -1;
512     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
513         if (port_no(dp, p) == in_port) {
514             continue;
515         }
516         if (flood && p->config & OFPPC_NO_FLOOD) {
517             continue;
518         }
519         if (prev_port != -1) {
520             dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
521                            false);
522         }
523         prev_port = port_no(dp, p);
524     }
525     if (prev_port != -1)
526         dp_output_port(dp, buffer, in_port, prev_port, false);
527     else
528         ofpbuf_delete(buffer);
529
530     return 0;
531 }
532
533 void
534 output_packet(struct datapath *dp, struct ofpbuf *buffer, int out_port) 
535 {
536     if (out_port >= 0 && out_port < OFPP_MAX) { 
537         struct sw_port *p = &dp->ports[out_port];
538         if (p->netdev != NULL && !(p->config & OFPPC_PORT_DOWN)) {
539             if (!netdev_send(p->netdev, buffer)) {
540                 p->tx_packets++;
541                 p->tx_bytes += buffer->size;
542             } else {
543                 p->tx_dropped++;
544             }
545             return;
546         }
547     }
548
549     ofpbuf_delete(buffer);
550     VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
551 }
552
553 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
554  */
555 void
556 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
557                int in_port, int out_port, bool ignore_no_fwd)
558 {
559
560     assert(buffer);
561     if (out_port == OFPP_FLOOD) {
562         output_all(dp, buffer, in_port, 1); 
563     } else if (out_port == OFPP_ALL) {
564         output_all(dp, buffer, in_port, 0); 
565     } else if (out_port == OFPP_CONTROLLER) {
566         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION); 
567     } else if (out_port == OFPP_IN_PORT) {
568         output_packet(dp, buffer, in_port);
569     } else if (out_port == OFPP_TABLE) {
570         struct sw_port *p = in_port < OFPP_MAX ? &dp->ports[in_port] : 0;
571                 if (run_flow_through_tables(dp, buffer, p)) {
572                         ofpbuf_delete(buffer);
573         }
574     } else {
575         if (in_port == out_port) {
576             VLOG_DBG_RL(&rl, "can't directly forward to input port");
577             return;
578         }
579         output_packet(dp, buffer, out_port);
580     }
581 }
582
583 static void *
584 make_openflow_reply(size_t openflow_len, uint8_t type,
585                     const struct sender *sender, struct ofpbuf **bufferp)
586 {
587     return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
588                              bufferp);
589 }
590
591 static int
592 send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer,
593                      const struct sender *sender)
594 {
595     struct remote *remote = sender ? sender->remote : dp->controller;
596     struct rconn *rconn = remote->rconn;
597     int retval;
598
599     update_openflow_length(buffer);
600     retval = rconn_send_with_limit(rconn, buffer, &remote->n_txq, TXQ_LIMIT);
601     if (retval) {
602         VLOG_WARN_RL(&rl, "send to %s failed: %s",
603                      rconn_get_name(rconn), strerror(retval));
604     }
605     return retval;
606 }
607
608 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If the
609  * packet can be saved in a buffer, then only the first max_len bytes of
610  * 'buffer' are sent; otherwise, all of 'buffer' is sent.  'reason' indicates
611  * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
612  * the caller wants to be sent; a value of 0 indicates the entire packet should
613  * be sent. */
614 void
615 dp_output_control(struct datapath *dp, struct ofpbuf *buffer, int in_port,
616                   size_t max_len, int reason)
617 {
618     struct ofp_packet_in *opi;
619     size_t total_len;
620     uint32_t buffer_id;
621
622     buffer_id = save_buffer(buffer);
623     total_len = buffer->size;
624     if (buffer_id != UINT32_MAX && max_len && buffer->size > max_len) {
625         buffer->size = max_len;
626     }
627
628     opi = ofpbuf_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
629     opi->header.version = OFP_VERSION;
630     opi->header.type    = OFPT_PACKET_IN;
631     opi->header.length  = htons(buffer->size);
632     opi->header.xid     = htonl(0);
633     opi->buffer_id      = htonl(buffer_id);
634     opi->total_len      = htons(total_len);
635     opi->in_port        = htons(in_port);
636     opi->reason         = reason;
637     opi->pad            = 0;
638     send_openflow_buffer(dp, buffer, NULL);
639 }
640
641 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
642                            struct ofp_phy_port *desc)
643 {
644     desc->port_no = htons(port_no(dp, p));
645     strncpy((char *) desc->name, netdev_get_name(p->netdev),
646             sizeof desc->name);
647     desc->name[sizeof desc->name - 1] = '\0';
648     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
649     desc->config = htonl(p->config);
650     desc->state = htonl(p->state);
651     desc->curr = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_CURRENT));
652     desc->supported = htonl(netdev_get_features(p->netdev, 
653                 NETDEV_FEAT_SUPPORTED));
654     desc->advertised = htonl(netdev_get_features(p->netdev, 
655                 NETDEV_FEAT_ADVERTISED));
656     desc->peer = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_PEER));
657 }
658
659 static void
660 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
661 {
662     struct ofpbuf *buffer;
663     struct ofp_switch_features *ofr;
664     struct sw_port *p;
665
666     ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
667                                sender, &buffer);
668     ofr->datapath_id  = htonll(dp->id); 
669     ofr->n_tables     = dp->chain->n_tables;
670     ofr->n_buffers    = htonl(N_PKT_BUFFERS);
671     ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
672     ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
673     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
674         struct ofp_phy_port *opp = ofpbuf_put_uninit(buffer, sizeof *opp);
675         memset(opp, 0, sizeof *opp);
676         fill_port_desc(dp, p, opp);
677     }
678     send_openflow_buffer(dp, buffer, sender);
679 }
680
681 void
682 dp_update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
683 {
684     int port_no = ntohs(opm->port_no);
685     if (port_no < OFPP_MAX) {
686         struct sw_port *p = &dp->ports[port_no];
687
688         /* Make sure the port id hasn't changed since this was sent */
689         if (!p || memcmp(opm->hw_addr, netdev_get_etheraddr(p->netdev),
690                          ETH_ADDR_LEN) != 0) {
691             return;
692         }
693
694
695         if (opm->mask) {
696             uint32_t config_mask = ntohl(opm->mask);
697             p->config &= ~config_mask;
698             p->config |= ntohl(opm->config) & config_mask;
699         }
700
701         if (opm->mask & htonl(OFPPC_PORT_DOWN)) {
702             if ((opm->config & htonl(OFPPC_PORT_DOWN))
703                 && (p->config & OFPPC_PORT_DOWN) == 0) {
704                 p->config |= OFPPC_PORT_DOWN;
705                 netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
706             } else if ((opm->config & htonl(OFPPC_PORT_DOWN)) == 0
707                        && (p->config & OFPPC_PORT_DOWN)) {
708                 p->config &= ~OFPPC_PORT_DOWN;
709                 netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
710             }
711         }
712     }
713 }
714
715 /* Update the port status field of the bridge port.  A non-zero return
716  * value indicates some field has changed. 
717  *
718  * NB: Callers of this function may hold the RCU read lock, so any
719  * additional checks must not sleep.
720  */
721 static int
722 update_port_status(struct sw_port *p)
723 {
724     int retval;
725     enum netdev_flags flags;
726     uint32_t orig_config = p->config;
727     uint32_t orig_state = p->state;
728
729     if (netdev_get_flags(p->netdev, &flags) < 0) {
730         VLOG_WARN_RL(&rl, "could not get netdev flags for %s", 
731                      netdev_get_name(p->netdev));
732         return 0;
733     } else {
734         if (flags & NETDEV_UP) {
735             p->config &= ~OFPPC_PORT_DOWN;
736         } else {
737             p->config |= OFPPC_PORT_DOWN;
738         } 
739     }
740
741     /* Not all cards support this getting link status, so don't warn on
742      * error. */
743     retval = netdev_get_link_status(p->netdev);
744     if (retval == 1) {
745         p->state &= ~OFPPS_LINK_DOWN;
746     } else if (retval == 0) {
747         p->state |= OFPPS_LINK_DOWN;
748     } 
749
750     return ((orig_config != p->config) || (orig_state != p->state));
751 }
752
753 static void
754 send_port_status(struct sw_port *p, uint8_t status) 
755 {
756     struct ofpbuf *buffer;
757     struct ofp_port_status *ops;
758     ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
759     ops->reason = status;
760     memset(ops->pad, 0, sizeof ops->pad);
761     fill_port_desc(p->dp, p, &ops->desc);
762
763     send_openflow_buffer(p->dp, buffer, NULL);
764 }
765
766 void
767 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
768                   enum ofp_flow_expired_reason reason)
769 {
770     struct ofpbuf *buffer;
771     struct ofp_flow_expired *ofe;
772     ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
773     flow_fill_match(&ofe->match, &flow->key);
774
775     ofe->priority = htons(flow->priority);
776     ofe->reason = reason;
777     memset(ofe->pad, 0, sizeof ofe->pad);
778
779     ofe->duration     = htonl(time_now() - flow->created);
780     memset(ofe->pad2, 0, sizeof ofe->pad2);
781     ofe->packet_count = htonll(flow->packet_count);
782     ofe->byte_count   = htonll(flow->byte_count);
783     send_openflow_buffer(dp, buffer, NULL);
784 }
785
786 void
787 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
788                   uint16_t type, uint16_t code, const void *data, size_t len)
789 {
790     struct ofpbuf *buffer;
791     struct ofp_error_msg *oem;
792     oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
793     oem->type = htons(type);
794     oem->code = htons(code);
795     memcpy(oem->data, data, len);
796     send_openflow_buffer(dp, buffer, sender);
797 }
798
799 static void
800 fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
801                 int table_idx, time_t now)
802 {
803     struct ofp_flow_stats *ofs;
804     int length = sizeof *ofs + flow->sf_acts->actions_len;
805     ofs = ofpbuf_put_uninit(buffer, length);
806     ofs->length          = htons(length);
807     ofs->table_id        = table_idx;
808     ofs->pad             = 0;
809     ofs->match.wildcards = htonl(flow->key.wildcards);
810     ofs->match.in_port   = flow->key.flow.in_port;
811     memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
812     memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
813     ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
814     ofs->match.dl_type   = flow->key.flow.dl_type;
815     ofs->match.nw_src    = flow->key.flow.nw_src;
816     ofs->match.nw_dst    = flow->key.flow.nw_dst;
817     ofs->match.nw_proto  = flow->key.flow.nw_proto;
818     ofs->match.pad       = 0;
819     ofs->match.tp_src    = flow->key.flow.tp_src;
820     ofs->match.tp_dst    = flow->key.flow.tp_dst;
821     ofs->duration        = htonl(now - flow->created);
822     ofs->priority        = htons(flow->priority);
823     ofs->idle_timeout    = htons(flow->idle_timeout);
824     ofs->hard_timeout    = htons(flow->hard_timeout);
825     memset(ofs->pad2, 0, sizeof ofs->pad2);
826     ofs->packet_count    = htonll(flow->packet_count);
827     ofs->byte_count      = htonll(flow->byte_count);
828     memcpy(ofs->actions, flow->sf_acts->actions, flow->sf_acts->actions_len);
829 }
830
831 \f
832 /* 'buffer' was received on 'p', which may be a a physical switch port or a
833  * null pointer.  Process it according to 'dp''s flow table.  Returns 0 if
834  * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
835  * matching flow, in which case 'buffer' still belongs to the caller. */
836 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
837                             struct sw_port *p)
838 {
839     struct sw_flow_key key;
840     struct sw_flow *flow;
841
842     key.wildcards = 0;
843     if (flow_extract(buffer, p ? port_no(dp, p) : OFPP_NONE, &key.flow)
844         && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
845         /* Drop fragment. */
846         ofpbuf_delete(buffer);
847         return 0;
848     }
849         if (p && p->config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP)
850         && p->config & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
851                        ? OFPPC_NO_RECV : OFPPC_NO_RECV_STP)) {
852                 ofpbuf_delete(buffer);
853                 return 0;
854         }
855
856     flow = chain_lookup(dp->chain, &key);
857     if (flow != NULL) {
858         flow_used(flow, buffer);
859         execute_actions(dp, buffer, &key, flow->sf_acts->actions, 
860                         flow->sf_acts->actions_len, false);
861         return 0;
862     } else {
863         return -ESRCH;
864     }
865 }
866
867 /* 'buffer' was received on 'p', which may be a a physical switch port or a
868  * null pointer.  Process it according to 'dp''s flow table, sending it up to
869  * the controller if no flow matches.  Takes ownership of 'buffer'. */
870 void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
871                     struct sw_port *p)
872 {
873     if (run_flow_through_tables(dp, buffer, p)) {
874         dp_output_control(dp, buffer, port_no(dp, p),
875                           dp->miss_send_len, OFPR_NO_MATCH);
876     }
877 }
878
879 static int
880 recv_features_request(struct datapath *dp, const struct sender *sender,
881                       const void *msg) 
882 {
883     dp_send_features_reply(dp, sender);
884     return 0;
885 }
886
887 static int
888 recv_get_config_request(struct datapath *dp, const struct sender *sender,
889                         const void *msg) 
890 {
891     struct ofpbuf *buffer;
892     struct ofp_switch_config *osc;
893
894     osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
895                               sender, &buffer);
896
897     osc->flags = htons(dp->flags);
898     osc->miss_send_len = htons(dp->miss_send_len);
899
900     return send_openflow_buffer(dp, buffer, sender);
901 }
902
903 static int
904 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
905                 const void *msg)
906 {
907     const struct ofp_switch_config *osc = msg;
908     int flags;
909
910     flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
911     if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
912         && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
913         flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
914     }
915     dp->flags = flags;
916     dp->miss_send_len = ntohs(osc->miss_send_len);
917     return 0;
918 }
919
920 static int
921 recv_packet_out(struct datapath *dp, const struct sender *sender,
922                 const void *msg)
923 {
924     const struct ofp_packet_out *opo = msg;
925     struct sw_flow_key key;
926     uint16_t v_code;
927     struct ofpbuf *buffer;
928     size_t actions_len = ntohs(opo->actions_len);
929
930     if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
931         VLOG_DBG_RL(&rl, "message too short for number of actions");
932         return -EINVAL;
933     }
934
935     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
936         /* FIXME: can we avoid copying data here? */
937         int data_len = ntohs(opo->header.length) - sizeof *opo - actions_len;
938         buffer = ofpbuf_new(data_len);
939         ofpbuf_put(buffer, (uint8_t *)opo->actions + actions_len, data_len);
940     } else {
941         buffer = retrieve_buffer(ntohl(opo->buffer_id));
942         if (!buffer) {
943             return -ESRCH; 
944         }
945     }
946  
947     flow_extract(buffer, ntohs(opo->in_port), &key.flow);
948
949     v_code = validate_actions(dp, &key, opo->actions, actions_len);
950     if (v_code != ACT_VALIDATION_OK) {
951         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
952                   msg, ntohs(opo->header.length));
953         goto error;
954     }
955
956     execute_actions(dp, buffer, &key, opo->actions, actions_len, true);
957
958     return 0;
959
960 error:
961     ofpbuf_delete(buffer);
962     return -EINVAL;
963 }
964
965 static int
966 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
967               const void *msg)
968 {
969     const struct ofp_port_mod *opm = msg;
970
971     dp_update_port_flags(dp, opm);
972
973     return 0;
974 }
975
976 static int
977 add_flow(struct datapath *dp, const struct sender *sender,
978         const struct ofp_flow_mod *ofm)
979 {
980     int error = -ENOMEM;
981     uint16_t v_code;
982     struct sw_flow *flow; 
983     size_t actions_len = ntohs(ofm->header.length) - sizeof *ofm;
984
985     /* Allocate memory. */
986     flow = flow_alloc(actions_len);
987     if (flow == NULL)
988         goto error;
989
990     flow_extract_match(&flow->key, &ofm->match);
991
992     v_code = validate_actions(dp, &flow->key, ofm->actions, actions_len);
993     if (v_code != ACT_VALIDATION_OK) {
994         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
995                   ofm, ntohs(ofm->header.length));
996         goto error;
997     }
998
999     /* Fill out flow. */
1000     flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1001     flow->idle_timeout = ntohs(ofm->idle_timeout);
1002     flow->hard_timeout = ntohs(ofm->hard_timeout);
1003     flow->used = flow->created = time_now();
1004     flow->sf_acts->actions_len = actions_len;
1005     flow->byte_count = 0;
1006     flow->packet_count = 0;
1007     memcpy(flow->sf_acts->actions, ofm->actions, actions_len);
1008
1009     /* Act. */
1010     error = chain_insert(dp->chain, flow);
1011     if (error == -ENOBUFS) {
1012         dp_send_error_msg(dp, sender, OFPET_FLOW_MOD_FAILED, 
1013                 OFPFMFC_ALL_TABLES_FULL, ofm, ntohs(ofm->header.length));
1014         goto error_free_flow; 
1015     } else if (error) {
1016         goto error_free_flow; 
1017     }
1018     error = 0;
1019     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1020         struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1021         if (buffer) {
1022             struct sw_flow_key key;
1023             uint16_t in_port = ntohs(ofm->match.in_port);
1024             flow_used(flow, buffer);
1025             flow_extract(buffer, in_port, &key.flow);
1026             execute_actions(dp, buffer, &key, 
1027                     ofm->actions, actions_len, false);
1028         } else {
1029             error = -ESRCH; 
1030         }
1031     }
1032     return error;
1033
1034 error_free_flow:
1035     flow_free(flow);
1036 error:
1037     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1038         discard_buffer(ntohl(ofm->buffer_id));
1039     return error;
1040 }
1041
1042 static int
1043 mod_flow(struct datapath *dp, const struct sender *sender,
1044         const struct ofp_flow_mod *ofm)
1045 {
1046     int error = -ENOMEM;
1047     uint16_t v_code;
1048     size_t actions_len;
1049     struct sw_flow_key key;
1050     uint16_t priority;
1051     int strict;
1052
1053     flow_extract_match(&key, &ofm->match);
1054  
1055     actions_len = ntohs(ofm->header.length) - sizeof *ofm;
1056  
1057     v_code = validate_actions(dp, &key, ofm->actions, actions_len);
1058     if (v_code != ACT_VALIDATION_OK) {
1059         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1060                   ofm, ntohs(ofm->header.length));
1061         goto error;
1062     }
1063
1064     priority = key.wildcards ? ntohs(ofm->priority) : -1;
1065     strict = (ofm->command == htons(OFPFC_MODIFY_STRICT)) ? 1 : 0;
1066     chain_modify(dp->chain, &key, priority, strict, ofm->actions, actions_len);
1067
1068     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1069         struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1070         if (buffer) {
1071             struct sw_flow_key skb_key;
1072             uint16_t in_port = ntohs(ofm->match.in_port);
1073             flow_extract(buffer, in_port, &skb_key.flow);
1074             execute_actions(dp, buffer, &skb_key,
1075                             ofm->actions, actions_len, false);
1076         } else {
1077             error = -ESRCH; 
1078         }
1079     }
1080     return error;
1081
1082 error:
1083     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1084         discard_buffer(ntohl(ofm->buffer_id));
1085     return error;
1086 }
1087
1088 static int
1089 recv_flow(struct datapath *dp, const struct sender *sender,
1090           const void *msg)
1091 {
1092     const struct ofp_flow_mod *ofm = msg;
1093     uint16_t command = ntohs(ofm->command);
1094
1095     if (command == OFPFC_ADD) {
1096         return add_flow(dp, sender, ofm);
1097     } else if ((command == OFPFC_MODIFY) || (command == OFPFC_MODIFY_STRICT)) {
1098         return mod_flow(dp, sender, ofm);
1099     }  else if (command == OFPFC_DELETE) {
1100         struct sw_flow_key key;
1101         flow_extract_match(&key, &ofm->match);
1102         return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1103     } else if (command == OFPFC_DELETE_STRICT) {
1104         struct sw_flow_key key;
1105         uint16_t priority;
1106         flow_extract_match(&key, &ofm->match);
1107         priority = key.wildcards ? ntohs(ofm->priority) : -1;
1108         return chain_delete(dp->chain, &key, priority, 1) ? 0 : -ESRCH;
1109     } else {
1110         return -ENODEV;
1111     }
1112 }
1113
1114 static int desc_stats_dump(struct datapath *dp, void *state,
1115                               struct ofpbuf *buffer)
1116 {
1117     struct ofp_desc_stats *ods = ofpbuf_put_uninit(buffer, sizeof *ods);
1118
1119     strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
1120     strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
1121     strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
1122     strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
1123
1124     return 0;
1125 }
1126
1127 struct flow_stats_state {
1128     int table_idx;
1129     struct sw_table_position position;
1130     struct ofp_flow_stats_request rq;
1131     time_t now;
1132
1133     struct ofpbuf *buffer;
1134 };
1135
1136 #define MAX_FLOW_STATS_BYTES 4096
1137
1138 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1139                            void **state)
1140 {
1141     const struct ofp_flow_stats_request *fsr = body;
1142     struct flow_stats_state *s = xmalloc(sizeof *s);
1143     s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1144     memset(&s->position, 0, sizeof s->position);
1145     s->rq = *fsr;
1146     *state = s;
1147     return 0;
1148 }
1149
1150 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1151 {
1152     struct flow_stats_state *s = private;
1153     fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1154     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1155 }
1156
1157 static int flow_stats_dump(struct datapath *dp, void *state,
1158                            struct ofpbuf *buffer)
1159 {
1160     struct flow_stats_state *s = state;
1161     struct sw_flow_key match_key;
1162
1163     flow_extract_match(&match_key, &s->rq.match);
1164     s->buffer = buffer;
1165     s->now = time_now();
1166     while (s->table_idx < dp->chain->n_tables
1167            && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1168     {
1169         struct sw_table *table = dp->chain->tables[s->table_idx];
1170
1171         if (table->iterate(table, &match_key, &s->position,
1172                            flow_stats_dump_callback, s))
1173             break;
1174
1175         s->table_idx++;
1176         memset(&s->position, 0, sizeof s->position);
1177     }
1178     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1179 }
1180
1181 static void flow_stats_done(void *state)
1182 {
1183     free(state);
1184 }
1185
1186 struct aggregate_stats_state {
1187     struct ofp_aggregate_stats_request rq;
1188 };
1189
1190 static int aggregate_stats_init(struct datapath *dp,
1191                                 const void *body, int body_len,
1192                                 void **state)
1193 {
1194     const struct ofp_aggregate_stats_request *rq = body;
1195     struct aggregate_stats_state *s = xmalloc(sizeof *s);
1196     s->rq = *rq;
1197     *state = s;
1198     return 0;
1199 }
1200
1201 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1202 {
1203     struct ofp_aggregate_stats_reply *rpy = private;
1204     rpy->packet_count += flow->packet_count;
1205     rpy->byte_count += flow->byte_count;
1206     rpy->flow_count++;
1207     return 0;
1208 }
1209
1210 static int aggregate_stats_dump(struct datapath *dp, void *state,
1211                                 struct ofpbuf *buffer)
1212 {
1213     struct aggregate_stats_state *s = state;
1214     struct ofp_aggregate_stats_request *rq = &s->rq;
1215     struct ofp_aggregate_stats_reply *rpy;
1216     struct sw_table_position position;
1217     struct sw_flow_key match_key;
1218     int table_idx;
1219
1220     rpy = ofpbuf_put_uninit(buffer, sizeof *rpy);
1221     memset(rpy, 0, sizeof *rpy);
1222
1223     flow_extract_match(&match_key, &rq->match);
1224     table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1225     memset(&position, 0, sizeof position);
1226     while (table_idx < dp->chain->n_tables
1227            && (rq->table_id == 0xff || rq->table_id == table_idx))
1228     {
1229         struct sw_table *table = dp->chain->tables[table_idx];
1230         int error;
1231
1232         error = table->iterate(table, &match_key, &position,
1233                                aggregate_stats_dump_callback, rpy);
1234         if (error)
1235             return error;
1236
1237         table_idx++;
1238         memset(&position, 0, sizeof position);
1239     }
1240
1241     rpy->packet_count = htonll(rpy->packet_count);
1242     rpy->byte_count = htonll(rpy->byte_count);
1243     rpy->flow_count = htonl(rpy->flow_count);
1244     return 0;
1245 }
1246
1247 static void aggregate_stats_done(void *state) 
1248 {
1249     free(state);
1250 }
1251
1252 static int table_stats_dump(struct datapath *dp, void *state,
1253                             struct ofpbuf *buffer)
1254 {
1255     int i;
1256     for (i = 0; i < dp->chain->n_tables; i++) {
1257         struct ofp_table_stats *ots = ofpbuf_put_uninit(buffer, sizeof *ots);
1258         struct sw_table_stats stats;
1259         dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1260         strncpy(ots->name, stats.name, sizeof ots->name);
1261         ots->table_id = i;
1262         ots->wildcards = htonl(stats.wildcards);
1263         memset(ots->pad, 0, sizeof ots->pad);
1264         ots->max_entries = htonl(stats.max_flows);
1265         ots->active_count = htonl(stats.n_flows);
1266         ots->lookup_count = htonll(stats.n_lookup);
1267         ots->matched_count = htonll(stats.n_matched);
1268     }
1269     return 0;
1270 }
1271
1272 struct port_stats_state {
1273     int port;
1274 };
1275
1276 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1277                void **state)
1278 {
1279     struct port_stats_state *s = xmalloc(sizeof *s);
1280     s->port = 0;
1281     *state = s;
1282     return 0;
1283 }
1284
1285 static int port_stats_dump(struct datapath *dp, void *state,
1286                            struct ofpbuf *buffer)
1287 {
1288     struct port_stats_state *s = state;
1289     int i;
1290
1291     for (i = s->port; i < OFPP_MAX; i++) {
1292         struct sw_port *p = &dp->ports[i];
1293         struct ofp_port_stats *ops;
1294         if (!p->netdev) {
1295             continue;
1296         }
1297         ops = ofpbuf_put_uninit(buffer, sizeof *ops);
1298         ops->port_no = htons(port_no(dp, p));
1299         memset(ops->pad, 0, sizeof ops->pad);
1300         ops->rx_packets   = htonll(p->rx_packets);
1301         ops->tx_packets   = htonll(p->tx_packets);
1302         ops->rx_bytes     = htonll(p->rx_bytes);
1303         ops->tx_bytes     = htonll(p->tx_bytes);
1304         ops->rx_dropped   = htonll(-1);
1305         ops->tx_dropped   = htonll(p->tx_dropped);
1306         ops->rx_errors    = htonll(-1);
1307         ops->tx_errors    = htonll(-1);
1308         ops->rx_frame_err = htonll(-1);
1309         ops->rx_over_err  = htonll(-1);
1310         ops->rx_crc_err   = htonll(-1);
1311         ops->collisions   = htonll(-1);
1312         ops++;
1313     }
1314     s->port = i;
1315     return 0;
1316 }
1317
1318 static void port_stats_done(void *state)
1319 {
1320     free(state);
1321 }
1322
1323 struct stats_type {
1324     /* Value for 'type' member of struct ofp_stats_request. */
1325     int type;
1326
1327     /* Minimum and maximum acceptable number of bytes in body member of
1328      * struct ofp_stats_request. */
1329     size_t min_body, max_body;
1330
1331     /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1332      * 'body_len' are the 'body' member of the struct ofp_stats_request.
1333      * Returns zero if successful, otherwise a negative error code.
1334      * May initialize '*state' to state information.  May be null if no
1335      * initialization is required.*/
1336     int (*init)(struct datapath *dp, const void *body, int body_len,
1337             void **state);
1338
1339     /* Appends statistics for 'dp' to 'buffer', which initially contains a
1340      * struct ofp_stats_reply.  On success, it should return 1 if it should be
1341      * called again later with another buffer, 0 if it is done, or a negative
1342      * errno value on failure. */
1343     int (*dump)(struct datapath *dp, void *state, struct ofpbuf *buffer);
1344
1345     /* Cleans any state created by the init or dump functions.  May be null
1346      * if no cleanup is required. */
1347     void (*done)(void *state);
1348 };
1349
1350 static const struct stats_type stats[] = {
1351     {
1352         OFPST_DESC,
1353         0,
1354         0,
1355         NULL,
1356         desc_stats_dump,
1357         NULL
1358     },
1359     {
1360         OFPST_FLOW,
1361         sizeof(struct ofp_flow_stats_request),
1362         sizeof(struct ofp_flow_stats_request),
1363         flow_stats_init,
1364         flow_stats_dump,
1365         flow_stats_done
1366     },
1367     {
1368         OFPST_AGGREGATE,
1369         sizeof(struct ofp_aggregate_stats_request),
1370         sizeof(struct ofp_aggregate_stats_request),
1371         aggregate_stats_init,
1372         aggregate_stats_dump,
1373         aggregate_stats_done
1374     },
1375     {
1376         OFPST_TABLE,
1377         0,
1378         0,
1379         NULL,
1380         table_stats_dump,
1381         NULL
1382     },
1383     {
1384         OFPST_PORT,
1385         0,
1386         0,
1387         port_stats_init,
1388         port_stats_dump,
1389         port_stats_done
1390     },
1391 };
1392
1393 struct stats_dump_cb {
1394     bool done;
1395     struct ofp_stats_request *rq;
1396     struct sender sender;
1397     const struct stats_type *s;
1398     void *state;
1399 };
1400
1401 static int
1402 stats_dump(struct datapath *dp, void *cb_)
1403 {
1404     struct stats_dump_cb *cb = cb_;
1405     struct ofp_stats_reply *osr;
1406     struct ofpbuf *buffer;
1407     int err;
1408
1409     if (cb->done) {
1410         return 0;
1411     }
1412
1413     osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1414                               &buffer);
1415     osr->type = htons(cb->s->type);
1416     osr->flags = 0;
1417
1418     err = cb->s->dump(dp, cb->state, buffer);
1419     if (err >= 0) {
1420         int err2;
1421         if (!err) {
1422             cb->done = true;
1423         } else {
1424             /* Buffer might have been reallocated, so find our data again. */
1425             osr = ofpbuf_at_assert(buffer, 0, sizeof *osr);
1426             osr->flags = ntohs(OFPSF_REPLY_MORE);
1427         }
1428         err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1429         if (err2) {
1430             err = err2;
1431         }
1432     }
1433
1434     return err;
1435 }
1436
1437 static void
1438 stats_done(void *cb_)
1439 {
1440     struct stats_dump_cb *cb = cb_;
1441     if (cb) {
1442         if (cb->s->done) {
1443             cb->s->done(cb->state);
1444         }
1445         free(cb);
1446     }
1447 }
1448
1449 static int
1450 recv_stats_request(struct datapath *dp, const struct sender *sender,
1451                    const void *oh)
1452 {
1453     const struct ofp_stats_request *rq = oh;
1454     size_t rq_len = ntohs(rq->header.length);
1455     const struct stats_type *st;
1456     struct stats_dump_cb *cb;
1457     int type, body_len;
1458     int err;
1459
1460     type = ntohs(rq->type);
1461     for (st = stats; ; st++) {
1462         if (st >= &stats[ARRAY_SIZE(stats)]) {
1463             VLOG_WARN_RL(&rl, "received stats request of unknown type %d",
1464                          type);
1465             return -EINVAL;
1466         } else if (type == st->type) {
1467             break;
1468         }
1469     }
1470
1471     cb = xmalloc(sizeof *cb);
1472     cb->done = false;
1473     cb->rq = xmemdup(rq, rq_len);
1474     cb->sender = *sender;
1475     cb->s = st;
1476     cb->state = NULL;
1477     
1478     body_len = rq_len - offsetof(struct ofp_stats_request, body);
1479     if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1480         VLOG_WARN_RL(&rl, "stats request type %d with bad body length %d",
1481                      type, body_len);
1482         err = -EINVAL;
1483         goto error;
1484     }
1485
1486     if (cb->s->init) {
1487         err = cb->s->init(dp, rq->body, body_len, &cb->state);
1488         if (err) {
1489             VLOG_WARN_RL(&rl,
1490                          "failed initialization of stats request type %d: %s",
1491                          type, strerror(-err));
1492             goto error;
1493         }
1494     }
1495
1496     remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1497     return 0;
1498
1499 error:
1500     free(cb->rq);
1501     free(cb);
1502     return err;
1503 }
1504
1505 static int
1506 recv_echo_request(struct datapath *dp, const struct sender *sender,
1507                   const void *oh)
1508 {
1509     return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1510 }
1511
1512 static int
1513 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1514                   const void *oh UNUSED)
1515 {
1516     return 0;
1517 }
1518
1519 /* 'msg', which is 'length' bytes long, was received from the control path.
1520  * Apply it to 'chain'. */
1521 int
1522 fwd_control_input(struct datapath *dp, const struct sender *sender,
1523                   const void *msg, size_t length)
1524 {
1525     int (*handler)(struct datapath *, const struct sender *, const void *);
1526     struct ofp_header *oh;
1527     size_t min_size;
1528
1529     /* Check encapsulated length. */
1530     oh = (struct ofp_header *) msg;
1531     if (ntohs(oh->length) > length) {
1532         return -EINVAL;
1533     }
1534     assert(oh->version == OFP_VERSION);
1535
1536     /* Figure out how to handle it. */
1537     switch (oh->type) {
1538     case OFPT_FEATURES_REQUEST:
1539         min_size = sizeof(struct ofp_header);
1540         handler = recv_features_request;
1541         break;
1542     case OFPT_GET_CONFIG_REQUEST:
1543         min_size = sizeof(struct ofp_header);
1544         handler = recv_get_config_request;
1545         break;
1546     case OFPT_SET_CONFIG:
1547         min_size = sizeof(struct ofp_switch_config);
1548         handler = recv_set_config;
1549         break;
1550     case OFPT_PACKET_OUT:
1551         min_size = sizeof(struct ofp_packet_out);
1552         handler = recv_packet_out;
1553         break;
1554     case OFPT_FLOW_MOD:
1555         min_size = sizeof(struct ofp_flow_mod);
1556         handler = recv_flow;
1557         break;
1558     case OFPT_PORT_MOD:
1559         min_size = sizeof(struct ofp_port_mod);
1560         handler = recv_port_mod;
1561         break;
1562     case OFPT_STATS_REQUEST:
1563         min_size = sizeof(struct ofp_stats_request);
1564         handler = recv_stats_request;
1565         break;
1566     case OFPT_ECHO_REQUEST:
1567         min_size = sizeof(struct ofp_header);
1568         handler = recv_echo_request;
1569         break;
1570     case OFPT_ECHO_REPLY:
1571         min_size = sizeof(struct ofp_header);
1572         handler = recv_echo_reply;
1573         break;
1574     default:
1575         dp_send_error_msg(dp, sender, OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE,
1576                           msg, length);
1577         return -EINVAL;
1578     }
1579
1580     /* Handle it. */
1581     if (length < min_size)
1582         return -EFAULT;
1583     return handler(dp, sender, msg);
1584 }
1585 \f
1586 /* Packet buffering. */
1587
1588 #define OVERWRITE_SECS  1
1589
1590 struct packet_buffer {
1591     struct ofpbuf *buffer;
1592     uint32_t cookie;
1593     time_t timeout;
1594 };
1595
1596 static struct packet_buffer buffers[N_PKT_BUFFERS];
1597 static unsigned int buffer_idx;
1598
1599 uint32_t save_buffer(struct ofpbuf *buffer)
1600 {
1601     struct packet_buffer *p;
1602     uint32_t id;
1603
1604     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1605     p = &buffers[buffer_idx];
1606     if (p->buffer) {
1607         /* Don't buffer packet if existing entry is less than
1608          * OVERWRITE_SECS old. */
1609         if (time_now() < p->timeout) { /* FIXME */
1610             return -1;
1611         } else {
1612             ofpbuf_delete(p->buffer); 
1613         }
1614     }
1615     /* Don't use maximum cookie value since the all-bits-1 id is
1616      * special. */
1617     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1618         p->cookie = 0;
1619     p->buffer = ofpbuf_clone(buffer);      /* FIXME */
1620     p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
1621     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1622
1623     return id;
1624 }
1625
1626 static struct ofpbuf *retrieve_buffer(uint32_t id)
1627 {
1628     struct ofpbuf *buffer = NULL;
1629     struct packet_buffer *p;
1630
1631     p = &buffers[id & PKT_BUFFER_MASK];
1632     if (p->cookie == id >> PKT_BUFFER_BITS) {
1633         buffer = p->buffer;
1634         p->buffer = NULL;
1635     } else {
1636         printf("cookie mismatch: %x != %x\n",
1637                id >> PKT_BUFFER_BITS, p->cookie);
1638     }
1639
1640     return buffer;
1641 }
1642
1643 static void discard_buffer(uint32_t id)
1644 {
1645     struct packet_buffer *p;
1646
1647     p = &buffers[id & PKT_BUFFER_MASK];
1648     if (p->cookie == id >> PKT_BUFFER_BITS) {
1649         ofpbuf_delete(p->buffer);
1650         p->buffer = NULL;
1651     }
1652 }