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