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