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