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