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