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