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