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