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