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