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