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