Remove MAX_ACTIONS (which was 16) as a limit on the number of actions in a flow table...
[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     memset(ops->pad, 0, sizeof ops->pad);
679     fill_port_desc(p->dp, p, &ops->desc);
680
681     send_openflow_buffer(p->dp, buffer, NULL);
682 }
683
684 void
685 send_flow_expired(struct datapath *dp, struct sw_flow *flow)
686 {
687     struct buffer *buffer;
688     struct ofp_flow_expired *ofe;
689     ofe = alloc_openflow_buffer(dp, sizeof *ofe, OFPT_FLOW_EXPIRED, NULL,
690                                 &buffer);
691     flow_fill_match(&ofe->match, &flow->key);
692
693     memset(ofe->pad, 0, sizeof ofe->pad);
694     ofe->priority = htons(flow->priority);
695
696     ofe->duration     = htonl(flow->timeout - flow->max_idle - flow->created);
697     ofe->packet_count = htonll(flow->packet_count);
698     ofe->byte_count   = htonll(flow->byte_count);
699     send_openflow_buffer(dp, buffer, NULL);
700 }
701
702 void
703 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
704         uint16_t type, uint16_t code, const uint8_t *data, size_t len)
705 {
706     struct buffer *buffer;
707     struct ofp_error_msg *oem;
708     oem = alloc_openflow_buffer(dp, sizeof(*oem)+len, OFPT_ERROR_MSG, 
709                                 sender, &buffer);
710     oem->type = htons(type);
711     oem->code = htons(code);
712     memcpy(oem->data, data, len);
713     send_openflow_buffer(dp, buffer, sender);
714 }
715
716 static void
717 fill_flow_stats(struct buffer *buffer, struct sw_flow *flow,
718                 int table_idx, time_t now)
719 {
720     struct ofp_flow_stats *ofs;
721     int length = sizeof *ofs + sizeof *ofs->actions * flow->n_actions;
722     ofs = buffer_put_uninit(buffer, length);
723     ofs->length          = htons(length);
724     ofs->table_id        = table_idx;
725     ofs->pad             = 0;
726     ofs->match.wildcards = htons(flow->key.wildcards);
727     ofs->match.in_port   = flow->key.flow.in_port;
728     memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
729     memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
730     ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
731     ofs->match.dl_type   = flow->key.flow.dl_type;
732     ofs->match.nw_src    = flow->key.flow.nw_src;
733     ofs->match.nw_dst    = flow->key.flow.nw_dst;
734     ofs->match.nw_proto  = flow->key.flow.nw_proto;
735     memset(ofs->match.pad, 0, sizeof ofs->match.pad);
736     ofs->match.tp_src    = flow->key.flow.tp_src;
737     ofs->match.tp_dst    = flow->key.flow.tp_dst;
738     ofs->duration        = htonl(now - flow->created);
739     ofs->packet_count    = htonll(flow->packet_count);
740     ofs->byte_count      = htonll(flow->byte_count);
741     ofs->priority        = htons(flow->priority);
742     ofs->max_idle        = htons(flow->max_idle);
743     memcpy(ofs->actions, flow->actions,
744            sizeof *ofs->actions * flow->n_actions);
745 }
746
747 \f
748 /* 'buffer' was received on 'in_port', a physical switch port between 0 and
749  * OFPP_MAX.  Process it according to 'chain'. */
750 void fwd_port_input(struct datapath *dp, struct buffer *buffer, int in_port)
751 {
752     struct sw_flow_key key;
753     struct sw_flow *flow;
754
755     key.wildcards = 0;
756     flow_extract(buffer, in_port, &key.flow);
757     flow = chain_lookup(dp->chain, &key);
758     if (flow != NULL) {
759         flow_used(flow, buffer);
760         execute_actions(dp, buffer, in_port, &key,
761                         flow->actions, flow->n_actions);
762     } else {
763         dp_output_control(dp, buffer, in_port, ntohs(dp->config.miss_send_len),
764                           OFPR_NO_MATCH);
765     }
766 }
767
768 static void
769 do_output(struct datapath *dp, struct buffer *buffer, int in_port,
770           size_t max_len, int out_port)
771 {
772     if (out_port != OFPP_CONTROLLER) {
773         dp_output_port(dp, buffer, in_port, out_port);
774     } else {
775         dp_output_control(dp, buffer, in_port, max_len, OFPR_ACTION);
776     }
777 }
778
779 static void
780 execute_actions(struct datapath *dp, struct buffer *buffer,
781                 int in_port, const struct sw_flow_key *key,
782                 const struct ofp_action *actions, int n_actions)
783 {
784     /* Every output action needs a separate clone of 'buffer', but the common
785      * case is just a single output action, so that doing a clone and then
786      * freeing the original buffer is wasteful.  So the following code is
787      * slightly obscure just to avoid that. */
788     int prev_port;
789     size_t max_len=0;        /* Initialze to make compiler happy */
790     uint16_t eth_proto;
791     int i;
792
793     prev_port = -1;
794     eth_proto = ntohs(key->flow.dl_type);
795
796     for (i = 0; i < n_actions; i++) {
797         const struct ofp_action *a = &actions[i];
798         struct eth_header *eh = buffer->l2;
799
800         if (prev_port != -1) {
801             do_output(dp, buffer_clone(buffer), in_port, max_len, prev_port);
802             prev_port = -1;
803         }
804
805         switch (ntohs(a->type)) {
806         case OFPAT_OUTPUT:
807             prev_port = ntohs(a->arg.output.port);
808             max_len = ntohs(a->arg.output.max_len);
809             break;
810
811         case OFPAT_SET_DL_VLAN:
812             modify_vlan(buffer, key, a);
813             break;
814
815         case OFPAT_SET_DL_SRC:
816             memcpy(eh->eth_src, a->arg.dl_addr, sizeof eh->eth_src);
817             break;
818
819         case OFPAT_SET_DL_DST:
820             memcpy(eh->eth_dst, a->arg.dl_addr, sizeof eh->eth_dst);
821             break;
822
823         case OFPAT_SET_NW_SRC:
824         case OFPAT_SET_NW_DST:
825             modify_nh(buffer, eth_proto, key->flow.nw_proto, a);
826             break;
827
828         case OFPAT_SET_TP_SRC:
829         case OFPAT_SET_TP_DST:
830             modify_th(buffer, eth_proto, key->flow.nw_proto, a);
831             break;
832
833         default:
834             NOT_REACHED();
835         }
836     }
837     if (prev_port != -1)
838         do_output(dp, buffer, in_port, max_len, prev_port);
839     else
840         buffer_delete(buffer);
841 }
842
843 /* Returns the new checksum for a packet in which the checksum field previously
844  * contained 'old_csum' and in which a field that contained 'old_u16' was
845  * changed to contain 'new_u16'. */
846 static uint16_t
847 recalc_csum16(uint16_t old_csum, uint16_t old_u16, uint16_t new_u16)
848 {
849     /* Ones-complement arithmetic is endian-independent, so this code does not
850      * use htons() or ntohs().
851      *
852      * See RFC 1624 for formula and explanation. */
853     uint16_t hc_complement = ~old_csum;
854     uint16_t m_complement = ~old_u16;
855     uint16_t m_prime = new_u16;
856     uint32_t sum = hc_complement + m_complement + m_prime;
857     uint16_t hc_prime_complement = sum + (sum >> 16);
858     return ~hc_prime_complement;
859 }
860
861 /* Returns the new checksum for a packet in which the checksum field previously
862  * contained 'old_csum' and in which a field that contained 'old_u32' was
863  * changed to contain 'new_u32'. */
864 static uint16_t
865 recalc_csum32(uint16_t old_csum, uint32_t old_u32, uint32_t new_u32)
866 {
867     return recalc_csum16(recalc_csum16(old_csum, old_u32, new_u32),
868                          old_u32 >> 16, new_u32 >> 16);
869 }
870
871 static void modify_nh(struct buffer *buffer, uint16_t eth_proto,
872                       uint8_t nw_proto, const struct ofp_action *a)
873 {
874     if (eth_proto == ETH_TYPE_IP) {
875         struct ip_header *nh = buffer->l3;
876         uint32_t new, *field;
877
878         new = a->arg.nw_addr;
879         field = a->type == OFPAT_SET_NW_SRC ? &nh->ip_src : &nh->ip_dst;
880         if (nw_proto == IP_TYPE_TCP) {
881             struct tcp_header *th = buffer->l4;
882             th->tcp_csum = recalc_csum32(th->tcp_csum, *field, new);
883         } else if (nw_proto == IP_TYPE_UDP) {
884             struct udp_header *th = buffer->l4;
885             if (th->udp_csum) {
886                 th->udp_csum = recalc_csum32(th->udp_csum, *field, new);
887                 if (!th->udp_csum) {
888                     th->udp_csum = 0xffff;
889                 }
890             }
891         }
892         nh->ip_csum = recalc_csum32(nh->ip_csum, *field, new);
893         *field = new;
894     }
895 }
896
897 static void modify_th(struct buffer *buffer, uint16_t eth_proto,
898                       uint8_t nw_proto, const struct ofp_action *a)
899 {
900     if (eth_proto == ETH_TYPE_IP) {
901         uint16_t new, *field;
902
903         new = a->arg.tp;
904
905         if (nw_proto == IP_TYPE_TCP) {
906             struct tcp_header *th = buffer->l4;
907             field = a->type == OFPAT_SET_TP_SRC ? &th->tcp_src : &th->tcp_dst;
908             th->tcp_csum = recalc_csum16(th->tcp_csum, *field, new);
909             *field = new;
910         } else if (nw_proto == IP_TYPE_UDP) {
911             struct udp_header *th = buffer->l4;
912             field = a->type == OFPAT_SET_TP_SRC ? &th->udp_src : &th->udp_dst;
913             th->udp_csum = recalc_csum16(th->udp_csum, *field, new);
914             *field = new;
915         }
916     }
917 }
918
919 static void
920 modify_vlan(struct buffer *buffer,
921             const struct sw_flow_key *key, const struct ofp_action *a)
922 {
923     uint16_t new_id = a->arg.vlan_id;
924     struct vlan_eth_header *veh;
925
926     if (new_id != OFP_VLAN_NONE) {
927         if (key->flow.dl_vlan != htons(OFP_VLAN_NONE)) {
928             /* Modify vlan id, but maintain other TCI values */
929             veh = buffer->l2;
930             veh->veth_tci &= ~htons(VLAN_VID);
931             veh->veth_tci |= htons(new_id);
932         } else {
933             /* Insert new vlan id. */
934             struct eth_header *eh = buffer->l2;
935             struct vlan_eth_header tmp;
936             memcpy(tmp.veth_dst, eh->eth_dst, ETH_ADDR_LEN);
937             memcpy(tmp.veth_src, eh->eth_src, ETH_ADDR_LEN);
938             tmp.veth_type = htons(ETH_TYPE_VLAN);
939             tmp.veth_tci = new_id;
940             tmp.veth_next_type = eh->eth_type;
941             
942             veh = buffer_push_uninit(buffer, VLAN_HEADER_LEN);
943             memcpy(veh, &tmp, sizeof tmp);
944             buffer->l2 -= VLAN_HEADER_LEN;
945         }
946     } else  {
947         /* Remove an existing vlan header if it exists */
948         veh = buffer->l2;
949         if (veh->veth_type == htons(ETH_TYPE_VLAN)) {
950             struct eth_header tmp;
951             
952             memcpy(tmp.eth_dst, veh->veth_dst, ETH_ADDR_LEN);
953             memcpy(tmp.eth_src, veh->veth_src, ETH_ADDR_LEN);
954             tmp.eth_type = veh->veth_next_type;
955             
956             buffer->size -= VLAN_HEADER_LEN;
957             buffer->data += VLAN_HEADER_LEN;
958             buffer->l2 += VLAN_HEADER_LEN;
959             memcpy(buffer->data, &tmp, sizeof tmp);
960         }
961     }
962 }
963
964 static int
965 recv_features_request(struct datapath *dp, const struct sender *sender,
966                       const void *msg) 
967 {
968     dp_send_features_reply(dp, sender);
969     return 0;
970 }
971
972 static int
973 recv_get_config_request(struct datapath *dp, const struct sender *sender,
974                         const void *msg) 
975 {
976     struct buffer *buffer;
977     struct ofp_switch_config *osc;
978
979     osc = alloc_openflow_buffer(dp, sizeof *osc, OFPT_GET_CONFIG_REPLY,
980                                 sender, &buffer);
981
982     assert(sizeof *osc == sizeof dp->config);
983     memcpy(((char *)osc) + sizeof osc->header,
984            ((char *)&dp->config) + sizeof dp->config.header,
985            sizeof dp->config - sizeof dp->config.header);
986
987     return send_openflow_buffer(dp, buffer, sender);
988 }
989
990 static int
991 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
992                 const void *msg)
993 {
994     const struct ofp_switch_config *osc = msg;
995     dp->config = *osc;
996     return 0;
997 }
998
999 static int
1000 recv_packet_out(struct datapath *dp, const struct sender *sender UNUSED,
1001                 const void *msg)
1002 {
1003     const struct ofp_packet_out *opo = msg;
1004
1005     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1006         /* FIXME: can we avoid copying data here? */
1007         int data_len = ntohs(opo->header.length) - sizeof *opo;
1008         struct buffer *buffer = buffer_new(data_len);
1009         buffer_put(buffer, opo->u.data, data_len);
1010         dp_output_port(dp, buffer,
1011                        ntohs(opo->in_port), ntohs(opo->out_port));
1012     } else {
1013         struct sw_flow_key key;
1014         struct buffer *buffer;
1015         int n_acts;
1016
1017         buffer = retrieve_buffer(ntohl(opo->buffer_id));
1018         if (!buffer) {
1019             return -ESRCH; 
1020         }
1021
1022         n_acts = (ntohs(opo->header.length) - sizeof *opo) 
1023             / sizeof *opo->u.actions;
1024         flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1025         execute_actions(dp, buffer, ntohs(opo->in_port),
1026                         &key, opo->u.actions, n_acts);
1027     }
1028     return 0;
1029 }
1030
1031 static int
1032 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1033               const void *msg)
1034 {
1035     const struct ofp_port_mod *opm = msg;
1036
1037     dp_update_port_flags(dp, &opm->desc);
1038
1039     return 0;
1040 }
1041
1042 static int
1043 add_flow(struct datapath *dp, const struct ofp_flow_mod *ofm)
1044 {
1045     int error = -ENOMEM;
1046     int n_acts;
1047     int i;
1048     struct sw_flow *flow;
1049
1050
1051     /* To prevent loops, make sure there's no action to send to the
1052      * OFP_TABLE virtual port.
1053      */
1054     n_acts = (ntohs(ofm->header.length) - sizeof *ofm) / sizeof *ofm->actions;
1055     for (i=0; i<n_acts; i++) {
1056         const struct ofp_action *a = &ofm->actions[i];
1057
1058         if (a->type == htons(OFPAT_OUTPUT)
1059                     && a->arg.output.port == htons(OFPP_TABLE)) {
1060             /* xxx Send fancy new error message? */
1061             goto error;
1062         }
1063     }
1064
1065     /* Allocate memory. */
1066     flow = flow_alloc(n_acts);
1067     if (flow == NULL)
1068         goto error;
1069
1070     /* Fill out flow. */
1071     flow_extract_match(&flow->key, &ofm->match);
1072     flow->max_idle = ntohs(ofm->max_idle);
1073     flow->priority = ntohs(ofm->priority);
1074     flow->timeout = time(0) + flow->max_idle; /* FIXME */
1075     flow->n_actions = n_acts;
1076     flow->created = time(0);    /* FIXME */
1077     flow->byte_count = 0;
1078     flow->packet_count = 0;
1079     memcpy(flow->actions, ofm->actions, n_acts * sizeof *flow->actions);
1080
1081     /* Act. */
1082     error = chain_insert(dp->chain, flow);
1083     if (error) {
1084         goto error_free_flow; 
1085     }
1086     error = 0;
1087     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1088         struct buffer *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1089         if (buffer) {
1090             struct sw_flow_key key;
1091             uint16_t in_port = ntohs(ofm->match.in_port);
1092             flow_used(flow, buffer);
1093             flow_extract(buffer, in_port, &key.flow);
1094             execute_actions(dp, buffer, in_port, &key, ofm->actions, n_acts);
1095         } else {
1096             error = -ESRCH; 
1097         }
1098     }
1099     return error;
1100
1101 error_free_flow:
1102     flow_free(flow);
1103 error:
1104     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1105         discard_buffer(ntohl(ofm->buffer_id));
1106     return error;
1107 }
1108
1109 static int
1110 recv_flow(struct datapath *dp, const struct sender *sender UNUSED,
1111           const void *msg)
1112 {
1113     const struct ofp_flow_mod *ofm = msg;
1114     uint16_t command = ntohs(ofm->command);
1115
1116     if (command == OFPFC_ADD) {
1117         return add_flow(dp, ofm);
1118     }  else if (command == OFPFC_DELETE) {
1119         struct sw_flow_key key;
1120         flow_extract_match(&key, &ofm->match);
1121         return chain_delete(dp->chain, &key, 0, 0) ? 0 : -ESRCH;
1122     } else if (command == OFPFC_DELETE_STRICT) {
1123         struct sw_flow_key key;
1124         flow_extract_match(&key, &ofm->match);
1125         return chain_delete(dp->chain, &key, 
1126                     ntohs(ofm->priority), 1) ? 0 : -ESRCH;
1127     } else {
1128         return -ENODEV;
1129     }
1130 }
1131
1132 struct flow_stats_state {
1133     int table_idx;
1134     struct sw_table_position position;
1135     struct ofp_flow_stats_request rq;
1136     time_t now;
1137
1138     struct buffer *buffer;
1139 };
1140
1141 #define MAX_FLOW_STATS_BYTES 4096
1142
1143 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1144                            void **state)
1145 {
1146     const struct ofp_flow_stats_request *fsr = body;
1147     struct flow_stats_state *s = xmalloc(sizeof *s);
1148     s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1149     memset(&s->position, 0, sizeof s->position);
1150     s->rq = *fsr;
1151     *state = s;
1152     return 0;
1153 }
1154
1155 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1156 {
1157     struct flow_stats_state *s = private;
1158     fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1159     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1160 }
1161
1162 static int flow_stats_dump(struct datapath *dp, void *state,
1163                            struct buffer *buffer)
1164 {
1165     struct flow_stats_state *s = state;
1166     struct sw_flow_key match_key;
1167
1168     flow_extract_match(&match_key, &s->rq.match);
1169     s->buffer = buffer;
1170     s->now = time(0);
1171     while (s->table_idx < dp->chain->n_tables
1172            && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1173     {
1174         struct sw_table *table = dp->chain->tables[s->table_idx];
1175
1176         if (table->iterate(table, &match_key, &s->position,
1177                            flow_stats_dump_callback, s))
1178             break;
1179
1180         s->table_idx++;
1181         memset(&s->position, 0, sizeof s->position);
1182     }
1183     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1184 }
1185
1186 static void flow_stats_done(void *state)
1187 {
1188     free(state);
1189 }
1190
1191 static int table_stats_dump(struct datapath *dp, void *state,
1192                             struct buffer *buffer)
1193 {
1194     int i;
1195     for (i = 0; i < dp->chain->n_tables; i++) {
1196         struct ofp_table_stats *ots = buffer_put_uninit(buffer, sizeof *ots);
1197         struct sw_table_stats stats;
1198         dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1199         strncpy(ots->name, stats.name, sizeof ots->name);
1200         ots->table_id = i;
1201         memset(ots->pad, 0, sizeof ots->pad);
1202         ots->max_entries = htonl(stats.max_flows);
1203         ots->active_count = htonl(stats.n_flows);
1204         ots->matched_count = htonll(0); /* FIXME */
1205     }
1206     return 0;
1207 }
1208
1209 struct port_stats_state {
1210     int port;
1211 };
1212
1213 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1214                void **state)
1215 {
1216     struct port_stats_state *s = xmalloc(sizeof *s);
1217     s->port = 0;
1218     *state = s;
1219     return 0;
1220 }
1221
1222 static int port_stats_dump(struct datapath *dp, void *state,
1223                            struct buffer *buffer)
1224 {
1225     struct port_stats_state *s = state;
1226     int i;
1227
1228     for (i = s->port; i < OFPP_MAX; i++) {
1229         struct sw_port *p = &dp->ports[i];
1230         struct ofp_port_stats *ops;
1231         if (!p->netdev) {
1232             continue;
1233         }
1234         ops = buffer_put_uninit(buffer, sizeof *ops);
1235         ops->port_no = htons(port_no(dp, p));
1236         memset(ops->pad, 0, sizeof ops->pad);
1237         ops->rx_count = htonll(p->rx_count);
1238         ops->tx_count = htonll(p->tx_count);
1239         ops->drop_count = htonll(p->drop_count);
1240         ops++;
1241     }
1242     s->port = i;
1243     return 0;
1244 }
1245
1246 static void port_stats_done(void *state)
1247 {
1248     free(state);
1249 }
1250
1251 struct stats_type {
1252     /* Minimum and maximum acceptable number of bytes in body member of
1253      * struct ofp_stats_request. */
1254     size_t min_body, max_body;
1255
1256     /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1257      * 'body_len' are the 'body' member of the struct ofp_stats_request.
1258      * Returns zero if successful, otherwise a negative error code.
1259      * May initialize '*state' to state information.  May be null if no
1260      * initialization is required.*/
1261     int (*init)(struct datapath *dp, const void *body, int body_len,
1262             void **state);
1263
1264     /* Appends statistics for 'dp' to 'buffer', which initially contains a
1265      * struct ofp_stats_reply.  On success, it should return 1 if it should be
1266      * called again later with another buffer, 0 if it is done, or a negative
1267      * errno value on failure. */
1268     int (*dump)(struct datapath *dp, void *state, struct buffer *buffer);
1269
1270     /* Cleans any state created by the init or dump functions.  May be null
1271      * if no cleanup is required. */
1272     void (*done)(void *state);
1273 };
1274
1275 static const struct stats_type stats[] = {
1276     [OFPST_FLOW] = {
1277         sizeof(struct ofp_flow_stats_request),
1278         sizeof(struct ofp_flow_stats_request),
1279         flow_stats_init,
1280         flow_stats_dump,
1281         flow_stats_done
1282     },
1283     [OFPST_TABLE] = {
1284         0,
1285         0,
1286         NULL,
1287         table_stats_dump,
1288         NULL
1289     },
1290     [OFPST_PORT] = {
1291         0,
1292         0,
1293         port_stats_init,
1294         port_stats_dump,
1295         port_stats_done
1296     },
1297 };
1298
1299 struct stats_dump_cb {
1300     bool done;
1301     struct ofp_stats_request *rq;
1302     struct sender sender;
1303     const struct stats_type *s;
1304     void *state;
1305 };
1306
1307 static int
1308 stats_dump(struct datapath *dp, void *cb_)
1309 {
1310     struct stats_dump_cb *cb = cb_;
1311     struct ofp_stats_reply *osr;
1312     struct buffer *buffer;
1313     int err;
1314
1315     if (cb->done) {
1316         return 0;
1317     }
1318
1319     osr = alloc_openflow_buffer(dp, sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1320                                 &buffer);
1321     osr->type = htons(cb->s - stats);
1322     osr->flags = 0;
1323
1324     err = cb->s->dump(dp, cb->state, buffer);
1325     if (err >= 0) {
1326         int err2;
1327         if (!err) {
1328             cb->done = true;
1329         } else {
1330             /* Buffer might have been reallocated, so find our data again. */
1331             osr = buffer_at_assert(buffer, 0, sizeof *osr);
1332             osr->flags = ntohs(OFPSF_REPLY_MORE);
1333         }
1334         err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1335         if (err2) {
1336             err = err2;
1337         }
1338     }
1339
1340     return err;
1341 }
1342
1343 static void
1344 stats_done(void *cb_)
1345 {
1346     struct stats_dump_cb *cb = cb_;
1347     if (cb) {
1348         if (cb->s->done) {
1349             cb->s->done(cb->state);
1350         }
1351         free(cb);
1352     }
1353 }
1354
1355 static int
1356 recv_stats_request(struct datapath *dp, const struct sender *sender,
1357                    const void *oh)
1358 {
1359     const struct ofp_stats_request *rq = oh;
1360     size_t rq_len = ntohs(rq->header.length);
1361     struct stats_dump_cb *cb;
1362     int type, body_len;
1363     int err;
1364
1365     type = ntohs(rq->type);
1366     if (type >= ARRAY_SIZE(stats) || !stats[type].dump) {
1367         VLOG_WARN("received stats request of unknown type %d", type);
1368         return -EINVAL;
1369     }
1370
1371     cb = xmalloc(sizeof *cb);
1372     cb->done = false;
1373     cb->rq = xmemdup(rq, rq_len);
1374     cb->sender = *sender;
1375     cb->s = &stats[type];
1376     cb->state = NULL;
1377     
1378     body_len = rq_len - offsetof(struct ofp_stats_request, body);
1379     if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1380         VLOG_WARN("stats request type %d with bad body length %d",
1381                   type, body_len);
1382         err = -EINVAL;
1383         goto error;
1384     }
1385
1386     if (cb->s->init) {
1387         err = cb->s->init(dp, rq->body, body_len, &cb->state);
1388         if (err) {
1389             VLOG_WARN("failed initialization of stats request type %d: %s",
1390                       type, strerror(-err));
1391             goto error;
1392         }
1393     }
1394
1395     remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1396     return 0;
1397
1398 error:
1399     free(cb->rq);
1400     free(cb);
1401     return err;
1402 }
1403
1404 /* 'msg', which is 'length' bytes long, was received from the control path.
1405  * Apply it to 'chain'. */
1406 int
1407 fwd_control_input(struct datapath *dp, const struct sender *sender,
1408                   const void *msg, size_t length)
1409 {
1410     struct openflow_packet {
1411         size_t min_size;
1412         int (*handler)(struct datapath *, const struct sender *, const void *);
1413     };
1414
1415     static const struct openflow_packet packets[] = {
1416         [OFPT_FEATURES_REQUEST] = {
1417             sizeof (struct ofp_header),
1418             recv_features_request,
1419         },
1420         [OFPT_GET_CONFIG_REQUEST] = {
1421             sizeof (struct ofp_header),
1422             recv_get_config_request,
1423         },
1424         [OFPT_SET_CONFIG] = {
1425             sizeof (struct ofp_switch_config),
1426             recv_set_config,
1427         },
1428         [OFPT_PACKET_OUT] = {
1429             sizeof (struct ofp_packet_out),
1430             recv_packet_out,
1431         },
1432         [OFPT_FLOW_MOD] = {
1433             sizeof (struct ofp_flow_mod),
1434             recv_flow,
1435         },
1436         [OFPT_PORT_MOD] = {
1437             sizeof (struct ofp_port_mod),
1438             recv_port_mod,
1439         },
1440         [OFPT_STATS_REQUEST] = {
1441             sizeof (struct ofp_stats_request),
1442             recv_stats_request,
1443         },
1444     };
1445
1446     const struct openflow_packet *pkt;
1447     struct ofp_header *oh;
1448
1449     oh = (struct ofp_header *) msg;
1450     if (oh->version != OFP_VERSION || oh->type >= ARRAY_SIZE(packets)
1451         || ntohs(oh->length) > length)
1452         return -EINVAL;
1453
1454     pkt = &packets[oh->type];
1455     if (!pkt->handler)
1456         return -ENOSYS;
1457     if (length < pkt->min_size)
1458         return -EFAULT;
1459
1460     return pkt->handler(dp, sender, msg);
1461 }
1462 \f
1463 /* Packet buffering. */
1464
1465 #define OVERWRITE_SECS  1
1466
1467 struct packet_buffer {
1468     struct buffer *buffer;
1469     uint32_t cookie;
1470     time_t timeout;
1471 };
1472
1473 static struct packet_buffer buffers[N_PKT_BUFFERS];
1474 static unsigned int buffer_idx;
1475
1476 uint32_t save_buffer(struct buffer *buffer)
1477 {
1478     struct packet_buffer *p;
1479     uint32_t id;
1480
1481     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1482     p = &buffers[buffer_idx];
1483     if (p->buffer) {
1484         /* Don't buffer packet if existing entry is less than
1485          * OVERWRITE_SECS old. */
1486         if (time(0) < p->timeout) { /* FIXME */
1487             return -1;
1488         } else {
1489             buffer_delete(p->buffer); 
1490         }
1491     }
1492     /* Don't use maximum cookie value since the all-bits-1 id is
1493      * special. */
1494     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1495         p->cookie = 0;
1496     p->buffer = buffer_clone(buffer);      /* FIXME */
1497     p->timeout = time(0) + OVERWRITE_SECS; /* FIXME */
1498     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1499
1500     return id;
1501 }
1502
1503 static struct buffer *retrieve_buffer(uint32_t id)
1504 {
1505     struct buffer *buffer = NULL;
1506     struct packet_buffer *p;
1507
1508     p = &buffers[id & PKT_BUFFER_MASK];
1509     if (p->cookie == id >> PKT_BUFFER_BITS) {
1510         buffer = p->buffer;
1511         p->buffer = NULL;
1512     } else {
1513         printf("cookie mismatch: %x != %x\n",
1514                id >> PKT_BUFFER_BITS, p->cookie);
1515     }
1516
1517     return buffer;
1518 }
1519
1520 static void discard_buffer(uint32_t id)
1521 {
1522     struct packet_buffer *p;
1523
1524     p = &buffers[id & PKT_BUFFER_MASK];
1525     if (p->cookie == id >> PKT_BUFFER_BITS) {
1526         buffer_delete(p->buffer);
1527         p->buffer = NULL;
1528     }
1529 }