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