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